text stringlengths 8 1.32M |
|---|
#!/usr/bin/env xcrun -sdk macosx swift
import Foundation
//A simple counted set implementation that uses a dictionary for storage.
struct CountedSet<Element: Hashable>: Sequence {
typealias Iterator = DictionaryIterator<Element, Int>
private var backingDictionary: [Element: Int] = [:]
@discardableResult
mutating func addObject(_ object: Element) -> Int {
let currentCount = backingDictionary[object] ?? 0
let newCount = currentCount + 1
backingDictionary[object] = newCount
return newCount
}
func countForObject(_ object: Element) -> Int {
return backingDictionary[object] ?? 0
}
func makeIterator() -> DictionaryIterator<Element, Int> {
return backingDictionary.makeIterator()
}
}
struct EnumBuilder {
private enum Resource {
case file(String)
case directory(String, [Resource])
}
private static let forbiddenCharacterSet: CharacterSet = {
let validSet = NSMutableCharacterSet(charactersIn: "_")
validSet.formUnion(with: CharacterSet.letters)
return validSet.inverted
}()
private static let forbiddenPathExtensions = [".appiconset/", ".launchimage/", ".colorset/"]
private static let imageSetExtension = "imageset"
static func enumStringForPath(_ path: String, topLevelName: String = "Shark") throws -> String {
let resources = try imageResourcesAtPath(path)
if resources.isEmpty {
return ""
}
let topLevelResource = Resource.directory(topLevelName, resources)
return createEnumDeclarationForResources([topLevelResource], indentLevel: 0)
}
private static func imageResourcesAtPath(_ path: String) throws -> [Resource] {
var results = [Resource]()
let url = URL(fileURLWithPath: path)
let contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
for fileURL in contents {
var directoryKey: AnyObject?
try (fileURL as NSURL).getResourceValue(&directoryKey, forKey: URLResourceKey.isDirectoryKey)
guard let isDirectory = directoryKey as? NSNumber else { continue }
if isDirectory.intValue == 1 {
if fileURL.pathExtension == imageSetExtension {
if let name = fileURL.lastPathComponent.components(separatedBy: "." + imageSetExtension).first {
results.append(.file(name))
}
} else if forbiddenPathExtensions.index(where: { fileURL.absoluteString.hasSuffix($0) }) == nil {
let folderName = fileURL.lastPathComponent
let subResources = try imageResourcesAtPath(fileURL.relativePath)
results.append(.directory(folderName, subResources))
}
}
}
return results
}
private static func correctedNameForString(_ string: String) -> String? {
//First try replacing -'s with _'s only, then remove illegal characters
if let _ = string.range(of: "-") {
let replacedString = string.replacingOccurrences(of: "-", with: "_")
if replacedString.rangeOfCharacter(from: forbiddenCharacterSet) == nil {
return replacedString
}
}
if let _ = string.rangeOfCharacter(from: forbiddenCharacterSet) {
return string.components(separatedBy: forbiddenCharacterSet).joined(separator: "")
}
return nil
}
//An enum should extend String and conform to SharkImageConvertible if and only if it has at least on image asset in it.
//We return empty string when we get a Directory of directories.
private static func conformanceStringForResource(_ resource: Resource) -> String {
switch resource {
case .directory(_, let subResources):
for resource in subResources {
if case .file = resource {
return ": String, SharkImageConvertible"
}
}
return ""
case _:
return ""
}
}
private static func createEnumDeclarationForResources(_ resources: [Resource], indentLevel: Int) -> String {
let sortedResources = resources.sorted { first, _ in
if case .directory = first {
return true
}
return false
}
var fileNameSeen = CountedSet<String>()
var folderNameSeen = CountedSet<String>()
var resultString = ""
for singleResource in sortedResources {
switch singleResource {
case .file(let name):
print("Creating Case: \(name)")
let indentationString = String(repeating: " ", count: 4 * (indentLevel + 1))
if let correctedName = correctedNameForString(name) {
let seenCount = fileNameSeen.countForObject(correctedName)
let duplicateCorrectedName = correctedName + String(repeating: "_", count: seenCount)
resultString += indentationString + "case \(duplicateCorrectedName) = \"\(name)\"\n"
fileNameSeen.addObject(correctedName)
} else {
resultString += indentationString + "case \(name)\n"
}
case .directory(let (name, subResources)):
print("Creating Enum: \(name)")
let indentationString = String(repeating: " ", count: 4 * (indentLevel))
let duplicateCorrectedName: String
if let correctedName = correctedNameForString(name) {
let seenCount = folderNameSeen.countForObject(correctedName)
duplicateCorrectedName = correctedName + String(repeating: "_", count: seenCount)
folderNameSeen.addObject(correctedName)
} else {
duplicateCorrectedName = name
}
resultString += "\n" + indentationString + "public enum \(duplicateCorrectedName)" + conformanceStringForResource(singleResource) + " {" + "\n"
resultString += createEnumDeclarationForResources(subResources, indentLevel: indentLevel + 1)
resultString += indentationString + "}\n\n"
}
}
return resultString
}
}
struct FileBuilder {
static func fileStringWithEnumString(_ enumString: String) -> String {
return acknowledgementsString() + "\n\n" + importString() + "\n\n" + imageExtensionString() + "\n" + enumString
}
private static func importString() -> String {
return "import UIKit"
}
private static func acknowledgementsString() -> String {
return "//SharkImages.swift\n//Generated by Shark"
}
private static func imageExtensionString() -> String {
return "public protocol SharkImageConvertible {}\n\npublic extension SharkImageConvertible where Self: RawRepresentable, Self.RawValue == String {\n public var image: UIImage? {\n return UIImage(named: self.rawValue)\n }\n}\n\npublic extension UIImage {\n convenience init?<T: RawRepresentable>(shark: T) where T.RawValue == String {\n self.init(named: shark.rawValue)\n }\n}\n"
}
}
//-----------------------------------------------------------//
//-----------------------------------------------------------//
//Process arguments and run the script
let arguments = CommandLine.arguments
if arguments.count != 3 {
print("You must supply the path to the .xcassets folder, and the output path for the Shark file")
print("\n\nExample Usage:\nswift Shark.swift /Users/john/Code/GameProject/GameProject/Images.xcassets/ /Users/john/Code/GameProject/GameProject/")
exit(1)
}
let path = arguments[1]
if !(path.hasSuffix(".xcassets") || path.hasSuffix(".xcassets/")) {
print("The path should point to a .xcassets folder")
exit(1)
}
let outputPath = arguments[2]
var isDirectory: ObjCBool = false
if FileManager.default.fileExists(atPath: outputPath, isDirectory: &isDirectory) == false {
print("The output path does not exist")
exit(1)
}
if isDirectory.boolValue == false {
print("The output path is not a valid directory")
exit(1)
}
//Create the file string
let enumString = try EnumBuilder.enumStringForPath(path)
let fileString = FileBuilder.fileStringWithEnumString(enumString)
//Save the file string
let outputURL = URL(fileURLWithPath: outputPath).appendingPathComponent("SharkImages.swift")
try fileString.write(to: outputURL, atomically: true, encoding: String.Encoding.utf8)
|
//
// EpisodePlayer.swift
// ExCast
//
// Created by Tasuku Tozawa on 2019/07/21.
// Copyright © 2019 Tasuku Tozawa. All rights reserved.
//
import MaterialComponents
import UIKit
protocol EpisodePlayerPlaybackButtonsDelegate: AnyObject {
func didTapPlaybackButton()
func didTapSkipForwardButton()
func didTapSkipBackwardButton()
}
public class EpisodePlayerPlaybackButtons: UIView {
// MARK: - Properties
weak var delegate: EpisodePlayerPlaybackButtonsDelegate?
public var isEnabled: Bool {
set {
playbackButton.isEnabled = newValue
forwardSkipButton.isEnabled = newValue
backwardSkipButton.isEnabled = newValue
}
get {
// TODO:
return false
}
}
public var isPlaying: Bool {
set {
if newValue {
playbackButton.setImage(UIImage(named: "player_pause"), for: .normal)
} else {
playbackButton.setImage(UIImage(named: "player_playback"), for: .normal)
}
}
get {
// TODO:
return false
}
}
// MARK: - IBOutlets
@IBOutlet var baseView: UIView!
@IBOutlet var playbackButton: MDCFloatingButton!
@IBOutlet var forwardSkipButton: MDCFloatingButton!
@IBOutlet var backwardSkipButton: MDCFloatingButton!
@IBOutlet var playbackButtonSizeConstraint: NSLayoutConstraint!
@IBOutlet var forwardSkipButtonSizeConstraint: NSLayoutConstraint!
@IBOutlet var backwardSkipButtonSizeConstraint: NSLayoutConstraint!
@IBOutlet var buttonMarginLeftConstraint: NSLayoutConstraint!
@IBOutlet var buttonMarginRightConstraint: NSLayoutConstraint!
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
loadFromNib()
setupAppearences()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadFromNib()
setupAppearences()
}
// MARK: - IBActions
@IBAction func didTapPlaybackButton(_: Any) {
delegate?.didTapPlaybackButton()
}
@IBAction func didTapSkipForwardButton(_: Any) {
delegate?.didTapSkipForwardButton()
}
@IBAction func didTapSkipBackwardButton(_: Any) {
delegate?.didTapSkipBackwardButton()
}
// MARK: - Methods
private func loadFromNib() {
let bundle = Bundle.main
bundle.loadNibNamed("EpisodePlayerPlaybackButtons", owner: self, options: nil)
baseView.frame = bounds
addSubview(baseView)
}
private func setupAppearences() {
backgroundColor = .clear
baseView.backgroundColor = .clear
playbackButton.setImage(UIImage(named: "player_playback")?.withRenderingMode(.alwaysTemplate), for: .normal)
playbackButton.imageEdgeInsets = UIEdgeInsets(top: 18, left: 18, bottom: 18, right: 18)
forwardSkipButton.setImage(UIImage(named: "player_skip_forward_15"), for: .normal)
forwardSkipButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
backwardSkipButton.setImage(UIImage(named: "player_skip_backward_15"), for: .normal)
backwardSkipButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
if #available(iOS 13.0, *) {
let buttonColor = UIColor { (trait: UITraitCollection) -> UIColor in
if trait.userInterfaceStyle == .dark {
return .lightGray
} else {
return .black
}
}
self.playbackButton.setBackgroundColor(buttonColor)
self.forwardSkipButton.setBackgroundColor(buttonColor)
self.backwardSkipButton.setBackgroundColor(buttonColor)
} else {
playbackButton.setBackgroundColor(.black)
forwardSkipButton.setBackgroundColor(.black)
backwardSkipButton.setBackgroundColor(.black)
}
}
}
|
protocol SpellsService {
func getAllSpells(onSuccess: @escaping ([Spells]) -> Void, onError: @escaping (DataError) -> Void)
}
|
//
// ValidationModel.swift
// Alphametrica
//
// Created by Iron Man on 18/04/21.
//
import Foundation
struct ValidationModel {
var validationName : String
var boldValidationName : String
var isValid : Bool
}
|
//
// FilmsList.swift
// FIlmWiki
//
// Created by Мария on 19/04/2019.
// Copyright © 2019 vlad. All rights reserved.
//
import Foundation
class FilmViewModel: FilmViewModelProtocol {
private let filmService: FilmServiceNetwork
private var films = [Film]() {
didSet {
onFilmsAppended?(films)
}
}
var onFilmsAppended: (([Film]) -> Void)?
init(filmService: FilmServiceNetwork) {
self.filmService = filmService
}
func loadMore() {
filmService.getData { [weak self] films in
guard let self = self else { return }
self.films = films
}
}
}
|
//
// TestView.swift
// ChatApp
//
// Created by Tung on 15/07/2020.
// Copyright © 2020 Tung. All rights reserved.
//
import SwiftUI
import FirebaseAuth
import FirebaseStorage
import FirebaseFirestore
struct FirstPageView: View
{
@State var no = ""
@State var code = ""
@State var show = false
@State var mgs = ""
@State var alert = false
@State var ID = ""
var body: some View
{
VStack
{
Image("message")
.resizable()
.frame(width: 100, height: 100, alignment: .center)
Text("Verifi your number")
.font(.largeTitle)
.fontWeight(.heavy)
Text("Please enter your number To veryfi your account")
.font(.body)
.foregroundColor(.gray)
.padding(.top, 10)
HStack
{
TextField("+1", text: $no)
.keyboardType(.numberPad)
.padding()
.frame(width: 70)
.background(Color.gray)
.cornerRadius(10)
TextField("Number", text: $code)
.keyboardType(.numberPad)
.padding()
.background(Color.gray)
.cornerRadius(10)
}.padding()
NavigationLink(destination: SecondPageView(show: $show, ID: $ID), isActive: $show)
{
Button(action: {
//remove Auth when testing with real phone number
Auth.auth().settings?.isAppVerificationDisabledForTesting = true
PhoneAuthProvider.provider().verifyPhoneNumber("+" + self.no + self.code, uiDelegate: nil){
(ID, err) in
if err != nil {
self.mgs = (err?.localizedDescription)!
self.alert.toggle()
return
}
str = "+" + self.no + self.code
self.ID = ID!
self.show.toggle()
}
}){
Text("Send").frame(width: UIScreen.main.bounds.width - 30, height: 50)
}.foregroundColor(.white)
.background(Color.orange)
.cornerRadius(10)
}.alert(isPresented: $alert){
Alert(title: Text("Error"), message: Text(self.mgs), dismissButton: .default(Text("OK")))
}
}
}
}
|
//
// APIManager.swift
// WeatherProject
//
// Created by Alexander on 12/07/2017.
// Copyright © 2017 Alexander. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
extension Notification.Name {
static let weatherWasUpdated = Notification.Name("WeatherWasUpdated")
}
class APIManager {
func fetchWeather(cityName: String, completion: ((WeatherConst?) -> Void)? = nil) {
guard let urlComponents =
NSURLComponents(string: "http://api.openweathermap.org/data/2.5/weather") else { return }
urlComponents.queryItems = [URLQueryItem(name: "q", value: "\(cityName),ru"),
URLQueryItem(name: "appid", value: "624cc73c21367a228af79250ce287fff"),
URLQueryItem(name: "units", value: "metric")]
guard let url = urlComponents.url else { return }
Alamofire.request(url, method: .get).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let weatherConst = WeatherConst(json: json)
NotificationCenter.default.post(name: .weatherWasUpdated,
object: nil,
userInfo: ["weather": weatherConst])
completion?(weatherConst)
case .failure(let error):
print(error)
}
}
}
}
|
import Foundation
// Swift controlFlow
var arrayStrings = [String]()
arrayStrings = ["Emerson", "Denzyl", "Wouter", "Kishen"]
var arrayDictionary = [String: String]()
arrayDictionary = ["rock": "Metallica", "pop": "NSync", "rap": "NWA"]
// for loop array of string
for item in arrayStrings {
print(item)
}
// for loop array of integers
let intArray = [2, 4, 6, 8, 10]
var sum = 1
for value in intArray {
sum += value
print(sum)
}
// for loop array of a dictionary
for (key, value) in arrayDictionary {
print("for \(key) you have \(value)")
}
// while loop
var timer = 0
var counter = 50
while counter > timer {
counter -= 1
print(counter)
if counter == timer {
print("Time is up!!!!")
}
}
|
//
// GPResult.swift
// GPlaceAPI-Swift
//
// Created by Darshan Patel on 7/23/15.
// Copyright (c) 2015 Darshan Patel. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Darshan Patel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class GPResult {
var icon: String?
var name: String?
var place_id: String?
var rating: Double?
var reference: String?
var scope: String?
var types: [String]?
var vicinity: String?
var geometry: GPGeometry?
var opening_hours: GPOpeningHours?
var photos: [GPPhoto]?
var formatted_address: String?
var price_level: GPPriceLevel!
var address_components: [GPAddressComponents]?
var adr_address: String?
var formatted_phone_number: String?
var international_phone_number: String?
var reviews: [GPReviews]?
var url: String?
var user_ratings_total: Int?
var utc_offset: Int?
var website: String?
init(attributes: Dictionary<String, AnyObject>)
{
if let icon = attributes["icon"] as? String
{
self.icon = icon;
}
if let name = attributes["name"] as? String
{
self.name = name;
}
if let place_id = attributes["place_id"] as? String
{
self.place_id = place_id;
}
if let rating = attributes["rating"] as? Double
{
self.rating = rating;
}
if let reference = attributes["reference"] as? String
{
self.reference = reference;
}
if let scope = attributes["scope"] as? String
{
self.scope = scope;
}
if let vicinity = attributes["vicinity"] as? String
{
self.vicinity = vicinity;
}
if let types = attributes["types"] as? [String]
{
self.types = types;
}
if let formatted_address = attributes["formatted_address"] as? String
{
self.formatted_address = formatted_address;
}
if let adr_address = attributes["adr_address"] as? String
{
self.adr_address = adr_address;
}
if let formatted_phone_number = attributes["formatted_phone_number"] as? String
{
self.formatted_phone_number = formatted_phone_number;
}
if let international_phone_number = attributes["international_phone_number"] as? String
{
self.international_phone_number = international_phone_number;
}
if let url = attributes["url"] as? String
{
self.url = url;
}
if let user_ratings_total = attributes["user_ratings_total"] as? Int
{
self.user_ratings_total = user_ratings_total;
}
if let utc_offset = attributes["utc_offset"] as? Int
{
self.utc_offset = utc_offset;
}
if let website = attributes["website"] as? String
{
self.website = website;
}
self.geometry = GPGeometry(attributes: attributes["geometry"] as! Dictionary<String, AnyObject>)
if let opening_hours = attributes["opening_hours"] as? Dictionary<String, AnyObject>
{
self.opening_hours = GPOpeningHours(attributes: opening_hours)
}
if let price_level = attributes["price_level"] as? Int
{
self.price_level = self.priceLevel("\(price_level)")
}
self.photos = self.photos(attributes)
self.address_components = self.address_components(attributes)
self.reviews = self.reviews(attributes)
}
private func photos(info: Dictionary<String, AnyObject>) -> [GPPhoto]
{
var muList = [GPPhoto]();
if let check_photos = info["photos"] as? Array<AnyObject>
{
var list = check_photos
for tempList in list
{
var dic = tempList as! Dictionary<String, AnyObject>
var result = GPPhoto(attributes: dic)
muList.append(result)
}
}
return muList
}
private func address_components(info: Dictionary<String, AnyObject>) -> [GPAddressComponents]
{
var muList = [GPAddressComponents]();
if let check_address = info["address_components"] as? Array<AnyObject>
{
var list = check_address
for tempList in list
{
var dic = tempList as! Dictionary<String, AnyObject>
var result = GPAddressComponents(attributes: dic)
muList.append(result)
}
}
return muList
}
private func reviews(info: Dictionary<String, AnyObject>) -> [GPReviews]
{
var muList = [GPReviews]();
if let reviews = info["reviews"] as? Array<AnyObject>
{
var list = reviews
for tempList in list
{
var dic = tempList as! Dictionary<String, AnyObject>
var result = GPReviews(attributes: dic)
muList.append(result)
}
}
return muList
}
func priceLevel(string: String) -> GPPriceLevel
{
if string == GPPriceLevel.GPPriceLevelFree.rawValue
{
return .GPPriceLevelFree
}else if string == GPPriceLevel.GPPriceLevelExpensive.rawValue
{
return .GPPriceLevelExpensive
}
else if string == GPPriceLevel.GPPriceLevelInexpensive.rawValue
{
return .GPPriceLevelInexpensive
}
else if string == GPPriceLevel.GPPriceLevelModerate.rawValue
{
return .GPPriceLevelModerate
}
else if string == GPPriceLevel.GPPriceLevelVeryExpensive.rawValue
{
return .GPPriceLevelVeryExpensive
}
return .GPPriceLevelFree
}
} |
//
// ViewController.swift
// jokes
//
// Created by Aileen Pierce on 2/17/21.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var jokeDataHandler = JokeDataHandler()
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
//assign the closure with the method we want called to the onDataUpdate closure
jokeDataHandler.onDataUpdate = {[weak self] (data:[Joke]) in self?.render()}
jokeDataHandler.loadjson()
print("Number of jokes \(jokes.count)")
// ues test data
// loadtestdata()
}
func loadtestdata() {
//test data
let joke1 = Joke(setup: "What's the best thing about a Boolean?", punchline: "Even if you're wrong, you're only off by a bit.")
let joke2 = Joke(setup: "What's the object-oriented way to become wealthy?", punchline: "Inheritance")
let joke3 = Joke(setup: "If you put a million monkeys at a million keyboards, one of them will eventually write a Java program?", punchline: "the rest of them will write Perl")
jokes.append(joke1)
jokes.append(joke2)
jokes.append(joke3)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
jokes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "jokeIdentifier", for: indexPath)
let joke = jokes[indexPath.row]
cell.textLabel!.text = joke.setup
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let alert = UIAlertController(title: jokes[indexPath.row].setup, message: jokes[indexPath.row].punchline, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Haha", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
tableView.deselectRow(at: indexPath, animated: true) //deselects the row that had been choosen
}
func render() {
jokes = jokeDataHandler.getJokes()
tableView.reloadData()
}
}
|
//
// SearchViewController.swift
// ForaSoft_Task
//
// Created by Roman Filippov on 20/02/2018.
// Copyright © 2018 romanfilippov. All rights reserved.
//
import UIKit
private let reuseIdentifier = "albumCell"
class SearchViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {
private var albums : Array<SearchResultItem> = Array<SearchResultItem>()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = true
self.collectionView?.register(UICollectionReusableView.classForCoder(), forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "emptyHeader")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showErrorWithDescription(desc: String) {
let alert = UIAlertController(title: "Error", message: desc, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func searchForTerm(term: String) {
IndicatorView.sharedIndicator.showLoading()
APISearchManager.sharedManager.fetchMedia(with: ["term":term], media: Constants.Media.music, entity: Constants.Entity.album) { albums, error in
if let error = error {
print("Error: ", error)
self.showErrorWithDescription(desc: error.localizedDescription)
} else if let albums = albums {
self.albums.removeAll()
//NOTE: Albums now are sorted in place for simplicity, in the future we can move that to a closure variable
// in fetchMedia func
self.albums.append(contentsOf: albums.sorted(by: { $0.albumName! < $1.albumName! }))
self.collectionView?.reloadSections(IndexSet([1]))
}
IndicatorView.sharedIndicator.hideLoading()
}
}
// 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?) {
let vc = segue.destination as! DetailViewController
let selectedIndex = self.collectionView?.indexPathsForSelectedItems![0].row
vc.albumItem = self.albums[selectedIndex!]
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if (section == 0) {
return 0
}
if (albums.count == 0) {
self.collectionView?.setEmptyMessage("Nothing to show :(")
} else {
self.collectionView?.resetEmptyMessage()
}
return albums.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : AlbumCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! AlbumCell
cell.albumItem = albums[indexPath.row]
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if (indexPath.section == 1)
{
self.performSegue(withIdentifier: "showDetail", sender: self)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if (section == 0) {
return CGSize(width: view.frame.width, height: 56)
}
return CGSize.zero
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if (kind == UICollectionElementKindSectionHeader) {
if (indexPath.section == 0) {
let headerView:UICollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "searchBarHeader", for: indexPath)
return headerView
}
//return empty header view
if (indexPath.section == 1) {
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "emptyHeader", for: indexPath)
}
}
return UICollectionReusableView()
}
//MARK: - SEARCH BAR
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if(!(searchBar.text?.isEmpty)!){
searchForTerm(term: searchBar.text!)
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if(!searchText.isEmpty){
searchForTerm(term: searchBar.text!)
}
}
}
|
//
// Trap.swift
// Ruins
//
// Created by Theodore Abshire on 7/13/16.
// Copyright © 2016 Theodore Abshire. All rights reserved.
//
import Foundation
class Trap
{
let trapPower:Int
let type:String
let good:Bool
var dead:Bool
init(type:String, trapPower:Int, good:Bool)
{
self.type = type
self.trapPower = trapPower
self.good = good
dead = false
}
func damage(trapResistance:Int) -> Int
{
let baseDamage = DataStore.getInt("Traps", type, "damage")!
return baseDamage * Creature.getMultiplier((trapPower - trapResistance) * damMultiplier) / 100
}
func activate(creature:Creature) -> Int
{
self.dead = true
let damage = self.damage(creature.trapRes)
creature.health = max(0, creature.health - damage)
//TODO: status effects
if let stun = DataStore.getInt("Traps", type, "stun")
{
creature.stun += (creature.stun == 0 ? 1 : 0) + stun
}
if let shake = DataStore.getInt("Traps", type, "shake")
{
creature.shake += (creature.shake == 0 ? 1 : 0) + shake
}
if let poison = DataStore.getInt("Traps", type, "poison")
{
creature.poison += (creature.poison == 0 ? 1 : 0) + poison
}
return damage
}
} |
//
// MockTorusUtils.swift
// torus-direct-swift-sdk-mock-example
//
// Created by Michael Lee on 17/10/2021.
//
import Foundation
import TorusUtils
import FetchNodeDetails
import OSLog
import TorusSwiftDirectSDK
public class MockTorusUtils: TorusUtils {
override open func getTimestamp() -> TimeInterval {
let ret = 0.0
print("[MockTorusUtils] getTimeStamp(): ", ret)
return ret
}
override open func generatePrivateKeyData() -> Data? {
// empty bytes
// let ret = Data(count: 32)
let ret = Data(base64Encoded: "FBz7bssmbsV6jBWoOJpkVOu14+6/Xgyt1pxTycODG08=")
print("[MockTorusUtils] generatePrivateKeyData(): ", ret!.bytes.toBase64())
return ret
}
}
public class MockTDSDKFactory: TDSDKFactoryProtocol {
public func createFetchNodeDetails(network: EthereumNetwork) -> FetchNodeDetails {
let net = network == .MAINNET ? "0x638646503746d5456209e33a2ff5e3226d698bea" : "0x4023d2a0D330bF11426B12C6144Cfb96B7fa6183"
return FetchNodeDetails(proxyAddress: net, network: network)
}
public func createTorusUtils(nodePubKeys: Array<TorusNodePub> = [], loglevel: OSLogType) -> AbstractTorusUtils {
return MockTorusUtils(nodePubKeys: nodePubKeys, loglevel: loglevel)
}
public init(){
}
}
|
//
// PictureViewController.swift
// imagefy
//
// Created by Alan on 5/22/16.
// Copyright © 2016 Alan M. Lira. All rights reserved.
//
import UIKit
import pop
import AssetsLibrary
import RNActivityView
enum CameraSourceType: Int {
case Camera = 0, Galery
}
class PictureViewController: UIViewController, WishCreationViewProtocol {
var presenter: WishCreationPresenterProtocol?
var pictureTaked: UIImage!
let picker = UIImagePickerController()
@IBOutlet var cameraContentView: UIView!
@IBOutlet var cameraAcessory: UIView!
@IBOutlet var cameraButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.allowsEditing = false
picker.sourceType = .Camera
picker.cameraCaptureMode = .Photo
picker.showsCameraControls = false
let frame = cameraContentView.frame
picker.view.frame = CGRectMake(frame.origin.x, frame.origin.y - 64, frame.width, frame.height + 64)
picker.view.backgroundColor = UIColor.clearColor()
picker.cameraOverlayView?.backgroundColor = UIColor.clearColor()
picker.navigationBarHidden = true
picker.toolbarHidden = true
picker.cameraViewTransform = CGAffineTransformMakeScale(1.4, 1.4)
picker.edgesForExtendedLayout = .None
cameraContentView.addSubview(picker.view)
WishCreationConfigurator.configure(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cameraSegmentationChanged(sender: UISegmentedControl) {
dispatch_async(dispatch_get_main_queue()) {
switch CameraSourceType(rawValue: sender.selectedSegmentIndex)! {
case CameraSourceType.Camera:
self.picker.sourceType = .Camera
self.cameraAcessory.hidden = false
break
case CameraSourceType.Galery:
self.picker.sourceType = .SavedPhotosAlbum
self.cameraAcessory.hidden = true
break
}
}
}
@IBAction func cameraTakePicture() {
if self.cameraButton.pop_animationForKey("size") == nil {
picker.takePicture()
let spring = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
spring.velocity = NSValue(CGPoint: CGPointMake(8, 8))
spring.springBounciness = 20
self.cameraButton.pop_addAnimation(spring, forKey: "size")
}
}
@IBAction func backAction(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - WishCreationViewProtocol
func wishCreationSuccess(wish: Wish) {
self.dismissViewControllerAnimated(true, completion: nil)
myAppDelegate.window!.showActivityViewWithLabel("Wish recorded ;)")
myAppDelegate.window!.hideActivityViewWithAfterDelay(1)
}
func showAlert(title: String, description: String) {
self.view.showActivityViewWithLabel("An error ocurred. Please, try again.")
self.view.hideActivityViewWithAfterDelay(2)
}
func wishCreationAlert(image: UIImage) {
let almostAlert = AlmostThereView.loadFromNib(image)
almostAlert.frame = CGRectMake(self.view.frame.origin.x - 4, self.view.frame.origin.y - 72, self.view.frame.width + 8, self.view.frame.height + 72)
almostAlert.delegate = self
self.navigationController?.view.addSubview(almostAlert)
let spring = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
spring.velocity = NSValue(CGPoint: CGPointMake(8, 8))
spring.springBounciness = 20
almostAlert.pop_addAnimation(spring, forKey: "size")
}
}
extension PictureViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.pictureTaked = chosenImage
self.wishCreationAlert(chosenImage)
} else if let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL{
let assetLibrary = ALAssetsLibrary()
assetLibrary.assetForURL(imageUrl , resultBlock: { (asset: ALAsset!) -> Void in
if let actualAsset = asset as ALAsset? {
let assetRep: ALAssetRepresentation = actualAsset.defaultRepresentation()
let iref = assetRep.fullResolutionImage().takeUnretainedValue()
let image = UIImage(CGImage: iref)
self.pictureTaked = image
self.wishCreationAlert(image)
}
}, failureBlock: { (error) -> Void in
})
}
}
}
extension PictureViewController: AlmostThereViewDelegate {
func setupSuccess(model: AlmostThereModelView) {
self.view.showActivityViewWithLabel("")
print("Model - brief: \(model.brief) - value: \(model.priceValue) - image: \(model.productImage)")
presenter?.sendWish(model.productImage!, description: model.brief, price: Double(model.priceValue))
}
} |
//
// ViewController.swift
// swiftcrypto
//
// Created by Satyam Tyagi on 11/9/16.
// Copyright © 2016 Satyam Tyagi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var enteredText: UITextField!
@IBOutlet weak var encryptedText: UITextView!
@IBOutlet weak var decryptedText: UITextField!
@IBOutlet weak var verificationResult: UITextField!
var pubEncKey = ""
var pubSignKey = ""
@IBAction func encryptAndSign(_ sender: UIButton) {
//take entered text
//encrypt with public key
guard let clearText = enteredText.text else {
print("no clear text")
return
}
let encryptedString =
CryptoSingleton.sharedInstance.encryptECCPubKeySupplied(
message: clearText,
externalKeyB64String: pubEncKey)
print("encryptedString:", encryptedString)
//take the encrypted output
//sign with private key (Requires TouchId)
let signString =
CryptoSingleton.sharedInstance.signECCPrivKey(message: encryptedString)
print("signString", signString)
//concat ":" separator and assign to encrypted text
encryptedText.text = encryptedString + ":" + signString
}
@IBAction func decryptAndVerify(_ sender: UIButton) {
//take the encyrpted signed text
guard let encryptText = encryptedText.text else {
print("no encryption text")
return
}
//parse with ":" separator
let encryptArray = encryptText.components(separatedBy: ":")
if encryptArray.count == 2 {
let encryptString = encryptArray[0]
let signString = encryptArray[1]
//verify the signature
//assign result to verify Result
if CryptoSingleton.sharedInstance.verifySignECCPubKeySupplied(
message: encryptString,
signatueString: signString,
externalKeyB64String: pubSignKey) {
verificationResult.text = "Success!"
}
else {
verificationResult.text = "Failure!"
}
//decrypt with private key (Require TouchId)
CryptoSingleton.sharedInstance.decryptECCPrivKey(encryptedString: encryptString)
}
else {
print("failed to parse", encryptArray.count, encryptText)
for stringElem in encryptArray {
print(stringElem)
}
}
}
func encryptionComplete() {
//assign decryption result to decryptedText
decryptedText.text = CryptoSingleton.sharedInstance.decryptedMessage
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pubEncKey = CryptoSingleton.sharedInstance.generateECCKeys()
pubSignKey = CryptoSingleton.sharedInstance.generateECCSignKeys()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "encryptionComplete"), object: nil, queue: nil) { _ in self.encryptionComplete()}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// RotationSlider.swift
// LunarReader
//
// Created by Satyam Ghodasara on 4/25/19.
// Copyright © 2019 Satyam Ghodasara. All rights reserved.
//
import UIKit
class RotationSlider: UIControl, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
var rotationAngle: CGFloat { // radians
get {
return (self.scrollView.contentOffset.x - 137) / 135 * 37 / 180 * CGFloat.pi
}
set {
var contentOffset = self.scrollView.contentOffset
contentOffset.x = newValue / 37 * 180 / CGFloat.pi * 135 + 137
self.scrollView.setContentOffset(contentOffset, animated: false)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Add observer for page changes
NotificationCenter.default.addObserver(forName: .didChangePage, object: nil, queue: OperationQueue.main) { notification in
let wordBoxImageView = notification.userInfo!["WordBoxImageView"] as! WordBoxImageView
self.rotationAngle = wordBoxImageView.page!.lineRotationAngle
}
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.sendActions(for: .valueChanged)
}
}
|
//
// HomeCell.swift
// HelpingHand
//
// Created by amota511 on 1/16/18.
// Copyright © 2018 Aaron Motayne. All rights reserved.
//
import UIKit
class HomeCell: UICollectionViewCell {
var image = UIImageView()
var title = UILabel()
var shadow = UIView()
}
|
struct OriginalEnvironmentVariable: Codable {
static let sourceBitriseBuildNumberKey = "SOURCE_BITRISE_BUILD_NUMBER"
let key: String
let value: String
}
// MARK: - Converter for build trigger
extension OriginalEnvironmentVariable {
var asBuildTriggerEnvironmentVariable: BuildTriggerEnvironmentVariable {
BuildTriggerEnvironmentVariable(mappedTo: key, value: value)
}
}
|
//
// TIDestinationModel.swift
// TPLInsurance
//
// Created by Tahir Raza on 18/12/2018.
// Copyright © 2018 TPLHolding. All rights reserved.
//
import Foundation
struct TIDestinationModel : Codable {
let id : String?
let name : String?
enum CodingKeys: String, CodingKey {
case id = "Id"
case name = "Name"
}
init(with id:String, name:String) {
self.id = id
self.name = name
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id)
name = try values.decodeIfPresent(String.self, forKey: .name)
}
static func decodeJsonData(data: Data) -> [TIDestinationModel]? {
let decodedObject = try? JSONDecoder().decode([TIDestinationModel].self, from: data)
return decodedObject
}
}
struct DestinationStruct {
var id: String? = nil
var name: String? = nil
init(with id:String, name:String) {
self.id = id
self.name = name
}
}
|
//
// ViewController+CoreData.swift
// ShoppingCart
//
// Created by John Alexandert Torres on 9/20/15.
// Copyright © 2015 test. All rights reserved.
//
|
//
// MenuViewController.swift
// APPFORMANAGEMENT
//
// Created by Chanakan Jumnongwit on 1/31/2560 BE.
// Copyright © 2560 REVO. All rights reserved.
//
import UIKit
import SWRevealViewController
class MenuViewController: UIViewController {
@IBOutlet weak var avatarImage:UIImageView!
@IBOutlet weak var name:UILabel!
@IBOutlet weak var position:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
setUserInterface()
}
func setUserInterface(){
avatarImage.layer.masksToBounds = false
avatarImage.layer.cornerRadius = avatarImage.frame.height/2
avatarImage.clipsToBounds = true
avatarImage.image = UIImage(named: "profile_icon")
name.text = String(format:"%@ %@",SetttingController.shareInstance.getFirstname(),SetttingController.shareInstance.getLastname())
position.text = SetttingController.shareInstance.getUsertype()
}
@IBAction func onClikcedToGoToDialyReport(){
let SWRealVC = self.storyboard?.instantiateViewController(withIdentifier: "DialyReportViewController")
self.navigationController?.pushViewController(SWRealVC!, animated: true)
self.revealViewController().revealToggle(animated: false)
}
@IBAction func onClikcedToGoToProfitExpectReport(){
let SWRealVC = self.storyboard?.instantiateViewController(withIdentifier: "ProfitAndLostExpectReportViewController")
self.navigationController?.pushViewController(SWRealVC!, animated: true)
self.revealViewController().revealToggle(animated: false)
}
@IBAction func onClickedToGoToPerformanceReport(){
let SWRealVC = self.storyboard?.instantiateViewController(withIdentifier: "PerformanceReportViewController")
self.navigationController?.pushViewController(SWRealVC!, animated: true)
self.revealViewController().revealToggle(animated: false)
}
@IBAction func onClickedToGoToSetting(){
let SWRealVC = self.storyboard?.instantiateViewController(withIdentifier: "SetttingViewController")
self.navigationController?.pushViewController(SWRealVC!, animated: true)
self.revealViewController().revealToggle(animated: false)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// BeersListView.swift
// Paging
//
// Created by Evgeniya Bubnova on 08.04.2020.
// Copyright © 2020 Evgeniya Bubnova. All rights reserved.
//
import SwiftUI
final class BeersViewModel: ObservableObject {
@Published private(set) var items: [Beer] = [Beer]()
@Published private(set) var page: Int = 0
@Published private(set) var isPageLoading: Bool = false
func loadPage() {
guard isPageLoading == false else {
return
}
isPageLoading = true
page += 1
BeersAPI.getBeers(page: page) { (beers, error) in
if let beers = beers {
self.items += beers
}
self.isPageLoading = false
}
}
}
extension Beer: Identifiable {
var imageURL: URL? {
guard let url = self.imageUrl else { return nil }
return URL(string: url)
}
}
struct BeersListView: View {
@EnvironmentObject var viewModel: BeersViewModel
var body: some View {
List(self.viewModel.items) { item in
VStack(alignment: .leading) {
BeerRowView(item: item)
.onAppear() {
if self.viewModel.items.isLast(item) {
self.viewModel.loadPage()
}
}
}
}
.onAppear() {
self.viewModel.loadPage()
}
}
}
struct BeersListView_Previews: PreviewProvider {
static var previews: some View {
BeersListView()
}
}
|
//
// Commend.swift
// NSCP
//
// Created by MuMhu on 2/9/2561 BE.
// Copyright © 2561 MuMhu. All rights reserved.
//
import UIKit
class Commend: NSObject {
var fromId: String?
var text: String?
var timestamp: NSNumber?
}
|
// ===================================================================================
// Fichier: ViewController.swift
// Projet: JouerUneVideoLocale
// Auteur: Alain Boudreault
// Copyright: 17-11-24 © ve2cuy, All rights reserved.
// ===================================================================================
// NOTE: À l'usage exclusif des étudiants et étudiantes de
// Techniques d'Intégration Multimédia
// du cégep de Saint-Jérôme.
// ----------------------------------------------------------------------------------
// Il est interdit de reproduire, en tout ou en partie, à des fins commerciales,
// le code source, les scènes, les éléments graphiques, les classes et
// tout autre contenu du présent projet sans l’autorisation écrite de l'auteur.
//
// Pour obtenir l’autorisation de reproduire ou d’utiliser, en tout ou en partie,
// le présent projet, veuillez communiquer avec:
//
// Alain Boudreault, aboudrea@cstj.qc.ca, ve2cuy.wordpress.com, ve2cuy @ github
//
// ===================================================================================
//
// Référence sur 'xcode_markup'
// https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/index.html#//apple_ref/doc/uid/TP40016497-CH2-SW1
// ===================================================================================
//
// Extrait:
//
// Ceci vient d'où?
/*
GOOD FOOD
At the
Peoples Grill (both)
SHORT ORDER &
REGULAR MEALS
*/
// Importation des librairies
import UIKit
import AVKit
// ****************************************************
class ViewController: UIViewController {
// Définition des constantes
let urlVideoWeb = URL(string:"http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")!
let urlVideoLocale = Bundle.main.url(forResource: "piano", withExtension: "m4v")! // Utiliser: Bundle.main.url pour un fichier local.
// Définition des liens MVC
@IBOutlet weak var viewStreamDuNet: UIView!
@IBOutlet weak var viewStreamLocal: UIView!
// ****************************************************
override func viewDidLoad() {
super.viewDidLoad()
// Jouer une vidéo à partir du web
chargerVideo(uneURL: urlVideoWeb, uneView: viewStreamDuNet)
// Jouer une vidéo locale
chargerVideo(uneURL: urlVideoLocale, uneView: viewStreamLocal)
} // viewDidLoad()
// Voici un exemple de documentation en ligne:
/**
Cette méthode a la mauvaise habitude de soliciter le web
ou le bundle local pour localiser une vidéo dans le
but de la présenter dans une des UIViews du projet.
- Author:
Alain Boudreault
- parameters:
- uneURL: lien vers la vidéo
- uneView: lien vers la UIView qui présentera la vidéo
*/
func chargerVideo(uneURL:URL, uneView:UIView) {
// Initialiser un lecteur de vidéo à partir d'une URL
let player = AVPlayer(url: uneURL)
// Créer une palette de contrôle vidéo
let playerViewController = AVPlayerViewController()
// Associer la palette de contrôle vidéo au lecteur vidéo
playerViewController.player = player
// Ajuster la taille de la vidéo à celle de la view de présentation
playerViewController.view.frame = uneView.bounds
// Présenter le vidéo player à l'écran
uneView.addSubview(playerViewController.view)
// Facultatif, Ajouter le panneau de control de la vidéo
self.addChildViewController(playerViewController)
// Démarrer la vidéo
player.play()
} // chargerVideoÀPartirDuWeb
} // ViewController
|
// Leetcode - https://leetcode.com/problems/rotate-array/
class Solution {
// by creating a new array
func rotate(_ nums: inout [Int], _ k: Int) {
var temp = nums
for i in 0 ..< nums.count {
temp[(i + k) % nums.count] = nums[i]
}
nums = temp
}
func rotate(_ nums: inout [Int], _ k: Int) {
var k = k % nums.count
reverse(&nums, 0, nums.count-1)
reverse(&nums, 0, k-1)
reverse(&nums, k, nums.count-1)
}
func reverse(_ nums: inout [Int], _ s: Int, _ e: Int) {
var s = s
var e = e
while s < e {
nums.swapAt(s, e)
s += 1
e -= 1
}
}
}
assert(rotate([1,2,3,4,5,6,7], 3)) // [5,6,7,1,2,3,4]
|
//
// TKTransitionSubmitButton
//
// Created by Takuya Okamoto on 2015/08/07.
// Copyright (c) 2015年 Uniface. All rights reserved.
//
import Foundation
import UIKit
let PINK = UIColor(red:0.992157, green: 0.215686, blue: 0.403922, alpha: 1)
let DARK_PINK = UIColor(red:0.798012, green: 0.171076, blue: 0.321758, alpha: 1)
@IBDesignable
public class TKTransitionSubmitButton : UIButton, UIViewControllerTransitioningDelegate {
public var didEndFinishAnimation : (()->())? = nil
let springGoEase = CAMediaTimingFunction(controlPoints: 0.45, -0.36, 0.44, 0.92)
let shrinkCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let expandCurve = CAMediaTimingFunction(controlPoints: 0.95, 0.02, 1, 0.05)
let shrinkDuration: CFTimeInterval = 0.1
lazy var spiner: SpinerLayer! = {
let s = SpinerLayer(frame: self.frame)
self.layer.addSublayer(s)
return s
}()
@IBInspectable public var highlightedBackgroundColor: UIColor? = DARK_PINK {
didSet {
self.setBackgroundColor()
}
}
@IBInspectable public var normalBackgroundColor: UIColor? = PINK {
didSet {
self.setBackgroundColor()
}
}
var cachedTitle: String?
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
override public var highlighted: Bool {
didSet {
self.setBackgroundColor()
}
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {
self.layer.cornerRadius = self.frame.height / 2
self.clipsToBounds = true
self.setBackgroundColor()
}
func setBackgroundColor() {
if (highlighted) {
self.backgroundColor = highlightedBackgroundColor
}
else {
self.backgroundColor = normalBackgroundColor
}
}
public func startLoadingAnimation() {
self.cachedTitle = titleForState(.Normal)
self.setTitle("", forState: .Normal)
self.shrink()
NSTimer.schedule(delay: shrinkDuration - 0.25) { timer in
self.spiner.animation()
}
}
public func stopLoadingAnimation() {
self.spiner.stopAnimation()
self.restore()
NSTimer.schedule(delay: shrinkDuration - 0.25) { timer in
self.returnToOriginalState()
}
}
public func startFinishAnimation(delay: NSTimeInterval, completion:(()->())?) {
NSTimer.schedule(delay: delay) { timer in
self.didEndFinishAnimation = completion
self.expand()
self.spiner.stopAnimation()
}
}
public func animate(duration: NSTimeInterval, completion:(()->())?) {
startLoadingAnimation()
startFinishAnimation(duration, completion: completion)
}
public override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
let a = anim as! CABasicAnimation
if a.keyPath == "transform.scale" {
didEndFinishAnimation?()
NSTimer.schedule(delay: 1) { timer in
self.returnToOriginalState()
}
}
}
func returnToOriginalState() {
self.layer.removeAllAnimations()
self.setTitle(self.cachedTitle, forState: .Normal)
}
func shrink() {
let shrinkAnim = CABasicAnimation(keyPath: "bounds.size.width")
shrinkAnim.fromValue = frame.width
shrinkAnim.toValue = frame.height
shrinkAnim.duration = shrinkDuration
shrinkAnim.timingFunction = shrinkCurve
shrinkAnim.fillMode = kCAFillModeForwards
shrinkAnim.removedOnCompletion = false
layer.addAnimation(shrinkAnim, forKey: shrinkAnim.keyPath)
}
func restore() {
let restoreAnim = CABasicAnimation(keyPath: "bounds.size.width")
restoreAnim.fromValue = frame.height
restoreAnim.toValue = frame.width
restoreAnim.duration = shrinkDuration
restoreAnim.timingFunction = shrinkCurve
restoreAnim.fillMode = kCAFillModeForwards
restoreAnim.removedOnCompletion = false
layer.addAnimation(restoreAnim, forKey: restoreAnim.keyPath)
}
func expand() {
let expandAnim = CABasicAnimation(keyPath: "transform.scale")
expandAnim.fromValue = 1.0
expandAnim.toValue = 26.0
expandAnim.timingFunction = expandCurve
expandAnim.duration = 0.5
expandAnim.delegate = self
expandAnim.fillMode = kCAFillModeForwards
expandAnim.removedOnCompletion = false
layer.addAnimation(expandAnim, forKey: expandAnim.keyPath)
}
}
class SpinerLayer :CAShapeLayer {
init(frame:CGRect) {
super.init()
let radius:CGFloat = (frame.height / 2) * 0.5
self.frame = CGRectMake(0, 0, frame.height, frame.height)
let center = CGPointMake(frame.height / 2, bounds.center.y)
let startAngle = 0 - M_PI_2
let endAngle = M_PI * 2 - M_PI_2
let clockwise: Bool = true
self.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).CGPath
self.fillColor = nil
self.strokeColor = UIColor.whiteColor().CGColor
self.lineWidth = 1
self.strokeEnd = 0.4
self.hidden = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animation() {
self.hidden = false
let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
rotate.fromValue = 0
rotate.toValue = M_PI * 2
rotate.duration = 0.4
rotate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
rotate.repeatCount = HUGE
rotate.fillMode = kCAFillModeForwards
rotate.removedOnCompletion = false
self.addAnimation(rotate, forKey: rotate.keyPath)
}
func stopAnimation() {
self.hidden = true
self.removeAllAnimations()
}
}
public class TKFadeInAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var transitionDuration: NSTimeInterval = 0.5
var startingAlpha: CGFloat = 0.0
public convenience init(transitionDuration: NSTimeInterval, startingAlpha: CGFloat){
self.init()
self.transitionDuration = transitionDuration
self.startingAlpha = startingAlpha
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return transitionDuration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
toView.alpha = startingAlpha
fromView.alpha = 0.8
/*
var frame = toView.frame
if (frame.y > 0)
{
// In my experience, the final frame is always a zero rect, so this is always hit
var insets = UIEdgeInsetsZero;
// My "solution" was to inset the container frame by the difference between the
// actual status bar height and the normal status bar height
insets.top = UIApplication.sharedApplication().statusBarFrame.height - 20;
frame = UIEdgeInsetsInsetRect(containerView.bounds, insets)
}
toView.frame = frame
*/
containerView.addSubview(toView)
UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in
toView.alpha = 1.0
fromView.alpha = 0.0
}, completion: {
_ in
fromView.alpha = 1.0
transitionContext.completeTransition(true)
})
}
}
|
//
// DateFormatter+JSONCache.swift
// JSONCache
//
// Created by Anders Blehr on 11/03/2017.
// Copyright © 2017 Anders Blehr. All rights reserved.
//
import Foundation
public extension DateFormatter {
public static func date(fromISO8601String string: String) -> Date? {
return iso8601DateFormatter.date(from: string)
}
public static func iso8601String(from date: Date) -> String {
return iso8601DateFormatter.string(from: date)
}
// Private implementation details
private enum ISO8601Format: String {
case withSeparators = "yyyy-MM-dd'T'HH:mm:ss'Z'"
case withoutSeparators = "yyyyMMdd'T'HHmmss'Z'"
}
private static var iso8601DateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
dateFormatter.dateFormat = (JSONCache.dateFormat == .iso8601WithSeparators ? ISO8601Format.withSeparators : ISO8601Format.withoutSeparators).rawValue
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
return dateFormatter
}
}
|
#if canImport(Darwin) && !SWIFT_PACKAGE
import Foundation
import XCTest
@testable import Quick
/**
Runs an XCTestSuite instance containing only the given QuickSpec subclass.
Use this to run QuickSpec subclasses from within a set of unit tests.
Due to implicit dependencies in _XCTFailureHandler, this function raises an
exception when used in Swift to run a failing test case.
@param specClass The class of the spec to be run.
@return An XCTestRun instance that contains information such as the number of failures, etc.
*/
@discardableResult
func qck_runSpec(_ specClass: QuickSpec.Type) -> XCTestRun? {
return qck_runSpecs([specClass])
}
/**
Runs an XCTestSuite instance containing the given QuickSpec subclasses, in the order provided.
See the documentation for `qck_runSpec` for more details.
@param specClasses An array of QuickSpec classes, in the order they should be run.
@return An XCTestRun instance that contains information such as the number of failures, etc.
*/
@discardableResult
func qck_runSpecs(_ specClasses: [QuickSpec.Type]) -> XCTestRun? {
World.sharedWorld.isRunningAdditionalSuites = true
defer { World.sharedWorld.isRunningAdditionalSuites = false }
let suite = XCTestSuite(name: "MySpecs")
for specClass in specClasses {
let test = XCTestSuite(forTestCaseClass: specClass)
suite.addTest(test)
}
let result = XCTestObservationCenter.shared.qck_suspendObservation {
suite.run()
return suite.testRun
}
return result
}
@objc(QCKSpecRunner)
@objcMembers
class QuickSpecRunner: NSObject {
static func runSpec(_ specClass: QuickSpec.Type) -> XCTestRun? {
return qck_runSpec(specClass)
}
static func runSpecs(_ specClasses: [QuickSpec.Type]) -> XCTestRun? {
return qck_runSpecs(specClasses)
}
}
#endif
|
//
// ContributeTableViewCell.swift
// LinkX
//
// Created by Rodney Gainous Jr on 7/1/19.
// Copyright © 2019 CodeSigned. All rights reserved.
//
import UIKit
class ActivityTableViewCell: UITableViewCell {
@IBOutlet var typeText: UILabel!
@IBOutlet var pointsLabel: UILabel!
@IBOutlet var descriptionText: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func configure(activity: Activity) {
typeText.text = activity.name
descriptionText.text = activity.description
if let points = activity.points {
pointsLabel.text = "\(points) \npoints"
pointsLabel.layer.cornerRadius = 5.0
pointsLabel.layer.borderColor = UIColor(white: 0, alpha: 0.2).cgColor
pointsLabel.layer.borderWidth = 0.5
} else {
pointsLabel.isHidden = true
}
}
}
|
//
// StructFashion.swift
// MVVMPractice
//
// Created by Ruoming Gao on 9/18/19.
// Copyright © 2019 Ruoming Gao. All rights reserved.
//
import Foundation
struct StructFashion: Decodable {
let hits: [HitsContainer]
}
struct HitsContainer: Decodable {
let largeImageURL: String
let likes: Int
let views: Int
let type: String
}
|
//
// TodayProfileApp.swift
// TodayProfile
//
// Created by 박지승 on 2020/11/30.
//
import SwiftUI
@main
struct TodayProfileApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ProfileView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
|
//
// Todo.swift
// DemoTodoList
//
// Created by David Mardashev on 25.09.2020.
//
import Foundation
struct Todo: Identifiable {
var id = UUID()
var title: String
var isCompleted: Bool = false
}
|
//
// ChatRoomPresenter.swift
// WalkTalk
//
// Created by Sylvain Chan on 9/2/2020.
// Copyright (c) 2020 Sylvain. All rights reserved.
//
// Purpose of Presenter:
// - Control view state, view presentation logic
// - Get response from interaction, parse it to view model, which will be the only view data received by View
import UIKit
// MARK: - Presentation logic goes here
protocol ChatRoomPresentationLogic {
func presentSearchPeer()
func presentViewControllerDismissal(response: ChatRoom.Response.DismissViewController)
func presentChatRoomStatus(response: ChatRoom.Response.ChatRoomStatus)
func presentViewInit(response: ChatRoom.Response.PredefinedMessage)
func presentQuitChat()
func presentEmptyInputField()
func presentUpdatedMessage(response: [ChatRoom.Response.IncomingMessage])
}
// MARK: - Presenter main body
class ChatRoomPresenter: ChatRoomPresentationLogic {
// - VIP
weak var viewController: ChatRoomDisplayLogic?
}
// MARK: - Presentation receiver
extension ChatRoomPresenter {
// will show text corresponding to connection status
func presentChatRoomStatus(response: ChatRoom.Response.ChatRoomStatus) {
switch response.status {
case .connected:
self.viewController?.displayNavMessage(viewModel: ChatRoom.ViewModel.NavigationMessage(message: "You can chat now"))
self.viewController?.displayUserInteractiveElements(viewModel: ChatRoom.ViewModel.UserInteractiveElements(enable: true))
case .waiting:
self.viewController?.displayNavMessage(viewModel: ChatRoom.ViewModel.NavigationMessage(message: "Waiting other to join..."))
self.viewController?.displayUserInteractiveElements(viewModel: ChatRoom.ViewModel.UserInteractiveElements(enable: false))
}
}
func presentViewInit(response: ChatRoom.Response.PredefinedMessage) {
let strings = response.all.compactMap{ $0.message }
self.viewController?.displayPredefinedMessage(viewModel: ChatRoom.ViewModel.PredefinedMessage(all: strings))
}
func presentEmptyInputField() {
self.viewController?.displayEmptyInputField()
}
func presentQuitChat() {
self.viewController?.quitChat()
}
func presentUpdatedMessage(response: [ChatRoom.Response.IncomingMessage]) {
let messages = response.compactMap { $0.message }
self.viewController?.displayLatestMessage(messages: messages)
}
func presentViewControllerDismissal(response: ChatRoom.Response.DismissViewController) {
self.viewController?.dismissViewController(viewModel: ChatRoom.ViewModel.DismissViewController(viewcontroller: response.viewcontroller))
}
func presentSearchPeer() {
self.viewController?.displaySearchPeer()
}
}
|
//
// FileManager.swift
// LinuxFoundation
//
// Created by yuuji on 7/14/16.
//
//
import Foundation
#if os(Linux) || os(FreeBSD)
/* not needed since swift 3 preview 3
public typealias FileManager = NSFileManager
private var def = FileManager()
extension FileManager {
public static var `default`: FileManager { return def }
}
*/
#endif
|
//
// main.swift
// ChuaBaiTapBuoi2
//
// Created by Taof on 1/2/20.
// Copyright © 2020 Taof. All rights reserved.
//
import Foundation
//tamGiac(a: 3, b: 4 ,c: 5)
//namNhuan(a: 1600)
//bai5()
//timSoNBeNhat()
//tamGiacCan()
drawTriangle()
|
//
// ViewController.swift
// horoscope
//
// Created by Ryan on 22/12/2015.
// Copyright © 2015 Ryan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var showHoroscope: UIButton!
@IBOutlet weak var showMyHoroscope: UIButton!
var arrayHoroscope = ["水瓶座", "雙魚座", "牡羊座", "金牛座", "雙子座", "巨蟹座", "獅子座", "處女座", "天秤座", "天蝎座", "射手座", "山羊座"]
var arrayPosition = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
showHoroscope.setTitle(arrayHoroscope[arrayPosition], forState: . Normal)
showMyHoroscope.setTitle("跳回我的星座", forState: .Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showHoroscopePressed(sender: AnyObject) {
if arrayPosition <= 10 {
showHoroscope.setTitle(arrayHoroscope[arrayPosition + 1], forState: .Normal)
arrayPosition += 1
} else {
arrayPosition = 0
showHoroscope.setTitle(arrayHoroscope[arrayPosition], forState: .Normal)
arrayPosition += 1
}
}
@IBAction func showMyHoroscopePressed(sender: AnyObject) {
arrayPosition = 7
showHoroscope.setTitle(arrayHoroscope[arrayPosition], forState: .Normal)
}
}
|
/// Birdui in SwiftUI
///
/// Created by Maitri Mehta and Alberto Talaván on 4/7/20.
/// Copyright © 2020. All rights reserved.
import SwiftUI
struct PostListView: View {
private var postViewModel = PostViewModel()
// @ObservedObject var postViewModel: PostViewModel
let testUserImage: String = "mascot_swift-badge"
@State private var isNewPostViewVisible = false
@State private var searchText = ""
// init() {
// UITableView.appearance().separatorColor = .clear
// }
private var posts: [MediaPost] {
if !searchText.isEmpty {
return postViewModel.searchPost(searchText)
}else{
return postViewModel.posts
}
}
var body: some View {
VStack {
VStack(alignment: .leading) {
ZStack {
VStack {
Image(testUserImage)
.resizable()
.frame(width: 50, height: 50, alignment: .leading)
}
.frame(maxWidth: .infinity, alignment: .leading)
Text("Home")
.font(.title)
// Spacer()
}
Button(
action:{
self.isNewPostViewVisible = true
}){
Image(systemName: "plus")
.font(.system(size: 25))
.foregroundColor(.blue)
.padding(.trailing, 5)
Text("Create New Post")
.foregroundColor(.blue)
}
.modifier(ButtonStyle())
.sheet(isPresented: self.$isNewPostViewVisible) {
NewPostView(postHandler: self.postViewModel)
}
.font(.headline)
}
.padding(.horizontal, 16)
SearchBar(text: $searchText)
.padding(.bottom)
List {
ForEach(posts) { post in
PostView(post: post)
}
}
}
}
}
struct PostListView_Previews: PreviewProvider {
static var previews: some View {
Group {
PostListView()
// PostListView(postViewModel: PostViewModel())
.environment(\.colorScheme, .light)
// PostListView()
// .environment(\.colorScheme, .dark)
}
}
}
|
//
// TestingHelper.swift
// Hammer
//
// Created by Mike Sabo on 10/31/15.
// Copyright © 2015 FlyingDinosaurs. All rights reserved.
//
import Foundation
import Hammer
class TestingHelper {
class func jsonFromFile(_ filename: String) -> Data {
if let filePath = Bundle(for: self).path(forResource: filename, ofType:"json") {
if let data = try? Data(contentsOf: URL(fileURLWithPath: filePath), options:NSData.ReadingOptions.uncached) {
return data
}
}
return Data.init()
}
}
|
//
// Electron.swift
// atoms
//
// Created by Luobin Wang on 7/31/15.
// Copyright © 2015 Luobin Wang. All rights reserved.
//
import Foundation
import SpriteKit
class Electron {
let etron = SKSpriteNode(imageNamed: "electron")
var pos = CGPointZero
var osciScale = CGFloat()
var timeOffset = CGFloat()
var orbitSpeed = CGFloat()
var clockWise = Bool()
func setup(_pos:CGPoint, _osciScale:CGFloat){
self.pos = _pos
self.osciScale = _osciScale
let decideOrbitOrient = random(0, max: 1)
if decideOrbitOrient > 0.5 {
clockWise = true
}else{
clockWise = false
}
timeOffset = CGFloat(random(0, max: CGFloat(M_PI * 2)))
orbitSpeed = CGFloat(random(0, max: 10))
etron.name = "electron"
etron.position = pos
}
func update(){
let time = CGFloat(CFAbsoluteTimeGetCurrent()) * orbitSpeed + timeOffset
let xOsci = CGFloat(sin(time)) * osciScale
let yOsci = CGFloat(cos(time)) * osciScale
if clockWise {
etron.position = CGPoint(x: pos.x + xOsci, y: pos.y + yOsci)
}else{
etron.position = CGPoint(x: pos.x + yOsci, y: pos.y + xOsci)
}
}
func random() ->CGFloat{
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min: CGFloat, max: CGFloat) ->CGFloat{
return random() * (max - min) + min
}
} |
//
// ContentView.swift
// GuessTheFlag
//
// Created by Guillermo Frias on 30/05/2021.
//
import SwiftUI
struct ContentView: View {
@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()
@State private var correctAnswer = Int.random(in:0...2)
@State private var selectedAnswer: Int?
@State private var showingScore = false
@State private var scoreTitle = ""
@State private var score = 0
var body: some View {
ZStack {
LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
VStack(spacing: 30) {
VStack {
Text("Tap the flag of")
.foregroundColor(.white)
Text(countries[correctAnswer]).foregroundColor(.white)
.font(.largeTitle)
.fontWeight(.black)
Text("Score: \(score)")
.foregroundColor(.white)
}
Spacer()
VStack(spacing:20){
ForEach(0 ..< 3) { number in
Button(action: {
if selectedAnswer == nil {
self.flagTapped(number)
}
}) {
FlagImage(country: self.countries[number], selectedAnswer: selectedAnswer,
correctAnswer: correctAnswer,
number: number)
}
}
}
Spacer()
}
}.alert(isPresented: $showingScore) {
Alert(title: Text(scoreTitle), message: Text("Your score is \(score)"), dismissButton: .default(Text("Continue")) {
self.askQuestion()
})
}
}
func flagTapped(_ number: Int) {
withAnimation {
selectedAnswer = number
}
if number == correctAnswer {
scoreTitle = "Correct"
score += 1
showingScore = true
} else {
scoreTitle = "Wrong, that is the flag of \(countries[number])"
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
showingScore = true
}
}
}
func askQuestion() {
countries = countries.shuffled()
correctAnswer = Int.random(in: 0...2)
self.selectedAnswer = nil
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct FlagImage: View {
var country: String
var selectedAnswer: Int?
var correctAnswer: Int
var number: Int
var body: some View {
ZStack {
Image(self.country).renderingMode(.original).clipShape(Capsule())
.overlay(Capsule().stroke(Color.black, lineWidth: 1)).shadow(color:. black, radius: 2).opacity(isForeground ? 1: 0.25)
if isTapped && !isRight {
Image(systemName: "xmark.circle.fill").font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/.weight(.heavy)).accentColor(.red)
}
}.rotationEffect(isTapped && isRight ? .degrees(360) : .zero)
.rotationEffect(isTapped && !isRight ? .degrees(-360) : .zero)
}
var isForeground: Bool {
if let _ = selectedAnswer {
return number == correctAnswer
}
return true
}
var isTapped: Bool {
selectedAnswer == number
}
var isRight: Bool {
selectedAnswer == correctAnswer
}
}
|
//
// CreditCard.swift
// FirebaseSmsOnay
//
// Created by imac1 on 28.01.2019.
// Copyright © 2019 imac2. All rights reserved.
//
import Foundation
class Credit_Card {
var Cards_ID="1"
var Card_CVV="1"
var Card_Exprition_Month="1"
var Card_Exprition_Year="1"
var Card_Name="1"
var Card_Number="1"
var Card_Type="1"
var Credit_Card_Name="1"
var User_ID="1"
}
|
//
// CountryDetailViewController.swift
// CovidApp
//
// Created by Joan Martin Martrus on 22/01/2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol CountryDetailDisplayLogic: class
{
func showData(cellsModels: [CollectionDrawerItemProtocol])
func showError(error: Error)
}
class CountryDetailViewController: BaseViewController, CountryDetailDisplayLogic
{
var interactor: CountryDetailBusinessLogic?
var router: (NSObjectProtocol & CountryDetailRoutingLogic)?
// MARK: IBoutlets
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var datePicker: UIDatePicker!
@IBOutlet var countryNameLabel: UILabel!
// MARK: Properties
var countryName: String?
var cellsModels: [CollectionDrawerItemProtocol] = []
// MARK: Acttions
@IBAction func datePickerEditingDidEnd(_ sender: Any) {
let stringDate = datePicker.date.toString(withFormatter: nil)
self.reloadData(withDate: stringDate)
}
private func reloadData(withDate dateString: String) {
self.showSpinner(onView: self.view)
interactor?.getCountryInfo(countryName: self.countryName ?? "", date: dateString)
}
// MARK: CountryDetailDisplayLogic protocol implementation
func showData(cellsModels: [CollectionDrawerItemProtocol]) {
self.removeSpinner()
self.cellsModels = cellsModels
collectionView.reloadData()
}
func showError(error: Error) {
self.removeSpinner()
self.showErrorAlert(error: error)
}
// MARK: Object lifecycle
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
}
// MARK: Setup
private func setup()
{
let viewController = self
let interactor = CountryDetailInteractor()
let presenter = CountryDetailPresenter()
let router = CountryDetailRouter()
viewController.interactor = interactor
viewController.router = router
interactor.presenter = presenter
presenter.viewController = viewController
router.viewController = viewController
}
// MARK: View lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
self.countryNameLabel.text = self.countryName
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
beginLoadInfo()
}
private func beginLoadInfo() {
self.showSpinner(onView: self.view)
if let countryName = self.countryName {
interactor?.getCountryInfo(countryName: countryName, date: datePicker.date.toString(withFormatter: nil))
}
}
}
extension CountryDetailViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
cellsModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellModel = cellsModels[indexPath.row]
let drawer = cellModel.collectionDrawer
let cell = drawer.dequeueCollectionCell(collectionView, indexPath: indexPath)
drawer.drawCollectionCell(cell, withItem: cellModel)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewWidth = collectionView.frame.size.width
let collectionViewHeight = collectionView.frame.size.height
return CGSize(width: collectionViewWidth/2.0, height: collectionViewHeight/2.0)
}
}
|
//
// shape.swift
// work1
//
// Created by ljy on 2021/10/19.
//
//import Foundation
import SwiftUI
struct left_hand_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 121, y: 442))
path.addCurve(to: CGPoint(x: 74, y: 254), control1: CGPoint(x: 40, y: 406), control2: CGPoint(x: 6, y: 310))
path.addQuadCurve(to: CGPoint(x: 103, y: 317), control: CGPoint(x: 139, y: 263))
path.addQuadCurve(to: CGPoint(x: 81, y: 333), control: CGPoint(x: 118, y: 330))
path.addQuadCurve(to: CGPoint(x: 106, y: 361), control: CGPoint(x: 86, y: 358))
}
}
}
struct right_hand_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 325, y: 394))
path.addQuadCurve(to: CGPoint(x: 395, y: 287), control: CGPoint(x: 402, y: 352))
path.addQuadCurve(to: CGPoint(x: 366, y: 217), control: CGPoint(x: 411, y: 237))
path.addQuadCurve(to: CGPoint(x: 318, y: 274), control: CGPoint(x: 316, y: 228))
path.addQuadCurve(to: CGPoint(x: 344, y: 299), control: CGPoint(x: 307, y: 296))
path.addQuadCurve(to: CGPoint(x: 325, y: 328), control: CGPoint(x: 350, y: 322))
}
}
}
struct body_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 160, y: 266))
path.addQuadCurve(to: CGPoint(x: 138, y: 237), control: CGPoint(x: 140, y: 259))
path.addQuadCurve(to: CGPoint(x: 135, y: 284), control: CGPoint(x: 111, y: 274))
path.addQuadCurve(to: CGPoint(x: 110, y: 335), control: CGPoint(x: 115, y: 306))
path.addQuadCurve(to: CGPoint(x: 107, y: 397), control: CGPoint(x: 100, y: 368))
path.addQuadCurve(to: CGPoint(x: 125, y: 450), control: CGPoint(x: 110, y: 428))
path.addLine(to: CGPoint(x: 323, y: 399))
path.addQuadCurve(to: CGPoint(x: 322, y: 314), control: CGPoint(x: 337, y: 355))
path.addQuadCurve(to: CGPoint(x: 251, y: 248), control: CGPoint(x: 310, y: 264))
path.addQuadCurve(to: CGPoint(x: 160, y: 266), control: CGPoint(x: 216, y: 234))
path.move(to: CGPoint(x: 251, y: 248))
path.addQuadCurve(to: CGPoint(x: 278, y: 201), control: CGPoint(x: 276, y: 235))
path.addQuadCurve(to: CGPoint(x: 285, y: 261), control: CGPoint(x: 300, y: 225))
}
}
}
struct mouth_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 137, y: 345))
path.addQuadCurve(to: CGPoint(x: 130, y: 413), control: CGPoint(x: 120, y: 380))
path.addQuadCurve(to: CGPoint(x: 261, y: 395), control: CGPoint(x: 210, y: 412))
path.addQuadCurve(to: CGPoint(x: 280, y: 378), control: CGPoint(x: 275, y: 391))
path.addQuadCurve(to: CGPoint(x: 288, y: 337), control: CGPoint(x: 287, y: 360))
path.addQuadCurve(to: CGPoint(x: 137, y: 345), control: CGPoint(x: 215, y: 328))
}
}
}
struct teeth_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 146, y: 344))
path.addQuadCurve(to: CGPoint(x: 146, y: 377), control: CGPoint(x: 141, y: 370))
path.addLine(to: CGPoint(x: 157, y: 371))
path.addLine(to: CGPoint(x: 165, y: 340))
path.move(to: CGPoint(x: 174, y: 339))
path.addLine(to: CGPoint(x: 176, y: 354))
path.addLine(to: CGPoint(x: 186, y: 352))
path.addLine(to: CGPoint(x: 188, y: 337))
path.move(to: CGPoint(x: 194, y: 336))
path.addLine(to: CGPoint(x: 194, y: 347))
path.addLine(to: CGPoint(x: 198, y: 353))
path.addLine(to: CGPoint(x: 205, y: 336))
path.move(to: CGPoint(x: 212, y: 336))
path.addLine(to: CGPoint(x: 208, y: 352))
path.addLine(to: CGPoint(x: 221, y: 346))
path.addLine(to: CGPoint(x: 224, y: 335))
path.move(to: CGPoint(x: 230, y: 335))
path.addLine(to: CGPoint(x: 228, y: 349))
path.addLine(to: CGPoint(x: 238, y: 349))
path.addLine(to: CGPoint(x: 242, y: 335))
path.move(to: CGPoint(x: 252, y: 335))
path.addQuadCurve(to: CGPoint(x: 250, y: 368), control: CGPoint(x: 255, y: 355))
path.addLine(to: CGPoint(x: 259, y: 368))
path.addQuadCurve(to: CGPoint(x: 270, y: 336), control: CGPoint(x: 270, y: 357))
path.move(to: CGPoint(x: 148, y: 412))
path.addQuadCurve(to: CGPoint(x: 159, y: 390), control: CGPoint(x: 149, y: 399))
path.addLine(to: CGPoint(x: 162, y: 411))
path.move(to: CGPoint(x: 169, y: 411))
path.addLine(to: CGPoint(x: 168, y: 395))
path.addLine(to: CGPoint(x: 176, y: 389))
path.addLine(to: CGPoint(x: 182, y: 410))
path.move(to: CGPoint(x: 187, y: 409))
path.addLine(to: CGPoint(x: 186, y: 390))
path.addLine(to: CGPoint(x: 198, y: 387))
path.addLine(to: CGPoint(x: 199, y: 408))
path.move(to: CGPoint(x: 206, y: 407))
path.addLine(to: CGPoint(x: 204, y: 387))
path.addLine(to: CGPoint(x: 215, y: 386))
path.addLine(to: CGPoint(x: 217, y: 405))
path.move(to: CGPoint(x: 222, y: 404))
path.addLine(to: CGPoint(x: 221, y: 387))
path.addLine(to: CGPoint(x: 230, y: 383))
path.addLine(to: CGPoint(x: 233, y: 402))
path.move(to: CGPoint(x: 238, y: 401))
path.addLine(to: CGPoint(x: 243, y: 385))
path.addLine(to: CGPoint(x: 251, y: 381))
path.addQuadCurve(to: CGPoint(x: 256, y: 396), control: CGPoint(x: 257, y: 394))
}
}
}
struct eyes_out_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 182, y: 315))
path.addLine(to: CGPoint(x: 153, y: 269))
path.addQuadCurve(to: CGPoint(x: 182, y: 315), control: CGPoint(x: 119, y: 321))
path.move(to: CGPoint(x: 205, y: 308))
path.addLine(to: CGPoint(x: 244, y: 265))
path.addQuadCurve(to: CGPoint(x: 205, y: 308), control: CGPoint(x: 278, y: 333))
}
}
}
struct eyes_in_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 171, y: 300))
path.addQuadCurve(to: CGPoint(x: 161, y: 284), control: CGPoint(x: 141, y: 306))
path.move(to: CGPoint(x: 219, y: 295))
path.addQuadCurve(to: CGPoint(x: 235, y: 277), control: CGPoint(x: 251, y: 308))
}
}
}
struct bracelet1_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 26, y: 350))
path.addLine(to: CGPoint(x: 84, y: 332))
path.addLine(to: CGPoint(x: 97, y: 347))
path.addQuadCurve(to: CGPoint(x: 41, y: 380), control: CGPoint(x: 78, y: 378))
path.addLine(to: CGPoint(x: 26, y: 350))
path.move(to: CGPoint(x: 30, y: 359))
path.addLine(to: CGPoint(x: 24, y: 371))
path.addLine(to: CGPoint(x: 38, y: 373))
}
}
}
struct bracelet2_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 403, y: 290))
path.addQuadCurve(to: CGPoint(x: 347, y: 288), control: CGPoint(x: 371, y: 302))
path.addLine(to: CGPoint(x: 338, y: 306))
path.addQuadCurve(to: CGPoint(x: 402, y: 323), control: CGPoint(x: 366, y: 329))
path.addLine(to: CGPoint(x: 403, y: 290))
path.move(to: CGPoint(x: 401, y: 313))
path.addLine(to: CGPoint(x: 415, y: 307))
path.addLine(to: CGPoint(x: 402, y: 298))
}
}
}
struct words_outline:Shape{
private let OFFSET=190;
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 53, y: 455))
path.addLine(to: CGPoint(x: 48, y: 464))
path.addLine(to: CGPoint(x: 39, y: 462))
path.addLine(to: CGPoint(x: 33, y: 479))
path.addLine(to: CGPoint(x: 44, y: 484))
path.addLine(to: CGPoint(x: 5, y: 553))
path.addQuadCurve(to: CGPoint(x: 42, y: 545), control: CGPoint(x: 23, y: 556))
path.addLine(to: CGPoint(x: 58, y: 509))
path.addLine(to: CGPoint(x: 72, y: 506))
path.addLine(to: CGPoint(x: 86, y: 528))
path.addQuadCurve(to: CGPoint(x: 116, y: 530), control: CGPoint(x: 102, y: 538))
path.addLine(to: CGPoint(x: 141, y: 515))
path.addLine(to: CGPoint(x: 108, y: 514))
path.addLine(to: CGPoint(x: 93, y: 494))
path.addLine(to: CGPoint(x: 103, y: 490))
path.addLine(to: CGPoint(x: 101, y: 478))
path.addLine(to: CGPoint(x: 88, y: 481))
path.addLine(to: CGPoint(x: 77, y: 450))
path.addLine(to: CGPoint(x: 53, y: 455))
path.move(to: CGPoint(x: 67, y: 471))
path.addLine(to: CGPoint(x: 59, y: 489))
path.addLine(to: CGPoint(x: 74, y: 487))
path.addLine(to: CGPoint(x: 67, y: 471))
path.move(to: CGPoint(x: 136, y: 456))
path.addQuadCurve(to: CGPoint(x: 103, y: 476), control: CGPoint(x: 101, y: 456))
path.addQuadCurve(to: CGPoint(x: 119, y: 490), control: CGPoint(x: 106, y: 487))
path.addQuadCurve(to: CGPoint(x: 102, y: 497), control: CGPoint(x: 118, y: 498))
path.addLine(to: CGPoint(x: 102, y: 507))
path.addQuadCurve(to: CGPoint(x: 135, y: 492), control: CGPoint(x: 134, y: 504))
path.addQuadCurve(to: CGPoint(x: 121, y: 473), control: CGPoint(x: 142, y: 477))
path.addQuadCurve(to: CGPoint(x: 137, y: 467), control: CGPoint(x: 128, y: 464))
path.addLine(to: CGPoint(x: 136, y: 456))
path.move(to: CGPoint(x: 175, y: 446))
path.addQuadCurve(to: CGPoint(x: 142, y: 467), control: CGPoint(x: 143, y: 445))
path.addQuadCurve(to: CGPoint(x: 157, y: 480), control: CGPoint(x: 144, y: 477))
path.addQuadCurve(to: CGPoint(x: 139, y: 485), control: CGPoint(x: 155, y: 489))
path.addLine(to: CGPoint(x: 140, y: 498))
path.addQuadCurve(to: CGPoint(x: 174, y: 478), control: CGPoint(x: 174, y: 494))
path.addQuadCurve(to: CGPoint(x: 158, y: 463), control: CGPoint(x: 177, y: 469))
path.addQuadCurve(to: CGPoint(x: 175, y: 458), control: CGPoint(x: 166, y: 452))
path.addLine(to: CGPoint(x: 175, y: 446))
path.move(to: CGPoint(x: 184, y: 445))
path.addLine(to: CGPoint(x: 183, y: 460))
path.addQuadCurve(to: CGPoint(x: 206, y: 449), control: CGPoint(x: 208, y: 444))
path.addLine(to: CGPoint(x: 204, y: 456))
path.addQuadCurve(to: CGPoint(x: 177, y: 478), control: CGPoint(x: 186, y: 462))
path.addQuadCurve(to: CGPoint(x: 198, y: 488), control: CGPoint(x: 179, y: 493))
path.addLine(to: CGPoint(x: 199, y: 478))
path.addLine(to: CGPoint(x: 191, y: 478))
path.addQuadCurve(to: CGPoint(x: 205, y: 466), control: CGPoint(x: 193, y: 465))
path.addLine(to: CGPoint(x: 205, y: 487))
path.addLine(to: CGPoint(x: 222, y: 481))
path.addLine(to: CGPoint(x: 223, y: 442))
path.addQuadCurve(to: CGPoint(x: 184, y: 445), control: CGPoint(x: 221, y: 432))
path.move(to: CGPoint(x: 262, y: 422))
path.addQuadCurve(to: CGPoint(x: 227, y: 442), control: CGPoint(x: 225, y: 422))
path.addQuadCurve(to: CGPoint(x: 243, y: 456), control: CGPoint(x: 230, y: 453))
path.addQuadCurve(to: CGPoint(x: 226, y: 463), control: CGPoint(x: 242, y: 464))
path.addLine(to: CGPoint(x: 226, y: 473))
path.addQuadCurve(to: CGPoint(x: 259, y: 458), control: CGPoint(x: 258, y: 470))
path.addQuadCurve(to: CGPoint(x: 245, y: 440), control: CGPoint(x: 266, y: 443))
path.addQuadCurve(to: CGPoint(x: 260, y: 433), control: CGPoint(x: 252, y: 430))
path.addLine(to: CGPoint(x: 262, y: 422))
path.move(to: CGPoint(x: 300, y: 413))
path.addQuadCurve(to: CGPoint(x: 265, y: 433), control: CGPoint(x: 263, y: 413))
path.addQuadCurve(to: CGPoint(x: 281, y: 447), control: CGPoint(x: 268, y: 444))
path.addQuadCurve(to: CGPoint(x: 264, y: 454), control: CGPoint(x: 280, y: 455))
path.addLine(to: CGPoint(x: 264, y: 464))
path.addQuadCurve(to: CGPoint(x: 297, y: 450), control: CGPoint(x: 296, y: 460))
path.addQuadCurve(to: CGPoint(x: 283, y: 430), control: CGPoint(x: 304, y: 434))
path.addQuadCurve(to: CGPoint(x: 300, y: 424), control: CGPoint(x: 290, y: 421))
path.addLine(to: CGPoint(x: 300, y: 413))
path.move(to: CGPoint(x: 305, y: 391))
path.addLine(to: CGPoint(x: 306, y: 405))
path.addLine(to: CGPoint(x: 323, y: 401))
path.addLine(to: CGPoint(x: 324, y: 386))
path.addLine(to: CGPoint(x: 305, y: 391))
path.move(to: CGPoint(x: 305, y: 410))
path.addLine(to: CGPoint(x: 303, y: 454))
path.addLine(to: CGPoint(x: 320, y: 450))
path.addLine(to: CGPoint(x: 322, y: 406))
path.addLine(to: CGPoint(x: 305, y: 410))
//n
path.move(to: CGPoint(x: 329, y: 404))
path.addLine(to: CGPoint(x: 327, y: 448))
path.addLine(to: CGPoint(x: 344, y: 445))
path.addLine(to: CGPoint(x: 345, y: 422))
path.addQuadCurve(to: CGPoint(x: 361, y: 419), control: CGPoint(x: 360, y: 401))
path.addLine(to: CGPoint(x: 361, y: 477))
path.addLine(to: CGPoint(x: 377, y: 471))
path.addLine(to: CGPoint(x: 379, y: 402))
path.addQuadCurve(to: CGPoint(x: 346, y: 406), control: CGPoint(x: 375, y: 384))
path.addLine(to: CGPoint(x: 346, y: 398))
path.addLine(to: CGPoint(x: 329, y: 404))
path.move(to: CGPoint(x: 417, y: 381))
path.addQuadCurve(to: CGPoint(x: 383, y: 400), control: CGPoint(x: 380, y: 380))
path.addQuadCurve(to: CGPoint(x: 400, y: 415), control: CGPoint(x: 386, y: 412))
path.addQuadCurve(to: CGPoint(x: 382, y: 422), control: CGPoint(x: 398, y: 423))
path.addLine(to: CGPoint(x: 382, y: 432))
path.addQuadCurve(to: CGPoint(x: 415, y: 417), control: CGPoint(x: 414, y: 430))
path.addQuadCurve(to: CGPoint(x: 400, y: 400), control: CGPoint(x: 422, y: 402))
path.addQuadCurve(to: CGPoint(x: 417, y: 392), control: CGPoint(x: 408, y: 389))
path.addLine(to: CGPoint(x: 417, y: 381))
//T
path.move(to: CGPoint(x: 207, y: 492))
path.addLine(to: CGPoint(x: 208, y: 500))
path.addLine(to: CGPoint(x: 235, y: 493))
path.addLine(to: CGPoint(x: 236, y: 514))
path.addLine(to: CGPoint(x: 245, y: 512))
path.addLine(to: CGPoint(x: 245, y: 489))
path.addLine(to: CGPoint(x: 255, y: 485))
path.addLine(to: CGPoint(x: 254, y: 477))
path.addLine(to: CGPoint(x: 207, y: 492))
//a
path.move(to: CGPoint(x: 258, y: 481))
path.addLine(to: CGPoint(x: 258, y: 491))
path.addQuadCurve(to: CGPoint(x: 269, y: 484), control: CGPoint(x: 267, y: 480))
path.addLine(to: CGPoint(x: 269, y: 489))
path.addQuadCurve(to: CGPoint(x: 255, y: 503), control: CGPoint(x: 261, y: 490))
path.addQuadCurve(to: CGPoint(x: 267, y: 507), control: CGPoint(x: 251, y: 510))
path.addLine(to: CGPoint(x: 267, y: 502))
path.addQuadCurve(to: CGPoint(x: 269, y: 493), control: CGPoint(x: 255, y: 502))
path.addLine(to: CGPoint(x: 270, y: 507))
path.addLine(to: CGPoint(x: 276, y: 505))
path.addLine(to: CGPoint(x: 277, y: 483))
path.addQuadCurve(to: CGPoint(x: 258, y: 481), control: CGPoint(x: 278, y: 473))
//i
path.move(to: CGPoint(x: 281, y: 466))
path.addLine(to: CGPoint(x: 281, y: 472))
path.addLine(to: CGPoint(x: 289, y: 470))
path.addLine(to: CGPoint(x: 290, y: 464))
path.addLine(to: CGPoint(x: 281, y: 466))
path.move(to: CGPoint(x: 281, y: 475))
path.addLine(to: CGPoint(x: 280, y: 498))
path.addLine(to: CGPoint(x: 289, y: 495))
path.addLine(to: CGPoint(x: 289, y: 474))
path.addLine(to: CGPoint(x: 281, y: 475))
//p
path.move(to: CGPoint(x: 293, y: 472))
path.addLine(to: CGPoint(x: 291, y: 520))
path.addLine(to: CGPoint(x: 299, y: 519))
path.addLine(to: CGPoint(x: 300, y: 490))
path.addQuadCurve(to: CGPoint(x: 300, y: 469), control: CGPoint(x: 335, y: 472))
path.addLine(to: CGPoint(x: 293, y: 472))
path.move(to: CGPoint(x: 300, y: 476))
path.addLine(to: CGPoint(x: 301, y: 484))
path.addQuadCurve(to: CGPoint(x: 300, y: 476), control: CGPoint(x: 316, y: 474))
//e
path.move(to: CGPoint(x: 342, y: 471))
path.addQuadCurve(to: CGPoint(x: 319, y: 476), control: CGPoint(x: 329, y: 457))
path.addQuadCurve(to: CGPoint(x: 331, y: 484), control: CGPoint(x: 319, y: 488))
path.addLine(to: CGPoint(x: 339, y: 482))
path.addLine(to: CGPoint(x: 340, y: 475))
path.addQuadCurve(to: CGPoint(x: 342, y: 471), control: CGPoint(x: 309, y: 479))
path.move(to: CGPoint(x: 328, y: 470))
path.addQuadCurve(to: CGPoint(x: 334, y: 468), control: CGPoint(x: 331, y: 462))
path.addLine(to: CGPoint(x: 328, y: 470))
path.move(to: CGPoint(x: 344, y: 450))
path.addLine(to: CGPoint(x: 341, y: 456))
path.addLine(to: CGPoint(x: 349, y: 454))
path.addLine(to: CGPoint(x: 350, y: 448))
path.addLine(to: CGPoint(x: 344, y: 450))
path.move(to: CGPoint(x: 341, y: 460))
path.addLine(to: CGPoint(x: 340, y: 482))
path.addLine(to: CGPoint(x: 349, y: 480))
path.addLine(to: CGPoint(x: 349, y: 458))
path.addLine(to: CGPoint(x: 340, y: 460))
}
}
}
|
//
// WebViewController.swift
// Web(json)App(Lesson10)
//
// Created by iD on 28.04.2020.
// Copyright © 2020 DmitrySedov. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
@IBOutlet var backButton: UIButton!
@IBOutlet var forwardButton: UIButton!
@IBOutlet var urlTextField: UITextField!
var urlArtist: String!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
let url = URL(string: urlArtist)
let request = URLRequest(url: url!)
webView.load(request)
webView.allowsBackForwardNavigationGestures = true
}
@IBAction func backButtonPressed(_ sender: Any) {
if webView.canGoBack {
webView.goBack()
}
}
@IBAction func forwardButtonPressed(_ sender: Any) {
if webView.canGoForward {
webView.goForward()
}
}
}
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
urlTextField.text = webView.url?.absoluteString
backButton.isEnabled = webView.canGoBack
forwardButton.isEnabled = webView.canGoForward
}
}
|
import Foundation
import UIKit
import CoreText
import Dispatch
open class BaseIcon {
open static let instance = BaseIcon()
fileprivate var customFontLoaded = false
fileprivate let load_queue = DispatchQueue(label: "com.insomenia.font.load.queue", attributes: [])
fileprivate var fontsMap :[String: IconFont] = [:]
fileprivate init() {
}
open func addCustomFont(_ prefix: String, fontFileName: String, fontName: String, fontIconMap: [String: String]) {
fontsMap[prefix] = CustomIconFont(fontFileName: fontFileName, fontName: fontName, fontMap: fontIconMap)
}
open func loadAllAsync() {
self.load_queue.async(execute: {
self.loadAllSync()
})
}
open func loadAllSync() {
for font in fontsMap.values {
font.loadFontIfNecessary()
}
}
open func getNSMutableAttributedString(_ iconName: String, fontSize: CGFloat) -> NSMutableAttributedString? {
for fontPrefix in fontsMap.keys {
if iconName.hasPrefix(fontPrefix) {
let iconFont = fontsMap[fontPrefix]!
if let iconValue = iconFont.getIconValue(iconName) {
let iconUnicodeValue = iconValue.substring(to: iconValue.index(iconValue.startIndex, offsetBy: 1))
if let uiFont = iconFont.getUIFont(fontSize) {
let attrs = [NSAttributedStringKey.font : uiFont, NSAttributedStringKey.foregroundColor : UIColor.white]
return NSMutableAttributedString(string:iconUnicodeValue, attributes:attrs)
}
}
}
}
return nil
}
open func getUIImage(_ iconName: String, iconSize: CGFloat, iconColour: UIColor = UIColor.black, imageSize: CGSize) -> UIImage {
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.left
style.baseWritingDirection = NSWritingDirection.leftToRight
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0);
let attString = getNSMutableAttributedString(iconName, fontSize: iconSize)
if attString != nil {
attString?.addAttributes([NSAttributedStringKey.foregroundColor: iconColour, NSAttributedStringKey.paragraphStyle: style], range: NSMakeRange(0, attString!.length))
// get the target bounding rect in order to center the icon within the UIImage:
let ctx = NSStringDrawingContext()
let boundingRect = attString!.boundingRect(with: CGSize(width: iconSize, height: iconSize), options: NSStringDrawingOptions.usesDeviceMetrics, context: ctx)
attString!.draw(in: CGRect(x: (imageSize.width/2.0) - boundingRect.size.width/2.0, y: (imageSize.height/2.0) - boundingRect.size.height/2.0, width: imageSize.width, height: imageSize.height))
var iconImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// if(iconImage!.responds(to: #selector(UIImage.withRenderingMode(_:)(_:)))){
// iconImage = iconImage!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
// }
return iconImage!
} else {
return UIImage()
}
}
}
private class CustomIconFont: IconFont {
fileprivate let fontFileName: String
fileprivate let fontName: String
fileprivate let fontMap: [String: String]
fileprivate var fontLoadedAttempted = false
fileprivate var fontLoadedSucceed = false
init(fontFileName: String, fontName: String, fontMap: [String: String]) {
self.fontFileName = fontFileName
self.fontName = fontName
self.fontMap = fontMap
}
func loadFontIfNecessary() {
if (!self.fontLoadedAttempted) {
self.fontLoadedAttempted = true
self.fontLoadedSucceed = loadFontFromFile(self.fontFileName, forClass: BaseIcon.self, isCustom: true)
}
}
func getUIFont(_ fontSize: CGFloat) -> UIFont? {
self.loadFontIfNecessary()
if (self.fontLoadedSucceed) {
return UIFont(name: self.fontName, size: fontSize)
} else {
return nil
}
}
func getIconValue(_ iconName: String) -> String? {
return self.fontMap[iconName]
}
}
private func loadFontFromFile(_ fontFileName: String, forClass: AnyClass, isCustom: Bool) -> Bool{
let bundle = Bundle(for: forClass)
var fontURL: URL?
_ = bundle.bundleIdentifier
fontURL = bundle.url(forResource: fontFileName, withExtension: "ttf")
if fontURL != nil {
let data = try! Data(contentsOf: fontURL!)
let provider = CGDataProvider(data: data as CFData)
let font = CGFont(provider!)
if (!CTFontManagerRegisterGraphicsFont(font!, nil)) {
NSLog("Failed to load font \(fontFileName)");
return false
} else {
return true
}
} else {
NSLog("Failed to load font \(fontFileName) because the file \(fontFileName) is not available");
return false
}
}
private protocol IconFont {
func loadFontIfNecessary()
func getUIFont(_ fontSize: CGFloat) -> UIFont?
func getIconValue(_ iconName: String) -> String?
}
|
//
// ConversionView.swift
// BHD-INR
//
// Copyright © 2018 e-Legion. All rights reserved.
//
import UIKit
protocol ConversionViewDelegate: class {
func conversionView(_ conversionView: ConversionView,
didPressCalculateButtonWith state: ConversionViewState)
}
struct ConversionViewState {
var amountString: String?
var resultString: String?
}
class ConversionView: UIView {
@IBOutlet private weak var conversionResultLabel: UILabel!
@IBOutlet private weak var amountTextField: UITextField!
@IBOutlet private weak var calculateButton: UIButton!
weak var delegate: ConversionViewDelegate?
var conversionViewState: ConversionViewState {
get {
return ConversionViewState(amountString: amountTextField.text,
resultString: conversionResultLabel.text)
}
set {
amountTextField.text = newValue.amountString
conversionResultLabel.text = newValue.resultString
}
}
// MARK: - Actions
@IBAction private func calculateButtonPressed(_ sender: UIButton) {
delegate?.conversionView(self,
didPressCalculateButtonWith: conversionViewState)
}
// MARK: - UIView
override func layoutSubviews() {
super.layoutSubviews()
let size = CGSize(width: bounds.width - Const.elementsOffset * 2,
height: bounds.height - Const.elementsOffset * 2)
let heightOfConversionResultLabel = size.height - Const.elementsOffset - calculateButton.frame.height
conversionResultLabel.frame = CGRect(x: Const.elementsOffset,
y: Const.elementsOffset,
width: size.width,
height: heightOfConversionResultLabel)
let calculateButtonX = bounds.size.width - Const.elementsOffset - calculateButton.frame.size.width
calculateButton.frame.origin = CGPoint(x: calculateButtonX,
y: conversionResultLabel.frame.maxY + Const.elementsOffset)
let amountTextFieldY = calculateButton.frame.midY - amountTextField.frame.size.height / 2
amountTextField.frame.origin = CGPoint(x: Const.elementsOffset,
y: amountTextFieldY)
amountTextField.frame.size.width = size.width - calculateButton.frame.size.width - Const.elementsOffset
}
}
extension ConversionView {
private enum Const {
static let elementsOffset: CGFloat = 16.0
}
}
|
//
// LabelStyle.swift
// time-me
//
// Created by Amir Shayegh on 2018-01-16.
// Copyright © 2018 Amir Shayegh. All rights reserved.
//
import Foundation
import UIKit
class LabelStyle {
var height: CGFloat
var roundCorners: Bool
var bgColor: UIColor
var labelTextColor: UIColor
init(height: CGFloat, roundCorners: Bool, bgColor: UIColor, labelTextColor: UIColor) {
self.height = height
self.roundCorners = roundCorners
self.bgColor = bgColor
self.labelTextColor = labelTextColor
}
}
|
import Foundation
// #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
// MARK: - UserDefaults
// #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
extension UserDefaults {
static var language: Language {
get {
if let lang = UserDefaults.standard.string(forKey: UserDefaultKey.kCurrentLanguage),
let language = Language(rawValue: lang) {
return language
} else {
//Set Default Language and return
UserDefaults.standard.set(Language.enLang.rawValue, forKey: UserDefaultKey.kCurrentLanguage)
return .enLang
}
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: UserDefaultKey.kCurrentLanguage)
}
}
static var languageId: String {
get {
if let langId = UserDefaults.standard.string(forKey: UserDefaultKey.kCurrentLanguageId) {
return langId
} else {
//Set Default Language and return
UserDefaults.standard.set("1", forKey: UserDefaultKey.kCurrentLanguageId)
return "1"
}
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaultKey.kCurrentLanguageId)
}
}
}
|
//
// ExampleRocket.swift
// SpaceX
//
// Created by Carmelo Ruymán Quintana Santana on 24/2/21.
//
import Foundation
#if DEBUG
let exampleRocket: Rocket = Rocket(id: UUID().uuidString,
flickr_images: ["https://farm5.staticflickr.com/4599/38583829295_581f34dd84_b.jpg", "https://farm5.staticflickr.com/4645/38583830575_3f0f7215e6_b.jpg", "https://farm5.staticflickr.com/4696/40126460511_b15bf84c85_b.jpg", "https://farm5.staticflickr.com/4711/40126461411_aabc643fd8_b.jpg"].map {URL(string: $0)!},
height: Measurement<UnitLength>(value: 20, unit: .meters),
diameter: Measurement<UnitLength>(value: 30, unit: .meters),
mass: Measurement<UnitMass>(value: 3000, unit: .kilograms),
name: "Example Rocket",
type: "Rocket",
active: true,
stages: 3,
country: "Spain",
company: "Space Telde",
wikipedia: URL(string: "https://en.wikipedia.org/wiki/Falcon_Heavy")!,
description: "With the ability to lift into orbit over 54 metric tons (119,000 lb)--a mass equivalent to a 737 jetliner loaded with passengers, crew, luggage and fuel--Falcon Heavy can lift more than twice the payload of the next closest operational vehicle, the Delta IV Heavy, at one-third the cost.")
#endif
|
//
// SocialApp.swift
// appStoreClone
//
// Created by George Solorio on 7/9/20.
// Copyright © 2020 George Solorio. All rights reserved.
//
import Foundation
struct SocialApp: Decodable {
let id, name, imageUrl, tagline: String
}
|
//
// ServiceProtocol.swift
// swapi_app
//
// Created by Andrew on 27/04/2019.
// Copyright © 2019 SPbSTU. All rights reserved.
//
protocol ServiceProtocol {
func getPage(_ completionHandler: @escaping (([Person], Bool) -> Void))
}
|
//
// HomeViewInteractor.swift
// TinderUser
//
// Created by Rajneesh Kumar on 7/26/20.
// Copyright © 2020 Rajneesh Kumar. All rights reserved.
//
import Foundation
import UIKit
struct HomeViewInteractor {
func showViewController(presenter:UIViewController, classIdenteifer:String) {
if let storyboard = presenter.storyboard {
let vc = storyboard.instantiateViewController(withIdentifier: classIdenteifer)
presenter.present(vc, animated: true, completion: nil)
}
}
}
|
//
// ViewController.swift
// Instagram
//
// Created by Julia Yu on 2/10/16.
// Copyright © 2016 Julia Yu. All rights reserved.
//
import UIKit
class PhotosViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var iTableView: UITableView!
var instagramData = NSMutableArray()
var total = 0
var loading = false
let imageHeight = 320
let headerHeight = 60
let padBottom = 20
let refreshControl = UIRefreshControl()
let tableFooterView: UIView = UIView(frame: CGRectMake(0, 0, 320, 50))
let loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
func stopLoading(){
self.loading = false
loadingView.stopAnimating()
self.iTableView.tableFooterView?.hidden = true
}
func loadMore() {
if (self.loading) {
return
}
loadingView.startAnimating()
self.iTableView.tableFooterView?.hidden = false
self.loading = true
getInstagramData()
}
func getInstagramData() {
let clientId = "e05c462ebd86446ea48a5af73769b602"
let url = NSURL(string:"https://api.instagram.com/v1/media/popular?client_id=\(clientId)")
let request = NSURLRequest(URL: url!)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate:nil,
delegateQueue:NSOperationQueue.mainQueue()
)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
let moreData = responseDictionary["data"] as? NSMutableArray
for data in moreData! {
let newData = data as! NSDictionary
self.instagramData.addObject(newData)
}
self.total = self.instagramData.count
self.iTableView.reloadData()
self.refreshControl.endRefreshing()
self.stopLoading()
}
}
});
task.resume()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("com.codepath.DemoPrototypeCell", forIndexPath: indexPath) as! iTableViewCell
let max = self.total - 1
let oneData = self.instagramData[indexPath.section]
let urlString = oneData.valueForKeyPath("images.low_resolution.url") as! String
let imageURL = NSURL(string:urlString)
cell.instaImage.setImageWithURL(imageURL!)
if (max == indexPath.section) {
self.loadMore()
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return total
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
headerView.backgroundColor = UIColor(white: 1, alpha: 0.9)
let profileView = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
profileView.clipsToBounds = true
profileView.layer.cornerRadius = 15;
profileView.layer.borderColor = UIColor(white: 0.7, alpha: 0.8).CGColor
profileView.layer.borderWidth = 1;
let usernameLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 280, height: 30))
usernameLabel.frame.origin.x = 50
usernameLabel.frame.origin.y = 8
usernameLabel.font = UIFont(name: "HelveticaNeue-Light", size: 14.0)
usernameLabel.textColor = UIColor.grayColor()
let oneData = self.instagramData[section]
let username = oneData.valueForKeyPath("user.username") as! String
let profilepic = oneData.valueForKeyPath("user.profile_picture") as! String
let profileImageURL = NSURL(string:profilepic)
profileView.setImageWithURL(profileImageURL!)
usernameLabel.text = username
headerView.addSubview(profileView)
headerView.addSubview(usernameLabel)
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func refreshControlAction(refreshControl: UIRefreshControl) {
self.getInstagramData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.getInstagramData()
iTableView.dataSource = self
iTableView.delegate = self
self.iTableView.rowHeight = CGFloat(imageHeight + headerHeight + padBottom)
self.refreshControl.addTarget(self, action: "refreshControlAction:", forControlEvents: UIControlEvents.ValueChanged)
iTableView.insertSubview(refreshControl, atIndex: 0)
loadingView.center = tableFooterView.center
tableFooterView.addSubview(loadingView)
self.iTableView.tableFooterView = tableFooterView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "detailSegue") {
let detailView = segue.destinationViewController as! PhotoDetailsViewController
let indexPath = iTableView.indexPathForCell(sender as! UITableViewCell)
let rowNum = indexPath?.section
let oneData = self.instagramData[rowNum!]
detailView.detailData = oneData as? NSDictionary
}
}
}
|
//
// AppDefine.swift
// CoAssets-Agent
//
// Created by Linh NGUYEN on 11/24/15.
// Copyright © 2015 Nikmesoft Ltd. All rights reserved.
//
import Foundation
import UIKit
// MARK: Func
func m_string(key: String) -> String {
return NSLocalizedString(key, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
}
// MARK: Global variables
let kAppDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
let kNotification = NSNotificationCenter.defaultCenter()
let kMainQueue = NSOperationQueue.mainQueue()
let kFileManager = NSFileManager.defaultManager()
let kApplication = UIApplication.sharedApplication()
|
//
// HudView.swift
// TrackLocation
//
// Created by iUS on 11/9/16.
// Copyright © 2016 ayush. All rights reserved.//
//
import Foundation
import UIKit
//Head-up Display
class HudView: UIView{
var text = ""
//convenience constructor
class func hudView(inView view: UIView , animated : Bool) -> HudView {
//add the new HudView object as a subview on top of the “parent” view object. This is the navigation controller’s view so the HUD will cover the entire screen.
let hudView = HudView(frame: view.bounds)
print("View bounds : \(view.bounds)")
print("View frame : \(view.frame)")
hudView.isOpaque = false
view.addSubview(hudView)
//It also sets view’s isUserInteractionEnabled property to false. While the HUD is showing you don’t want the user to interact with the screen anymore. The user has already pressed the Done button and the screen is in the process of closing.
view.isUserInteractionEnabled = false
hudView.show(animated: animated)
return hudView
}
//The draw() method is invoked whenever UIKit wants your view to redraw itself. Recall that everything in iOS is event-driven. The view doesn’t draw anything on the screen unless UIKit sends it the draw() event. That means you should never call draw() yourself.
override func draw(_ rect: CGRect) {
//When working with UIKit or Core Graphics (CG, get it?) you use CGFloat instead of the regular Float or Double.
let boxWidth : CGFloat = 96
let boxHeight : CGFloat = 96
//The HUD rectangle should be centered horizontally and vertically on the screen. The size of the screen is given by bounds.size (this really is the size of HudView itself, which spans the entire screen).
let boxRect = CGRect(x: (bounds.size.width - boxWidth) / 2,
y: (bounds.size.height - boxHeight) / 2,
width: boxWidth,
height: boxHeight)
//UIBezierPath is a very handy object for drawing rectangles with rounded corners. You just tell it how large the rectangle is and how round the corners should be. Then you fill it with an 80% opaque dark gray color.
let roundedRect = UIBezierPath(roundedRect: boxRect, cornerRadius: 10)
UIColor(white: 0.3, alpha: 0.8).setFill()
roundedRect.fill()
/*
Failable initializers
To create the UIImage you used if let to unwrap the resulting object. That’s because UIImage(named) is a so-called "failable initializer".
It is possible that loading the image fails, because there is no image with the specified name or the file doesn’t really contain a valid image.
That’s why UIImage’s init(named) method is really defined as init?(named). The question mark indicates that this method returns an optional. If there was a problem loading the image, it returns nil instead of a brand spanking new UIImage object.
*/
//This loads the checkmark image into a UIImage object. Then it calculates the position for that image based on the center coordinate of the HUD view (center) and the dimensions of the image (image.size).
if let image = UIImage(named: "Checkmark") {
let imagePoint = CGPoint(
x: center.x - round(image.size.width / 2),
y: center.y - round(image.size.height / 2) - boxHeight / 8)
image.draw(at: imagePoint)
}
//When drawing text you first need to know how big the text is, so you can figure out where to position it.
//First, you create the UIFont object that you’ll use for the text. This is a “System” font of size 16. As of iOS 9, the system font is San Francisco (on iOS 8 and before it was Helvetica Neue.
//So in the dictionary from draw(), the NSFontAttributeName key is associated with the UIFont object, and the NSForegroundColorAttributeName key is associated with the UIColor object. In other words, the attribs dictionary describes what the text will look like.
//You use these attributes and the string from the text property to calculate how wide and tall the text will be. The result ends up in the textSize constant, which is of type CGSize. (As you can tell, CGPoint, CGSize, and CGRect are types you use a lot when making your own views.)
//Finally, you calculate where to draw the text (textPoint), and then draw it.
let attribs = [ NSFontAttributeName: UIFont.systemFont(ofSize: 16),
NSForegroundColorAttributeName: UIColor.white ]
let textSize = text.size(attributes: attribs)
let textPoint = CGPoint(
x: center.x - round(textSize.width / 2),
y: center.y - round(textSize.height / 2) + boxHeight / 4)
text.draw(at: textPoint, withAttributes: attribs)
}
func show(animated : Bool){
if animated{
// 1 - Setup the initial state of the view before the animation starts.Here you set alpha to 0, making the view fully transparent. You also set the transform to a scale factor of "1.3" . We’re not going to go into depth on transforms here, but basically this means the view is initially stretched out.
alpha = 0
transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
// 2 - Call UIView.animate(withDuration:...) to setup ananimation.You give this a closure that describes the animation.UIKit will animate the properties that you change inside the closure from their initial state to the final state.
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
// 3 - Inside the closure,setup the new state of the view that it should have after the animation completes. You set alpha to 1, which means the HudView is now fully opaque. You also set the transform to the “identity” transform, restoring the scale back to normal. Because this code is part of a closure, you need to use self to refer to the HudView instance and its properties. That’s the rule for closures.
self.alpha = 1
self.transform = CGAffineTransform.identity
},
completion: nil)
}
}
}
|
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
let container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
container.backgroundColor = UIColor.white
XCPlaygroundPage.currentPage.liveView = container
//let square = UIView(frame: CGRectMake(50,50,100,100))
//square.backgroundColor = UIColor.redColor()
//
//container.addSubview(square)
func animation1() {
let r = CAReplicatorLayer()
r.bounds = CGRect(x: 0.0, y: 0.0, width: 60.0, height: 200.0)
r.position = container.center
r.backgroundColor = UIColor.lightGray.cgColor
container.layer.addSublayer(r)
let bar = CALayer()
bar.bounds = CGRect(x: 0.0, y: 0.0, width: 8.0, height: 50.0)
bar.position = CGPoint(x: 10.0, y: 100.0)
bar.cornerRadius = 2.0
bar.backgroundColor = UIColor.red.cgColor
r.addSublayer(bar)
let move = CABasicAnimation(keyPath: "position.y")
move.toValue = bar.position.y - 35.0
move.duration = 0.5
move.autoreverses = true
move.repeatCount = Float.infinity
//bar.addAnimation(move, forKey: nil)
r.instanceCount = 3
r.instanceDelay = 0.33
r.masksToBounds = true
r.instanceTransform = CATransform3DMakeTranslation(20.0, 0.0, 0.0)
}
animation1()
|
//
// MainVC.swift
// KBTUApp
//
// Created by User on 02.03.2021.
// Copyright © 2021 User. All rights reserved.
//
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
onlineBtn.layer.backgroundColor = UIColor(red: 85, green: 120, blue: 245).cgColor
onlineBtn.layer.cornerRadius = onlineBtn.frame.height/2
onlineBtn.layer.shadowPath = UIBezierPath(roundedRect: onlineBtn.bounds, cornerRadius: 20).cgPath
onlineBtn.titleLabel!.numberOfLines = 0; // Dynamic number of lines
onlineBtn.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping;
onlineBtn.titleLabel!.textAlignment = NSTextAlignment.center
onlineBtn.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
onlineBtn.layer.shadowRadius = 10
onlineBtn.layer.shadowOffset = CGSize(width: 0, height: 0)
onlineBtn.layer.shadowOpacity = 0.5
onlineBtn.layer.shadowColor = UIColor(red: 85, green: 200, blue: 245).cgColor
textView.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 0)
NotificationCenter.default.addObserver(self,
selector: #selector(showNews),
name: NSNotification.Name("ShowNews"),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(showAboutUs),
name: NSNotification.Name("ShowAboutUs"),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(showFaculties),
name: NSNotification.Name("ShowFaculties"),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(showFavorites),
name: NSNotification.Name("ShowFavorites"),
object: nil)
}
@objc func showNews(){
performSegue(withIdentifier: "ShowNews", sender: nil)
}
@objc func showAboutUs(){
performSegue(withIdentifier: "ShowAboutUs", sender: nil)
}
@objc func showFaculties(){
performSegue(withIdentifier: "ShowFaculties", sender: nil)
}
@objc func showFavorites(){
performSegue(withIdentifier: "ShowFavorites", sender: nil)
}
@IBAction func menuTap(_ sender: UIBarButtonItem) {
NotificationCenter.default.post(name: NSNotification.Name("ToggleSideMenu"), object: nil)
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
}
|
//
// CollectionViewCellCathegories.swift
// Monithor
//
// Created by Cristina Salerno on 17/05/17.
// Copyright © 2017 Pipsqueaks. All rights reserved.
//
import UIKit
class CollectionViewCellCathegories: UICollectionViewCell {
@IBOutlet weak var labelNameCathegory: UILabel!
@IBOutlet weak var imageCathegory: UIImageView!
}
|
import Foundation
import PlaygroundSupport
func fetchBooks(for url: URL, completion: @escaping (Result<[Book], Error>) -> Void) {
// Consists of a series of imperatives, or steps, to be completed
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
let result = Result<[Book], Error> {
guard error == nil else {
throw error ?? TestError.test
}
guard let data = data else {
throw NetworkError.missingData
}
guard let httpResponse = response as? HTTPURLResponse,
(200..<300).contains(httpResponse.statusCode) else {
throw NetworkError.invalidResponse
}
return try JSONDecoder()
.decode([Book].self, from: data)
}
completion(result)
}
task.resume()
}
PlaygroundPage.current.needsIndefiniteExecution = true
fetchBooks(for: url) { (result) in
switch result {
case let .success(books):
print("number of books: \(books.count)")
case let .failure(error):
print("an error occurred: \(error)")
}
PlaygroundPage.current.finishExecution()
}
//: [Next](@next)
|
//
// AppUserDefaults.swift
// PodcastsKo
//
// Created by John Roque Jorillo on 8/5/20.
// Copyright © 2020 JohnRoque Inc. All rights reserved.
//
import Foundation
/*
Service class for userdefaults usage.
*/
class AppUserDefaults {
static let shared = {
return AppUserDefaults()
}()
let defaults = UserDefaults.init(suiteName: "group.com.johnroque.PodcastsKo")!
private init() {
}
// MARK: - Functions
/// Stores object.
func store<T: Encodable>(_ object: T, key: AppUserDefaultsKeys) {
let encoder = JSONEncoder()
let encoded = try? encoder.encode(object)
if encoded == nil {
defaults.set(object, forKey: key.stringValue)
return
}
defaults.set(encoded, forKey: key.stringValue)
}
/// Remove
func removeDefaultsWithKey(_ key: AppUserDefaultsKeys) {
defaults.removeObject(forKey: key.stringValue)
}
// Returns stored object (optional) if any.
func getObjectWithKey<T: Decodable>(_ key: AppUserDefaultsKeys, type: T.Type) -> T? {
if let savedData = defaults.data(forKey: key.stringValue) {
let object = try? JSONDecoder().decode(type, from: savedData)
return object
}
return defaults.object(forKey: key.stringValue) as? T
}
}
enum AppUserDefaultsKeys: CodingKey {
case favoritedPodcastKey
case downloadEpisodeKey
}
|
import UIKit
class GuestViewController: UIViewController {
private let delegate: IGuestViewDelegate
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var subtitleLabel: UILabel?
@IBOutlet weak var createButton: UIButton?
@IBOutlet weak var restoreButton: UIButton?
init(delegate: IGuestViewDelegate) {
self.delegate = delegate
super.init(nibName: String(describing: GuestViewController.self), bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
titleLabel?.text = "guest.title".localized
subtitleLabel?.text = "guest.subtitle".localized
createButton?.setTitle("guest.create_wallet".localized, for: .normal)
restoreButton?.setTitle("guest.restore_wallet".localized, for: .normal)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return AppTheme.statusBarStyle
}
@IBAction func createNewWalletDidTap() {
delegate.createWalletDidClick()
}
@IBAction func restoreWalletDidTap() {
delegate.restoreWalletDidClick()
}
}
|
//
// ViewController.swift
// GuigueSwiftEvaluation
//
// Created by stagiaire on 05/05/2017.
// Copyright © 2017 stagiaire. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request("https://swapi/api/people/1/").responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Alarm.swift
// ClockClone
//
// Created by Logan Melton on 21/8/21.
//
import Foundation
struct Alarm {
var label: String
var time: String
var date: Date
var doesRepeat: Bool
var snooze: Bool
}
|
//
// Sudoku.swift
// SudokuSolver
//
// Created by James Attree on 07/06/2015.
// Copyright (c) 2015 Hawkapps. All rights reserved.
//
import Foundation
class Coord
{
internal var x : Int;
internal var y : Int;
init(CoordX x: Int, CoordY y: Int)
{
self.x = x;
self.y = y;
}
}
class Sudoku
{
private var grid : Array<Array<Int>>;
private var backtracks : Int;
init()
{
self.grid = Array<Array<Int>>();
self.backtracks = 0;
for x in 0...8 {
grid.append(Array(count: 9, repeatedValue: Int()));
}
self.print_grid();
self.solve(Coord: find_next_zero());
println("");
self.print_grid();
}
internal func print_grid() -> Void
{
var n: Int = 0;
for x in 0...8
{
for y in 0...8
{
print("[" + String(self.grid[x][y]) + "]");
n++;
}
print("\n");
}
}
internal func solve(Coord c : Coord) -> Bool
{
if (no_zeros()) { return true; }
for num in 1...9
{
if (no_conflicts(inputCoord: c, numberToCheck: num))
{
self.grid[c.x][c.y] = num;
if (solve(Coord: find_next_zero())) { return true; }
self.grid[c.x][c.y] = 0;
self.backtracks++;
}
}
return false;
}
internal func no_conflicts(inputCoord c : Coord, numberToCheck num: Int) -> Bool
{
for x in 0...8
{
if (self.grid[x][c.y] == num) { return false; }
if (self.grid[c.x][x] == num) { return false; }
}
if (!no_box_conflict(inputCoord: c, numberToCheck: num)) { return false; }
return true;
}
internal func no_box_conflict(inputCoord c : Coord, numberToCheck num : Int) -> Bool
{
var startRow : Int = 0;
var startCol : Int = 0;
if (c.x >= 3 && c.x < 6) { startRow = 3; }
if (c.x >= 6) { startRow = 6; }
if (c.y >= 3 && c.y < 6) { startCol = 3; }
if (c.y >= 6) { startCol = 6; }
for x in startRow...startRow+2
{
for y in startCol...startCol+2
{
if (self.grid[x][y] == num)
{
return false;
}
}
}
return true;
}
internal func no_zeros() -> Bool
{
for x in 0...8
{
for y in 0...8
{
if (self.grid[x][y] == 0)
{
return false;
}
}
}
return true;
}
internal func find_next_zero() -> Coord
{
for x in 0...8
{
for y in 0...8
{
if (self.grid[x][y] == 0)
{
return Coord(CoordX: x, CoordY: y);
}
}
}
return Coord(CoordX: 0, CoordY: 0);
}
}
|
@testable import GoTrue
import XCTest
final class GoTrueTests: XCTestCase {
let gotrue = GoTrueClient(url: gotrueURL(), headers: ["apikey": apikey()], autoRefreshToken: true)
static func apikey() -> String {
if let token = ProcessInfo.processInfo.environment["apikey"] {
return token
} else {
fatalError()
}
}
static func gotrueURL() -> String {
if let url = ProcessInfo.processInfo.environment["GoTrueURL"] {
return url
} else {
fatalError()
}
}
func testSignIN() {
let e = expectation(description: "testSignIN")
gotrue.signIn(email: "sample@mail.com", password: "secret") { result in
switch result {
case let .success(session):
print(session)
XCTAssertNotNil(session.accessToken)
case let .failure(error):
print(error.localizedDescription)
XCTFail("testSignIN failed: \(error.localizedDescription)")
}
e.fulfill()
}
waitForExpectations(timeout: 30) { error in
if let error = error {
XCTFail("testSignIN failed: \(error.localizedDescription)")
}
}
}
static var allTests = [
("testSignIN", testSignIN),
]
}
|
//
// DashBoardElement_Actual500.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 01. 10..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import UIKit
class DashBoardElement_Actual500: DashBoardelementTime {
static let tagInt = 2
override func getStringFormatter() -> String {
return TimeEnum.timeFormatTwo.rawValue
}
override func getValue() -> Double {
return UnitHelper.getPaceValue(pace: Pace.pace500, metricValue: telemetry.t_500)
}
override func getTitleMetric() -> String {
return getString("dashboard_outdoor_title_actual_500_metric")
}
override func getTitleImperial() -> String {
return getString("dashboard_outdoor_title_actual_500_imperial")
}
override func getTitleOneLineMetric() -> String {
return getString("dashboard_title_actual_500_metric")
}
override func getTitleOneLineImperial() -> String {
return getString("dashboard_title_actual_500_imperial")
}
override func getTagInt() -> Int {
return DashBoardElement_Actual500.tagInt
}
override func isMetric() -> Bool {
return UnitHelper.isMetricPace()
}
}
|
//
// InputPresenter.swift
// APSoft
//
// Created by Yesid Melo on 4/4/19.
// Copyright © 2019 Exsis. All rights reserved.
//
import Foundation
protocol IInputPresenter {
}
|
//
// InitialViewController.swift
// FinalKnife
//
// Created by Trivedi on 12/2/18.
// Copyright © 2018 Trivedi. All rights reserved.
//
import UIKit
import Firebase
class InitialViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Checking if user exist or not
if Auth.auth().currentUser != nil{
performSegue(withIdentifier: "toMainScreenFromHome", sender: self)
}
hideKeyboardWhenTappedAround()
}
@IBAction func signIn(_ sender: Any) {
if let password = passwordTextField.text , let email = emailTextField.text{
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
if error != nil{
self.showError(errorMessege: (error?.localizedDescription)!)
}else{
self.performSegue(withIdentifier: "toMainScreenFromHome", sender: sender)
}
guard (user?.user) != nil else { return }
}
}else{
showError(errorMessege: "Please add email & password")
}
}
func showError(errorMessege:String) {
let alert = UIAlertController(title: "Error", message: errorMessege, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
self.present(alert, animated: true, completion: nil)
}
@IBAction func backToInitial(unwindSegue:UIStoryboardSegue){
}
}
//Hide keyboard when touch outside textview
extension InitialViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(InitialViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
|
//
// AnimalNoises.swift
// MASSDK_Swift
//
// Created by Big Shark on 15/03/2017.
// Copyright © 2017 MasterApp. All rights reserved.
//
import Foundation
class AnimalNoises{
static func getAnimalNoises() -> [AnimalNoiseModel]{
var result : [AnimalNoiseModel] = []
var animalModel = AnimalNoiseModel()
animalModel.animal_name = "cat"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "goat"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "cock"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "dog"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "hen"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "sheep"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "cow"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "horse"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
animalModel = AnimalNoiseModel()
animalModel.animal_name = "pig"
animalModel.animal_status = Constants.ANIMAL_SLEEP
result.append(animalModel)
return result
}
}
|
//
// EventManagerTests.swift
// CallstatsTests
//
// Created by Amornchai Kanokpullwad on 10/9/18.
// Copyright © 2018 callstats. All rights reserved.
//
import XCTest
@testable import Callstats
class EventManagerTests: XCTestCase {
private var interceptor1: MockInterceptor!
private var interceptor2: MockInterceptor!
var sender: EventSender!
var manager: EventManager!
override func setUp() {
interceptor1 = MockInterceptor()
interceptor2 = MockInterceptor()
sender = MockEventSender()
manager = EventManagerImpl(
sender: sender,
localID: "local1",
remoteID: "remote1",
connection: DummyConnection(),
config: CallstatsConfig(),
interceptors: [interceptor1, interceptor2])
}
func testForwardEventToAllInterceptor() {
manager.process(event: CSIceConnectionChangeEvent(state: .disconnected))
XCTAssertTrue(interceptor1.lastProcess?.event is CSIceConnectionChangeEvent)
XCTAssertTrue(interceptor2.lastProcess?.event is CSIceConnectionChangeEvent)
}
}
private class MockEventSender: EventSender {
var lastSendEvent: Event?
func send(event: Event) {
lastSendEvent = event
}
}
private class MockInterceptor: Interceptor {
var lastProcess: (connection: Connection, event: PeerEvent, localID: String, remoteID: String, connectionID: String, stats: [WebRTCStats])?
func process(connection: Connection, event: PeerEvent, localID: String, remoteID: String, connectionID: String, stats: [WebRTCStats]) -> [Event] {
lastProcess = (connection, event, localID, remoteID, connectionID, stats)
return []
}
}
private struct DummyConnection: Connection {
func localSessionDescription() -> String? { return "" }
func remoteSessionDescription() -> String? { return "" }
func getStats(_ completion: @escaping ([WebRTCStats]) -> Void) { completion([]) }
}
|
//
// AddPetViewController.swift
// PetPal
//
// Created by Sabareesh Kappagantu on 5/7/17.
// Copyright © 2017 PetPal. All rights reserved.
//
import UIKit
import Parse
class AddPetViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var user: User!
@IBOutlet weak var petName: UITextField!
@IBOutlet weak var petType: UITextField!
@IBOutlet weak var petAge: UITextField!
@IBOutlet weak var petDescription: UITextField!
@IBOutlet weak var mainPetView: UIView!
@IBOutlet weak var petImageView: UIImageView!
@IBOutlet weak var petImageContainerView: UIView!
@IBOutlet weak var changePetPictureButton: UIButton!
@IBOutlet weak var petNameFieldContainer: UIView!
@IBOutlet weak var petTypeFieldContainer: UIView!
@IBOutlet weak var petAgeFieldContainer: UIView!
@IBOutlet weak var petDescriptionFieldContainer: UIView!
@IBOutlet weak var petAddButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
user = User.currentUser
petName.signupTextBox()
petType.signupTextBox()
petAge.signupTextBox()
petDescription.signupTextBox()
//Image Stuff
petImageView.setRounded()
let containerRadius = petImageContainerView.frame.width / 2
petImageContainerView.layer.cornerRadius = containerRadius
petImageContainerView.layer.borderColor = UIColor.black.cgColor
petImageContainerView.layer.borderWidth = 1
changePetPictureButton.layer.cornerRadius = 3
changePetPictureButton.layer.borderColor = UIColor.darkGray.cgColor
changePetPictureButton.layer.borderWidth = 0.5
//TextField UI Effect
petNameFieldContainer.layer.cornerRadius = 20
petNameFieldContainer.alpha = 0.3
petTypeFieldContainer.layer.cornerRadius = 20
petTypeFieldContainer.alpha = 0.3
petAgeFieldContainer.layer.cornerRadius = 20
petAgeFieldContainer.alpha = 0.3
petDescriptionFieldContainer.layer.cornerRadius = 20
petDescriptionFieldContainer.alpha = 0.3
//Button Styling
petAddButton.greenButton()
cancelButton.greenButton()
cancelButton.setTitleColor(UIColor.red, for: .normal)
//Background Gradient
let topColor = UIColor(displayP3Red: (57.0/255.0), green: (147.0/255.0), blue: (227.0/255.0), alpha: 1)
let bottomColor = UIColor(displayP3Red: (111.0/255.0), green: (116.0/255.0), blue: (163.0/255.0), alpha: 1)
let background = CAGradientLayer().gradientBackground(topColor: topColor.cgColor, bottomColor: bottomColor.cgColor)
background.frame = mainPetView.bounds
mainPetView.layer.insertSublayer(background, at: 0)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(recognizer:)))
view.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view.
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
func handleSingleTap(recognizer: UITapGestureRecognizer) {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onPetPictureChange(_ sender: Any) {
imagePicker.delegate = self
imagePicker.allowsEditing = false
if UIImagePickerController.isSourceTypeAvailable(.camera) {
print("Camera is Available")
imagePicker.sourceType = .camera
} else {
print("Camera 🚫 available so we will use photo library instead")
imagePicker.sourceType = .photoLibrary
}
self.present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let newPetImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.petImageView.image = newPetImage
self.dismiss(animated: true, completion: nil)
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
viewController.navigationController?.navigationBar.barTintColor = UIColor(colorLiteralRed: 57/256, green: 127/256, blue: 204/256, alpha: 1.0)
viewController.navigationController?.navigationBar.tintColor = UIColor.white
if(imagePicker.sourceType == UIImagePickerControllerSourceType.photoLibrary){
let button = UIBarButtonItem(title: "Take Photo", style: .plain, target: self, action: #selector(showCamera))
viewController.navigationItem.rightBarButtonItem = button
} else {
let button = UIBarButtonItem(title: "Choose Photo", style: .plain, target: self, action: #selector(showPhotoLibrary))
viewController.navigationItem.rightBarButtonItem = button
viewController.navigationController?.isNavigationBarHidden = false
viewController.navigationController?.navigationBar.isTranslucent = true
}
}
func showCamera(){
imagePicker.sourceType = .camera
}
func showPhotoLibrary(){
imagePicker.sourceType = .photoLibrary
}
@IBAction func onAddPetButton(_ sender: Any) {
let name = petName.text
let type = petType.text
let age = Int(petAge.text!)
let compressedPetImage = petImageView.image?.compress()
let pfPetImage = Utilities.getPFFileFromImage(image: compressedPetImage)
let petDescription = self.petDescription.text
if name != nil && type != nil && age != nil && petDescription != nil && pfPetImage != nil{
let pet = Pet(petName: name!, petType: type!, petAge: age!, petDescription: petDescription!, petImage: pfPetImage!, petOwner: user)
let pfPet = pet.makePFObject()
pet.pfPet = pfPet
PetPalAPIClient.sharedInstance.addPet(pet: pet, success: { (pet: Pet) in
print("Successfully Added a Pet to the Pet Table")
}, failure: { (error: Error?) in
print("Error: \(error?.localizedDescription ?? "Error Value in Nil")")
}, completion: {
PetPalAPIClient.sharedInstance.addPetToUser(pet: pet, success: { (user: User) in
print("Owner has a pet!")
}) {(error: Error?) in
print("Error: \(error?.localizedDescription ?? "Error Value is Nil")")
}
PetPalAPIClient.sharedInstance.populatePets(forUser: User.currentUser!)
self.dismiss(animated: true, completion: nil)
})
}
}
@IBAction func onCancel(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// File.swift
// WorldTrotter
//
// Created by Gino T on 11/17/16.
// Copyright © 2016 Gino T. All rights reserved.
//
import UIKit
class MapViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
print("MapViewController loaded it's view")
}
}
|
//
// Tienda.swift
// recetas
//
// Created by Eugenia Perez Velasco on 20/3/15.
// Copyright (c) 2015 Roberto Dehesa. All rights reserved.
//
import Foundation
import CoreData
class Tienda: NSManagedObject {
@NSManaged var direccion: String
@NSManaged var idtienda: NSNumber
@NSManaged var localizacion_latitud: NSDecimalNumber
@NSManaged var localizacion_longitud: NSDecimalNumber
@NSManaged var nombre: String
@NSManaged var poblacion: String
@NSManaged var newRelationship: NSSet
}
|
//
// CustomPeopleCell.swift
// Starwars
//
// Created by Admin on 12/24/17.
// Copyright © 2017 Greg Dominguez. All rights reserved.
//
//import Foundation
import UIKit
class CustomPeopleCell: UITableViewCell{
@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myName: UITextField!
//check the cache
func loadPersonImage(fromName name:String) {
if let image = GlobalCache.shared.imgCache.object(forKey:name as NSString){
self.myImage.image = image
return
}
Networking.downloadPersonImage(byName: name) { [unowned self](image, error) in
guard error == nil else {return}
guard let image = image else{return}
GlobalCache.shared.imgCache.setObject(image,forKey: name as NSString)
DispatchQueue.main.async {
self.myImage.image = image
}
}
}
func setPlaceholder(){
self.myImage.image = #imageLiteral(resourceName: "frog")
}
}
|
// SCNPlaneExtensionsTests.swift - Copyright 2020 SwifterSwift
@testable import SwifterSwift
import XCTest
#if canImport(SceneKit)
import SceneKit
final class SCNPlaneExtensionsTests: XCTestCase {
func testInitWithWidth() {
let plane = SCNPlane(width: 10)
XCTAssertEqual(plane.boundingSize, SCNVector3(10, 10, 0))
}
func testInitWithMaterial() {
let material = SCNMaterial(color: .red)
let plane = SCNPlane(width: 10, height: 20, material: material)
XCTAssertEqual(plane.materials, [material])
}
func testInitWithColor() {
let color = SFColor.red
let plane = SCNPlane(width: 10, height: 20, color: color)
XCTAssertEqual(plane.materials[0].diffuse.contents as? SFColor, color)
}
func testInitWithWidthAndMaterial() {
let material = SCNMaterial(color: .red)
let plane = SCNPlane(width: 10, material: material)
XCTAssertEqual(plane.boundingSize, SCNVector3(10, 10, 0))
XCTAssertEqual(plane.materials, [material])
}
func testInitWithWidthAndColor() {
let color = SFColor.red
let plane = SCNPlane(width: 10, color: color)
XCTAssertEqual(plane.boundingSize, SCNVector3(10, 10, 0))
XCTAssertEqual(plane.materials[0].diffuse.contents as? SFColor, color)
}
}
#endif
|
import RxSwift
import RxRelay
import RxCocoa
import HdWalletKit
class CreateAccountViewModel {
private let service: CreateAccountService
private let disposeBag = DisposeBag()
private let wordCountRelay = BehaviorRelay<String>(value: "")
private let passphraseCautionRelay = BehaviorRelay<Caution?>(value: nil)
private let passphraseConfirmationCautionRelay = BehaviorRelay<Caution?>(value: nil)
private let clearInputsRelay = PublishRelay<Void>()
private let showErrorRelay = PublishRelay<String>()
private let finishRelay = PublishRelay<()>()
init(service: CreateAccountService) {
self.service = service
subscribe(disposeBag, service.wordCountObservable) { [weak self] in self?.sync(wordCount: $0) }
sync(wordCount: service.wordCount)
}
private func sync(wordCount: Mnemonic.WordCount) {
wordCountRelay.accept("create_wallet.n_words".localized("\(wordCount.rawValue)"))
}
private func clearInputs() {
clearInputsRelay.accept(())
clearCautions()
service.passphrase = ""
service.passphraseConfirmation = ""
}
private func clearCautions() {
if passphraseCautionRelay.value != nil {
passphraseCautionRelay.accept(nil)
}
if passphraseConfirmationCautionRelay.value != nil {
passphraseConfirmationCautionRelay.accept(nil)
}
}
}
extension CreateAccountViewModel {
var wordCountDriver: Driver<String> {
wordCountRelay.asDriver()
}
var inputsVisibleDriver: Driver<Bool> {
service.passphraseEnabledObservable.asDriver(onErrorJustReturn: false)
}
var passphraseCautionDriver: Driver<Caution?> {
passphraseCautionRelay.asDriver()
}
var passphraseConfirmationCautionDriver: Driver<Caution?> {
passphraseConfirmationCautionRelay.asDriver()
}
var clearInputsSignal: Signal<Void> {
clearInputsRelay.asSignal()
}
var showErrorSignal: Signal<String> {
showErrorRelay.asSignal()
}
var finishSignal: Signal<()> {
finishRelay.asSignal()
}
var namePlaceholder: String {
service.defaultAccountName
}
var wordCountViewItems: [AlertViewItem] {
Mnemonic.WordCount.allCases.map { wordCount in
let title: String
switch wordCount {
case .twelve: title = "create_wallet.12_words".localized
default: title = "create_wallet.n_words".localized("\(wordCount.rawValue)")
}
return AlertViewItem(text: title, selected: wordCount == service.wordCount)
}
}
func onChange(name: String) {
service.name = name
}
func onSelectWordCount(index: Int) {
service.set(wordCount: Mnemonic.WordCount.allCases[index])
}
func onTogglePassphrase(isOn: Bool) {
service.set(passphraseEnabled: isOn)
clearInputs()
}
func onChange(passphrase: String) {
service.passphrase = passphrase
clearCautions()
}
func onChange(passphraseConfirmation: String) {
service.passphraseConfirmation = passphraseConfirmation
clearCautions()
}
func validatePassphrase(text: String?) -> Bool {
let validated = service.validate(text: text)
if !validated {
passphraseCautionRelay.accept(Caution(text: "create_wallet.error.forbidden_symbols".localized, type: .warning))
}
return validated
}
func validatePassphraseConfirmation(text: String?) -> Bool {
let validated = service.validate(text: text)
if !validated {
passphraseConfirmationCautionRelay.accept(Caution(text: "create_wallet.error.forbidden_symbols".localized, type: .warning))
}
return validated
}
func onTapCreate() {
passphraseCautionRelay.accept(nil)
passphraseConfirmationCautionRelay.accept(nil)
do {
try service.createAccount()
finishRelay.accept(())
} catch {
if case CreateAccountService.CreateError.emptyPassphrase = error {
passphraseCautionRelay.accept(Caution(text: "create_wallet.error.empty_passphrase".localized, type: .error))
} else if case CreateAccountService.CreateError.invalidConfirmation = error {
passphraseConfirmationCautionRelay.accept(Caution(text: "create_wallet.error.invalid_confirmation".localized, type: .error))
} else {
showErrorRelay.accept(error.smartDescription)
}
}
}
}
|
//
// Speaker.swift
// iVerbs
//
// Created by Brad Reed on 17/02/2016.
// Copyright © 2016 Brad Reed. All rights reserved.
//
import Foundation
import AVFoundation
/**
* Class to manage speaking verbs and conjugations.
*/
class Speaker: NSObject, AVSpeechSynthesizerDelegate {
// The speed at which the text is spoken
var speechRate: Float = Setting.by(identifier: "speechrate")?.value ?? 0.5
var synth: AVSpeechSynthesizer
var voice: AVSpeechSynthesisVoice?
var callback: (() -> ())?
// Create new speaker instance, set up language synth and voice
// with given Language instance
convenience init(language: Language, callback: (() -> ())? = nil) {
self.init(locale: language.locale, callback: callback)
}
// Init with locale as string
init(locale: String, callback: (() -> ())? = nil) {
synth = AVSpeechSynthesizer()
self.callback = callback
super.init()
synth.delegate = self
// language.locale tells the speech synthesizer what language voice to speak in
voice = AVSpeechSynthesisVoice(language: locale)
}
// Speak the given text
func speak(_ text: String) {
let utterance = AVSpeechUtterance(string: text)
utterance.voice = voice
utterance.rate = speechRate
synth.speak(utterance)
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
if callback != nil {
self.callback!()
}
}
}
|
/******************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
* Copyright 2016 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property of
* Adobe Systems Incorporated and its suppliers, if any. The intellectual and
* technical concepts contained herein are proprietary to Adobe Systems
* Incorporated and its suppliers and are protected by trade secret or
* copyright law. Dissemination of this information or reproduction of this
* material is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
******************************************************************************/
import UIKit
class ImageTableItem {
fileprivate(set) var image: UIImage!
fileprivate(set) var text: String
required init(image: UIImage, text: String) {
self.image = image
self.text = text
}
}
|
//
// APIService.swift
// TrendTestTask
//
// Created by Nikolay on 13/04/2019.
// Copyright © 2019 Nikolay. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
typealias PositionsCompletion = (PositionsData) -> Void
enum SortType: String {
case price
case subway
case region
}
class APIService {
private let domain = URL(string: "http://api.trend-dev.ru/v3_1/blocks/search/?show_type=list")
private let headers = ["Content-Type": "application/json"]
func fetchInitialData(completion: @escaping PositionsCompletion) {
fetchPositions(completion: completion)
}
func fetch(sortedBy sortType: SortType = SortType.price, withOffset offset: Int = 0, completion: @escaping PositionsCompletion) {
fetchPositions(count: 10, offset: offset, sortType: sortType, completion: completion)
}
func fetch(sortedBy sortType: SortType = SortType.price, withOffset offset: Int = 0, priceFrom: Int = 0, priceTo: Int = 0, completion: @escaping PositionsCompletion) {
fetchPositions(offset: offset, priceFrom: priceFrom, priceTo: priceTo, sortType: sortType, completion: completion)
}
private func fetchPositions(
showType: String = "list",
count: Int = 10,
offset: Int = 0,
cache: Bool = false,
priceFrom: Int = 0,
priceTo: Int = 0,
sortType: SortType = SortType.price,
completion: @escaping PositionsCompletion) {
DispatchQueue.global(qos: .background).async {
var parameters: [String: Any] = [:]
parameters.updateValue(count, forKey: "count")
parameters.updateValue(offset, forKey: "offset")
parameters.updateValue(cache, forKey: "cache")
parameters.updateValue(priceTo, forKey: "price_to")
parameters.updateValue(priceFrom, forKey: "price_from")
parameters.updateValue(sortType.rawValue, forKey: "sort")
request(self.domain!, method: .get, parameters: parameters, encoding: URLEncoding.queryString, headers: self.headers).responseJSON { response in
if let data = response.result.value {
let buildingsInfoJSON: JSON = JSON(data)
var tempArray = [ResponseModel]()
var amount = 0
if let subJson = buildingsInfoJSON["data"]["results"].array {
for items in subJson {
var model = ResponseModel()
model.builderName = items["builder"]["name"].stringValue
model.buildingName = items["name"].stringValue
model.deadline = items["deadline"].stringValue
model.areaName = items["region"]["name"].stringValue
model.subwayName = items["subways"][0]["name"].stringValue
model.subwayTime = items["subways"][0]["distance_timing"].intValue
model.subwayColor = items["subways"][0]["color"].stringValue
model.travelType = items["subways"][0]["distance_type"].stringValue
model.image = items["image"].stringValue
let minPrices = items["min_prices"].arrayValue.map({
MinPriceModel(
room: $0["room"].intValue,
rooms: $0["rooms"].stringValue,
minPrices: $0["price"].intValue
)
})
let filteredMinPrices = minPrices.filter { $0.room != 100 }
model.minPrices = filteredMinPrices
tempArray.append(model)
}
}
if let objectsCount = buildingsInfoJSON["data"]["apartmentsCount"].int {
amount = objectsCount
}
completion(PositionsData(models: tempArray, amount: amount))
}
}
}
}
}
|
//
// FlipAnimationView.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 12/31/19.
// Copyright © 2019 Badarinath Venkatnarayansetty. All rights reserved.
//
import Foundation
import SwiftUI
struct FlipAnimationView: View {
@State private var flipHorizontal = false
@State private var flipVertical = false
var body: some View {
VStack {
HStack(spacing : 50 ) {
Button(action: {
//( Animation.default )
withAnimation {
self.flipHorizontal.toggle()
}
}) {
Image(systemName: "flip.horizontal.fill")
.font(.system(size: 50))
.padding()
}
Button(action: {
withAnimation {
self.flipVertical.toggle()
}
}) {
Image(systemName: "flip.horizontal.fill")
.font(.system(size: 50))
.padding()
.rotationEffect(Angle.degrees(90))
}
}
Image("y1")
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(30)
.padding()
.scaleEffect(x: flipHorizontal ? -1 : 1, y: flipVertical ? -1 : 1)
}
}
}
|
//
// UIColorData.swift
// RuangGuru Trivia
//
// Created by Faiz Umar Baraja on 10/12/2017.
// Copyright © 2017 FaizBarajaApps. All rights reserved.
//
import UIKit
class UIColorData: NSObject {
class func getColorCorrectGreen()->UIColor{
return UIColor(displayP3Red: 80.0/255.0, green: 227.0/255.0, blue: 194.0/255.0, alpha: 1.0)
}
class func getColorInCorrectRed()->UIColor{
return UIColor(displayP3Red: 251.0/255.0, green: 64.0/255.0, blue: 64.0/255.0, alpha: 1.0)
}
}
|
import Foundation
import GraphQL
/**
# Concrete Resolvable
A Resolvable that is required to have a type name
*/
public protocol ConcreteResolvable: Resolvable {
/**
Name that should be used in GraphQL
*/
static var concreteTypeName: String { get }
}
extension ConcreteResolvable {
/**
- Warning: default implementation from `GraphZahl`. Do not override unless you know exactly what you are doing.
*/
public static var typeName: String? {
return concreteTypeName
}
public static var concreteTypeName: String {
return String(describing: Self.self)
}
}
extension ConcreteResolvable where Self: OutputResolvable {
/**
- Warning: default implementation from `GraphZahl`. Do not override unless you know exactly what you are doing.
*/
public static func reference(using context: inout Resolution.Context) throws -> GraphQLOutputType {
return GraphQLNonNull(GraphQLTypeReference(concreteTypeName))
}
}
|
//
// ViewController.swift
// CollectionViewCustom
//
// Created by 有村 琢磨 on 2015/05/14.
// Copyright (c) 2015年 有村 琢磨. All rights reserved.
//
import UIKit
class CollectionViewController:UICollectionViewController,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
var objects: NSArray! = []
let API_KEY :String = "AIzaSyDbu0hCWS21FOP2DsBEjTO95NQ65MP_96s"
var selectedURL :NSString = ""
let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
//API取得
func searchWord(text :String){
println("search text\(text)")
//URLエンコーディング(文字列エスケープ処理)
let searchWord:String! = text.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
//Youtubeに対して、検索をかける文字列
let urlString:String = "https://www.googleapis.com/youtube/v3/search?key=\(API_KEY)&q=healthcare&part=id,snippet&maxResults=10&order=viewCount"
//api処理
let url:NSURL! = NSURL(string: urlString)
let urlRequest :NSURLRequest! = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(urlRequest,
queue: NSOperationQueue.mainQueue(),
completionHandler: {(response,jsonData,error) -> Void in
//データが取得できた場合にJSONを解析してNSDictionaryに格納
let dic:NSDictionary = NSJSONSerialization.JSONObjectWithData(
jsonData!,
options: NSJSONReadingOptions.AllowFragments,
error: nil) as! NSDictionary
//結果のJSON配列から必要なもののみ格納
let resultArray: NSArray! = dic["items"] as! NSArray
println(resultArray)
//取得したデータの表示
self.objects = resultArray
self.collectionView!.reloadData()
})
}
//MARK: - collectionView datasource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return objects.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:CollectionViewCell! = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! CollectionViewCell
//cellに表示するデータを1件だけ取得
let record:NSDictionary = self.objects[indexPath.row]["snippet"] as! NSDictionary
cell.textLabel?.text = record["titles"] as? String
//(JSONデータから表示したいurlを設定)
var urlString:NSString = (record["thumbnails"]!["default"] as! NSDictionary)["url"] as! String
//サムネイル画像をNSDataにダウンロードし、imageViewに設定
let imageData:NSData = NSData(contentsOfURL:NSURL(string:urlString as! String)!)!
cell.cellImage?.image = UIImage(data: imageData)
return cell
}
//MARK: collectionView delegate
//MARK: collectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 170, height: 300)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInsets
}
//MARK: - main
override func viewDidLoad() {
super.viewDidLoad()
searchWord("healthcare")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Tree.swift
// Polindrom
//
// Created by Евгений Сергеев on 28.05.16.
// Copyright © 2016 Евгений Сергеев. All rights reserved.
//
import Foundation
class BSearchTree<T: Comparable>{
private var value: T?
private var left: BSearchTree<T>?
private var right: BSearchTree<T>?
weak private var parent: BSearchTree<T>?
init(){}
internal init(value: T, leftChild: BSearchTree?, rightChild: BSearchTree?, parent: BSearchTree?) {
self.value=value
self.left=leftChild
self.left?.parent = self
self.right=rightChild
self.right?.parent = self
self.parent=parent
}
internal convenience init(array: [T]) {
precondition(array.count > 0)
self.init(value: array.first!)
for value in array.dropFirst() {
add(value)
}
}
internal convenience init(value: T) {
self.init(value: value,leftChild: nil,rightChild: nil,parent: nil)
}
internal var isRoot: Bool {
return parent == nil
}
internal var isLeaf: Bool {
return right == nil && left == nil
}
internal var isLeftChild: Bool {
return parent?.left === self
}
internal var isRightChild: Bool {
return parent?.right === self
}
internal var hasLeftChild: Bool {
return left != nil
}
internal var hasRightChild: Bool {
return right != nil
}
internal func add(value: T) {
insert(value, parent: self)
}
internal func insert(value: T, parent: BSearchTree) {
if self.value == nil {
self.value = value
return
}
if value < self.value {
if hasLeftChild {
left?.insert(value, parent: left!)
} else {
left = BSearchTree<T>(value: value)
left?.parent=parent
}
} else if value > self.value {
if hasRightChild {
right?.insert(value, parent: right!)
} else {
right = BSearchTree<T>(value: value)
right?.parent=parent
}
}
}
internal func remove() {
if hasLeftChild {
if hasRightChild {
let successor = right!.min()
value = successor.value
successor.remove()
} else {
reconnectParentToNode(left)
}
} else if hasRightChild {
reconnectParentToNode(right)
} else {
reconnectParentToNode(nil)
}
}
private func reconnectParentToNode(node: BSearchTree?) {
if !isRoot {
if isLeftChild {
parent!.left = node
} else {
parent!.right = node
}
}
node?.parent = parent
}
internal func search(value: T) -> BSearchTree? {
var node: BSearchTree? = self
while case let n? = node {
if value < n.value {
node = n.left
} else if value > n.value {
node = n.right
} else {
return node
}
}
return nil
}
internal func contains(x: T) -> Bool {
return search(x) != nil
}
internal func min() -> BSearchTree {
var node = self
while case let next? = node.left {
node = next
}
return node
}
internal func max() -> BSearchTree {
var node = self
while case let next? = node.right {
node = next
}
return node
}
internal func traverse() {
if self.value == nil {
return
}
if hasLeftChild {
left!.traverse()
}
print(" "+String(self.value))
if hasRightChild {
right!.traverse()
}
}
internal func traverseInOrder(@noescape process: T -> Void) {
left?.traverseInOrder(process)
process(value!)
right?.traverseInOrder(process)
}
func map(@noescape formula: T -> T) -> [T] {
var a = [T]()
if let left = left { a += left.map(formula) }
a.append(formula(value!))
if let right = right { a += right.map(formula) }
return a
}
internal func toArray() -> [T] {
return map { $0 }
}
func commonDescription()->String {
var s = "Value:'\(value)'"
if let parent = parent {
s += ", Parent:'\(parent.value)'"
}
if let left = left {
s += ", Left = [" + left.debugDescription + "]"
}
if let right = right {
s += ", Right = [" + right.debugDescription + "]"
}
s+="\n"
return s
}
internal var description: String {
let s = commonDescription()
return s
}
internal var debugDescription: String {
let s = commonDescription()
return s
}
}
|
//
// VisualEffectView.swift
// Instancing
//
// Created by Reza Ali on 1/21/21.
// Copyright © 2020 Reza Ali. All rights reserved.
//
import SwiftUI
#if os(macOS)
import Cocoa
import AppKit
struct VisualEffectView: NSViewRepresentable
{
var material: NSVisualEffectView.Material = .sidebar
var blendingMode: NSVisualEffectView.BlendingMode = .withinWindow
var isEmphasized: Bool = true
func makeNSView(context: Self.Context) -> NSVisualEffectView
{
let visualEffectView = NSVisualEffectView()
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
visualEffectView.state = NSVisualEffectView.State.active
return visualEffectView
}
func updateNSView(_ visualEffectView: NSVisualEffectView, context: Self.Context)
{
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
visualEffectView.isEmphasized = isEmphasized
}
}
#elseif os(iOS)
struct VisualEffectView: UIViewRepresentable {
var style: UIBlurEffect.Style = .systemThinMaterial
func makeUIView(context: Context) -> UIVisualEffectView {
return UIVisualEffectView(effect: UIBlurEffect(style: style))
}
func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
uiView.effect = UIBlurEffect(style: style)
}
}
#endif
struct VisualEffectView_Previews: PreviewProvider {
static var previews: some View {
VisualEffectView().frame(width: 100, height: 100)
}
}
|
//
// UserController.swift
// Mixtape
//
// Created by Eva Marie Bresciano on 7/11/16.
// Copyright © 2016 Eva Bresciano. All rights reserved.
//
import UIKit
import CoreData
import CloudKit
class UserController {
var playlist = Playlist()
var isSyncing: Bool = false
let songs = [Song?]()
private let kUserData = "userData"
static let sharedController = UserController()
private let cloudKitManager = CloudKitManager()
let fetchRequest = NSFetchRequest(entityName: "User")
var currentUser: User? {
let results = (try? Stack.sharedStack.managedObjectContext.executeFetchRequest(fetchRequest)) as? [User] ?? []
return results.first ?? nil
}
//var followedUsers = [User]()
var users: [User] {
let moc = Stack.sharedStack.managedObjectContext
do {
if let users = try moc.executeFetchRequest(fetchRequest) as? [User] {
return users
} else {
return []
}
} catch let error as NSError {
print(error.localizedDescription)
return []
}
}
func fetchAllUsers(searchTerm: String, completion: ((users: [User]) -> Void)?) {
cloudKitManager.fetchRecordsWithType("User", recordFetchedBlock: nil) { (records, error) in
if let records = records {
let users = records.flatMap({ User(record: $0 )})
if let completion = completion {
let resultsArray = users.filter({$0.matchesSearchTerm(searchTerm)})
completion(users: resultsArray)
}
}
}
}
func createUser(username: String) {
let user = User(username: username)
SongController.sharedController.createPlaylist(user, songs: songs) { (playlist) in
user.playlist = playlist
self.saveContext()
}
cloudKitManager.saveRecord(user.cloudKitRecord!) { (record, error) in
}
if let userCloudKitRecord = user.cloudKitRecord {
cloudKitManager.saveRecord(userCloudKitRecord, completion: { (record, error) in
if let record = record {
user.update(record)
} else {
print(error?.localizedDescription)
}
})
}
performFullSync()
}
// So users have an array of people they follow. If the "Follow" button is tapped on a user, then add that users display name to the current users "Following" array. make main feed the current users, following users songs by time of post.
func saveContext() {
do {
try Stack.sharedStack.managedObjectContext.save()
} catch {
print("Very very sorry, could not save User")
}
}
func userWithName(userRecordID: CKRecordID, completion: ((user: User?) -> Void)?) {
cloudKitManager.fetchRecordWithID(userRecordID) { (record, error) in
if let record = record,
let user = User(record: record) {
if let completion = completion{
completion(user: user)
}
} else {
if let completion = completion {
completion(user: nil)
}
}
}
}
func pushChangesToCloudKit(user: User, completion: ((success: Bool, error: NSError?)->Void)?) {
guard let userRecord = user.cloudKitRecord else { return }
cloudKitManager.saveRecords([userRecord], perRecordCompletion: nil, completion: nil)
}
func fetchUserRecords(type: String, completion: ((records:[CKRecord]) -> Void)?) {
let predicate = NSPredicate(value: true)
cloudKitManager.fetchRecordsWithType(type, predicate: predicate, recordFetchedBlock: { (record) in
}) { (records, error) in
if error != nil {
print("Error: Could not retrieve user records\(error?.localizedDescription)")
}
if let completion = completion, records = records {
completion(records: records)
}
}
}
// MARK: - Sync
func syncedRecords(type: String) -> [CloudKitManagedObject] {
let fetchRequest = NSFetchRequest(entityName: type)
let predicate = NSPredicate(format: "recordIDData != nil")
fetchRequest.predicate = predicate
let results = (try? Stack.sharedStack.managedObjectContext.executeFetchRequest(fetchRequest)) as? [CloudKitManagedObject] ?? []
return results
}
func unsyncedRecords(type: String) -> [CloudKitManagedObject] {
let fetchRequest = NSFetchRequest(entityName: type)
let predicate = NSPredicate(format: "recordIDData == nil")
fetchRequest.predicate = predicate
let results = (try? Stack.sharedStack.managedObjectContext.executeFetchRequest(fetchRequest)) as? [CloudKitManagedObject] ?? []
return results
}
func performFullSync(completion: (() -> Void)? = nil) {
if isSyncing {
if let completion = completion {
completion()
}
} else {
isSyncing = true
self.fetchNewRecords("User") {
self.isSyncing = false
if let completion = completion {
completion()
}
}
}
}
func fetchNewRecords(type: String, completion: (() -> Void)?) {
let referencesToExclude = syncedRecords(type).flatMap({ $0.cloudKitReference })
var predicate = NSPredicate(format: "NOT(recordID IN %@)", argumentArray: [referencesToExclude])
if referencesToExclude.isEmpty {
predicate = NSPredicate(value: true)
}
cloudKitManager.fetchRecordsWithType(type, predicate: predicate, recordFetchedBlock: { (record) in
switch type {
case "Playlist":
let _ = Playlist(record: record)
default:
return
}
self.saveContext()
}) { (records, error) in
if error != nil {
print("😱 Error fetching records \(error?.localizedDescription)")
}
if let completion = completion {
completion()
}
}
}
// func addUserToPlaylist(playlist: Playlist, user: User) {
// followedUsers.append(user)
// }
// func removeUserFromPlaylist(playlist: Playlist, user: User) {
// let unfollowedUser = followedUsers.filter ({
// $0.username == User.username })
// }
}
|
//
// EventsCollectionCell.swift
// HSAPP-iOS
//
// Created by Sunny Ouyang on 6/23/18.
// Copyright © 2018 Tony Cioara. All rights reserved.
//
import UIKit
class EventsCollectionCell: UICollectionViewCell {
var event: Event?
//MARK: UICOMPONENTS
private var containerView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.AppColors.viewWhite
view.layer.shadowColor = UIColor.lightGray.cgColor
view.layer.shadowOpacity = 0.3
view.layer.shadowOffset = CGSize.zero
view.layer.shadowRadius = 7
return view
}()
private var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: ".SFUIText-SemiBold", size: 18)
return label
}()
private var dateLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: ".SFUIText-SemiBold", size: 14)
return label
}()
private var locationLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: ".SFUIText-SemiBold", size: 14)
return label
}()
private func addUI() {
self.contentView.addSubview(containerView)
[titleLabel, dateLabel, locationLabel].forEach { (label) in
containerView.addSubview(label)
}
}
private func setUpConstraints() {
containerView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(-30)
make.left.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-20)
make.bottom.equalToSuperview()
}
titleLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(20)
make.left.equalToSuperview().offset(16)
make.right.equalToSuperview().offset(-16)
}
dateLabel.snp.makeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(16)
make.left.equalToSuperview().offset(16)
make.right.equalToSuperview().offset(-16)
}
locationLabel.snp.makeConstraints { (make) in
make.top.equalTo(dateLabel.snp.bottom).offset(16)
make.left.equalToSuperview().offset(16)
make.right.equalToSuperview().offset(-16)
}
}
func setUp(event: Event) {
self.event = event
titleLabel.text = event.title
dateLabel.text = event.date
locationLabel.text = event.place
addUI()
setUpConstraints()
}
}
|
//
// UIButtonHelper.swift
// Diarly
//
// Created by Alessandro Bolattino on 11/04/18.
// Copyright © 2018 Diarly. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
extension UIButton {
convenience init?(imageName: String) {
guard UIImage(named: imageName) != nil else {
return nil
}
self.init(imageName: imageName)
}
func setCenteredImage(with name: String) -> UIButton{
let image = UIImage(named: name)
return setCenteredImage(with: image!)
}
func setCenteredImage(with image: UIImage) -> UIButton{
self.layoutIfNeeded()
self.imageView?.contentMode = .scaleAspectFit
self.setImage(image, for: .normal)
self.imageView?.snp.makeConstraints{ (make) -> Void in
make.height.equalTo(self.snp.height).multipliedBy(0.6)
make.center.equalTo(self)
}
return self
}
override func updatedSize(){
super.updatedSize()
if let image = self.imageView?.image {
self.setCenteredImage(with: image)
}
}
}
|
//
// ViewController.swift
// WMVideo
//
// Created by wumeng on 2019/11/25.
// Copyright © 2019 wumeng. All rights reserved.
//
import UIKit
import AVKit
class ViewController: UIViewController {
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Get stored media files
print(WMCameraFileTools.wm_getAllfiles())
}
@IBAction func recordVideoClick(_ sender: Any) {
let vc = WMCameraViewController()
// vc.inputType = .video
vc.videoMaxLength = 20
vc.completeBlock = { url, type in
print("url == \(url)")
//normal
// if type == .video {
// let videoUrl = URL.init(fileURLWithPath: url)
// self.WM_FUNC_PresentPlay(videoUrl: videoUrl)
// }
//export
if type == .video {
let videoEditer = WMVideoEditor.init(videoUrl: URL.init(fileURLWithPath: url))
videoEditer.addWaterMark(image: UIImage.init(named: "billbill")!)
videoEditer.addAudio(audioUrl: Bundle.main.path(forResource: "孤芳自赏", ofType: "mp3")!)
self.loadingIndicator.startAnimating()
videoEditer.assetReaderExport(completeHandler: { url in
self.loadingIndicator.stopAnimating()
// play video
let videoUrl = URL.init(fileURLWithPath: url)
self.WM_FUNC_PresentPlay(videoUrl: videoUrl)
})
}
//image
if type == .image {
//save image to PhotosAlbum
self.WM_FUNC_saveImage(UIImage.init(contentsOfFile: url)!)
}
}
present(vc, animated: true, completion: nil)
}
//MARK:- save image
func WM_FUNC_saveImage(_ image:UIImage) -> Void {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
//MARK:- play video
func WM_FUNC_PresentPlay(videoUrl: URL) -> Void {
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: videoUrl)
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
present(controller, animated: true) {
player.play()
}
}
}
|
//
// UserDataRepository.swift
// KeioClient
//
// Created by 荻原湧志 on 2018/05/05.
// Copyright © 2018年 ogiwara. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class UserDataRepository{
static let instance = UserDataRepository()
private init(){}
var fromPersistence: [UserData]?{
get{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
return try! context.fetch(UserData.fetchRequest()) as? [UserData]
}
}
}
|
//
// MainViewController.swift
// APPDemo
//
// Created by Francesco Colleoni on 28/04/16.
// Copyright © 2016 Near srl. All rights reserved.
//
import UIKit
import NMNet
import NMSDK
import NMJSON
import NMPlug
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NearSDKDelegate {
// MARK: Properties
var sections = ["%d notifications", "%d contents", "%d polls"]
var notifications = [Notification]()
var contents = [Content]()
var polls = [Poll]()
// MARK: Outlets
@IBOutlet weak var tableView: UITableView!
// MARK: Actions
@IBAction func showSimulate(sender: AnyObject) {
let alertViewController = UIAlertController(title: "Simulate reaction".localized, message: "Choose reaction".localized, preferredStyle: .ActionSheet)
let notificationAction = UIAlertAction(title: "Notification".localized, style: .Default) { (action) in
self.simulateNotification()
}
let contentAction = UIAlertAction(title: "Content".localized, style: .Default) { (action) in
self.simulateContent()
}
let pollAction = UIAlertAction(title: "Poll".localized, style: .Default) { (action) in
self.simulatePoll()
}
let cancel = UIAlertAction(title: "Cancel".localized, style: .Destructive) { (action) in
alertViewController.dismissViewControllerAnimated(true, completion: nil)
}
alertViewController.addAction(notificationAction)
alertViewController.addAction(contentAction)
alertViewController.addAction(pollAction)
alertViewController.addAction(cancel)
presentViewController(alertViewController, animated: true, completion: nil)
}
// MARK: viewDidLoad, viewDidAppear, ...
override func viewDidLoad() {
super.viewDidLoad()
NearSDK.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: UITableView delegates
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch sections[section] {
case "%d notifications":
return notifications.count
case "%d contents":
return contents.count
case "%d polls":
return polls.count
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
return notificationCellForRowAtIndexPath(indexPath)
case 1:
return contentCellForRowAtIndexPath(indexPath)
case 2:
return pollCellForRowAtIndexPath(indexPath)
default:
return UITableViewCell()
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return sections[section].pluralized(notifications.count)
case 1:
return sections[section].pluralized(contents.count)
case 2:
return sections[section].pluralized(polls.count)
default:
return nil
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
private func notificationCellForRowAtIndexPath(indexPath: NSIndexPath) -> NotificationCell {
let cell = tableView.dequeueReusableCellWithIdentifier("notification", forIndexPath: indexPath) as! NotificationCell
cell.setNotification(notifications[indexPath.row])
return cell
}
private func contentCellForRowAtIndexPath(indexPath: NSIndexPath) -> ContentCell {
let cell = tableView.dequeueReusableCellWithIdentifier("content", forIndexPath: indexPath) as! ContentCell
cell.setContent(contents[indexPath.row])
return cell
}
private func pollCellForRowAtIndexPath(indexPath: NSIndexPath) -> PollCell {
let cell = tableView.dequeueReusableCellWithIdentifier("poll", forIndexPath: indexPath) as! PollCell
cell.setPoll(polls[indexPath.row])
return cell
}
// MARK: Simulation
private func simulateNotification() {
guard let
id = firstReactionID(CorePlugin.Notifications.name),
notification = APRecipeNotification(json: JSON(dictionary: reaction(id, pluginName: CorePlugin.Notifications.name).dictionary)) else {
return
}
notifications.append(Notification(notification: notification, recipe: nil))
refresh()
}
private func simulateContent() {
guard let
id = firstReactionID(CorePlugin.Contents.name),
content = APRecipeContent(json: JSON(dictionary: reaction(id, pluginName: CorePlugin.Contents.name).dictionary)) else {
return
}
contents.append(Content(content: content, recipe: nil))
refresh()
}
private func simulatePoll() {
guard let
id = firstReactionID(CorePlugin.Polls.name),
poll = APRecipePoll(json: JSON(dictionary: reaction(id, pluginName: CorePlugin.Polls.name).dictionary)) else {
return
}
polls.append(Poll(poll: poll, recipe: nil))
refresh()
}
private func firstReactionID(pluginName: String) -> String? {
let response = NearSDK.plugins.run(pluginName, withArguments: JSON(dictionary: ["do": "index"]))
guard let reactionIdentifiers = response.content.stringArray("reactions"), id = reactionIdentifiers.first else {
return nil
}
return id
}
private func reaction(id: String, pluginName: String) -> JSON {
return NearSDK.plugins.run(pluginName, withArguments: JSON(dictionary: ["do": "read", "content": id])).content
}
// MARK: NearSDK delegate
func nearSDKDidEvaluate(notifications collection: [Notification]) {
notifications += collection
refresh()
if collection.count > 0 {
showLocalNotification("%d notifications".pluralized(collection.count))
}
}
func nearSDKDidEvaluate(contents collection: [Content]) {
contents += collection
refresh()
if collection.count > 0 {
showLocalNotification("%d contents".pluralized(collection.count))
}
}
func nearSDKDidEvaluate(polls collection: [Poll]) {
polls += collection
refresh()
if collection.count > 0 {
showLocalNotification("%d polls".pluralized(collection.count))
}
}
private func refresh() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
private func showLocalNotification(message: String) {
let localNotification = UILocalNotification()
localNotification.alertTitle = "May I have your attention?".localized
localNotification.alertBody = message
localNotification.fireDate = NSDate().dateByAddingTimeInterval(1)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
}
|
import Foundation
public enum TypeEnum: String, Codable {
case movie = "movie"
}
|
//
// RMEventCombination.swift
// RealmPlatform
//
// Created by 이광용 on 24/04/2019.
// Copyright © 2019 GwangYongLee. All rights reserved.
//
import Foundation
import Domain
import RealmSwift
@objcMembers
final class RMActionCombination: Object {
dynamic var uuid: String = ""
dynamic var title: String = ""
override static func primaryKey() -> String? {
return "uuid"
}
var actions = List<RMAnyAction>()
}
extension RMActionCombination: DomainConvertible {
func asDomain() -> Domain.ActionCombination {
return Domain.ActionCombination(uuid: uuid,
title: title,
actions: actions.asDomainArray())
}
}
extension Domain.ActionCombination: RealmRepresentable {
func asRealm() -> RMActionCombination {
let eventList = events.map { event -> RMAnyAction? in
if let rmTimeEvent = (event as? SimpleEvent)?.asRealm() {
return RMAnyEvent(rmTimeEvent)
} else if let rmCountingEvent = (event as? CountingEvent)?.asRealm() {
return RMAnyEvent(rmCountingEvent)
} else {
return nil
}
}.compactMap { $0 }
.asList()
return RMActionCombination.build {
$0.uuid = uuid
$0.title = title
$0.events = eventList
}
}
}
|
type messagefile;
type countfile;
app (countfile t) countwords (messagefile f) {
sh @filename(f) stdout=@filename(t);
}
string inputNames = "scott3a.sh";
messagefile inputfiles[] <fixed_array_mapper;files=inputNames>;
foreach f in inputfiles {
countfile c;
c = countwords(f);
}
|
//
// DiscogsAlbum.swift
// Dikke Ploaten
//
// Created by Victor Vanhove on 24/04/2019.
// Copyright © 2019 bazookas. All rights reserved.
//
import Firebase
import ObjectMapper
class DiscogsDocument: ImmutableMappable, Hashable, Comparable {
var id: String = ""
var releases: [Album]?
// MARK: - Constructors
init(releases: [Album]?) {
self.releases = releases
}
// MARK: - ObjectMapper
required init(map: Map) throws {
releases = try? map.value("releases")
}
func mapping(map: Map) {
releases >>> map["releases"]
}
// Hashable
var hashValue: Int {
return id.hashValue
}
static func < (lhs: DiscogsDocument, rhs: DiscogsDocument) -> Bool {
return lhs.id < lhs.id
}
static func == (lhs: DiscogsDocument, rhs: DiscogsDocument) -> Bool {
return lhs.id == rhs.id
}
static func docToDiscogsDocument(document: DocumentSnapshot) -> DiscogsDocument {
let albumDocument = try! Mapper<DiscogsDocument>().map(JSON: document.data()!)
albumDocument.id = document.documentID
return albumDocument
}
}
|
public protocol PileItemRepository: PileItemsCountHolder {
func fetchPiles()
}
public protocol PileItemsCountHolder {
var count: Int { get }
}
public protocol PilesRepositoryChanger {
func add(pileItem: PileItem)
func change(pileItem: PileItem, at index: Int)
}
public protocol PileItemRepositoryDelegate: PilesCountChangersListener, PileItemChangeListener {}
public protocol PilesCountChangersListener: PilesFetchedListener {
func onPileRemoved(at index: Int)
func onPileAdded(pile: PileItem, at index: Int)
}
public protocol PilesFetchedListener {
func onPilesFetched(_ pileItems: [PileItem])
}
public protocol PileItemChangeListener {
func onPileChanged(pile: PileItem, at index: Int)
}
public protocol RepositoryIndexFinder {
func repositoryIndexFor(section: Int, row: Int) -> Int?
}
|
//
// CollectionViewController.swift
// Virtual Tourist
//
// Created by SimranJot Singh on 16/04/17.
// Copyright © 2017 SimranJot Singh. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class CollectionViewController: UIViewController {
//MARK: Outlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var newCollectionButton: UIButton!
@IBOutlet weak var collectionView: UICollectionView!
//MARK: Properties
var pin: Pin? = nil
var insertedIndexPaths: [IndexPath]!
var deletedIndexPaths: [IndexPath]!
lazy var fetchedResultsController: NSFetchedResultsController < Photos > = {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Photos")
request.sortDescriptors = []
request.predicate = NSPredicate(format: "pin == %@", self.pin!)
return NSFetchedResultsController(fetchRequest: request as! NSFetchRequest< Photos >, managedObjectContext:
context, sectionNameKeyPath: nil, cacheName: nil)
}()
//MARK: LifeCycle Methods
override func viewDidLoad() {
super.viewDidLoad()
initFetchedResultsController()
fetchedResultsController.delegate = self;
navigationItem.rightBarButtonItem = editButtonItem
mapView.addAnnotation(pin!)
mapView.setRegion(MKCoordinateRegion(center: pin!.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)), animated: true)
mapView.isUserInteractionEnabled = false
collectionView.delegate = self
collectionView.dataSource = self
fetchedResultsController.delegate = self
}
override func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
setCollectionFlowLayout()
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
newCollectionButton.isEnabled = !editing
}
//MARK: Actions
@IBAction func newCollectionsTapped(_ sender: Any) {
loadNewCollection()
}
func backTapped() {
let _ = navigationController?.popViewController(animated: true)
}
//MARK: Helper Methods
func initFetchedResultsController() {
do {
try fetchedResultsController.performFetch()
} catch { }
if fetchedResultsController.fetchedObjects!.count == 0 {
loadNewCollection()
}
}
func setCollectionFlowLayout() {
let items: CGFloat = view.frame.size.width > view.frame.size.height ? 5.0 : 3.0
let space: CGFloat = 3.0
let dimension = (view.frame.size.width - ((items + 1) * space)) / items
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumLineSpacing = 8.0 - items
layout.minimumInteritemSpacing = space
layout.itemSize = CGSize(width: dimension, height: dimension)
collectionView.collectionViewLayout = layout
}
func loadNewCollection() {
newCollectionButton.isEnabled = false
pin?.deletePhotos(context: context) { _ in }
pin?.flickrConfig?.getPhotosForLocation(context: context) { _ in
DispatchQueue.main.async {
self.newCollectionButton.isEnabled = true
}
sharedDataManager.save()
}
}
}
//MARK: CollectionView Delegate Extension
extension CollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return fetchedResultsController.sections?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fetchedResultsController.sections![section].numberOfObjects
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.CollectionVC.CollectionViewCellIdentifier, for: indexPath) as! PhotoCollectionViewCell
let photo = fetchedResultsController.object(at: indexPath)
cell.image = photo
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if isEditing {
context.delete(fetchedResultsController.object(at: indexPath))
sharedDataManager.save()
}
}
}
//MARK: FetchedResultsController Delegates
extension CollectionViewController: NSFetchedResultsControllerDelegate {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
insertedIndexPaths.append(newIndexPath!)
case .delete:
deletedIndexPaths.append(indexPath!)
default: ()
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
collectionView.performBatchUpdates({
self.collectionView.insertItems(at: self.insertedIndexPaths)
self.collectionView.deleteItems(at: self.deletedIndexPaths)
}, completion: nil)
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
insertedIndexPaths = []
deletedIndexPaths = []
}
}
|
//
// NewCity.swift
// WeatherMan
//
// Created by Jesse Tayler on 8/8/19.
// Copyright © 2019 Jesse Tayler. All rights reserved.
//
import SwiftUI
struct NewCity : View {
@State var search = ""
@State private var isValidating = false
@ObservedObject private var completer = CityCompletion()
@Binding var isPresentingSearch: Bool
@EnvironmentObject var cityStore: CityStore
var body: some View {
NavigationView {
List {
Section {
TextField("Search City", text: $search, onEditingChanged: { changed in
print("onEditing: \(changed)")
self.searchNearby()
})
.onAppear { self.searchNearby() }
.textFieldStyle(RoundedBorderTextFieldStyle())
.onReceive(search.publisher.last(), perform: { _search in self.searchNearby() })
}
Section {
ForEach(completer.predictions) { prediction in
Button(action: {
self.addCity(from: prediction)
}) {
Text(prediction.description)
}
}
}
}
.listStyle(GroupedListStyle())
.disabled(isValidating)
.navigationBarTitle("Add City")
.navigationBarItems(trailing: doneButton)
}
}
private func searchNearby() {
DispatchQueue.main.async {
print("\n search.publisher() \(self.search)")
self.completer.search(self.search)
}
}
private var doneButton: some View {
Button(action: {
self.isPresentingSearch = false
}) {
Text("Done")
}
}
private func addCity(from prediction: CityCompletion.Prediction) {
isValidating = true
print("adding city \(prediction)")
CityValidationManager.validateCity(withID: prediction.id) { (city) in
if let city = city {
print("found city \(city)")
DispatchQueue.main.async {
self.isPresentingSearch = false
self.cityStore.cities.append(city)
}
}
DispatchQueue.main.async {
self.isValidating = false
}
}
}
}
//#if DEBUG
//struct NewCity_Previews : PreviewProvider {
// static var previews: some View {
// NewCity(isPresentingSearch: self.$isPresentingSearch)
// }
//}
//#endif
|
//
// ObservableVariable.swift
// SailingThroughHistory
//
// Created by henry on 17/3/19.
// Copyright © 2019 Sailing Through History Team. All rights reserved.
//
/// Serves as an adapter for observable containers
import Foundation
protocol ObservableVariable {
associatedtype Element: Any
func subscribe(onNext: @escaping (Element) -> Void, onError: @escaping (Error?) -> Void, onDisposed: (() -> Void)?)
func subscribe(with observer: @escaping (Element) -> Void)
}
|
//
// ChangePW.swift
// YumaApp
//
// Created by Yuma Usa on 2018-05-09.
// Copyright © 2018 Yuma Usa. All rights reserved.
//
import UIKit
protocol PopupDelegate
{
func popupValueSelected(value: String)
}
private let reuseIdentifier = "helpCell"
class ChangePW: UIViewController, UIGestureRecognizerDelegate
{
let store = DataStore.sharedInstance
let dialogWindow: UIView =
{
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.white
view.isUserInteractionEnabled = true
view.cornerRadius = 20
view.shadowColor = R.color.YumaDRed
view.shadowRadius = 5
view.shadowOffset = .zero
view.shadowOpacity = 1
return view
}()
let titleLabel: UILabel =
{
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = R.color.YumaRed
view.text = "Title"
// view.cornerRadius = 20
view.clipsToBounds = true
view.layer.masksToBounds = true
view.textColor = UIColor.white
view.textAlignment = .center
let titleShadow: NSShadow =
{
let view = NSShadow()
view.shadowColor = UIColor.black
view.shadowOffset = CGSize(width: 1, height: 1)
return view
}()
view.attributedText = NSAttributedString(string: view.text!, attributes: [NSAttributedStringKey.font : UIFont(name: "AvenirNext-Bold", size: 20)!, NSAttributedStringKey.shadow : titleShadow])
view.font = UIFont(name: "ArialRoundedMTBold", size: 20)
view.shadowColor = UIColor.black
view.shadowRadius = 3
view.shadowOffset = CGSize(width: 1, height: 1)
return view
}()
let exisiting: InputField =
{
let view = InputField(frame: .zero, inputType: .hiddenLikePassword, hasShowHideIcon: true)
view.translatesAutoresizingMaskIntoConstraints = false
view.label.text = R.string.exist
view.label.textColor = UIColor.darkGray
view.inputType = .hiddenLikePassword
view.displayShowHideIcon = true
return view
}()
let generate: UILabel =
{
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.text = R.string.generate
view.textColor = R.color.YumaRed
view.shadowColor = R.color.YumaYel
view.shadowOffset = CGSize(width: 1, height: 1)
view.shadowRadius = 3
//NEVER PLACE GESTURE-RECOGNIOSERS HERE
//view.isUserInteractionEnabled = true
//view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(doGenerate(_:))))
return view
}()
let newPW: InputField =
{
let view = InputField(frame: .zero, inputType: .hiddenLikePassword, hasShowHideIcon: true)
view.translatesAutoresizingMaskIntoConstraints = false
view.label.text = R.string.newPW
view.label.textColor = UIColor.darkGray
view.inputType = .hiddenLikePassword
view.displayShowHideIcon = true
return view
}()
let verifyPW: InputField =
{
let view = InputField(frame: .zero, inputType: .hiddenLikePassword, hasShowHideIcon: true)
view.translatesAutoresizingMaskIntoConstraints = false
view.label.text = R.string.verify
view.label.textColor = UIColor.darkGray
view.inputType = .hiddenLikePassword
view.displayShowHideIcon = true
return view
}()
let buttonLeft: GradientButton =
{
let view = GradientButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.setTitle(R.string.cancel.uppercased(), for: .normal)
view.titleLabel?.shadowOffset = CGSize(width: 2, height: 2)
view.titleLabel?.shadowRadius = 3
view.titleLabel?.textColor = UIColor.white
view.setTitleShadowColor(R.color.YumaDRed, for: .normal)
//view.widthAnchor.constraint(equalToConstant: 200).isActive = true
view.backgroundColor = R.color.YumaRed.withAlphaComponent(0.8)
view.cornerRadius = 3
view.shadowColor = UIColor.darkGray
view.shadowOffset = CGSize(width: 1, height: 1)
view.shadowRadius = 3
view.borderColor = R.color.YumaDRed
view.borderWidth = 1
// view.shadowOpacity = 0.9
let titleShadow: NSShadow =
{
let view = NSShadow()
view.shadowColor = UIColor.black
// view.shadowRadius = 3
view.shadowOffset = CGSize(width: 1, height: 1)
return view
}()
view.setAttributedTitle(NSAttributedString(string: view.title(for: .normal)!, attributes: [NSAttributedStringKey.font : UIFont(name: "AvenirNext-DemiBold", size: 17)!, NSAttributedStringKey.shadow : titleShadow]), for: .normal)
view.layer.addBackgroundGradient(colors: [R.color.YumaRed, R.color.YumaYel], isVertical: true)
view.layer.addGradienBorder(colors: [R.color.YumaYel, R.color.YumaRed], width: 3.6, isVertical: true)
return view
}()
let buttonRight: GradientButton =
{
let view = GradientButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.setTitle(R.string.cont.uppercased(), for: .normal)
view.titleLabel?.shadowOffset = CGSize(width: 2, height: 2)
view.titleLabel?.shadowRadius = 3
view.titleLabel?.textColor = UIColor.white
view.setTitleShadowColor(R.color.YumaDRed, for: .normal)
//view.widthAnchor.constraint(equalToConstant: 200).isActive = true
view.backgroundColor = R.color.YumaRed.withAlphaComponent(0.8)
view.cornerRadius = 3
view.shadowColor = UIColor.darkGray
view.shadowOffset = CGSize(width: 1, height: 1)
view.shadowRadius = 3
view.borderColor = R.color.YumaDRed
view.borderWidth = 1
// view.shadowOpacity = 0.9
let titleShadow: NSShadow =
{
let view = NSShadow()
view.shadowColor = UIColor.black
// view.shadowRadius = 3
view.shadowOffset = CGSize(width: 1, height: 1)
return view
}()
view.setAttributedTitle(NSAttributedString(string: view.title(for: .normal)!, attributes: [NSAttributedStringKey.font : UIFont(name: "AvenirNext-DemiBold", size: 17)!, NSAttributedStringKey.shadow : titleShadow]), for: .normal)
view.layer.addBackgroundGradient(colors: [R.color.YumaRed, R.color.YumaYel], isVertical: true)
view.layer.addGradienBorder(colors: [R.color.YumaYel, R.color.YumaRed], width: 3.6, isVertical: true)
return view
}()
let backgroundAlpha: CGFloat = 0.7
let titleBarHeight: CGFloat = 50
let buttonHeight: CGFloat = 42
let minWidth: CGFloat = 300
let maxWidth: CGFloat = 600
let minHeight: CGFloat = 420
let maxHeight: CGFloat = 800
var dialogWidth: CGFloat = 0
var dialogHeight: CGFloat = 0
var delegate: PopupDelegate?
// let redArea = UIView()
//let blueArea = UIView()
// let greenArea = UIView()
// let purpleArea = UIView()
let stack: UIStackView =
{
let view = UIStackView()
return view
}()
// MARK: Overrides
override func viewDidLoad()
{
super.viewDidLoad()
dialogWidth = min(max(view.frame.width/2, minWidth), maxWidth)
dialogHeight = min(max(view.frame.height/2, minHeight), maxHeight)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.view.backgroundColor = R.color.YumaRed.withAlphaComponent(self.backgroundAlpha)
}, completion: nil)
drawTitle()
drawFields()
drawButton()
let str = "V:|[v0(\(titleBarHeight))]-5-[v1]-5-[v2(\(buttonHeight))]-5-|"
dialogWindow.addConstraintsWithFormat(format: str, views: titleLabel, stack, buttonLeft)
drawDialog()
// 2018-06-23 12:39:35.410 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7820 H:|-(10)-[UITextField:0x171a4530] (Names: '|':UIView:0x15d45060 )>",
// "<NSLayoutConstraint:0x171c7aa0 H:[UITextField:0x171a4530]-(4)-[UILabel:0x171ae4b0'\Uf06e']>",
// "<NSLayoutConstraint:0x171c7b00 H:[UILabel:0x171ae4b0'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171c7ad0 H:[UILabel:0x171ae4b0'\Uf06e']-(10)-| (Names: '|':UIView:0x15d45060 )>",
// "<NSLayoutConstraint:0x171c7e20 H:|-(10)-[UILabel:0x171bf8f0'Exisiting'] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7f10 H:[UILabel:0x171bf8f0'Exisiting'(120)]>",
// "<NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>",
// "<NSLayoutConstraint:0x171c7f80 H:[UIView:0x15d45060]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x172a5b20 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7aa0 H:[UITextField:0x171a4530]-(4)-[UILabel:0x171ae4b0'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.414 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7e20 H:|-(10)-[UILabel:0x171bf8f0'Exisiting'] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7f10 H:[UILabel:0x171bf8f0'Exisiting'(120)]>",
// "<NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>",
// "<NSLayoutConstraint:0x171c7f80 H:[UIView:0x15d45060]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x172a5b20 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.417 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7d60 H:|-(10)-[UILabel:0x171a3730] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7df0 H:[UILabel:0x171a3730]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x172a5b20 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7df0 H:[UILabel:0x171a3730]-(10)-| (Names: '|':UIView:0x17293fb0 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.428 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cb750 H:|-(10)-[UITextField:0x171c8b70] (Names: '|':UIView:0x171c8a80 )>",
// "<NSLayoutConstraint:0x171cb820 H:[UITextField:0x171c8b70]-(4)-[UILabel:0x171c9640'\Uf06e']>",
// "<NSLayoutConstraint:0x171cb880 H:[UILabel:0x171c9640'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171cb850 H:[UILabel:0x171c9640'\Uf06e']-(10)-| (Names: '|':UIView:0x171c8a80 )>",
// "<NSLayoutConstraint:0x171cba90 H:|-(10)-[UILabel:0x171c8790'New password'] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbb80 H:[UILabel:0x171c8790'New password'(120)]>",
// "<NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>",
// "<NSLayoutConstraint:0x171cbbf0 H:[UIView:0x171c8a80]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x172a8120 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cb820 H:[UITextField:0x171c8b70]-(4)-[UILabel:0x171c9640'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.431 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cba90 H:|-(10)-[UILabel:0x171c8790'New password'] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbb80 H:[UILabel:0x171c8790'New password'(120)]>",
// "<NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>",
// "<NSLayoutConstraint:0x171cbbf0 H:[UIView:0x171c8a80]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x172a8120 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.435 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cb9c0 H:|-(10)-[UILabel:0x171c9360] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cba60 H:[UILabel:0x171c9360]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x172a8120 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cba60 H:[UILabel:0x171c9360]-(10)-| (Names: '|':UIView:0x171c86d0 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.446 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cef00 H:|-(10)-[UITextField:0x171cc4c0] (Names: '|':UIView:0x171cc400 )>",
// "<NSLayoutConstraint:0x171cefd0 H:[UITextField:0x171cc4c0]-(4)-[UILabel:0x171ccf10'\Uf06e']>",
// "<NSLayoutConstraint:0x171cf030 H:[UILabel:0x171ccf10'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171cf000 H:[UILabel:0x171ccf10'\Uf06e']-(10)-| (Names: '|':UIView:0x171cc400 )>",
// "<NSLayoutConstraint:0x171cf240 H:|-(10)-[UILabel:0x171cc2f0'Verify'] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf330 H:[UILabel:0x171cc2f0'Verify'(120)]>",
// "<NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>",
// "<NSLayoutConstraint:0x171cf3a0 H:[UIView:0x171cc400]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171dc250 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cefd0 H:[UITextField:0x171cc4c0]-(4)-[UILabel:0x171ccf10'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.449 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cf240 H:|-(10)-[UILabel:0x171cc2f0'Verify'] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf330 H:[UILabel:0x171cc2f0'Verify'(120)]>",
// "<NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>",
// "<NSLayoutConstraint:0x171cf3a0 H:[UIView:0x171cc400]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171dc250 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.452 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cf170 H:|-(10)-[UILabel:0x171ccc30] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf210 H:[UILabel:0x171ccc30]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171dc250 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cf210 H:[UILabel:0x171ccc30]-(10)-| (Names: '|':UIView:0x171cc230 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.464 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7820 H:|-(10)-[UITextField:0x171a4530] (Names: '|':UIView:0x15d45060 )>",
// "<NSLayoutConstraint:0x171c7aa0 H:[UITextField:0x171a4530]-(4)-[UILabel:0x171ae4b0'\Uf06e']>",
// "<NSLayoutConstraint:0x171c7b00 H:[UILabel:0x171ae4b0'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171c7ad0 H:[UILabel:0x171ae4b0'\Uf06e']-(10)-| (Names: '|':UIView:0x15d45060 )>",
// "<NSLayoutConstraint:0x171c7e20 H:|-(10)-[UILabel:0x171bf8f0'Exisiting'] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7f10 H:[UILabel:0x171bf8f0'Exisiting'(120)]>",
// "<NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>",
// "<NSLayoutConstraint:0x171c7f80 H:[UIView:0x15d45060]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x172aa3c0 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7aa0 H:[UITextField:0x171a4530]-(4)-[UILabel:0x171ae4b0'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.468 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7e20 H:|-(10)-[UILabel:0x171bf8f0'Exisiting'] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7f10 H:[UILabel:0x171bf8f0'Exisiting'(120)]>",
// "<NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>",
// "<NSLayoutConstraint:0x171c7f80 H:[UIView:0x15d45060]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x172aa3c0 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.473 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7d60 H:|-(10)-[UILabel:0x171a3730] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7df0 H:[UILabel:0x171a3730]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x172aa3c0 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7df0 H:[UILabel:0x171a3730]-(10)-| (Names: '|':UIView:0x17293fb0 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.488 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cb750 H:|-(10)-[UITextField:0x171c8b70] (Names: '|':UIView:0x171c8a80 )>",
// "<NSLayoutConstraint:0x171cb820 H:[UITextField:0x171c8b70]-(4)-[UILabel:0x171c9640'\Uf06e']>",
// "<NSLayoutConstraint:0x171cb880 H:[UILabel:0x171c9640'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171cb850 H:[UILabel:0x171c9640'\Uf06e']-(10)-| (Names: '|':UIView:0x171c8a80 )>",
// "<NSLayoutConstraint:0x171cba90 H:|-(10)-[UILabel:0x171c8790'New password'] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbb80 H:[UILabel:0x171c8790'New password'(120)]>",
// "<NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>",
// "<NSLayoutConstraint:0x171cbbf0 H:[UIView:0x171c8a80]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x15e3b520 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cb820 H:[UITextField:0x171c8b70]-(4)-[UILabel:0x171c9640'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.491 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cba90 H:|-(10)-[UILabel:0x171c8790'New password'] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbb80 H:[UILabel:0x171c8790'New password'(120)]>",
// "<NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>",
// "<NSLayoutConstraint:0x171cbbf0 H:[UIView:0x171c8a80]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x15e3b520 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.497 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cb9c0 H:|-(10)-[UILabel:0x171c9360] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cba60 H:[UILabel:0x171c9360]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x15e3b520 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cba60 H:[UILabel:0x171c9360]-(10)-| (Names: '|':UIView:0x171c86d0 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.508 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cef00 H:|-(10)-[UITextField:0x171cc4c0] (Names: '|':UIView:0x171cc400 )>",
// "<NSLayoutConstraint:0x171cefd0 H:[UITextField:0x171cc4c0]-(4)-[UILabel:0x171ccf10'\Uf06e']>",
// "<NSLayoutConstraint:0x171cf030 H:[UILabel:0x171ccf10'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171cf000 H:[UILabel:0x171ccf10'\Uf06e']-(10)-| (Names: '|':UIView:0x171cc400 )>",
// "<NSLayoutConstraint:0x171cf240 H:|-(10)-[UILabel:0x171cc2f0'Verify'] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf330 H:[UILabel:0x171cc2f0'Verify'(120)]>",
// "<NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>",
// "<NSLayoutConstraint:0x171cf3a0 H:[UIView:0x171cc400]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171e1c80 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cefd0 H:[UITextField:0x171cc4c0]-(4)-[UILabel:0x171ccf10'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.512 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cf240 H:|-(10)-[UILabel:0x171cc2f0'Verify'] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf330 H:[UILabel:0x171cc2f0'Verify'(120)]>",
// "<NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>",
// "<NSLayoutConstraint:0x171cf3a0 H:[UIView:0x171cc400]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171e1c80 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.516 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cf170 H:|-(10)-[UILabel:0x171ccc30] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf210 H:[UILabel:0x171ccc30]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171e1c80 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cf210 H:[UILabel:0x171ccc30]-(10)-| (Names: '|':UIView:0x171cc230 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.530 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x15edbbb0 H:|-(0)-[YumaApp.InputField:0x17293bb0] (Names: '|':UIStackView:0x17291860 )>",
// "<NSLayoutConstraint:0x15defd00 H:|-(100)-[UILabel:0x171c8490'Generate'] (Names: '|':UIStackView:0x17291860 )>",
// "<NSLayoutConstraint:0x171e3660 'UISV-alignment' YumaApp.InputField:0x17293bb0.leading == UILabel:0x171c8490'Generate'.leading>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171e3660 'UISV-alignment' YumaApp.InputField:0x17293bb0.leading == UILabel:0x171c8490'Generate'.leading>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.541 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7820 H:|-(10)-[UITextField:0x171a4530] (Names: '|':UIView:0x15d45060 )>",
// "<NSLayoutConstraint:0x171c7aa0 H:[UITextField:0x171a4530]-(4)-[UILabel:0x171ae4b0'\Uf06e']>",
// "<NSLayoutConstraint:0x171c7b00 H:[UILabel:0x171ae4b0'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171c7ad0 H:[UILabel:0x171ae4b0'\Uf06e']-(10)-| (Names: '|':UIView:0x15d45060 )>",
// "<NSLayoutConstraint:0x171c7e20 H:|-(10)-[UILabel:0x171bf8f0'Exisiting'] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7f10 H:[UILabel:0x171bf8f0'Exisiting'(120)]>",
// "<NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>",
// "<NSLayoutConstraint:0x171c7f80 H:[UIView:0x15d45060]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171e5c40 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7aa0 H:[UITextField:0x171a4530]-(4)-[UILabel:0x171ae4b0'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.545 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7e20 H:|-(10)-[UILabel:0x171bf8f0'Exisiting'] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7f10 H:[UILabel:0x171bf8f0'Exisiting'(120)]>",
// "<NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>",
// "<NSLayoutConstraint:0x171c7f80 H:[UIView:0x15d45060]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171e5c40 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7f50 H:[UILabel:0x171bf8f0'Exisiting']-(10)-[UIView:0x15d45060]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.550 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171c7d60 H:|-(10)-[UILabel:0x171a3730] (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c7df0 H:[UILabel:0x171a3730]-(10)-| (Names: '|':UIView:0x17293fb0 )>",
// "<NSLayoutConstraint:0x171c8330 H:|-(0)-[UIView:0x17293fb0] (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171c8380 H:[UIView:0x17293fb0]-(0)-| (Names: '|':YumaApp.InputField:0x17293bb0 )>",
// "<NSLayoutConstraint:0x171e5c40 'fittingSizeHTarget' H:[YumaApp.InputField:0x17293bb0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171c7df0 H:[UILabel:0x171a3730]-(10)-| (Names: '|':UIView:0x17293fb0 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.560 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cb750 H:|-(10)-[UITextField:0x171c8b70] (Names: '|':UIView:0x171c8a80 )>",
// "<NSLayoutConstraint:0x171cb820 H:[UITextField:0x171c8b70]-(4)-[UILabel:0x171c9640'\Uf06e']>",
// "<NSLayoutConstraint:0x171cb880 H:[UILabel:0x171c9640'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171cb850 H:[UILabel:0x171c9640'\Uf06e']-(10)-| (Names: '|':UIView:0x171c8a80 )>",
// "<NSLayoutConstraint:0x171cba90 H:|-(10)-[UILabel:0x171c8790'New password'] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbb80 H:[UILabel:0x171c8790'New password'(120)]>",
// "<NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>",
// "<NSLayoutConstraint:0x171cbbf0 H:[UIView:0x171c8a80]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171e85f0 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cb820 H:[UITextField:0x171c8b70]-(4)-[UILabel:0x171c9640'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.564 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cba90 H:|-(10)-[UILabel:0x171c8790'New password'] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbb80 H:[UILabel:0x171c8790'New password'(120)]>",
// "<NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>",
// "<NSLayoutConstraint:0x171cbbf0 H:[UIView:0x171c8a80]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171e85f0 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cbbc0 H:[UILabel:0x171c8790'New password']-(10)-[UIView:0x171c8a80]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.567 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cb9c0 H:|-(10)-[UILabel:0x171c9360] (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cba60 H:[UILabel:0x171c9360]-(10)-| (Names: '|':UIView:0x171c86d0 )>",
// "<NSLayoutConstraint:0x171cbf70 H:|-(0)-[UIView:0x171c86d0] (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171cbfe0 H:[UIView:0x171c86d0]-(0)-| (Names: '|':YumaApp.InputField:0x171c85a0 )>",
// "<NSLayoutConstraint:0x171e85f0 'fittingSizeHTarget' H:[YumaApp.InputField:0x171c85a0(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cba60 H:[UILabel:0x171c9360]-(10)-| (Names: '|':UIView:0x171c86d0 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.579 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cef00 H:|-(10)-[UITextField:0x171cc4c0] (Names: '|':UIView:0x171cc400 )>",
// "<NSLayoutConstraint:0x171cefd0 H:[UITextField:0x171cc4c0]-(4)-[UILabel:0x171ccf10'\Uf06e']>",
// "<NSLayoutConstraint:0x171cf030 H:[UILabel:0x171ccf10'\Uf06e'(21)]>",
// "<NSLayoutConstraint:0x171cf000 H:[UILabel:0x171ccf10'\Uf06e']-(10)-| (Names: '|':UIView:0x171cc400 )>",
// "<NSLayoutConstraint:0x171cf240 H:|-(10)-[UILabel:0x171cc2f0'Verify'] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf330 H:[UILabel:0x171cc2f0'Verify'(120)]>",
// "<NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>",
// "<NSLayoutConstraint:0x171cf3a0 H:[UIView:0x171cc400]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x172b9960 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cefd0 H:[UITextField:0x171cc4c0]-(4)-[UILabel:0x171ccf10'']>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.582 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cf240 H:|-(10)-[UILabel:0x171cc2f0'Verify'] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf330 H:[UILabel:0x171cc2f0'Verify'(120)]>",
// "<NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>",
// "<NSLayoutConstraint:0x171cf3a0 H:[UIView:0x171cc400]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x172b9960 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cf370 H:[UILabel:0x171cc2f0'Verify']-(10)-[UIView:0x171cc400]>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
// 2018-06-23 12:39:35.586 YumaApp[45137:4391137] Unable to simultaneously satisfy constraints.
// Probably at least one of the constraints in the following list is one you don't want.
// Try this:
// (1) look at each constraint and try to figure out which you don't expect;
// (2) find the code that added the unwanted constraint or constraints and fix it.
// (
// "<NSLayoutConstraint:0x171cf170 H:|-(10)-[UILabel:0x171ccc30] (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf210 H:[UILabel:0x171ccc30]-(10)-| (Names: '|':UIView:0x171cc230 )>",
// "<NSLayoutConstraint:0x171cf720 H:|-(0)-[UIView:0x171cc230] (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x171cf790 H:[UIView:0x171cc230]-(0)-| (Names: '|':YumaApp.InputField:0x171cc100 )>",
// "<NSLayoutConstraint:0x172b9960 'fittingSizeHTarget' H:[YumaApp.InputField:0x171cc100(0)]>"
// )
//
// Will attempt to recover by breaking constraint
// <NSLayoutConstraint:0x171cf210 H:[UILabel:0x171ccc30]-(10)-| (Names: '|':UIView:0x171cc230 )>
//
// Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
// The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
_ = buttonLeft.addBackgroundGradient(colors: [R.color.YumaRed.cgColor, R.color.YumaYel.cgColor], isVertical: true)
buttonLeft.layer.addGradienBorder(colors: [R.color.YumaYel, R.color.YumaRed], width: 4, isVertical: true)
_ = buttonRight.addBackgroundGradient(colors: [R.color.YumaRed.cgColor, R.color.YumaYel.cgColor], isVertical: true)
buttonRight.layer.addGradienBorder(colors: [R.color.YumaYel, R.color.YumaRed], width: 4, isVertical: true)
}
override var keyCommands: [UIKeyCommand]?
{
return [
UIKeyCommand(input: UIKeyInputEscape,
modifierFlags: [],
action: #selector(self.buttonLeftTapped),
discoverabilityTitle: NSLocalizedString("CloseWindow", comment: "Close window"))
]
}
// MARK: Methods
private func drawTitle()
{
titleLabel.text = R.string.changePass.uppercased()
dialogWindow.addSubview(titleLabel)
dialogWindow.addConstraintsWithFormat(format: "H:|[v0]|", views: titleLabel)
}
func drawFields()
{
generate.isUserInteractionEnabled = true
generate.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(doGenerate(_:))))
clearErrors()
stack.addArrangedSubview(exisiting)
stack.addArrangedSubview(generate)
stack.addArrangedSubview(newPW)
stack.addArrangedSubview(verifyPW)
stack.spacing = 5
stack.isUserInteractionEnabled = true
stack.translatesAutoresizingMaskIntoConstraints = false
stack.distribution = .fillProportionally
stack.axis = .vertical
stack.addConstraintsWithFormat(format: "H:|[v0]|", views: exisiting)
stack.addConstraintsWithFormat(format: "H:|-100-[v0]|", views: generate)
stack.addConstraintsWithFormat(format: "H:|[v0]|", views: newPW)
stack.addConstraintsWithFormat(format: "H:|[v0]|", views: verifyPW)
// stack.addConstraintsWithFormat(format: "V:|[v0(90)][v1]-5-[v2(90)]-5-[v3(90)]|", views: exisiting, generate, newPW, verifyPW)
dialogWindow.addSubview(stack)
// dialogWindow.addConstraintsWithFormat(format: "V:[v0]", views: stack)
dialogWindow.addConstraintsWithFormat(format: "H:|[v0]|", views: stack)
exisiting.invalid.text = "\(R.string.wrong) \(R.string.txtPass)"
newPW.invalid.text = "\(R.string.invalid) \(R.string.txtPass) - \(R.string.minPass)"
verifyPW.invalid.text = "\(R.string.txtPass) \(R.string.mismatch)"
}
func clearErrors()
{
exisiting.fieldFrame.borderColor = UIColor.clear
exisiting.invalid.alpha = 0
newPW.invalid.alpha = 0
verifyPW.invalid.alpha = 0
newPW.fieldFrame.borderColor = UIColor.clear
verifyPW.fieldFrame.borderColor = UIColor.clear
}
func drawButton()
{
buttonLeft.setTitle(R.string.dismiss.uppercased(), for: .normal)
buttonRight.setTitle(R.string.complete.uppercased(), for: .normal)
dialogWindow.addSubview(buttonLeft)
dialogWindow.addSubview(buttonRight)
dialogWindow.addConstraintsWithFormat(format: "H:|-15-[v0(\(dialogWidth/3))]", views: buttonLeft)
dialogWindow.addConstraintsWithFormat(format: "H:[v0(\(dialogWidth/3))]-15-|", views: buttonRight)
dialogWindow.addConstraint(NSLayoutConstraint(item: buttonLeft, attribute: .centerY, relatedBy: .equal, toItem: buttonRight, attribute: .centerY, multiplier: 1, constant: 0))
dialogWindow.addConstraint(NSLayoutConstraint(item: buttonRight, attribute: .height, relatedBy: .equal, toItem: dialogWindow, attribute: .height, multiplier: 0, constant: buttonHeight))
buttonLeft.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buttonLeftTapped(_:))))
buttonRight.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buttonRightTapped(_:))))
}
func drawDialog()
{
view.addSubview(dialogWindow)
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0, constant: dialogWidth+10))
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0, constant: dialogHeight+10))
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0))
}
private func checkFields() -> Bool
{
var success = true
clearErrors()
if exisiting.textEdit.text == nil || (exisiting.textEdit.text?.isEmpty)!
{
exisiting.invalid.alpha = 1
exisiting.fieldFrame.borderColor = UIColor.red
success = false
}
if newPW.textEdit.text == nil || (newPW.textEdit.text?.isEmpty)! || !isValid(.passwd, newPW.textEdit.text!)
{
newPW.invalid.alpha = 1
newPW.fieldFrame.borderColor = UIColor.red
success = false
}
if verifyPW.textEdit.text == nil || (verifyPW.textEdit.text?.isEmpty)! || verifyPW.textEdit.text != newPW.textEdit.text
{
verifyPW.invalid.alpha = 1
verifyPW.fieldFrame.borderColor = UIColor.red
success = false
}
return success
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
@objc func buttonLeftTapped(_ sender: UITapGestureRecognizer?)
{
store.flexView(view: buttonLeft)
self.dismiss(animated: true, completion: nil)
}
@objc func buttonRightTapped(_ sender: UITapGestureRecognizer)
{
store.flexView(view: buttonRight)
if checkFields()
{
delegate?.popupValueSelected(value: newPW.textEdit.text!)
self.dismiss(animated: true, completion: nil)
}
// else
// {
// newPW.invalid.alpha = 1
// newPW.fieldFrame.borderColor = .red
// }
}
@objc func doGenerate(_ sender: UITapGestureRecognizer)
{
if isValid(.passwd, newPW.textEdit.text!) && ((newPW.textEdit.text != nil && !(newPW.textEdit.text?.isEmpty)!) || (verifyPW.textEdit.text != nil && !(verifyPW.textEdit.text?.isEmpty)!))
{
OperationQueue.main.addOperation
{
myAlertOKCancel(self, title: R.string.txtPass, message: R.string.overw, okAction: {
let (passwd, formatted) = self.store.makePassword()
self.newPW.textEdit.text = passwd
self.verifyPW.textEdit.text = passwd
self.store.myAlert(title: R.string.txtPass, message: "", attributedMessage: formatted, viewController: self)
}, cancelAction: {
}, completion: {
})
}
}
else
{
let (passwd, formatted) = store.makePassword()
newPW.textEdit.text = passwd
verifyPW.textEdit.text = passwd
store.myAlert(title: R.string.txtPass, message: "", attributedMessage: formatted, viewController: self)
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.