text stringlengths 8 1.32M |
|---|
//
// HomeCollectionViewController.swift
// CP103D_Topic0308
//
// Created by min-chia on 2019/3/27.
// Copyright © 2019 min-chia. All rights reserved.
//
import UIKit
private let reuseIdentifier = "homeCollectionViewCell"
class HomeCollectionViewController: UICollectionViewController {
var goods = [Good]()
var goodDetail = Good.init(id: -1, name: "-1", descrip: "-1", price: -1, mainclass: "-1", subclass: "-1", shelf: "-1", evulation: -1, color1: "-1", color2: "-1", size1: "-1", size2: "-1", specialPrice: -1, quatity: -1)
let url_server = URL(string: common_url + "GoodsServlet1")
func tableViewAddRefreshControl() { // refresh
let refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(showAllGoods), for: .valueChanged)
self.collectionView.refreshControl = refreshControl
}
override func viewDidLoad() {
super.viewDidLoad()
setCellsize()
tableViewAddRefreshControl()
showAllGoods()
// Do any additional setup after loading the view.
}
func setCellsize(){
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
// Cell的大小
let cellwidth = (UIScreen.main.bounds.size.width - CGFloat(8*3))/2
layout.itemSize = CGSize(width: cellwidth, height: cellwidth)
// 同一列Cell之間的間距
layout.minimumInteritemSpacing = 8
// 列和列之間的間距
layout.minimumLineSpacing = 20
// Section的邊界
layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
}
// 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 controller = segue.destination as! GooddetailViewController
controller.goodDetail = sender as! Good
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return goods.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HomeCollectionViewCell
// 尚未取得圖片,另外開啟task請求
var requestParam = [String: Any]()
requestParam["param"] = "getImage"
requestParam["id"] = goods[indexPath.row].id
// 圖片寬度為tableViewCell的1/4,ImageView的寬度也建議在storyboard加上比例設定的constraint
requestParam["imageSize"] = cell.frame.width / 4
var image: UIImage?
executeTask(url_server!, requestParam) { (data, response, error) in
if error == nil {
if data != nil {
image = UIImage(data: data!)
}
if image == nil {
image = UIImage(named: "noImage.jpg")
}
DispatchQueue.main.async { cell.homecellImageview.image = image }
} else {
print(error!.localizedDescription)
}
}
cell.homecellLabel.text = goods[indexPath.row].name
goodDetail = goods[indexPath.row]
return cell }
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let goodDetail = goods[indexPath.row]
performSegue(withIdentifier: "home", sender: goodDetail)
}
// MARK: UICollectionViewDelegate
@objc func showAllGoods(){
var requestParam = [String: String]()
requestParam["param"] = "consumerGetAll"
executeTask(url_server!, requestParam) { (data, response, error) in
let decoder = JSONDecoder()
// JSON含有日期時間,解析必須指定日期時間格式
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(format)
if error == nil {
if data != nil {
print("input: \(String(data: data!, encoding: .utf8)!)")
do{
self.goods = try decoder.decode([Good].self, from: data!)
DispatchQueue.main.async {
if let control = self.collectionView.refreshControl {
if control.isRefreshing {
// 停止下拉更新動作
control.endRefreshing()
}
}
self.collectionView.reloadData()
}
}catch{
print(error)
}
}
} else {
print(error!.localizedDescription)
}
}
}
}
|
//
// List.swift
//
//
// Created by OMER on 15.11.2015.
//
//
import Foundation
import CoreData
@objc(List)
class List: NSManagedObject {
@NSManaged var item: String
@NSManaged var note: String
@NSManaged var qty: String
}
|
//
// CurrentWeather.swift
// Weather-Events-News App
//
// Created by Michael Cmiel on 1/17/15.
// Copyright (c) 2015 PoKoBros. All rights reserved.
//
import Foundation
import UIKit
struct Current {
var maxTemp: Int
var minTemp: Int
var currentTemp: Int
var summary: String
// Hourly Temperatures
var firstTemp: Int
var secondTemp: Int
var thirdTemp: Int
var fourthTemp: Int
var fifthTemp: Int
// Hourly Hours
var firstHour: Int
var secondHour: Int
var thirdHour: Int
var fourthHour: Int
var fifthHour: Int
// Hourly Icons
var firstIcon: UIImage?
var secondIcon: UIImage?
var thirdIcon: UIImage?
var fourthIcon: UIImage?
var fifthIcon: UIImage?
init(weatherDictionary: NSDictionary) {
// Dictionaries and Arrays
let maxAndMinTempDict = weatherDictionary["daily"] as NSDictionary
let todayArray = maxAndMinTempDict["data"] as NSArray
let maxAndMinTemp = todayArray[0] as NSDictionary
let tempAndSummary = weatherDictionary["currently"] as NSDictionary
// Max Temperature
maxTemp = maxAndMinTemp["temperatureMax"] as Int
// Min Temperature
minTemp = maxAndMinTemp["temperatureMin"] as Int
// Current Temperature
currentTemp = tempAndSummary["temperature"] as Int
// Short Summary of the Day
summary = tempAndSummary["summary"] as String
// Hourly Dictionary
let hourlyDict = weatherDictionary["hourly"] as NSDictionary
let arrayOfHours = hourlyDict["data"] as NSArray
let firstHourDict = arrayOfHours[1] as NSDictionary
let secondHourDict = arrayOfHours[2] as NSDictionary
let thirdHourDict = arrayOfHours[3] as NSDictionary
let fourthHourDict = arrayOfHours[4] as NSDictionary
let fifthHourDict = arrayOfHours[5] as NSDictionary
// Set the hourly temperatures
firstTemp = firstHourDict["temperature"] as Int
secondTemp = secondHourDict["temperature"] as Int
thirdTemp = thirdHourDict["temperature"] as Int
fourthTemp = fourthHourDict["temperature"] as Int
fifthTemp = fifthHourDict["temperature"] as Int
//Set the hourly times
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: NSDate())
firstHour = components.hour + 1
secondHour = components.hour + 2
thirdHour = components.hour + 3
fourthHour = components.hour + 4
fifthHour = components.hour + 5
//Set the icons
let firstIconStr = firstHourDict["icon"] as String
firstIcon = weatherIconFromString(firstIconStr)
let secondIconStr = secondHourDict["icon"] as String
secondIcon = weatherIconFromString(secondIconStr)
let thirdIconStr = thirdHourDict["icon"] as String
thirdIcon = weatherIconFromString(thirdIconStr)
let fourthIconStr = fourthHourDict["icon"] as String
fourthIcon = weatherIconFromString(fourthIconStr)
let fifthIconStr = fifthHourDict["icon"] as String
fifthIcon = weatherIconFromString(fifthIconStr)
}
func weatherIconFromString(stringIcon: String) -> UIImage {
var imageName: String
switch stringIcon {
case "clear-day":
imageName = "clear-day"
case "clear-night":
imageName = "clear-night"
case "rain":
imageName = "rain"
case "snow":
imageName = "snow"
case "sleet":
imageName = "sleet"
case "wind":
imageName = "wind"
case "fog":
imageName = "fog"
case "cloudy":
imageName = "cloudy"
case "partly-cloudy-day":
imageName = "partly-cloudy"
case "partly-cloudy-night":
imageName = "cloudy-night"
default:
imageName = "default"
}
var iconName = UIImage(named: imageName)
return iconName!
}
}
|
import Foundation
enum Path: String {
case about = "about"
case office = "offices"
case apps = "apps"
case none
}
|
//
// OCRViewController.swift
// CoreML_test
//
// Created Осина П.М. on 19.02.18.
// Copyright © 2018 Осина П.М.. All rights reserved.
//
import UIKit
import CoreML
import Vision
class OCRViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var detectedText: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var presenter: OCRPresenter!
var model: VNCoreMLModel!
var request = [VNRequest]()
var textMetadata = [Int: [Int: String]]()
override func viewDidLoad() {
super.viewDidLoad()
loadModel()
activityIndicator.hidesWhenStopped = true
}
private func loadModel(){
model = try? VNCoreMLModel(for: Alphanum_28x28().model)
}
@IBAction func pickImageClicked(_ sender: UIButton){
let alertController = createActionSheet()
let action1 = UIAlertAction(title: "Camera", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.showImagePicker(withType: .camera)
})
let action2 = UIAlertAction(title: "Photos", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.showImagePicker(withType: .photoLibrary)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
addActionsToAlertController(controller: alertController,
actions: [action1, action2, cancelAction])
self.present(alertController, animated: true, completion: nil)
}
func showImagePicker(withType type: UIImagePickerControllerSourceType){
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = type
present(pickerController, animated: true, completion: nil)
}
func detectText(image: UIImage){
let convertedImage = image |> adjustColors |> convertToGrayscale
let handler = VNImageRequestHandler(cgImage: convertedImage.cgImage!)
let request: VNDetectTextRectanglesRequest =
VNDetectTextRectanglesRequest(completionHandler: {
[unowned self] (request, error) in
if (error != nil){
print("Got Error in run text detect request")
} else{
guard let results = request.results as? Array<VNTextObservation> else {
fatalError("Unexpected result type from VNDetectTextRectanglesRequest")
}
if (results.count == 0) {
self.handleEmptyResults()
return
}
var numberOfWords = 0
for textObsevation in results {
var numberOfCharacters = 0
for rectangleObservation in textObsevation.characterBoxes! {
let croppedImage = crop(image: image, rectangle: rectangleObservation)
if let croppedImage = croppedImage {
let processedImage = preProcess(image: croppedImage)
self.classifyImage(image: processedImage,
wordNumber: numberOfWords, characterNumber: numberOfCharacters)
numberOfCharacters += 1
}
}
numberOfWords += 1
}
}
})
request.reportCharacterBoxes = true
do {
try handler.perform([request])
}catch{
print(error)
}
}
func handleEmptyResults() {
DispatchQueue.main.async {
self.hideActivityIndicator()
self.detectedText.text = "The image does not contain any text"
}
}
func classifyImage(image: UIImage, wordNumber: Int, characterNumber: Int){
let request = VNCoreMLRequest(model: model) {
[weak self] request, error in
guard let results = request.results as? [VNClassificationObservation],
let topResult = results.first else {
fatalError("Unexpected result type from VNCoreMLRequest")
}
let result = topResult.identifier
let classificationInfo: [String: Any] = ["wordNumber" : wordNumber,
"characterNumber" : characterNumber,
"class" : result]
self?.handleResult(classificationInfo)
}
guard let ciImage = CIImage(image: image) else{
fatalError("Could not convert UIImage to CIImage :(")
}
let handler = VNImageRequestHandler(ciImage: ciImage)
DispatchQueue.global(qos: .userInteractive).async {
do {
try handler.perform([request])
}
catch{
print(error)
}
}
}
func handleResult(_ result: [String: Any]) {
objc_sync_enter(self)
guard let wordNumber = result["wordNumber"] as? Int else {
return
}
guard let characterNumber = result["characterNumber"] as? Int else {
return
}
guard let characterClass = result["class"] as? String else {
return
}
if (textMetadata[wordNumber] == nil){
let tmp: [Int: String] = [characterNumber: characterClass]
textMetadata[wordNumber] = tmp
} else{
var tmp = textMetadata[wordNumber]!
tmp[characterNumber] = characterClass
textMetadata[wordNumber] = tmp
}
objc_sync_exit(self)
DispatchQueue.main.async {
self.hideActivityIndicator()
self.showDetectedText()
}
}
func showDetectedText(){
var result: String = ""
if (textMetadata.isEmpty) {
detectedText.text = "The image does not contain any text."
return
}
let sortedKeys = textMetadata.keys.sorted()
for sortedKey in sortedKeys {
result += word(fromDictionary: textMetadata[sortedKey]!) + " "
}
detectedText.text = result
}
func word(fromDictionary dictionary: [Int : String]) -> String{
let sortedKeys = dictionary.keys.sorted()
var word: String = ""
for sortedKey in sortedKeys{
let char: String = dictionary[sortedKey]!
word += char
}
return word
}
private func clearOldData(){
detectedText.text = ""
textMetadata = [:]
}
private func showActivityIndicator(){
activityIndicator.startAnimating()
}
private func hideActivityIndicator(){
activityIndicator.stopAnimating()
}
// text detection
func startTextDetection(){
let textRequest = VNDetectTextRectanglesRequest(completionHandler: self.detectTextHandler)
textRequest.reportCharacterBoxes = true
self.request = [textRequest]
}
func detectTextHandler(request: VNRequest, error: Error?){
guard let observation = request.results else {
print("no result")
return
}
let result = observation.map({$0 as? VNTextObservation})
DispatchQueue.main.async() {
self.imageView.layer.sublayers?.removeSubrange(1...)
for region in result {
guard let rg = region else {
continue
}
self.highlightWord(box: rg)
if let boxes = region?.characterBoxes{
for characterBox in boxes{
self.highlightLetters(box: characterBox)
}
}
}
}
}
func highlightWord(box: VNTextObservation){
guard let boxes = box.characterBoxes else {
return
}
var maxX: CGFloat = 9999.0
var minX: CGFloat = 0.0
var maxY: CGFloat = 9999.0
var minY: CGFloat = 0.0
for char in boxes {
if char.bottomLeft.x < maxX{
maxX = char.bottomLeft.x
}
if char.bottomRight.x > minX {
minX = char.bottomRight.x
}
if char.bottomRight.y < maxY{
maxY = char.bottomRight.y
}
if char.topRight.y > minY {
minY = char.topRight.y
}
}
let xCord = maxX * imageView.frame.size.width
let yCord = (1 - minY) * imageView.frame.size.height
let width = (minX - maxX) * imageView.frame.size.width
let height = (minY - maxY) * imageView.frame.size.width
let outline = CALayer()
outline.frame = CGRect(x: xCord, y: yCord, width: width, height: height)
outline.borderWidth = 2.0
outline.borderColor = UIColor.red.cgColor
imageView.layer.addSublayer(outline)
}
func highlightLetters(box: VNRectangleObservation) {
let xCord = box.topLeft.x * imageView.frame.size.width
let yCord = (1 - box.topLeft.y) * imageView.frame.size.height
let width = (box.topRight.x - box.bottomLeft.x) * imageView.frame.size.width
let height = (box.topLeft.y - box.bottomLeft.y) * imageView.frame.size.height
let outline = CALayer()
outline.frame = CGRect(x: xCord, y: yCord, width: width, height: height)
outline.borderWidth = 1.0
outline.borderColor = UIColor.blue.cgColor
imageView.layer.addSublayer(outline)
}
}
extension OCRViewController: OCRView {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
dismiss(animated: true)
guard let image = info[UIImagePickerControllerOriginalImage] else {
fatalError("Couldn't load image")
}
let newImage = fixOrientation(image: image as! UIImage)
self.imageView.image = newImage
clearOldData()
showActivityIndicator()
DispatchQueue.global(qos: .userInteractive).async {
self.detectText(image: newImage)
self.startTextDetection()
}
}
}
|
//
// SelectedTransition.swift
// McKendrickUI
//
// Created by Steven Lipton on 3/15/20.
// Copyright © 2020 Steven Lipton. All rights reserved.
//
// An exercise file for iOS Development Tips Weekly
// A weekely course on LinkedIn Learning for iOS developers
// Season 10 (Q2 2020) video 10
// by Steven Lipton (C)2020, All rights reserved
// Learn more at https://linkedin-learning.pxf.io/YxZgj
// This Week: Create custom modifiers in SwiftUI while making the button panel a navigation panel.
// For more code, go to http://bit.ly/AppPieGithub
// Quarter Share, Ishmael Wang, Lois McKendrick, and
// Trader Tales from the Golden Age of the Solar Clipper
// copyright Nathan Lowell, used with permission
// To read the novel behind this project, see https://www.amazon.com/Quarter-Share-Traders-Golden-Clipper-ebook/dp/B00AMO7VM4
import SwiftUI
struct SelectedTransition: ViewModifier {
var isSelected:Bool
var geometry:GeometryProxy
func body(content: Content ) -> some View{
content
.frame(width: self.isSelected ? geometry.size.width : 0 )
.opacity(self.isSelected ? 1 : 0 )
.animation(.default)
}
}
extension View{
func selectedTransition(isSelected:Bool,geometry:GeometryProxy )-> some View{
self.modifier(SelectedTransition(isSelected:isSelected, geometry:geometry))
}
}
|
//
// DiscoverViewController.swift
// The Movie DB
//
// Created by v.a.jayachandran on 23/5/20.
// Copyright © 2020 v.a.jayachandran. All rights reserved.
//
import UIKit
class DiscoverViewController: BaseViewController {
private var vm: DiscoverViewModel? {
didSet {
collectionView.reloadData()
}
}
private let cellID: String = "cellID"
var output: DiscoverInteractorProtocol?
var router: DiscoverRouterProtocol?
private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "DiscoverViewCell", bundle: nil), forCellWithReuseIdentifier: cellID)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.fill(view: view)
output?.load()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let spacing: CGFloat = 10.0
layout.itemSize = CGSize(width: view.frame.width * 0.5 - spacing, height: view.frame.height * 0.5 - spacing)
layout.minimumLineSpacing = spacing
layout.minimumInteritemSpacing = spacing
}
}
}
extension DiscoverViewController: DiscoverViewProtocol {
func display(viewModel: DiscoverViewModel) {
self.vm = viewModel
}
}
extension DiscoverViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return vm?.movies.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as? DiscoverViewCell else {
return UICollectionViewCell()
}
cell.movie = vm?.movies[indexPath.row]
if indexPath.row == (vm?.movies.count ?? 1) - 1 {
output?.scrolledToEnd()
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let movie = vm?.movies[indexPath.row] {
router?.gotoMovieDetails(movieID: movie.id)
}
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
}
}
|
//
// Endpoint.swift
// ShowCities
//
// Created by Дмитрий Иванов on 05.07.2021.
//
import Foundation
public enum CountiesAPI {
case all
case name(name: String)
}
extension CountiesAPI: EndpointType {
public var baseURL: URL {
let urlString = "https://restcountries.eu/"
guard let url = URL(string: urlString) else {
fatalError("baseURL could not be configured.")
}
return url
}
public var path: String {
switch self {
case .all:
return "rest/v2/all"
case let .name(name):
return "rest/v2/name/\(name)"
}
}
public var httpMethod: HTTPMethod {
.get
}
public var task: HTTPTask {
switch self {
case .all:
return .request
case .name(_):
return .request
}
}
public var headers: HTTPHeaders? {
.none
}
}
|
//
// ProfileController.swift
// maqueta
//
// Created by Miguel Roncallo on 2/1/17.
// Copyright © 2017 Nativapps. All rights reserved.
//
import UIKit
import DropDown
class ProfileController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource{
@IBOutlet var contentView: UIView!
@IBOutlet var heightTextField: UITextField!
@IBOutlet var weightTextField: UITextField!
@IBOutlet var heartRateTextField: UITextField!
@IBOutlet var levelTextField: UITextField!
var heightPicker = UIPickerView()
var weightPicker = UIPickerView()
var heartRatePicker = UIPickerView()
var levelPicker = UIPickerView()
var heightText = ["150 cm", "151 cm","152 cm","153 cm","154 cm","155 cm","156 cm","157 cm","158 cm",
"159 cm","160 cm","161 cm","162 cm","163 cm","164 cm","165 cm","166 cm","167 cm",
"168 cm","169 cm","170 cm","171 cm","171 cm","172 cm","173 cm","174 cm","175 cm"]
var weightText = ["65 kg", "66 kg", "67 kg", "68 kg", "69 kg", "70 kg", "71 kg", "72 kg", "73 kg",
"74 kg","75 kg","76 kg","77 kg","78 kg","79 kg","80 kg","81 kg","82 kg","83 kg",
"84 kg","85 kg"]
var levelText = ["Beginner", "Intermediate", "Expert"]
var bpmText = ["80 bpm", "90 bpm", "100 bpm", "110 bpm", "120 bpm", "130 bpm", "140 bpm", "150 bpm",
"160 bpm", "170 bpm"]
override func viewDidLoad() {
super.viewDidLoad()
setNavigationBar()
setTextFields()
heightPicker.dataSource = self
heightPicker.delegate = self
weightPicker.dataSource = self
weightPicker.delegate = self
heartRatePicker.dataSource = self
heartRatePicker.delegate = self
levelPicker.dataSource = self
levelPicker.delegate = self
heightPicker.tag = 1
weightPicker.tag = 2
heartRatePicker.tag = 3
levelPicker.tag = 4
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//PickerView Delegates
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch pickerView.tag {
case 1:
//Height
return self.heightText.count
case 2:
//Weight
return self.weightText.count
case 3:
//Heart
return self.bpmText.count
case 4:
//Level
return self.levelText.count
default:
break
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch pickerView.tag {
case 1:
//Height
return self.heightText[row]
case 2:
//Weight
return self.weightText[row]
case 3:
//Heart
return self.bpmText[row]
case 4:
//Level
return self.levelText[row]
default:
break
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
switch pickerView.tag {
case 1:
//Height
self.heightTextField.text = self.heightText[row]
case 2:
//Weight
self.weightTextField.text = self.weightText[row]
case 3:
//Heart
self.heartRateTextField.text = self.bpmText[row]
case 4:
//Level
self.levelTextField.text = self.levelText[row]
default:
break
}
self.view.endEditing(true)
}
//Supporting functions
func setNavigationBar(){
self.navigationController?.navigationBar.barTintColor = UIColor.black
let label = UILabel()
label.text = "PROFILE"
label.textColor = UIColor.white
label.font = UIFont.boldSystemFont(ofSize: 15)
label.sizeToFit()
let saveButton = UIBarButtonItem(title: "NEXT", style: .plain, target: self, action: #selector(self.navigate(_:)))
saveButton.tintColor = UIColor(red: 25/255, green: 90/255, blue: 85/255, alpha: 1.0)
self.navigationItem.rightBarButtonItems = [saveButton]
self.navigationItem.titleView = label
}
func navigate( _ sender: UIBarButtonItem){
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Profile 3 VC") as! Profile3Controller
self.navigationController?.pushViewController(vc, animated: true)
}
func setTextFields(){
heightTextField.layer.borderColor = UIColor.white.cgColor
weightTextField.layer.borderColor = UIColor.white.cgColor
heartRateTextField.layer.borderColor = UIColor.white.cgColor
levelTextField.layer.borderColor = UIColor.white.cgColor
heightTextField.delegate = self
weightTextField.delegate = self
heartRateTextField.delegate = self
levelTextField.delegate = self
heightTextField.inputView = self.heightPicker
weightTextField.inputView = self.weightPicker
heartRateTextField.inputView = self.heartRatePicker
levelTextField.inputView = self.levelPicker
}
}
|
//
// CenterVCDelegate.swift
// UberX
//
// Created by pop on 6/24/20.
// Copyright © 2020 pop. All rights reserved.
//
import UIKit
protocol CenterVCDelegate {
func ToggleLeftPanel()
func addLeftPanelViewController()
func animateLeftPanel(shouldAnimate:Bool)
}
|
//
// DetailEventViewController.swift
// EventWeek_CollectionView
//
// Created by Duy Bùi on 5/2/17.
// Copyright © 2017 Duy Bùi. All rights reserved.
//
import UIKit
class DetailEventViewController: UIViewController {
@IBOutlet weak var lblDay: UILabel!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDes: UILabel!
@IBOutlet weak var lblAddress: UILabel!
var event: Event?
var dayEvent: String?
override func viewDidLoad() {
super.viewDidLoad()
lblDes.text = event?.description
lblTitle.text = event?.title
lblAddress.text = event?.address
lblDay.text = dayEvent;
}
}
|
// ___FILEHEADER___
import MobiusCore
struct ___VARIABLE_productName___Model {
let <#property#>: <#type#>
}
enum ___VARIABLE_productName___Event {
case <#eventName#>
}
enum ___VARIABLE_productName___Effect: Equatable {
case <#effectName#>
}
|
//
// APIManager.swift
// JSON_Feed
//
// Created by Sourish on 07/07/18.
// Copyright © 2018 Sourish. All rights reserved.
//
import Foundation
import UIKit
import Reachability
class APIManager {
let reachability = Reachability()
class func getFeedRequest(withCompletion completion: @escaping (_ feedResponse: Feed?, _ error: Error?) -> Void) {
let url = URL(string: "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json")
let request = URLRequest(url: url!)
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: request) { data, response, error -> Void in
if error != nil {
completion(nil, error)
}
else {
var iso = ""
if let aData = data {
iso = String(data: aData, encoding: .isoLatin1)!
}
let dutf8: Data? = iso.data(using: .utf8)
var serializedResponse: Any? = nil
if let aDutf8 = dutf8 {
serializedResponse = try? JSONSerialization.jsonObject(with: aDutf8, options: .mutableContainers)
}
let feedResponse: Feed? = Feed(dictionary: serializedResponse as! [AnyHashable : Any])
completion(feedResponse, nil)
}
}
task.resume()
}
class func downLoadImage(item: Item?, withCallBack completion: @escaping (Item?, Error?) -> Void) {
if item?.imageHref != nil {
var request: URLRequest? = nil
if let aHref = URL(string: (item?.imageHref)!) {
request = URLRequest(url: aHref)
}
if let _ = request, let aHref = URL(string: (item?.imageHref)!) {
URLSession.shared.dataTask(with: aHref) { (data, response, error) in
if error != nil {
print("item: \(String(describing: item?.title)) error: \(String(describing: error?.localizedDescription))")
completion(nil, error)
}
else {
var downloadedImage: UIImage?
if let aData = data {
print("data\(String(describing: data))")
downloadedImage = UIImage(data: aData)
}
item?.feedImage = downloadedImage
completion(item!, nil)
}
}.resume()
}
}
}
}
|
//
// main.swift
// HelloWorld
//
// Created by Conrad Huang on 8/8/15.
// Copyright (c) 2015 Conrad Huang. All rights reserved.
//
import Foundation
println("Hello, World!")
println("Don't you know?")
var x: Double = 20
let y: Double = 20
x = 30
println(x)
let label = "Remarkable year"
let width = 45
let widthLabel = label + String(width)
println("Hello Yo \(20.0)")
var shoppingList = ["cat", "dog"]
var category = [String: String]();
category["a"] = "test"
category["b"] = "try"
println(category)
for s in shoppingList {
println(s + " has put into shopping cart")
}
for (c, cat) in category {
println(c)
println(cat)
}
switch category["a"]! {
case "test":
println("case a")
case "try":
println("case b")
default:
println("default case")
}
var name: String? = "David"
println(name == nil)
name = nil
var greeting = "Hello! "
if let myName = name {
greeting = "Hello, \(name)"
}
println(greeting)
func greet(name: String, day: String) -> (String, sum: Int) {
return (name + day, 20)
}
let returnResult = greet("David", "2015")
println(returnResult.1)
println(returnResult.sum)
func sum(numbers: Int...) -> (Int, count: Int) {
var sum = 0
for num in numbers {
func add(a: Int, b: Int) -> Int {
println("add \(a) and \(b)")
return a + b
}
sum = add(sum, num)
}
return (sum, numbers.count)
}
println(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
func hasAnyMatches(condition: Int -> Bool, list: Int...) -> Bool {
for item in list {
if (condition(item)) {
return true
}
}
return false
}
println(hasAnyMatches({(num: Int) -> Bool in return num == 3}, 1, 2, 5, 4))
var numbers = [1, 2, 3, 4, 5]
let squareMap = numbers.map({
(num: Int) -> Int in
//println(num * num)
return num * num
}
)
println(squareMap)
let squareMap2 = numbers.map({ num in num * num })
println(squareMap2)
let sortNum = sorted(numbers) { $0 > $1 }
println(sortNum) |
//
// ProfilesRowController.swift
// PollsFramework
//
// Created by Stefanita Oaca on 19/09/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import WatchKit
import PollsFramework
class ProfilesRowController: NSObject {
@IBOutlet var separator: WKInterfaceSeparator!
@IBOutlet var titleLabel: WKInterfaceLabel!
var contact: Contact? {
didSet {
if let contact = contact {
titleLabel.setText(contact.firstName! + " " + contact.lastName!)
}
}
}
}
|
//
// TweetsViewController.swift
// Twitter
//
// Created by Lucas Andrade on 2/20/16.
// Copyright © 2016 LucasAndradeRibeiro. All rights reserved.
//
import UIKit
class TweetsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var tweets: [Tweet]!
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.navigationBar.barTintColor = UIColor(red: 0, green: 0, blue: 0.8, alpha: 0.3)
self.tableView.dataSource = self
self.tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
tableView.tag = 0
//fetching data
TwitterClient.sharedInstance.homeTimeLine({ (tweets: [Tweet]) -> () in
self.tweets = tweets
self.tableView.reloadData()
}, failure: { (error: NSError) -> () in
print(error.localizedDescription)
})
NSNotificationCenter.defaultCenter().addObserverForName("ProfileTouch", object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) -> Void in
self.profilePage()
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogoutButton(sender: AnyObject) {
TwitterClient.sharedInstance.logout()
}
override func viewWillAppear(animated: Bool) {
self.tableView.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tweetCell", forIndexPath: indexPath) as! CustomTableViewCell
let tweet = tweets[indexPath.row]
tweet.positionInArray = indexPath.row
cell.tweet = tweet
cell.tag = indexPath.row
//tweet labels
cell.tweetText.text = String(tweet.text!)
cell.tweetText.sizeToFit()
cell.tweetText.numberOfLines = 0
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.dateStyle = .MediumStyle
let dateToPrint: NSString = dateFormatter.stringFromDate(tweet.timeStamp!) as NSString
cell.labelDate.text = String(dateToPrint)
cell.labelFavoriteNumber.text = String(tweet.favoritesCount)
cell.labelRetweetNumber.text = String(tweet.retweetCount)
//user labels
cell.labelUserName.text = tweet.userName
cell.labelUserHandle.text = "@\(tweet.userHandle!)"
//user profile picture
cell.imageProfilePicture.setImageWithURL(tweet.imageProfileURL!)
cell.imageProfilePicture.layer.cornerRadius = 28
cell.imageProfilePicture.clipsToBounds = true
if(cell.tweet?.favorited == 0){
cell.buttonFavorite.setImage(UIImage(named: "like-action-grey"), forState: .Normal)
cell.labelFavoriteNumber.textColor = UIColor.grayColor()
}
else{
cell.buttonFavorite.setImage(UIImage(named: "like-action-pink"), forState: .Normal)
cell.labelFavoriteNumber.textColor = UIColor.redColor()
}
if(cell.tweet?.retweeted == 1){
cell.buttonRetweet.setImage(UIImage(named: "retweet-action-green"), forState: .Normal)
cell.labelRetweetNumber.textColor = UIColor(red: 0, green: 0.8, blue: 0, alpha: 1)
}
else{
cell.buttonRetweet.setImage(UIImage(named: "retweet-action-grey"), forState: .Normal)
cell.labelRetweetNumber.textColor = UIColor.grayColor()
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detailVC = self.storyboard!.instantiateViewControllerWithIdentifier("DetailsVC") as! TweetsDetailViewController
detailVC.tweet = tweets[indexPath.row]
detailVC.rowFromTableView = indexPath.row
self.navigationController!.pushViewController(detailVC, animated: true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let tweets = tweets{
return tweets.count
}
else{
return 0
}
}
@IBAction func userProfilePage(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let profileVC = storyboard.instantiateViewControllerWithIdentifier("ProfileVC") as! ProfileViewController
profileVC.userHandleFromCell = User.currentUser!.screenname! as String
self.navigationController?.pushViewController(profileVC, animated: true)
}
func profilePage(){
let saving = NSUserDefaults.standardUserDefaults()
let imageTouchedTag = saving.valueForKey("cellTouchedTag") as! Int
let userHandle = tweets[imageTouchedTag].userHandle!
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let profileVC = storyboard.instantiateViewControllerWithIdentifier("ProfileVC") as! ProfileViewController
profileVC.userHandleFromCell = userHandle
self.navigationController?.pushViewController(profileVC, animated: true)
}
}
|
import CoreML
// MARK: - Style Transfer Model Input
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final class TransferInput : MLFeatureProvider {
// MARK: - Constants
private struct Constants {
static let inputName = "input1"
}
// MARK: - Properties
/// Pixel Buffer with size 224 x 224 and 32ARGB pixel format
var inputBuffer: CVPixelBuffer
var featureNames: Set<String> { [Constants.inputName] }
// MARK: - Initializer
init(with buffer: CVPixelBuffer) {
self.inputBuffer = buffer
}
// MARK: - Methods
func featureValue(for featureName: String) -> MLFeatureValue? {
guard featureName == Constants.inputName else { return nil }
return MLFeatureValue(pixelBuffer: inputBuffer)
}
}
// MARK: - Style Transfer Model Output
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final class TransferOutput : MLFeatureProvider {
// MARK: - Constants
private struct Constants {
static let outputName = "output1"
}
// MARK: - Properties
/// Pixel Buffer with size 224 x 224 and 32ARGB pixel format
lazy var outputBuffer: CVPixelBuffer? = { [weak self] in
self?.provider.featureValue(for: Constants.outputName)?.imageBufferValue
}()
var featureNames: Set<String> { self.provider.featureNames }
// MARK: - Private properties
private let provider : MLFeatureProvider
// MARK: - Initializer
init?(pixelBuffer: CVPixelBuffer) {
guard let provider = try? MLDictionaryFeatureProvider(
dictionary: [Constants.outputName : MLFeatureValue(pixelBuffer: pixelBuffer)]
) else { return nil }
self.provider = provider
}
init(features: MLFeatureProvider) {
self.provider = features
}
// MARK: - Methods
func featureValue(for featureName: String) -> MLFeatureValue? {
guard featureName == Constants.outputName else { return nil }
return self.provider.featureValue(for: featureName)
}
}
// MARK: - Style Transfer Model
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final class TransferModel {
// MARK: - Constants
private struct Constants {
static let fileType = "mlmodelc"
}
// MARK: - Properties
private var model: MLModel
// MARK: - Initializers
init?(name: String) {
guard
let compiledURL = Bundle.main.url(
forResource: name,
withExtension: Constants.fileType
),
let model = try? MLModel(contentsOf: compiledURL)
else { return nil }
self.model = model
}
// MARK: - Predict Methods
func prediction(input: TransferInput) throws -> TransferOutput {
try self.prediction(input: input, options: MLPredictionOptions())
}
func prediction(input: TransferInput, options: MLPredictionOptions) throws -> TransferOutput {
TransferOutput(features: try model.prediction(from: input, options:options))
}
}
|
//
// CityListViewController.swift
// CityList
//
// Created by riza milani on 5/17/1398 AP.
// Copyright © 1398 riza milani. All rights reserved.
//
import UIKit
protocol CityListViewControllerProtocol: class {
/// This is delegate that called in presenter after fetching and filtering cities.
func dataDidLoad(cities: [City])
/// It was better to implement this function in a base protocol, so other controllers can access it.
/// But in this case I keep it here
func showErrorMessage(string: String)
}
class CityListViewController: UIViewController, CityListViewControllerProtocol {
private var tableView: UITableView!
private var searchBar: UISearchBar!
private var activityIndicatorView: UIActivityIndicatorView!
var presenter: CityListPresenterProtocol?
var cities: [City] = [] {
didSet {
tableView.reloadData()
if !cities.isEmpty {
let indexPath = IndexPath(row: 0, section: 0)
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "City List"
createSearchBar()
createTableView()
presenter?.fetchData { [weak self] cities in
if cities.isEmpty {
self?.showErrorMessage(string: "Couldn't fetch data")
} else {
self?.dataDidLoad(cities: cities)
}
}
}
}
extension CityListViewController {
// MARK: - Create search bar
func createSearchBar() {
searchBar = UISearchBar()
searchBar.delegate = self
searchBar.autocapitalizationType = .none
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.showsCancelButton = true
// Wait until data loaded.
searchBarEnabled(state: false)
view.addSubview(searchBar)
searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
searchBar.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 0).isActive = true
}
func createTableView() {
tableView = UITableView()
tableView.register(CityListViewCell.self, forCellReuseIdentifier: String(describing: CityListViewCell.self))
tableView.tableFooterView = UIView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.delegate = self
tableView.separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
view.addSubview(tableView)
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
tableView.topAnchor.constraint(equalTo: searchBar.bottomAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
let activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
activityIndicatorView.color = .gray
tableView.backgroundView = activityIndicatorView
self.activityIndicatorView = activityIndicatorView
activityIndicatorView.startAnimating()
}
}
extension CityListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: CityListViewCell.self)) as? CityListViewCell else {
return UITableViewCell()
}
cell.presenter = presenter
cell.city = cities[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let coord = cities[indexPath.row].coord
presenter?.showMap(coord: coord)
}
}
// MARK: - view controller delegete implementation
extension CityListViewController {
func dataDidLoad(cities: [City]) {
DispatchQueue.main.async {
self.searchBarEnabled(state: true)
self.activityIndicatorView.stopAnimating()
self.cities = cities
}
}
func showErrorMessage(string: String) {
// Reused function
let alertController = UIAlertController(title: "Error",
message: string,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
// MARK: - search bar delegate
extension CityListViewController: UISearchBarDelegate {
func searchBarEnabled(state: Bool) {
if state {
searchBar.isUserInteractionEnabled = true
searchBar.placeholder = "Filter cities by name ..."
} else {
searchBar.isUserInteractionEnabled = false
searchBar.placeholder = "Please wait while loading ..."
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
presenter?.filterCity(startWith: searchText) { [weak self] cities in
if cities.isEmpty {
self?.showErrorMessage(string: "Couldn't fetch data")
} else {
self?.dataDidLoad(cities: cities)
}
}
}
}
|
//
// Barrage.swift
// BarrageDemo
//
// Created by Guo Zhiqiang on 17/3/16.
// Copyright © 2017年 Guo Zhiqiang. All rights reserved.
//
import UIKit
enum BarrageType: Int {
case rightToLeft
case leftToRight
case topToBottom
case bottomToTop
}
class Barrage {
var type: BarrageType
var time: Double!
var duration: Double!
var remainTime: Double = 0
var text: String!
var textColor: UIColor!
var textSize: CGFloat!
var originX: CGFloat!
var originY: CGFloat!
var size: CGSize!
var isMeasured = false
var isShowing = false
var label: UILabel?
weak var retainer: BarrageRetainer!
var isSelfSend = false
init(type: BarrageType) {
self.type = type
}
func renderlabel(paintHeight: CGFloat) {
label!.alpha = 1
label!.font = UIFont.systemFont(ofSize: textSize)
label!.text = text
label!.textColor = textColor
label!.sizeToFit()
size = CGSize(width: label!.frame.width, height: paintHeight)
}
func layoutWithScreenWidth(width: CGFloat) {
//子类实现
}
func originX(screenWidth: CGFloat, remainTime: Double) -> CGFloat {
return -self.size.width
}
func isLate(currentTime: TimeInterval) -> Bool {
return (currentTime + 1) < self.time
}
func isDraw(currentTime: TimeInterval) -> Bool {
return self.time >= currentTime
}
}
|
//
// BDCurrentUser+CoreDataProperties.swift
//
//
// Created by Andrey on 02.06.17.
//
//
import Foundation
import CoreData
extension BDCurrentUser {
@nonobjc public class func fetchRequest() -> NSFetchRequest<BDCurrentUser> {
return NSFetchRequest<BDCurrentUser>(entityName: "BDCurrentUser")
}
@NSManaged public var email: String?
@NSManaged public var phone: String?
@NSManaged public var userAvatar: String?
@NSManaged public var userName: String?
@NSManaged public var buyQuest: NSSet?
@NSManaged public var city: NSSet?
}
// MARK: Generated accessors for buyQuest
extension BDCurrentUser {
@objc(addBuyQuestObject:)
@NSManaged public func addToBuyQuest(_ value: BDBuyQuest)
@objc(removeBuyQuestObject:)
@NSManaged public func removeFromBuyQuest(_ value: BDBuyQuest)
@objc(addBuyQuest:)
@NSManaged public func addToBuyQuest(_ values: NSSet)
@objc(removeBuyQuest:)
@NSManaged public func removeFromBuyQuest(_ values: NSSet)
}
// MARK: Generated accessors for city
extension BDCurrentUser {
@objc(addCityObject:)
@NSManaged public func addToCity(_ value: BDCity)
@objc(removeCityObject:)
@NSManaged public func removeFromCity(_ value: BDCity)
@objc(addCity:)
@NSManaged public func addToCity(_ values: NSSet)
@objc(removeCity:)
@NSManaged public func removeFromCity(_ values: NSSet)
}
|
//
// FindAlertViewController.swift
// AlphaBeez
//
// Created by Nadia Ruocco on 06/06/2020.
// Copyright © 2020 Ivan Tilev. All rights reserved.
//
import UIKit
class FindAlertViewController: UIViewController {
// Outlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var firstParagraph: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var exitButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = "Parent Zone!"
firstParagraph.text = """
Take this time to explore more characteristics and descriptive words that can be used to categorize the word on the flashcard. This search and find activity provides you and your child with the opportunity to communicate and create a narrative around the word you just learned together.
Talk through why certain objects have the same characteristics and why they don’t and try to incorporate other words that you may have learned recently with your child.
Encourage creativity and help him/her observe your environment by talking about what you discover together. Create stories with the elements and objects that you find during your hunt. Remember that every moment is a teachable moment and to raise curiosity in learning new words!
"""
titleLabel.font = FontKit.roundedFont(ofSize: 28, weight: .bold)
firstParagraph.font = FontKit.roundedFont(ofSize: 26, weight: .regular)
self.scrollView.layer.borderWidth = 10
self.scrollView.layer.borderColor = UIColor.greenElement.cgColor
self.scrollView.layer.cornerRadius = 10
}
// MARK: - Action for exit button
@IBAction func exitButtonPressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
// MARK: - Dismiss view when touch outside
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch = touches.first
if touch?.view != self.scrollView
{
self.dismiss(animated: true, completion: nil) }
}
}
|
//
// RomPlatformInput.swift
// CHIP8WatchOS WatchKit Extension
//
// Created by Ryan Grey on 19/02/2021.
//
import Foundation
import Chip8Emulator
typealias PlatformMapping = [TouchInputCode : SemanticInputCode]
struct TouchInputMappingService {
private let mapping: [RomName : PlatformMapping] = [
.chip8 : [:],
.airplane : [
.tap : .primaryAction
],
.astroDodge: [
.tap : .primaryAction,
.left : .left,
.right : .right
],
.blinky : [
.left : .left,
.right : .right,
.down : .down,
.up : .up
],
.breakout: [
.left : .left,
.right : .right
],
.cave : [
.tap : .primaryAction,
.up : .up,
.down : .down,
.left : .left,
.right : .right
],
.filter : [
.left : .left,
.right : .right
],
.kaleidoscope : [
.tap : .primaryAction,
.up : .up,
.down : .down,
.left : .left,
.right : .right
],
.landing : [
.tap : .primaryAction
],
.lunarLander : [
.tap : .primaryAction,
.left : .left,
.right : .right
],
.maze : [:],
.missile : [
.tap : .primaryAction
],
.pong : [
.down : .down,
.up : .up
],
.rocket : [
.tap : .primaryAction
],
.spaceFlight : [
.tap : .primaryAction,
.longPress : .secondaryAction,
.down : .down,
.up : .up
],
.spaceIntercept : [
.tap : .primaryAction,
.longPress : .secondaryAction,
.left : .left,
.up : .up,
.right : .right
],
.spaceInvaders : [
.tap : .primaryAction,
.left : .left,
.right : .right
],
.squash : [
.up : .up,
.down : .down
],
.tank : [
.tap : .primaryAction,
.left : .left,
.right : .right,
.down : .down,
.up : .up
],
.tapeWorm : [
.tap : .primaryAction,
.left : .left,
.right : .right,
.up : .up,
.down : .down
],
.tetris : [
.down : .secondaryAction,
.tap : .primaryAction,
.left : .left,
.right : .right
],
.wipeOff : [
.left : .left,
.right : .right
],
.worm : [
.tap : .primaryAction,
.left : .left,
.right : .right,
.up : .up,
.down : .down
],
.xMirror : [
.tap : .primaryAction,
.up : .up,
.down : .down,
.left : .left,
.right : .right
]
]
func platformMapping(for romName: RomName) -> PlatformMapping? {
return mapping[romName]
}
}
extension TouchInputMappingService: PlatformInputMappingService {
typealias PlatformInputCode = TouchInputCode
func semanticInputCode(from romName: RomName, from platformInputCode: TouchInputCode) -> SemanticInputCode? {
return platformMapping(for: romName)?[platformInputCode]
}
}
|
//
// DiagnoseCell.swift
// HISmartPhone
//
// Created by DINH TRIEU on 12/26/17.
// Copyright © 2017 MACOS. All rights reserved.
//
import UIKit
protocol DiagnoseCellDelegate: class {
func didSelectItem(at indexPath: IndexPath)
}
class DiagnoseCell: BaseCollectionViewCell {
var diagnose: Diagnose? {
didSet {
self.dateLabel.text = self.diagnose?.createDate.getDescription_DDMMYYYY_WithSlash()
self.nameDoctorLabel.text = "BS." + (self.diagnose?.doctor.fullName ?? "")
}
}
var prescription: Prescription? {
didSet {
let date = self.prescription?.createDate.getDescription_DDMMYYYY_WithSlash() ?? ""
let presctiptionCode = (self.prescription?.prescriptionCode ?? "")
self.dateLabel.text = (presctiptionCode.uppercased() + " - " + date)
self.nameDoctorLabel.text = "BS." + (self.prescription?.doctor.fullName ?? "")
}
}
weak var delegate: DiagnoseCellDelegate?
private var indexPath = IndexPath()
//MARK: UIControl
private let dateLabel: UILabel = {
let label = UILabel()
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize, weight: UIFont.Weight.medium)
return label
}()
private let nameDoctorLabel: UILabel = {
let label = UILabel()
label.textColor = Theme.shared.grayTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
return label
}()
private let deleteImage: UIImageView = {
let image = UIImageView()
image.isUserInteractionEnabled = true
image.isHidden = true
image.image = UIImage(named: "checkbox_off")
return image
}()
private let lineDivider: UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0.7881147265, green: 0.8331988454, blue: 0.9022297263, alpha: 1)
return view
}()
//MARK: Initialize
override func setupView() {
self.setupViewDateLabe()
self.setupViewNameDoctorLabel()
self.setupViewLineDivider()
self.setupViewDeleteImage()
}
//MARK: Action UIControl
@objc func handleCheckBox() {
self.delegate?.didSelectItem(at: self.indexPath)
}
//MARK: Feature
func set(indexPath: IndexPath) {
self.indexPath = indexPath
}
func showImage(status: StatusDeleteImage) {
switch status {
case .on:
self.deleteImage.isHidden = false
self.deleteImage.image = UIImage(named: "checkbox_On")
break
case .off:
self.deleteImage.isHidden = false
self.deleteImage.image = UIImage(named: "checkbox_off")
break
case .hide:
self.deleteImage.isHidden = true
break
}
}
//MARK: SetupView
private func setupViewDateLabe() {
self.addSubview(self.dateLabel)
if #available(iOS 11, *) {
self.dateLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(Dimension.shared.normalHorizontalMargin)
make.left.equalTo(self.safeAreaLayoutGuide).offset(13 * Dimension.shared.widthScale)
}
} else {
self.dateLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(Dimension.shared.normalHorizontalMargin)
make.left.equalToSuperview().offset(13 * Dimension.shared.widthScale)
}
}
}
private func setupViewNameDoctorLabel() {
self.addSubview(self.nameDoctorLabel)
self.nameDoctorLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.dateLabel)
make.top.equalTo(self.dateLabel.snp.bottom).offset(Dimension.shared.smallVerticalMargin)
}
}
private func setupViewDeleteImage() {
self.addSubview(self.deleteImage)
if #available(iOS 11, *) {
self.deleteImage.snp.makeConstraints { (make) in
make.width.height.equalTo(18 * Dimension.shared.widthScale)
make.centerY.equalToSuperview()
make.right.equalTo(self.safeAreaLayoutGuide).offset(-28 * Dimension.shared.widthScale)
}
} else {
self.deleteImage.snp.makeConstraints { (make) in
make.width.height.equalTo(18 * Dimension.shared.widthScale)
make.centerY.equalToSuperview()
make.right.equalToSuperview().offset(-28 * Dimension.shared.widthScale)
}
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleCheckBox))
self.deleteImage.addGestureRecognizer(tapGesture)
}
private func setupViewLineDivider() {
self.addSubview(self.lineDivider)
self.lineDivider.snp.makeConstraints { (make) in
make.centerX.width.bottom.equalToSuperview()
make.height.equalTo(Dimension.shared.heightLineDivider)
}
}
}
|
//
// HttpHelper.swift
// Pods
//
// Created by Armando Contreras on 9/15/15.
//
//
import Foundation
enum HTTPRequestAuthType {
case HTTPBasicAuth
case HTTPTokenAuth
}
enum HTTPRequestContentType {
case HTTPJsonContent
case HTTPMultipartContent
}
struct HTTPHelper {
func sendRequest(request: NSURLRequest, completion:(NSData!, NSError!) -> Void) -> () {
// Create a NSURLSession task
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
if error != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(data, error)
})
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 || httpResponse.statusCode == 201 {
completion(data, nil)
} else {
let responseError : NSError = NSError(domain: "HTTPHelperError", code: httpResponse.statusCode, userInfo: nil)
completion(data, responseError)
}
}
})
}
// start the task
task.resume()
}
func getErrorMessage(error: NSError) -> NSString {
var errorMessage : NSString
// return correct error message
if error.domain == "HTTPHelperError" {
let userInfo = error.userInfo as NSDictionary!
errorMessage = userInfo.valueForKey("message") as! NSString
} else {
errorMessage = error.description
}
return errorMessage
}
} |
//
// LoginViewController2.swift
// EducationSystem
//
// Created by Serx on 16/6/5.
// Copyright © 2016年 Serx.Lee. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
import Observable
import AFNetworking
import SVProgressHUD
public let loginSession2 = AFHTTPSessionManager()
class NewLoginViewController: UIViewController {
var userName: UITextField!
var passWord: UITextField!
var formView: UIView!
var horizontalLine: UIView!
var confirmButton:UIButton!
var titleLabel: UILabel!
var historyTableView: UITableView!
var topConstraint: Constraint?
var historyHeight: Constraint?
var loginConstraint: Constraint?
var loginConstraintValue: CGFloat = 20.0
var classViewModel: LoginViewModel!
lazy var logicManager : LoginLogicManager = {
return LoginLogicManager()
}()
override func viewDidLoad() {
self.initProperties()
super.viewDidLoad()
self.initView()
}
func initView() {
self.view.backgroundColor = themeColor
let formViewHeight = 90
// let tapView = UITapGestureRecognizer(target: self, action: #selector(self.hideKyeBoard))
// self.view.userInteractionEnabled = true
// self.view.addGestureRecognizer(tapView)
self.formView = UIView()
self.formView.layer.borderWidth = 0.5
self.formView.layer.borderColor = UIColor.lightGrayColor().CGColor
self.formView.backgroundColor = UIColor.whiteColor()
self.formView.layer.cornerRadius = 5
self.view.addSubview(self.formView)
self.formView.snp_makeConstraints { (make) -> Void in
// make.left.equalTo(15)
// make.right.equalTo(-15)
make.centerX.equalTo(self.view)
make.width.equalTo(224)
//存储top属性
self.topConstraint = make.centerY.equalTo(self.view).constraint
make.height.equalTo(formViewHeight)
}
self.horizontalLine = UIView()
self.horizontalLine.backgroundColor = UIColor.lightGrayColor()
self.formView.addSubview(self.horizontalLine)
self.horizontalLine.snp_makeConstraints { (make) -> Void in
make.height.equalTo(0.5)
make.left.equalTo(15)
make.right.equalTo(-15)
make.centerY.equalTo(self.formView)
}
let imgLock1 = UIImageView(frame:CGRectMake(11, 11, 22, 22))
imgLock1.image = UIImage(named:"userImage")
let userTap = UIGestureRecognizer(target: self, action: #selector(self.userImageTapAction(_:)))
imgLock1.userInteractionEnabled = true
imgLock1.addGestureRecognizer(userTap)
let imgLock2 = UIImageView(frame:CGRectMake(11, 11, 22, 22))
imgLock2.image = UIImage(named:"psdImage")
imgLock2.userInteractionEnabled = true
//TODO: add gestrue
let tap = UITapGestureRecognizer(target: self, action: #selector((self.pasImageTapAction(_:))))
imgLock2.addGestureRecognizer(tap)
self.userName = UITextField()
self.userName.delegate = self
self.userName.placeholder = "学号"
self.userName.tag = 100
self.userName.leftView = UIView(frame:CGRectMake(0, 0, 44, 44))
self.userName.leftViewMode = UITextFieldViewMode.Always
self.userName.returnKeyType = UIReturnKeyType.Next
self.userName.addTarget(self, action: #selector(self.userNameEidtingChanged(_:)), forControlEvents: .EditingChanged)
self.userName.leftView!.addSubview(imgLock1)
self.formView.addSubview(self.userName)
self.userName.snp_makeConstraints { (make) -> Void in
make.left.equalTo(15)
make.right.equalTo(-15)
make.height.equalTo(44)
make.centerY.equalTo(0).offset(-formViewHeight/4)
}
self.passWord = UITextField()
self.passWord.delegate = self
self.passWord.placeholder = "密码"
self.passWord.tag = 101
self.passWord.leftView = UIView(frame:CGRectMake(0, 0, 44, 44))
self.passWord.leftViewMode = UITextFieldViewMode.Always
self.passWord.returnKeyType = UIReturnKeyType.Go
self.passWord.secureTextEntry = true
self.passWord.leftView!.addSubview(imgLock2)
self.formView.addSubview(self.passWord)
self.passWord.snp_makeConstraints { (make) -> Void in
make.left.equalTo(15)
make.right.equalTo(-15)
make.height.equalTo(44)
make.centerY.equalTo(0).offset(formViewHeight/4)
}
self.confirmButton = UIButton()
self.confirmButton.setTitle("登录", forState: UIControlState.Normal)
self.confirmButton.setTitleColor(UIColor.blackColor(),
forState: UIControlState.Normal)
self.confirmButton.layer.cornerRadius = 5
self.confirmButton.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.5)
self.confirmButton.addTarget(self, action: #selector(loginConfrim),
forControlEvents: .TouchUpInside)
self.view.addSubview(self.confirmButton)
self.confirmButton.snp_makeConstraints { (make) -> Void in
// make.left.equalTo(15)
self.loginConstraint = make.top.equalTo(self.formView.snp_bottom).offset(20).constraint
// make.right.equalTo(-15)
make.height.equalTo(44)
make.centerX.equalTo(self.view)
make.width.equalTo(224)
}
self.titleLabel = UILabel()
self.titleLabel.text = "URP综合教务系统"
self.titleLabel.textColor = UIColor.whiteColor()
self.titleLabel.font = UIFont.systemFontOfSize(28)
self.view.addSubview(self.titleLabel)
self.titleLabel.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(self.formView.snp_top).offset(-20)
make.centerX.equalTo(0)
make.height.equalTo(44)
}
let historyTableViewHeight: CGFloat = 0
self.historyTableView = UITableView()
self.historyTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
self.historyTableView.delegate = self
self.historyTableView.dataSource = self
self.historyTableView.tableFooterView = UIView()
self.historyTableView.layer.cornerRadius = 5.0
self.historyTableView.backgroundColor = UIColor.clearColor()
self.view.addSubview(self.historyTableView)
self.historyTableView.snp_makeConstraints { (make) in
make.left.equalTo(self.formView.snp_left).offset(80)
make.right.equalTo(self.formView.snp_right).offset(-0.5)
self.historyHeight = make.height.equalTo(historyTableViewHeight).constraint
make.top.equalTo(self.formView.snp_bottom).offset(-44)
}
}
func initProperties() {
self.classViewModel = self.logicManager.classViewModel //set the login view model local
self.classViewModel.LoginSuccess.afterChange += {old, new in
if new == 1 {
SVProgressHUD.showSuccessWithStatus("登录成功")
self.classViewModel.LoginSuccess <- 0
let nextController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MasterNavigation") as! UINavigationController
let master = nextController.topViewController as! MasterViewController
master.userName = self.userName.text!
master.passWord = self.passWord.text!
self.presentViewController(nextController, animated: true, completion: nil)
}
else if new == 2 {
SVProgressHUD.showErrorWithStatus(self.classViewModel.errorMessege1)
self.classViewModel.LoginSuccess <- 0
}
else if new == 3 {
SVProgressHUD.showErrorWithStatus("错误代码:\(self.classViewModel.errorMessege2)")
self.classViewModel.LoginSuccess <- 0
}
}
SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.Light)
SVProgressHUD.setBackgroundLayerColor(themeColor)
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
}
func hideKyeBoard() {
self.view.endEditing(true)
self.hideHistoryTable()
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.topConstraint?.updateOffset(0)
self.view.layoutIfNeeded()
})
}
func userImageTapAction(tapGestrue: UITapGestureRecognizer) {
self.userName.becomeFirstResponder()
}
func pasImageTapAction(tapGestrue: UITapGestureRecognizer) {
self.hideHistoryTable()
self.passWord.becomeFirstResponder()
}
func hideHistoryTable() {
if self.loginConstraintValue > 20 {
UIView.animateWithDuration(0.1, animations: {
self.loginConstraint?.updateOffset(20)
self.view.layoutIfNeeded()
})
}
UIView.animateWithDuration(0.3, animations: {
self.historyHeight?.updateOffset(0)
self.view.layoutIfNeeded()
})
}
func userNameEidtingChanged(textFiled: UITextField) {
if let statueCode = logicManager.didChange(textFiled) {
if statueCode == 0 {
self.hideHistoryTable()
}
else {
let height = CGFloat(statueCode) - 1
// UIView.animateWithDuration(0.3, animations: {
// self.historyHeight?.updateOffset(height)
// self.view.layoutIfNeeded()
// })
self.showHistoryWithHeight(height)
self.historyTableView.reloadData()
}
}
}
var currentlogin: CGFloat! = 20
var oldTableViewHeight: CGFloat = 0
func showHistoryWithHeight(height: CGFloat) {
let MAX_FIRST_TABLE: CGFloat = 64
if height <= MAX_FIRST_TABLE {
self.loginConstraintValue = 20.0
if self.oldTableViewHeight >= 64 {
// let CHA: CGFloat = oldTableViewHeight - 64
UIView.animateWithDuration(0.1, animations: {
self.historyHeight?.updateOffset(MAX_FIRST_TABLE)
self.loginConstraint?.updateOffset(20)
self.view.layoutIfNeeded()
}, completion: { (complete) in
UIView.animateWithDuration(0.2, animations: {
self.historyHeight?.updateOffset(height)
self.view.layoutIfNeeded()
})
})
}
else {
UIView.animateWithDuration(0.2, animations: {
self.historyHeight?.updateOffset(height)
self.view.layoutIfNeeded()
})
}
}
else {
let CHA = height - MAX_FIRST_TABLE
// if oldTableViewHeight != 0 {
// CHA = height - self.oldTableViewHeight
// }
self.loginConstraintValue = 20 + CHA
if oldTableViewHeight < 64{
UIView.animateWithDuration(0.2, animations: {
self.historyHeight?.updateOffset(MAX_FIRST_TABLE)
self.view.layoutIfNeeded()
}, completion: { (complete) in
UIView.animateWithDuration(0.2, animations: {
self.loginConstraint?.updateOffset(20 + CHA)
self.historyHeight?.updateOffset(height)
self.view.layoutIfNeeded()
})
})
}else if oldTableViewHeight >= 64 {
UIView.animateWithDuration(0.2, animations: {
UIView.animateWithDuration(0.2, animations: {
self.loginConstraint?.updateOffset(20 + CHA)
self.historyHeight?.updateOffset(height)
self.view.layoutIfNeeded()
})
})
}
}
self.oldTableViewHeight = height
}
func loginConfrim(){
//get up the key board
self.view.endEditing(true)
self.hideHistoryTable()
//recover all as the first position
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.topConstraint?.updateOffset(0)
self.view.layoutIfNeeded()
})
self.logicManager.checkLoginInformation(userName.text!, password: passWord.text!)
SVProgressHUD.show()
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier == "LoginToMater" {
let account = userName.text
let password = passWord.text
let limValue = self.classViewModel.LoginSuccess.value
if account == "" || password == "" || limValue == 2 || limValue == 3 || limValue == 0{
return false
}
}
//MARK: dddd
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "LoginToMater" {
let navigationController = segue.destinationViewController as! UINavigationController
let nextViewController = navigationController.topViewController as! MasterViewController
nextViewController.userName = self.userName.text!
nextViewController.passWord = self.passWord.text!
}
}
}
extension NewLoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField:UITextField) -> Bool {
let tag = textField.tag
switch tag {
case 100:
self.hideHistoryTable()
self.passWord.becomeFirstResponder()
case 101:
loginConfrim()
default:
print(textField.text)
}
return true
}
func textFieldDidBeginEditing(textField:UITextField) {
if textField.tag == 101 {
self.hideHistoryTable()
}
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.topConstraint?.updateOffset(-125)
self.view.layoutIfNeeded()
})
}
}
extension NewLoginViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row
self.userName.text = self.classViewModel.matchResultArray[row]
self.hideHistoryTable()
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
extension NewLoginViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return classViewModel.matchResultArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 25
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier: String = "myCell"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
let row = indexPath.row
cell.textLabel?.text = self.classViewModel.matchResultArray[row]
cell.textLabel?.textAlignment = .Center
cell.textLabel?.font = UIFont.boldSystemFontOfSize(15)
cell.textLabel?.backgroundColor = UIColor.clearColor()
cell.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.9)
return cell
}
} |
//
// View_And_Modifier_Concept.swift
// 100Views
//
// Created by Mark Moeykens on 9/27/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct View_And_Modifier_Concept: View {
var body: some View {
VStack(spacing: 20) {
Text("Views & Modifiers").font(.largeTitle)
Text("Concepts").foregroundColor(.gray)
Text("Building a UI with SwiftUI consists of using Views and Modifiers. Traditional methods used controls and properties. With SwiftUI, you add a view and then set properties with modifiers.")
.frame(maxWidth: .infinity)
.padding()
.background(Color.orange)
.layoutPriority(1)
Button(action: {}) {
Text("Button With Shadow")
.padding(12)
.foregroundColor(Color.white)
.background(Color.orange)
.cornerRadius(8)
}.shadow(color: Color.gray, radius: 5, y: 5)
}.font(.title)
}
}
struct View_And_Modifier_Concept_Previews: PreviewProvider {
static var previews: some View {
View_And_Modifier_Concept()
}
}
|
//
// Modal.swift
// Little Orion
//
// Created by Thomas Ricouard on 21/01/2017.
// Copyright © 2017 Thomas Ricouard. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
class ModalUI {
fileprivate static var systemUIShown = false
fileprivate static var selectionUIShown = false
fileprivate static var _systemUI: SystemUI?
fileprivate static var _selectionUI: SelectionMenu?
static var systemUI: SystemUI! {
if _systemUI == nil {
_systemUI = SystemUI.loadFromNib()
_systemUI!.isHidden = true
}
return _systemUI!
}
static var selectionUI: SelectionMenu! {
if _selectionUI == nil {
_selectionUI = SelectionMenu.loadFromNib()
_selectionUI!.isHidden = true
}
return _selectionUI!
}
static func presentSystemUI(from: SKScene, delegate: SystemUiDelegate) {
if (!systemUIShown) {
systemUIShown = true
from.view?.addSubview(systemUI)
systemUI.delegate = delegate
systemUI.show()
}
}
static func dismissSystemUI() {
systemUI.hide()
systemUIShown = false
}
static func presentSelectionUI(from: SKScene) {
if(!selectionUIShown) {
selectionUIShown = true
from.view?.addSubview(selectionUI)
selectionUI.isHidden = false
}
}
static func dismissSelectionUI() {
selectionUI.isHidden = true
selectionUIShown = false
}
}
|
//
// EventViewModel.swift
// GameSetPlay
//
// Created by Zack Falgout on 12/15/18.
// Copyright © 2018 Zack Falgout. All rights reserved.
//
import Foundation
import FirebaseDatabase
struct EventViewModel {
static let ref = Database.database().reference()
static func update(event: Event) {
let jsonEvent = try? JSONEncoder().encode(event)
let dictionary = try? JSONSerialization.jsonObject(with: jsonEvent!, options: .allowFragments) as! Dictionary<String,Any>
ref.child("Events").child(event.eventUID).setValue(dictionary)
}
}
|
//
// GuideViewController.swift
// Sohulc
//
// Created by 李博武 on 2018/10/23.
// Copyright © 2018年 linjing. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
class GuideViewController: UIViewController,UIScrollViewDelegate {
//页面数量
var numOfPages = 3
override func viewDidLoad()
{
let frame = self.view.bounds
//scrollView的初始化
let scrollView = UIScrollView()
scrollView.frame = self.view.bounds
scrollView.delegate = self
//为了能让内容横向滚动,设置横向内容宽度为3个页面的宽度总和
scrollView.contentSize = CGSize(width:frame.size.width * CGFloat(numOfPages),
height:frame.size.height)
print("\(frame.size.width*CGFloat(numOfPages)),\(frame.size.height)")
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
for i in 0..<numOfPages{
let imageView = UIImageView.init()
imageView.frame = CGRect(x: CGFloat(i) * screenW, y: 0, width: screenW, height: screenH)
imageView.image = UIImage(named: "GuideImage\(i + 1)")
scrollView.addSubview(imageView)
}
scrollView.contentOffset = CGPoint.zero
self.view.addSubview(scrollView)
}
//scrollview滚动的时候就会调用
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
print("scrolled:\(scrollView.contentOffset)")
let twidth = CGFloat(numOfPages-1) * self.view.bounds.size.width
//如果在最后一个页面继续滑动的话就会跳转到主页面
if(scrollView.contentOffset.x > twidth)
{
let mainVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateInitialViewController()
let leftMenuViewController = LeftMenuViewController()
let sideMenuViewController = RESideMenu.init(contentViewController: mainVC, leftMenuViewController: leftMenuViewController, rightMenuViewController: nil)
//sideMenuViewController?.delegate = self as! RESideMenuDelegate
sideMenuViewController?.contentViewShadowColor = UIColor(red: 255/255, green: 163/255, blue: 127/255, alpha: 1)
sideMenuViewController?.contentViewShadowOffset = CGSize(width: 0, height: 0);
sideMenuViewController?.contentViewShadowOpacity = 0.6;
sideMenuViewController?.contentViewShadowRadius = 12;
sideMenuViewController?.contentViewShadowEnabled = true;
sideMenuViewController?.animationDuration = 0.2
//sideMenuViewController?.contentViewScaleValue = 1
let nav: UINavigationController = sideMenuViewController?.contentViewController as! UINavigationController;
let dict:NSDictionary = [NSAttributedStringKey.foregroundColor: UIColor.white,NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)]
//标题颜色
nav.navigationBar.titleTextAttributes = dict as? [NSAttributedStringKey : AnyObject]
//item颜色
nav.navigationBar.tintColor = UIColor.white
self.present(sideMenuViewController!, animated: true, completion:nil)
}
}
}
|
//
// WNConfererce.swift
// WatNi
//
// Created by 홍창남 on 2020/02/15.
// Copyright © 2020 hcn1519. All rights reserved.
//
import Foundation
struct WNConference: Decodable {
let conferenceID: Int
let name: String
let description: String
let location: String
let startDate: TimeInterval
let endDate: TimeInterval
let attendances: [WNAttendance]?
private(set) var photoURLStr: String?
private(set) var notice: String?
enum CodingKeys: String, CodingKey {
case conferenceID = "conferenceId"
case name
case description
case location = "locationInfo"
case startDate = "startAt"
case endDate = "endAt"
case photoURLStr = "photoUrl"
case notice
case attendances
}
mutating func updatePhoto(urlStr: String?) {
self.photoURLStr = urlStr
}
mutating func updateNotice(_ notice: String?) {
self.notice = notice
}
}
extension WNConference: Comparable {
static func == (lhs: WNConference, rhs: WNConference) -> Bool {
return lhs.conferenceID == rhs.conferenceID
}
static func < (lhs: WNConference, rhs: WNConference) -> Bool {
guard lhs.startDate == rhs.startDate else {
return lhs.startDate < rhs.startDate
}
return lhs.endDate < rhs.endDate
}
}
extension Array where Element == WNConference {
var future: [WNConference] {
return filter {
return Date().timeIntervalSince1970 < $0.endDate
}
}
}
|
//
// Patient.swift
// GH Calculator
//
// Created by Maria Eduarda Senna on 10/03/20.
// Copyright © 2020 Maria Eduarda Senna. All rights reserved.
//
import Foundation
class Patient {
var weight: Int
var period: Int
init(weightParameter: Int, periodParameter: Int) {
weight = weightParameter
period = periodParameter
}
}
|
//
// AppDelegate.swift
// Devref
//
// Created by Alexander Shalamov on 03/07/2018.
// Copyright © 2018 Alexander Shalamov. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let mainView = MenuViewController()
let mainNavigationController = UINavigationController(rootViewController: mainView)
mainNavigationController.viewControllers = [mainView]
window?.rootViewController = mainNavigationController
return true
}
}
|
//
// SerializationServiceProtocol.swift
//
// Created by Sisov Aleksandr on 12/18/18.
//
import Foundation
public protocol SerializationServiceProtocol {
func serialize(_ responseObject: Any?) -> [String : AnyObject]?
func serialize<T: Decodable>(_ value: T.Type, from: Any?) -> T?
}
|
//
// EpisodeCollectionViewCell.swift
// MindValley
//
// Created by Sudhanshu Sharma (HLB) on 20/05/2020.
// Copyright © 2020 Sudhanshu Sharma (HLB). All rights reserved.
//
import UIKit
import Kingfisher
class EpisodeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var episodeImage : UIImageView!
@IBOutlet weak var episodeTitle : UILabel!
@IBOutlet weak var channelTitle : UILabel!
override func awakeFromNib() {
episodeImage.layer.cornerRadius = 5
episodeImage.layer.masksToBounds = true
}
public var episode: Episode! {
didSet {
self.episodeImage.layer.masksToBounds = true
let url = URL(string: self.episode.coverAsset.url)
self.episodeImage.kf.setImage(with: url)
self.episodeTitle.text = episode.title
self.channelTitle.text = episode.channel.title
}
}
private func backViewGenrator(){
// backView.loadImage(fromURL: episode.coverAsset.url)
}
override func prepareForReuse() {
episodeImage.image = UIImage()
//backView.image = UIImage()
}
}
|
//
// PostDetailsTableViewCell.swift
// BeeHive
//
// Created by Hyper Design on 9/19/18.
// Copyright © 2018 HyperDesign-Gehad. All rights reserved.
//
import UIKit
class PostDetailsTableViewCell: UITableViewCell {
// MARK: - Outlets
@IBOutlet weak var postImage: UIImageView!
@IBOutlet weak var imageHeightConstraint: NSLayoutConstraint!
// MARK: - ViewLifeCycle
override func awakeFromNib() {
super.awakeFromNib()
postImage.addShadowAndCornerRadiusToViewWith(shadowWidth: 0, shadowHeight: 0, shadowOpacity: 0, shadowRadius: 0, cornerRadius:5)
}
// MARK: - HelpingMethods
func config(image : Image){
if let photo = image.img , let url = URL(string : photo){
if photo != ""{
postImage.af_setImage(withURL: url) { (downloadedImage) in
guard let image = downloadedImage.value else{
return
}
let ratio = image.getCropRatio()
self.imageHeightConstraint.constant = CGFloat((((image.size.width) * self.postImage.frame.width / (image.size.height)) / ratio)/2)
}
}else{
self.imageHeightConstraint.constant = 0
}
}else{
self.imageHeightConstraint.constant = 0
}
}
}
|
//
// FormatterUtil.swift
// ForecastApp
//
// Created by Julio Collado on 4/7/21.
//
import Foundation
final class FormatterUtil {
static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .full
return formatter
}()
static var dayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE"
return formatter
}()
static var timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "hh a"
return formatter
}()
}
|
func printItOut(name: String) -> String{
print(name)
return name
}
printItOut(name: "Bill")
let a = 12
let b = 2
a + b
print("does this shit even work")
|
//
// UserCellViewModel.swift
// Pawie
//
// Created by Yu Ming Lin on 8/8/21.
//
import Foundation
struct UserCellViewModel{
private var user: User
var profileImageUrl: URL? {
return URL(string: user.profileImageURL)
}
var username: String {
return user.userName
}
var petname: String {
return user.petname
}
init(user: User){
self.user = user
}
}
|
//
// TemplateData+CoreDataProperties.swift
// NGenTodo
//
// Created by yamada.ryo on 2020/10/07.
// Copyright © 2020 yamada.ryo. All rights reserved.
//
//
import Foundation
import CoreData
extension TemplateData {
@nonobjc public class func fetchRequest() -> NSFetchRequest<TemplateData> {
return NSFetchRequest<TemplateData>(entityName: "TemplateData")
}
@NSManaged public var id: UUID?
@NSManaged public var order: Int
@NSManaged public var title: String?
@NSManaged public var templateTodoData: NSSet?
}
// MARK: Generated accessors for templateTodoData
extension TemplateData {
@objc(addTemplateTodoDataObject:)
@NSManaged public func addToTemplateTodoData(_ value: TemplateTodoData)
@objc(removeTemplateTodoDataObject:)
@NSManaged public func removeFromTemplateTodoData(_ value: TemplateTodoData)
@objc(addTemplateTodoData:)
@NSManaged public func addToTemplateTodoData(_ values: NSSet)
@objc(removeTemplateTodoData:)
@NSManaged public func removeFromTemplateTodoData(_ values: NSSet)
}
extension TemplateData : Identifiable {
}
|
//
// SignUp.swift
// SmartStreetProject
//
// Created by Maryam Jafari on 10/24/17.
// Copyright © 2017 Maryam Jafari. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class SignUp: UIViewController, UITextFieldDelegate {
@IBOutlet weak var pass: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var fullName: UITextField!
@IBOutlet weak var phoneNumber: UITextField!
var name: String!
var phone : String!
var emailAddress : String!
var password : String!
var uid : String!
var userEmail : String!
var userPhoneNumber : String!
var userFullName : String!
var userPass : String!
override func viewDidLoad() {
super.viewDidLoad()
pass.delegate = self
email.delegate = self
email.text = emailAddress
pass.text = password
fullName.text = name
phoneNumber.text = phone
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true;
}
@IBAction func signUp(_ sender: Any) {
if email.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: email.text!, password: pass.text!) { (user, error) in
let user = Auth.auth().currentUser
if let user = user {
self.uid = user.uid
}
if let password = self.pass.text{
self.userPass = password
}
if let name = self.fullName.text{
self.userFullName = name
}
if let email = self.email.text{
self.userEmail = email
}
if let phoneNum = self.phoneNumber.text {
self.userPhoneNumber = phoneNum
}
DBProvider.Instance.saveUser(withID: self.uid, pass: self.userPass, email : self.userEmail, phone: self.userPhoneNumber, name: self.userFullName)
if error == nil {
print("You have successfully signed up")
let alertController = UIAlertController(title: "Succesful", message: "You Signed up Succesfully", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
performSegue(withIdentifier: "BackFromSignUp", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "BackFromSignUp"{
if let destination = segue.destination as? SignIn{
destination.emailA = email.text
destination.password = pass.text
destination.name = fullName.text
destination.phone = phoneNumber.text
}
}
}
}
|
// Mission da 9 -> Part 1 - Sum
import UIKit
var odds = [5, 8, 14, 13, 29, 98]
var evens = [11, 6, 2, 87, 43, 22, 104]
var onlyOdds = odds.filter({$0 % 2 == 1})
print(onlyOdds)
var onlyEvens = evens.compactMap({$0 % 2 == 0 ? $0 : nil})
print(onlyEvens)
let numbersFromBothArrays = onlyOdds + onlyEvens
print(numbersFromBothArrays)
// This will sum the elements from the array odds and the array evens,
// and check if the array odds have more elements than the array evens or vice versa,
// if so, will add that elements in the end, after the sum.
func sumTowArrays(firstArr: [Int], secondArr: [Int]) -> [Int] {
return zip(firstArr, secondArr).map(+) + (firstArr.count < secondArr.count ? secondArr[firstArr.count..<secondArr.count] : firstArr[secondArr.count..<firstArr.count])
}
let sumOfTwoArrays = sumTowArrays(firstArr: onlyOdds, secondArr: onlyEvens)
print(sumOfTwoArrays)
let sum = onlyOdds.reduce(0, +) + onlyEvens.reduce(0, +)
print(sum)
|
//
// MyChatCell.swift
// MessagingApp
//
// Created by Prapawit Patthasirivichot on 15/3/2563 BE.
// Copyright © 2563 Prapawit Patthasirivichot. All rights reserved.
//
import UIKit
class MyChatCell: UITableViewCell {
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var messageText: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setupCell(image: UIImage, message: String){
avatarImage.image = image
messageText.text = message
}
}
|
//
// ViewController.swift
// JTNFCAssosiation
//
// Created by OCdes on 04/06/2021.
// Copyright (c) 2021 OCdes. All rights reserved.
//
import UIKit
import JTNFCAssosiation
class ViewController: UIViewController, NFCToolDelegate {
func nfcSuccessfullyWrite(msg: String) {
print(msg)
}
func nfcSuccessfullyReaded(msg: String) {
self.contentLal.text = msg
}
func nfcFailureReaded(msg: String) {
self.contentLal.text = msg
}
@IBOutlet weak var contentLal: UILabel!
@IBOutlet weak var readBtn: UIButton!
@IBOutlet weak var autoReadBtn: UIButton!
@IBOutlet weak var writeBtn: UIButton!
@IBOutlet weak var writeAndLockBtn: UIButton!
var tool: NFCTool = NFCTool.shareTool
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tool.delegate = self
}
@IBAction func readDataBtnClicked(_ sender: Any) {
self.tool.readData()
}
@IBAction func autoReadBtnClicked(_ sender: Any) {
}
@IBAction func writeDataBtnClicked(_ sender: Any) {
self.tool.writeData(contentStr: "")
}
@IBAction func writeDataLockBtnClicked(_ sender: Any) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// ThenKit.swift
// ThenKit
//
// Created by Rodrigo Lima on 8/18/15.
// Copyright © 2015 Rodrigo. All rights reserved.
//
import Foundation
// -----------------------------------------------------------------------------------------------------------------
// for Testing
public var promisesCounter = 0 {
didSet {
#if TESTING
let upDown = promisesCounter > oldValue ? "UP" : "DN"
Logger.escaped(color: .green, "Promise>>> \(upDown) -- promisesCounter \(promisesCounter)")
#endif
}
}
// -----------------------------------------------------------------------------------------------------------------
// Enums
public enum PromisesError: Error {
case pendingPromise
case emptyPromise
case cannotFulfillPromiseWithItself
case error(String)
}
public enum PromiseState {
case pending
case fulfilled
case rejected
}
// TypeAlias
public typealias PromiseFunction = ((Any?) throws -> (Any?))
public typealias RejectedFunction = ((Error) -> (Error))
public typealias CompleteFunction = ((Bool) -> Void)
// MARK: - Structs
struct CallbackInfo {
var onFulfilled: PromiseFunction?
var onRejected: RejectedFunction?
var onCompleted: CompleteFunction?
var promise: Promise
}
extension CallbackInfo: CustomStringConvertible {
func setOrNot(someFunction: Any?) -> String {
return someFunction != nil ? "set" : ""
}
var description: String {
return "\n\t\t>>CallbackInfo - onFulfilled[\(setOrNot(someFunction: onFulfilled))] " +
"- onRejected[\(setOrNot(someFunction: onRejected))] " +
"- onCompleted[\(setOrNot(someFunction: onCompleted))] " +
"- promise[\(promise)]"
}
}
// -----------------------------------------------------------------------------------------------------------------
// MARK: - Thenable Protocol
public protocol Thenable {
var name: String { set get }
// Swift Protocols currently do not accept default parameter values, so let's define a few helper methods
@discardableResult func then(onFulfilled: PromiseFunction?) -> Thenable
@discardableResult func then(onFulfilled: PromiseFunction?, onRejected: RejectedFunction?) -> Thenable
@discardableResult func then(onFulfilled: PromiseFunction?, onCompleted: CompleteFunction?) -> Thenable
@discardableResult func then(onFulfilled: PromiseFunction?, onRejected: RejectedFunction?,
onCompleted: CompleteFunction?) -> Thenable
}
// -----------------------------------------------------------------------------------------------------------------
// MARK: - Promise class
public class Promise: Thenable {
var internalName: String?
public var name: String {
get {
return internalName ?? "- no name \(promisesCounter)"
}
set (newValue) {
internalName = newValue
}
}
var state: PromiseState = .pending
var value: Any?
var reason: Error = PromisesError.pendingPromise
var callbacks: [CallbackInfo] = []
private lazy var queue: DispatchQueue = {
DispatchQueue(label: "PROMISES.q", qos: .utility, attributes: .concurrent)
}()
func runBlock(block: () -> Void) {
queue.sync {
block()
}
}
public var promise: Thenable {
return self as Thenable
}
public init() {
promisesCounter += 1
//internalName = "[#\(promisesCounter)]"
}
/**
Convenience constructor with promise name
- parameter promiseName: name for the new promise
- returns: Named promise
*/
public convenience init(_ promiseName: String) {
self.init()
internalName = "[#\(promisesCounter)] \(promiseName)"
}
deinit {
promisesCounter -= 1
#if TESTING
Logger.escaped(color: .lightBlue, "\t..BYE BYE -- '\(self.name)' - \(self.state)")
#endif
}
// -----------------------------------------------------------------------------------------------------------------
// MARK: - Callbacks
func storeCallbacks(onFulfilled: PromiseFunction?, onRejected: RejectedFunction?, onCompleted: CompleteFunction?, promise: Promise) {
Logger.log("\t..storeCallbacks - onFulfilled: \(onFulfilled) - onRejected: \(onRejected) - onCompleted: \(onCompleted)\n" +
"\tPROMISE_2: \(promise)")
// 2.2.6.1: Push onFulfilled callbacks in the order of calls to then
// 2.2.6.2: Push onRejected callbacks in the order of calls to then
callbacks += [CallbackInfo(onFulfilled: onFulfilled, onRejected: onRejected, onCompleted: onCompleted, promise: promise)]
}
func evaluateOnFulfilled(callback: PromiseFunction, promise promise2: Promise, argument: Any?) {
Logger.log("\t..evaluateOnFulfilled - callback: \(callback) - argument: \(argument)-\n\t\tPROMISE_2: \(promise2)-\n\t\tPROMISE_1: \(self)")
var result: Any? = nil
do {
try result = callback(argument)
Logger.log("\t....evaluateOnFulfilled - GOT RESULT \(result)")
} catch let e {
// 2.2.7.2: If either onFulfilled or onRejected throws an exception e, promise must be rejected with e as the reason.
Logger.log("\t....evaluateOnFulfilled - GOT EXCEPTION \(e)")
promise2.reject(reasonRejected: e)
return
}
// 2.2.7.2: If either onFulfilled or onRejected throws an exception e -- or return error --, promise must be rejected with e as the reason.
if let err = result as? Error {
promise2.reject(reasonRejected: err)
return
}
// final test
if shouldRejectSamePromise(promise: self, x: result) {
// 2.3.1: If promise and x refer to the same object, reject promise with a TypeError as the reason.
promise2.reject(reasonRejected: PromisesError.cannotFulfillPromiseWithItself)
return
} else {
// 2.2.7.1: If either onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure [[Resolve]](promise2, x).
resolve(promise: promise2, x: result)
}
}
// ---
func executeOnFulfilledCallback(callbackInfo: CallbackInfo) {
Logger.log("\t..execute_ONFULFILLED -- <<\(self.name)>> -- callbackInfo.onFulfilled: " +
callbackInfo.setOrNot(someFunction: callbackInfo.onFulfilled))
if let cbF = callbackInfo.onFulfilled {
evaluateOnFulfilled(callback: cbF, promise: callbackInfo.promise, argument: value)
} else {
// 2.2.7.3: If onFulfilled is not a function and promise1 is fulfilled, promise2 must be fulfilled with the same value.
callbackInfo.promise.fulfill(fulfilledValue: value)
}
}
func executeOnRejectedCallback(callbackInfo: CallbackInfo) {
Logger.log("\t..execute_ONREJECTED -- <<\(self.name)>> -- callbackInfo.onRejected: " +
callbackInfo.setOrNot(someFunction: callbackInfo.onRejected))
var rejectReason = reason
if let cbR = callbackInfo.onRejected {
rejectReason = cbR(reason)
Logger.log("\t....execute_ONREJECTED - GOT RESULT \(rejectReason)")
}
// 2.2.7.4: If onRejected is not a function and promise1 is rejected, promise2 must be rejected with the same reason.
callbackInfo.promise.reject(reasonRejected: rejectReason)
}
func executeOnCompletedCallback(callbackInfo: CallbackInfo) {
Logger.log("\t..execute_ONCOMPLETED -- <<\(self.name)>> -- callbackInfo.onCompleted: " +
callbackInfo.setOrNot(someFunction: callbackInfo.onCompleted))
callbackInfo.onCompleted?(state == .fulfilled)
}
func executeCallbacks(promiseState: PromiseState) {
Logger.log("\t..executeCallbacks - STATE: \(promiseState) -- PROMISE: \(self)\ncallbacks: \(callbacks)")
let cbacks = callbacks
// 2.2.2.3: Do not call onFulfilled callbacks more than once
// 2.2.3.3: Do not call onRejected callbacks more than once
callbacks.removeAll()
switch promiseState {
case .fulfilled:
// 2.2.6.1: If/when promise is fulfilled, all respective onFulfilled callbacks must execute in order of their originating calls.
cbacks.forEach { executeOnFulfilledCallback(callbackInfo: $0) }
case .rejected:
// 2.2.6.2: If/when promise is rejected, all respective onRejected callbacks must execute in order of their originating calls.
cbacks.forEach { executeOnRejectedCallback(callbackInfo: $0) }
default:
return
}
// run ON COMPLETION
cbacks.forEach { executeOnCompletedCallback(callbackInfo: $0) }
}
// -----------------------------------------------------------------------------------------------------------------
// MARK: - fulfill / reject
public func fulfill(fulfilledValue: Any?) {
Logger.log("\n!!INI--FULFILL!! --- PROMISE_1: \(self.name) -- \(self.state)")
// 2.1.1.1: When pending, a promise may transition to the fulfilled state.
// 2.1.2.1: When fulfilled, a promise must not transition to any other state.
if state != .pending {
Logger.log("!!ABORT FULFILL!! - NOT PENDING")
return
}
// 2.3.1: If promise and x refer to the same object, reject promise with a TypeError as the reason.
if shouldRejectSamePromise(promise: self, x: fulfilledValue) {
return
}
// are we fulfilling it with an Error? then it should actually be rejected
else if let err = fulfilledValue as? Error {
reject(reasonRejected: err)
}
// 2.1.2.2: When in fulfilled, a promise must have a value, which must not change.
state = .fulfilled
value = fulfilledValue
// 2.2.2.1 Call each onFulfilled after promise is fulfilled, with promise’s fulfillment value as its first argument.
// 2.2.4: onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
if callbacks.count > 0 {
Logger.log("!!PROC--FULFILL!! --- executing #[\(callbacks.count)] callbacks now...")
runBlock { [weak self] in self?.executeCallbacks(promiseState: .fulfilled) }
}
Logger.log("\n!!END--FULFILL!! --- PROMISE_1: \(self)\n")
}
public func reject(reasonRejected: Error) {
Logger.log("\n!!INI--REJECT!! --- PROMISE_1: \(self.name) -- \(self.state)")
// 2.1.1.1: When pending, a promise may transition to the fulfilled state.
// 2.1.3.1: When rejected, a promise must not transition to any other state.
if state != .pending {
Logger.log("!!ABORT REJECT!! - NOT PENDING")
return
}
// 2.1.3.2: When rejected, a promise must have a reason, which must not change.
state = .rejected
reason = reasonRejected
// 2.2.3.1 Call each onRejected after promise is rejected, with promise’s reason value as its first argument.
// 2.2.4: onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
runBlock { [weak self] in self?.executeCallbacks(promiseState: .rejected) }
Logger.log("\n!!END--REJECT!! --- PROMISE_1: \(self)\n")
}
// -----------------------------------------------------------------------------------------------------------------
// MARK: - Protocol methods
@discardableResult public func then(onFulfilled: PromiseFunction?) -> Thenable {
return then(onFulfilled: onFulfilled, onRejected: nil, onCompleted: nil)
}
@discardableResult public func then(onFulfilled: PromiseFunction?, onRejected: RejectedFunction?) -> Thenable {
return then(onFulfilled: onFulfilled, onRejected: onRejected, onCompleted: nil)
}
@discardableResult public func then(onFulfilled: PromiseFunction?, onCompleted: CompleteFunction?) -> Thenable {
return then(onFulfilled: onFulfilled, onRejected: nil, onCompleted: onCompleted)
}
@discardableResult public func then(onFulfilled: PromiseFunction?, onRejected: RejectedFunction?, onCompleted: CompleteFunction?) -> Thenable {
Logger.log("!!THEN-INI!! - onFulfilled: \(onFulfilled) - onRejected: \(onRejected) --\n\tPROMISE_1: \(self)")
let promise2 = Promise("_\(name).THEN__")
let v = value
switch state {
case .pending:
// 2.2.1: Both onFulfilled and onRejected are optional arguments
// We need to store them even if they're undefined so we can fulfill the newly created promise in the right order
storeCallbacks(onFulfilled: onFulfilled, onRejected: onRejected, onCompleted: onCompleted, promise: promise2)
case .fulfilled:
if onFulfilled != nil {
// 2.2.4: onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
runBlock { [weak self] in
self?.evaluateOnFulfilled(callback: onFulfilled!, promise: promise2, argument: v)
}
} else {
// 2.2.7.3: If onFulfilled is not a function and promise1 is fulfilled, promise must be fulfilled with the same value.
promise2.fulfill(fulfilledValue: value)
}
runBlock { onCompleted?(promise2.state == .fulfilled) }
case .rejected:
var r = reason
if let cbR = onRejected {
r = cbR(reason)
}
// 2.2.7.3: If onFulfilled is not a function and promise1 is fulfilled, promise must be fulfilled with the same value.
promise2.reject(reasonRejected: r)
runBlock { onCompleted?(promise2.state == .fulfilled) }
}
// 2.2.7: then must return a promise
let thenable: Thenable = promise2
Logger.log("!!THEN-END!! -- RETURNING:\n\tPROMISE_2: \(thenable) -- \n\tPROMISE_1: \(self)")
return thenable
}
}
// ---------------------------------------------------------------------------------------------------------------------
// MARK: -
extension Promise : CustomStringConvertible {
public var description: String {
var v: String
if let vp = value as? Promise {
v = vp.name
} else {
v = "\(value)"
}
return ">>~~~~//\(name)// - state[\(state)] - value: \(v) -- reason: \(reason) -- callbacks<\(callbacks.count)> ~~~~<<"
}
}
public extension Promise {
// empty signal - just an empty signal
public static func fulfilledEmptyPromise(named: String = "Empty.Promise.Fulfilled") -> Thenable {
let p = Promise(named)
p.then(onFulfilled: { someResult in
return someResult
})
p.fulfill(fulfilledValue: "")
return p.promise
}
// empty signal - just an empty signal
public static func emptyPromise(named: String = "Empty.Promise") -> Thenable {
let p = Promise(named)
p.then(onFulfilled: { someResult in
return someResult
})
p.reject(reasonRejected: PromisesError.emptyPromise)
return p.promise
}
// rejected promise with given error
public static func rejectedPromise(named: String = "Rejected.Promise", error: Error) -> Thenable {
let p = Promise(named)
p.reject(reasonRejected: error)
return p.promise
}
}
//----------------------------------------------------------------------------------------------------------------------
// MARK: - helper funcs
fileprivate func shouldRejectSamePromise(promise: Promise, x: Any?) -> Bool {
// 2.3.1: If promise and x refer to the same object, reject promise with a TypeError as the reason.
if let p = x as? Promise {
// callbacks array will be emptied before arriving here, so let's compare memory address
if Unmanaged.passUnretained(p).toOpaque() == Unmanaged.passUnretained(promise).toOpaque() {
promise.value = nil // so we avoid retain cycle
Logger.log("\n..shouldRejectSamePromise - REJECT -- P cannot be X\n")
promise.reject(reasonRejected: PromisesError.cannotFulfillPromiseWithItself)
return true
}
}
return false
}
fileprivate func resolve(promise: Promise, x: Any?) {
Logger.log("\n.$.$.$.$.resolve - X: \(x) -- PROMISE: \(promise)\n")
// 2.3.1: If promise and x refer to the same object, reject promise with a TypeError as the reason.
if shouldRejectSamePromise(promise: promise, x: x) {
return
}
// 2.3.3.1: Let then be x.then. 3.5
if var thenableX = x as? Thenable {
thenableX.name = "_TX_\(thenableX.name)"
var called = false
// 2.3.2: If x is a promise, adopt its state. 3.4
// 2.3.2.1: If x is pending, promise must remain pending until x is fulfilled or rejected.
// 2.3.3.3: If then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise
Logger.log("\n\t.$.$.$.$.resolve....CREATING THEN FOR THENABLE_X ----\n\t\t\tPROMISE \(promise) --\n" +
"\t\t\tthenableX \(thenableX)--\n\t\t\tX \(x)\n")
thenableX.then(onFulfilled: { y in
Logger.log("\n\t.$.$.$.$.resolve....thenableX.on_FULFILL with Y [\(y)] ----\n\t\t\tPROMISE \(promise) --\n\t\t\tX \(x)")
// 2.3.3.3.3: If both resolvePromise and rejectPromise are called, or multiple calls to the same argument are made,
// the first call takes precedence, and any further calls are ignored.
if called {
Logger.log("\t.$.$.$.$.resolve....then.onfulfill already called")
return y
}
// 2.3.2.2: If/when x is fulfilled, fulfill promise with the same value.
// 2.3.3.3.1: If/when resolvePromise is called with a value y, run [[Resolve]](promise, y).
resolve(promise: promise, x: y)
called = true
return y
},
onRejected: { r in
Logger.log("\n\t.$.$.$.$.resolve....thenableX.on_REJECT with R [\(r)] ----\n\t\t\tPROMISE \(promise) --\n\t\t\tX \(x)")
// 2.3.3.3.3: If both resolvePromise and rejectPromise are called, or multiple calls to the same argument are made,
// the first call takes precedence, and any further calls are ignored.
if called {
Logger.log("\t.$.$.$.$.resolve....then.onRejected already called")
}
// 2.3.2.3: If/when x is rejected, reject promise with the same reason..
// 2.3.3.3.2: If/when rejectPromise is called with a reason r, reject promise with r.
promise.reject(reasonRejected: r)
called = true
return r
})
} else {
// 2.3.4: If x is not an object or function, fulfill promise with x.
Logger.log("\n\t.$.$.$.$.resolve....INVOKING FULLFILL on PROMISE with X ----\n\t\t\tPROMISE \(promise) --\n\t\t\tX \(x)")
promise.fulfill(fulfilledValue: x)
}
}
/** EOF **/
|
//
// IntroductionToSwift.playground
//
// Created by Neil Hiddink on 7/31/18.
// Copyright © 2018 Neil Hiddink. All rights reserved.
//
import Foundation
import UIKit
// MARK: - Constants and Variables
let color = UIColor.red
var sum = 15
// MARK: - Data Types
let integer: Int = 3
let float: Float = 1.1
let double: Double = 12.0
var string: String = "String"
var test: Bool = false
// MARK: - Operators
sum += 3
sum -= 3
sum *= 3
sum /= 3
sum % 2
sum == 0
string += " String 2"
// MARK: - String Interpolation
string = "\(integer)"
// MARK: - Arrays and Dictionaries
let array = [Int]()
let dictionary = [String: Int]()
// MARK: - Conditional Statements
if 5 * 2 == 10 {
print("YES")
}
// MARK: _ Control Flow
for _ in 0...2 {
print("Hello, World!")
}
// MARK: - Functions and Methods
func convertInt(toString int: Int) -> String {
if int % 2 == 0 {
return "Even"
}
return "Odd"
}
convertInt(toString: 3)
convertInt(toString: 5)
convertInt(toString: 15)
convertInt(toString: 16)
// MARK: - Optionals
var maybe: Int? = 0
print(maybe ?? 0)
if let maybe = maybe {
print("Successfully unwrapped optional: \(maybe)")
}
// MARK: - Enumerations
enum Animals: Int {
case lions = 0, tigers, bears
}
print(Animals.bears.rawValue)
// MARK: - Classes and Structures
class Building: NSObject {
let height = 2000
let sqFeet = 10000
let occupancy = 500
}
struct PhysicsCategory {
static let none: UInt32 = 0 // 0
static let player: UInt32 = 0b1 // 1
static let enemy: UInt32 = 0b10 // 2
static let wall: UInt32 = 0b100 // 4
}
// MARK: - Property Observers
var observer = 0 {
didSet {
observer += 1
}
}
observer = 2
print(observer) // prints 3
// MARK: - Access Control
private var secret = "This is a secret message"
// MARK: - Typecasting
var value: Int? = 25
let output = value as! Int
print(output)
// MARK: - Closures
func test (closure: (String) -> Void) {
print("Hello, World!")
closure("Call Closure")
}
// Standard Syntax
test(closure: { str in
print(str)
})
// Trailing Syntax
test { str in
print(str)
}
|
//
// ARModel.swift
// ARtest2
//
// Created by Martin Kalaydzhiev on 3/12/21.
//
import SwiftUI
import RealityKit
final class ARModel: ObservableObject {
static var shared = ARModel()
static var coordinates1 = [
"fat": Coordinates(x: 0, y: 0.005, z: -0.20),
"sugar": Coordinates(x: 0.13, y: 0.005, z: -0.20),
"protein": Coordinates(x: -0.26, y: 0.005, z: -0.20),
"carb": Coordinates(x: -0.13, y: 0.005, z: -0.20),
"cal": Coordinates(x: 0.26, y: 0.005, z: -0.20),
]
static var coordinates2 = [
"protein": Coordinates(x: -0.2597, y: 0.005, z: -0.0306),
"carb": Coordinates(x: -0.1256, y: 0.005, z: -0.0306),
"fat": Coordinates(x: 0, y: 0.005, z: -0.0306),
"sugar": Coordinates(x: 0.1324, y: 0.005, z: -0.0306),
"cal": Coordinates(x: 0.26, y: 0.005, z: -0.0306)
]
init() {}
static func spawn(product1: Product, product2: Product) -> ARView {
let arView = ARView(frame: .null)
let anchor = try! Experience.loadBox()
arView.scene.anchors.append(anchor)
let fatBig = anchor.fat1
let fatSmall = anchor.fat2
let proteinBig = anchor.protein1
let proteinSmall = anchor.protein2
let carbBig = anchor.carbs1
let carbSmall = anchor.carbs2
let sugarBig = anchor.sugar1
let sugarSmall = anchor.sugar2
let calBig = anchor.cal1
let calMed = anchor.cal2
let calSmall = anchor.cal3
var p1BigFat = [Entity?]()
var p2BigFat = [Entity?]()
var p1SmallFat = [Entity?]()
var p2SmallFat = [Entity?]()
var p1BigProtein = [Entity?]()
var p1SmallProtein = [Entity?]()
var p2BigProtein = [Entity?]()
var p2SmallProtein = [Entity?]()
var p1BigSugar = [Entity?]()
var p1SmallSugar = [Entity?]()
var p2BigSugar = [Entity?]()
var p2SmallSugar = [Entity?]()
var p1BigCarb = [Entity?]()
var p1SmallCarb = [Entity?]()
var p2BigCarb = [Entity?]()
var p2SmallCarb = [Entity?]()
var p1BigCal = [Entity?]()
var p1SmallCal = [Entity?]()
var p2BigCal = [Entity?]()
var p2SmallCal = [Entity?]()
var p1MedCal = [Entity?]()
var p2MedCal = [Entity?]()
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
ARModel.spawnNutrient(amount: Int(product1.nutriments.proteins), listB: &p1BigProtein, listS: &p1SmallProtein, bigE: proteinBig!, smallE: proteinSmall!, c: ARModel.coordinates1["protein"]!, anchor: anchor)
ARModel.spawnNutrient(amount: Int(product2.nutriments.proteins), listB: &p2BigProtein, listS: &p2SmallProtein, bigE: proteinBig!, smallE: proteinSmall!, c: ARModel.coordinates2["protein"]!, anchor: anchor)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
ARModel.spawnNutrient(amount: Int(product1.nutriments.carbohydrates), listB: &p1BigCarb, listS: &p1SmallCarb, bigE: carbBig!, smallE: carbSmall!, c: ARModel.coordinates1["carb"]!, anchor: anchor)
ARModel.spawnNutrient(amount: Int(product2.nutriments.carbohydrates), listB: &p2BigCarb, listS: &p2SmallCarb, bigE: carbBig!, smallE: carbSmall!, c: ARModel.coordinates2["carb"]!, anchor: anchor)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 7) {
ARModel.spawnNutrient(amount: Int(product1.nutriments.fat), listB: &p1BigFat, listS: &p1SmallFat, bigE: fatBig!, smallE: fatSmall!, c: ARModel.coordinates1["fat"]!, anchor: anchor)
ARModel.spawnNutrient(amount: Int(product2.nutriments.fat), listB: &p2BigFat, listS: &p2SmallFat, bigE: fatBig!, smallE: fatSmall!, c: ARModel.coordinates2["fat"]!, anchor: anchor)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 9) {
ARModel.spawnNutrient(amount: Int(product1.nutriments.sugars), listB: &p1BigSugar, listS: &p1SmallSugar, bigE: sugarBig!, smallE: sugarSmall!, c: ARModel.coordinates1["sugar"]!, anchor: anchor)
ARModel.spawnNutrient(amount: Int(product2.nutriments.sugars), listB: &p2BigSugar, listS: &p2SmallSugar, bigE: sugarBig!, smallE: sugarSmall!, c: ARModel.coordinates2["sugar"]!, anchor: anchor)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 11) {
spawnCalories(amount: product1.nutriments.cals, listB: &p1BigCal, listM: &p1MedCal, listS: &p1SmallCal, bigE: calBig!, mediumE: calMed!, smallE: calSmall!, c: ARModel.coordinates1["cal"]!, anchor: anchor)
spawnCalories(amount: product2.nutriments.cals, listB: &p2BigCal, listM: &p2MedCal, listS: &p2SmallCal, bigE: calBig!, mediumE: calMed!, smallE: calSmall!, c: ARModel.coordinates2["cal"]!, anchor: anchor)
}
let chart1 = anchor.chart1
let chart2 = anchor.chart2
let chart3 = anchor.chart3
//chart1!.scale = [5, 5, 5]
print(chart1!.children[11])
var material = SimpleMaterial()
material.baseColor = .color(.white)
//set charts
setTagsToChart(chart: chart1!, material: material)
setTagsToChart(chart: chart2!, material: material)
setTagsToChart(chart: chart3!, material: material)
// bar text
setBarValues(chart: chart1!, material: material, nutriments: product1.nutriments)
setBarValues(chart: chart2!, material: material, nutriments: product2.nutriments)
setBarValues(chart: chart3!, material: material, nutriments: Nutriments(fat: 70, fiber: 1, sugars: 90, energy: 8372, carbohydrates: 260, proteins: 50))
//scale bars chart1
chart1!.children[6].scale = [1, 0.0909 * Float(0.8) * Float(product1.nutriments.proteins), 1]
chart1!.children[7].scale = [1, 0.0667 * Float(0.8) * Float(product1.nutriments.carbohydrates) * 5 / 26, 1]
chart1!.children[8].scale = [1, 0.1111 * Float(0.8) * Float(product1.nutriments.fat) * 5 / 7, 1]
chart1!.children[9].scale = [1, 0.0714 * Float(0.8) * Float(product1.nutriments.sugars) * 5 / 9, 1]
chart1!.children[10].scale = [1, 0.0476 * Float(0.8) * Float(product1.nutriments.cals) / 40, 1]
//scale bars chart2
chart2!.children[6].scale = [1, 0.0909 * Float(0.8) * Float(product2.nutriments.proteins), 1]
chart2!.children[7].scale = [1, 0.0667 * Float(0.8) * Float(product2.nutriments.carbohydrates) * 5 / 26, 1]
chart2!.children[8].scale = [1, 0.1111 * Float(0.8) * Float(product2.nutriments.fat) * 5 / 7, 1]
chart2!.children[9].scale = [1, 0.0714 * Float(0.8) * Float(product2.nutriments.sugars) * 5 / 9, 1]
chart2!.children[10].scale = [1, 0.0476 * Float(0.8) * Float(product2.nutriments.cals) / 40, 1]
chart3!.children[6].scale = [1, 0.0909 * Float(0.8) * Float(50), 1]
chart3!.children[7].scale = [1, 0.0667 * Float(0.8) * Float(260) * 5 / 26, 1]
chart3!.children[8].scale = [1, 0.1111 * Float(0.8) * Float(70) * 5 / 7 , 1]
chart3!.children[9].scale = [1, 0.0714 * Float(0.8) * Float(90) * 5 / 9, 1]
chart3!.children[10].scale = [1, 0.0476 * Float(0.8) * Float(2000) / 40, 1]
print("Floors: \(chart1!.children[0])")
print("Text on bar: \(chart1!.children[1])")
print("Bars: \(chart1!.children[6])")
print("Tags: \(chart1!.children[11])")
print("Plate element: \(anchor.plateElement)")
print("Protein ball: \(proteinBig)")
return arView
}
private static func setBarValues(chart: Entity, material: SimpleMaterial, nutriments: Nutriments) {
let textEntity: Entity = chart.children[0].children[0]
var textModelComp: ModelComponent = textEntity.components[ModelComponent]!
textModelComp.materials[0] = material
textModelComp.mesh = .generateText("\(nutriments.proteins)", extrusionDepth: 0.001, font: .systemFont(ofSize: 0.022), containerFrame: .zero, alignment: .left, lineBreakMode: .byCharWrapping)
chart.children[1].children[0].children[0].components.set(textModelComp)
textModelComp.mesh = .generateText("\(nutriments.carbohydrates)", extrusionDepth: 0.001, font: .systemFont(ofSize: 0.022), containerFrame: .zero, alignment: .left, lineBreakMode: .byCharWrapping)
chart.children[2].children[0].children[0].components.set(textModelComp)
textModelComp.mesh = .generateText("\(nutriments.fat)", extrusionDepth: 0.001, font: .systemFont(ofSize: 0.022), containerFrame: .zero, alignment: .left, lineBreakMode: .byCharWrapping)
chart.children[3].children[0].children[0].components.set(textModelComp)
textModelComp.mesh = .generateText("\(nutriments.sugars)", extrusionDepth: 0.001, font: .systemFont(ofSize: 0.022), containerFrame: .zero, alignment: .left, lineBreakMode: .byCharWrapping)
chart.children[4].children[0].children[0].components.set(textModelComp)
textModelComp.mesh = .generateText("\(nutriments.cals)", extrusionDepth: 0.001, font: .systemFont(ofSize: 0.022), containerFrame: .zero, alignment: .left, lineBreakMode: .byCharWrapping)
chart.children[5].children[0].children[0].components.set(textModelComp)
}
private static func setTagsToChart(chart: Entity, material: SimpleMaterial) {
var tag: Entity = chart.children[11].children[0].children[0]
setTags(entity: &tag, material: material, text: "proteins")
tag = chart.children[12].children[0].children[0]
setTags(entity: &tag, material: material, text: "carbs")
tag = chart.children[13].children[0].children[0]
setTags(entity: &tag, material: material, text: "fats")
tag = chart.children[14].children[0].children[0]
setTags(entity: &tag, material: material, text: "sugars")
tag = chart.children[15].children[0].children[0]
setTags(entity: &tag, material: material, text: "cals")
}
private static func setTags(entity: inout Entity, material: SimpleMaterial, text: String) {
entity.transform.translation = [-0.08, entity.transform.translation.y, entity.transform.translation.z]
var tagModelComp: ModelComponent = entity.components[ModelComponent]!
tagModelComp.materials[0] = material
tagModelComp.mesh = .generateText(text, extrusionDepth: 0.001, font: .systemFont(ofSize: 0.022), containerFrame: .zero, alignment: .left, lineBreakMode: .byCharWrapping)
entity.components.set(tagModelComp)
}
static func spawnNutrient(amount: Int, listB: inout [Entity?], listS: inout [Entity?], bigE: Entity, smallE: Entity, c: Coordinates, anchor: Experience.Box) {
let big = amount / 4
let small = amount % 4
listB = createNutriEntities(typeOf: bigE, numberOf: big)
listS = createNutriEntities(typeOf: smallE, numberOf: small)
setPositionToEntities(list: listB, x: c.x, y: c.y, z: c.z, delta: 0.015)
setPositionToEntities(list: listS, x: c.x, y: (c.y + 0.015 * Float(big)), z: c.z, delta: 0.015)
addChildrenToAnchor(list: listB, anchor: anchor)
addChildrenToAnchor(list: listS, anchor: anchor)
}
static func spawnCalories(amount: Int, listB: inout [Entity?], listM: inout [Entity?], listS: inout [Entity?], bigE: Entity, mediumE: Entity, smallE: Entity, c: Coordinates, anchor: Experience.Box) {
let big = amount / 100
let med = (amount % 100) / 10
let small = amount % 10
listB = createNutriEntities(typeOf: bigE, numberOf: big)
listM = createNutriEntities(typeOf: mediumE, numberOf: med)
listS = createNutriEntities(typeOf: smallE, numberOf: small)
setPositionToEntities(list: listB, x: c.x, y: c.y, z: c.z, delta: 0.02)
setPositionToEntities(list: listM, x: c.x, y: c.y, z: c.z, delta: 0.015)
setPositionToEntities(list: listS, x: c.x, y: c.y, z: c.z, delta: 0.015)
addChildrenToAnchor(list: listB, anchor: anchor)
addChildrenToAnchor(list: listM, anchor: anchor)
addChildrenToAnchor(list: listS, anchor: anchor)
}
static func createNutriEntities(typeOf entity: Entity?, numberOf n: Int) -> [Entity?] {
var list = [Entity?]()
for _ in 0..<n {
let temp = entity!.clone(recursive: true)
list.append(temp)
}
return list
}
static func setPositionToEntities(list: [Entity?], x: Float, y: Float, z: Float, delta: Float) {
var deltaY: Float = y
for i in 0..<list.count {
let stream = i % 5
switch stream {
case 0:
list[i]!.position = [x + delta, deltaY, z + delta]
case 1:
list[i]!.position = [x - delta, deltaY, z - delta]
case 2:
list[i]!.position = [x - delta, deltaY, z + delta]
case 3:
list[i]!.position = [x + delta, deltaY, z - delta]
case 4:
list[i]!.position = [x, deltaY, z]
default:
list[i]!.position = [x, y, z]
}
deltaY += delta
}
}
static func addChildrenToAnchor(list: [Entity?], anchor: Experience.Box) {
for entity in list {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
anchor.addChild(entity!)
}
}
}
func removeChildrenFromScene(list: [Entity?]) {
for entity in list {
entity!.removeFromParent()
}
}
}
struct Coordinates {
var x: Float
var y: Float
var z: Float
}
|
import FluentProvider
import AuthProvider
final class Routes: RouteCollection {
private let view: ViewRenderer
private let hash: HashProtocol
init(view: ViewRenderer, hash: HashProtocol) {
self.view = view
self.hash = hash
}
func build(_ builder: RouteBuilder) throws {
RoutingController.addRoute(builder: builder)
FluentController.addRoute(builder: builder)
LeafController.addRoute(builder: builder, view: view)
builder.resource("users", UserController(hash: hash))
builder.resource("login", LoginController(view: view, hash: hash))
let secureGroup = builder.grouped(PasswordAuthenticationMiddleware(User.self))
secureGroup.get("auth") { request in
return try request.auth.assertAuthenticated(User.self).makeJSON()
}
}
}
final class EmptyInitializableRoutes: RouteCollection, EmptyInitializable {
func build(_ builder: RouteBuilder) throws {}
}
|
//
// LoaderCirclesView.swift
// SocialApp
//
// Created by Иван Казанцев on 09.02.2021.
//
import UIKit
class LoaderCirclesView: UIView {
let firstCircle = UIView()
let secondCircle = UIView()
let thirdCircle = UIView()
override init(frame:CGRect) {
super.init(frame:frame)
initLoader()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initLoader()
}
private func initLoader() {
addSubview(firstCircle)
addSubview(secondCircle)
addSubview(thirdCircle)
firstCircle.backgroundColor = .gray
secondCircle.backgroundColor = .gray
thirdCircle.backgroundColor = .gray
}
override func layoutSubviews() {
super.layoutSubviews()
// задаем начальные параметры
let indent: CGFloat = bounds.height*0.1
let circleDiameter = bounds.height - indent
let circleStep = bounds.width/3 + (indent*2)
let cornerRadiusSize = circleDiameter/2
//создаемся фреймы
firstCircle.frame = CGRect(x: 0, y: indent, width: circleDiameter, height: circleDiameter)
secondCircle.frame = CGRect(x: circleStep, y: indent, width: circleDiameter, height: circleDiameter)
thirdCircle.frame = CGRect(x: circleStep*2, y: indent, width: circleDiameter, height: circleDiameter)
//скругляем углы так чтобы получились кружки
firstCircle.layer.cornerRadius = cornerRadiusSize
secondCircle.layer.cornerRadius = cornerRadiusSize
thirdCircle.layer.cornerRadius = cornerRadiusSize
}
public func animateLoader() {
UIView.animate(withDuration: 1,
delay: 0,
options: [.repeat, .autoreverse, .curveEaseIn],
animations: {
self.firstCircle.alpha = 0.5
})
UIView.animate(withDuration: 1,
delay: 0.6,
options: [.repeat, .autoreverse, .curveEaseIn],
animations: {
self.secondCircle.alpha = 0.5
})
UIView.animate(withDuration: 1,
delay: 1.2,
options: [.repeat, .autoreverse, .curveEaseIn],
animations: {
self.thirdCircle.alpha = 0.5
})
}
}
|
//
// ViewController.swift
// swift docs page view controller
//
// Created by Hashimoto Ryo on 2016/04/06.
// Copyright © 2016年 Hashimoto Ryo. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate{
private var pageControl: UIPageControl!
private var scrollView: UIScrollView!
override func viewDidLoad() {
// ビューの縦、横のサイズを取得する.
let width = self.view.frame.maxX, height = self.view.frame.maxY
// 背景の色をCyanに設定する.
self.view.backgroundColor = UIColor.cyanColor()
// ScrollViewを取得する.
scrollView = UIScrollView(frame: self.view.frame)
// ページ数を定義する.
let pageSize = 4
// 縦方向と、横方向のインディケータを非表示にする.
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
// ページングを許可する.
scrollView.pagingEnabled = true
// ScrollViewのデリゲートを設定する.
scrollView.delegate = self
// スクロールの画面サイズを指定する.
scrollView.contentSize = CGSizeMake(CGFloat(pageSize) * width, 0)
// ScrollViewをViewに追加する.
self.view.addSubview(scrollView)
// ページ数分ボタンを生成する.
for var i = 0; i < pageSize; i++ {
// ページごとに異なるラベルを生成する.
let myLabel:UILabel = UILabel(frame: CGRectMake(CGFloat(i) * width + width/2 - 40, height/2 - 40, 80, 80))
myLabel.backgroundColor = UIColor.blackColor()
myLabel.textColor = UIColor.whiteColor()
myLabel.textAlignment = NSTextAlignment.Center
myLabel.layer.masksToBounds = true
myLabel.text = "Page\(i)"
myLabel.font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize())
myLabel.layer.cornerRadius = 10.0
scrollView.addSubview(myLabel)
}
//
// // PageControlを作成する.
// pageControl = UIPageControl(frame: CGRectMake(0, self.view.frame.maxY - 100, width, 50))
// pageControl.backgroundColor = UIColor.orangeColor()
//
// // PageControlするページ数を設定する.
// pageControl.numberOfPages = pageSize
//
// // 現在ページを設定する.
// pageControl.currentPage = 0
// pageControl.userInteractionEnabled = false
//
// self.view.addSubview(pageControl)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
// スクロール数が1ページ分になったら時.
// if fmod(scrollView.contentOffset.x, scrollView.frame.maxX) == 0 {
// // ページの場所を切り替える.
// pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.frame.maxX)
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// RepositoryTableViewCell.swift
// SCTestTask
//
// Created by Aleksey Kornienko on 20/05/2018.
// Copyright © 2018 Aleksey Kornienko. All rights reserved.
//
import UIKit
protocol RepositoryCellProtocol {
var viewModel: RepositoryCellViewModelProtocol? { get set }
}
protocol RepositoryCommitsProtocol {
func commitsDidLoad()
}
class RepositoryTableViewCell: UITableViewCell, NibLoadable, ViewReusable, RepositoryCellProtocol {
@IBOutlet weak var repoName: UILabel!
@IBOutlet weak var lastCommit: UILabel!
@IBOutlet weak var repoDescription: UILinedTextView!
@IBOutlet weak var languageView: UIView!
@IBOutlet weak var forkedView: UIView!
@IBOutlet weak var licenseView: UIView!
@IBOutlet weak var updatedView: UIView!
@IBOutlet weak var language: UILabel!
@IBOutlet weak var forks: UILabel!
@IBOutlet weak var license: UILabel!
@IBOutlet weak var updated: UILabel!
var viewModel: RepositoryCellViewModelProtocol? {
didSet {
viewModel?.commitsDelegate = self
repoName.text = viewModel?.name
repoDescription.text = viewModel?.description
let languageText = viewModel?.language
language.text = languageText
languageView.isHidden = languageText == nil
let forksText = viewModel?.forks
forks.text = forksText
forkedView.isHidden = forksText == nil
let licenceText = viewModel?.license
license.text = licenceText
licenseView.isHidden = licenceText == nil
let updatedText = viewModel?.updated
updated.text = updatedText
updatedView.isHidden = updatedText == nil
}
}
}
extension RepositoryTableViewCell: RepositoryCommitsProtocol {
func commitsDidLoad() {
if let entity = viewModel?.commits.first {
lastCommit.text = "Last commit: \(entity.commit.message)" //TODO NSLocalizableString
} else {
lastCommit.text = "Last commit: no message"
}
layoutIfNeeded()
}
}
|
// Copyright © 2018 Nazariy Gorpynyuk.
// All rights reserved.
import Foundation
/// Replacement for Objective-C's `@synchronized`, with added support for return values.
public func synchronized<ReturnType>(_ lockToken: AnyObject, closure: ThrowingReturningClosure<ReturnType>) rethrows -> ReturnType {
objc_sync_enter(lockToken)
defer { objc_sync_exit(lockToken) }
return try closure()
}
|
//
// TaskHeader+CoreDataProperties.swift
// TaskOut
//
// Created by Reagan Wood on 8/16/16.
// Copyright © 2016 RW Software. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension TaskHeader {
@NSManaged var taskTitle: String?
@NSManaged var taskType: NSNumber?
@NSManaged var taskItem: NSSet?
}
|
//
// DatabaseManager.swift
// ProgrammingTutorials
//
// Created by Jakub "GPH4PPY" Dąbrowski on 05/11/2020.
//
import Foundation
import FirebaseDatabase
final class DatabaseManager {
static let shared = DatabaseManager()
private let database = Database.database().reference()
/// This method converts e-mail address to the safe version - removes dot and hyphen
/// - Parameter emailAddress: user's e-mail address
/// - Returns: (String) new, safe version of e-mail address
static func safeEmail(emailAddress: String) -> String {
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
return safeEmail
}
}
// MARK: - Account Management
extension DatabaseManager {
/// This method inserts new user to the Realtime Database
/// - Parameters:
/// - user: object with user data: name, email and name of profile picture file
/// - completion: when everything is done, check for errors
public func insertUser(with user: AppUser, completion: @escaping (Bool) -> Void) {
database.child(user.safeEmail).setValue([
"name": user.name,
"email": user.safeEmail,
"pictureName": user.profilePictureFileName
], withCompletionBlock: { error, _ in
guard error == nil else {
print("Failed to write to database")
return
}
})
}
}
extension DatabaseManager {
/// This method gets data from a Realtime Database path
/// - Parameters:
/// - path: a place of the data that we are looking for in Database
/// - completion: when everything is done, it gives result or an error
public func getDataFor(path: String, completion: @escaping (Result<Any, Error>) -> Void) {
self.database.child(path).observeSingleEvent(of: .value) { snapshot in
guard let value = snapshot.value else {
completion(.failure(DatabaseError.failedToFetch))
return
}
completion(.success(value))
}
}
}
// MARK: Errors
public enum DatabaseError: Error {
case failedToFetch
}
|
//
// NewsfeedViewController.swift
// CAGradientLayer
//
// Created by Thanh Nguyen Xuan on 9/14/18.
// Copyright © 2018 Thanh Nguyen. All rights reserved.
//
import UIKit
class NewsfeedViewController: UIViewController {
@IBOutlet fileprivate weak var tableView: UITableView!
fileprivate let numberOfPlaceHolderCells = 3
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startLoading()
}
private func startLoading() {
tableView.visibleCells.forEach({
$0.contentView.startAnimationLoading()
})
}
private func stopLoading() {
tableView.visibleCells.forEach({
$0.contentView.stopAnimationLoading()
})
}
@IBAction func startButtonTapped(_ sender: Any) {
startLoading()
}
@IBAction func stopButtonTapped(_ sender: Any) {
stopLoading()
}
}
// MARK: - UITableViewDatasource
extension NewsfeedViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfPlaceHolderCells
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "newsfeedCell", for: indexPath)
}
}
// MARK: - UITableViewDelegate
extension NewsfeedViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let tabBarHeight = tabBarController?.tabBar.frame.height ?? 0
return (view.frame.height - tabBarHeight) / CGFloat(numberOfPlaceHolderCells)
}
}
|
import Foundation
struct TodoModel:Codable{
var todoList = [Todo]()
var tagList = [Tag]()
mutating func newTag(string:String){
if !string.isEmpty {
tagList = tagList + [Tag(detail: string)]
}
}
mutating func addTodo(todo:Todo){
todoList = todoList + [todo]
}
mutating func deleteTodo(todo:Todo?){
guard let todo = todo else {return}
todoList = todoList.filter{$0 != todo}
}
mutating func doneTodo(todo:Todo){
deleteTodo(todo: todo)
let newTodo = Todo(
detail: todo.detail,
tag: todo.tag,
dueDate: todo.dueDate,
done: true,
doneDate: Date())
addTodo(todo: newTodo)
}
mutating func sortTodoList(){
todoList = todoList.sorted{
$0.dueDate.compare($1.dueDate) == ComparisonResult.orderedAscending
}
}
func save(todoModel:TodoModel){
guard let data = try? JSONEncoder().encode(todoModel) else {return}
UserDefaults.standard.set(data, forKey: "save")
}
func load()->TodoModel{
guard let data = UserDefaults.standard.data(forKey: "save") else {return TodoModel()}
return (try? JSONDecoder().decode(TodoModel.self, from: data)) ?? TodoModel()
}
}
|
//
// WideFindView.swift
// RobinX0001E WatchKit Extension
//
// Created by roblof-8 on 2021-07-28.
//
import SwiftUI
struct WideFindView: View {
let con : Connection?
init(con : Connection) {
self.con = con
}
var body: some View {
Text("Coordinate prints")
}
}
/*
struct WideFindView_Previews: PreviewProvider {
static var previews: some View {
WideFindView()
}
}*/
|
// RUN: true
public func go() throws {
throw AXError(0)
}
|
//
// 🦕.swift
// Dyno
//
// Created by strictlyswift on 16-Feb-19.
//
import Foundation
import Dispatch
import RxSwift
import Combine
import PythonKit
import PythonCodable
import StrictlySwiftLib
public typealias DynoResult<T> = Result<T,DynoError>
/// Dyno 🦕 represents an AWS DynamoDB database, and provides a number of 'safe' functions for handling data interactions in a Reactive manner.
public struct Dyno {
let dynoQueue : DispatchQueue // queue enforces serial access to boto3 resources
let connection : DynoConnection
let options : DynoOptions
let dynoSemaphore = DispatchSemaphore(value: 0)
/// Creates a connection to a dynamodb. If the accessKeyId/secretAccessKey/region is not passed in, it uses the information in ~/.aws/credentials and ~/.aws/config.
/// (You must pass all of them, or none of them).
/// The connection is _not_ accessed immediately, but only lazily when it is used to access data. `isValid`
/// actually does a table connection to force evaluation.
public init( resource: String = "dynamodb",
accessKeyId: String? = nil,
secretAccessKey: String? = nil,
region: String? = nil,
_ options : DynoOptions = DynoOptions() ) {
self.dynoQueue = DispatchQueue(label: "DynoQueue", qos: .default, attributes: [], autoreleaseFrequency: .inherit, target: nil)
self.options = options
self.connection = DynoBoto3(resource: resource, accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, region: region, options)
}
public init( connection: DynoConnection,
_ options : DynoOptions = DynoOptions() ) {
self.dynoQueue = DispatchQueue(label: "DynoQueue", qos: .default, attributes: [], autoreleaseFrequency: .inherit, target: nil)
self.options = options
self.connection = connection
}
/// Returns true if the connection is valid (eg, not timed out, and actually points to a real database).
/// To determine any error, use connectionError. Forces a table connection to confirm validity.
public func isValidConnection() -> Bool {
return self.connection.isValid()
}
/// Returns the most recent connection error, if one exists.
public func connectionError() -> DynoError? {
return self.connection.lastError()
}
internal func carryOutActivity<T,D>(action: D, completion: @escaping (DynoResult<T>) -> Void)
where D : DynoBotoAction, D.T == T {
switch self.connection.isValid() {
case true:
// Run next part async on semaphore... need the WorkItem to cancel
let semaphore = DispatchSemaphore(value: 0)
var cancelFlag = false
let workItem = DispatchWorkItem {
switch action.perform(connection: self.connection) {
case .success(let v):
if !cancelFlag {
completion(.success(v))
}
semaphore.signal()
case .failure(let f):
if !cancelFlag {
completion(.failure(f) )
}
semaphore.signal()
}
}
let stopTime = DispatchTime.now() + Double(self.options.timeout)
self.dynoQueue.async(execute: workItem) // run on 'dynoQueue' to force serial access to shared resources
if semaphore.wait(timeout: stopTime) == .timedOut {
completion(.failure(DynoError("Timeout")))
cancelFlag = true
workItem.cancel()
}
case false:
completion( .failure(self.connectionError()!) )
}
}
/// Performs an action on the DynamoDB database. Tries hard to not get 'stuck' if DynamoDB doesn't
/// respond in time; and allows for simultaneous calls to the same connection, which seems to be an
/// issue otherwise. Note that we re-try the Dyno connection each time (no connection caching).
///
/// If there is an error (eg Timeout), the next entry will be `DynoActivity.failure(DynoError)`
/// Otherwise, you will currently always get `DynoActivity.fullSuccess(T)`
///
/// - Parameter action: Action to perform
/// - Returns: Observable sequence constructed as above.
internal func perform<T,D>(action: D) -> DynoPublisher<T>
where D : DynoBotoAction, D.T == T {
Combine.Future<T,DynoError> { promise in
self.carryOutActivity(action: action) { result in
promise(result)
}
}
.print(action.logName)
.eraseToAnyPublisher()
// Removed the 'activityInProgress'.. don't think we need this?
// though note I am not wrapping the above in DispatchQueue.global().async {
// do I need to..?
}
internal func performOld<T,D>(action: D) -> Observable<DynoActivity<T>> where D : DynoBotoAction, D.T == T {
return Observable.create { observer in
DispatchQueue.global().async {
switch self.connection.isValid() {
case true:
observer.onNext( DynoActivity<T>.activityInProgress )
// Run next part async on semaphore... need the WorkItem to cancel
let semaphore = DispatchSemaphore(value: 0)
var cancelFlag = false
let workItem = DispatchWorkItem {
switch action.perform(connection: self.connection) {
case .success(let v):
if !cancelFlag {
observer.onNext(DynoActivity.fullSuccess(v))
observer.onCompleted()
}
semaphore.signal()
case .failure(let f):
if !cancelFlag {
observer.onNext( DynoActivity.failure(f) )
observer.onCompleted()
}
semaphore.signal()
}
}
let stopTime = DispatchTime.now() + Double(self.options.timeout)
self.dynoQueue.async(execute: workItem) // run on 'dynoQueue' to force serial access to shared resources
if semaphore.wait(timeout: stopTime) == .timedOut {
observer.onNext(DynoActivity.failure(DynoError("Timeout")))
observer.onCompleted()
cancelFlag = true
workItem.cancel()
}
case false:
observer.onNext( DynoActivity<T>.failure(self.connectionError()!) )
observer.onCompleted()
}
}
return Disposables.create()
}//.log(action.logName, do: self.options.log)
}
}
|
//
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
import XCTest
import AutoMate
class ___FILEBASENAMEASIDENTIFIER___: AppUITestCase {
// MARK: Arrange Page Objects
lazy var myReusablePage1: MyReusablePage = MyReusablePage(in: self.app)
// MARK: Set up
// Called once before whole class
override class func setUp() {
// Put setup code here.
super.setUp()
}
// Called before each test method
override func setUp() {
super.setUp()
// Put setup code here.
TestLauncher.configure(app, withOptions: []).launch()
}
// MARK: Tear down
// Called once after all tests are run
override class func tearDown() {
// Put teardown code here.
super.tearDown()
}
// Called once after each test
override func tearDown() {
// Put teardown code here.
super.tearDown()
}
// MARK: Tests
func testMethod1() {
// Put your test code here.
}
func testMethod2() {
// Put your test code here.
}
// MARK: Helpers
func localMethod() {
// Put a reusable code here.
}
}
|
//
// DetailViewController.swift
// hw1
//
// Created by Александр Пономарёв on 13/03/2019.
// Copyright © 2019 Александр Пономарёв. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet private var avatarView: UIImageView!
@IBOutlet private var genderLabel: UILabel!
@IBOutlet private var originNameLabel: UILabel!
@IBOutlet private var nameLable: UILabel!
@IBOutlet private var statusLabel: UILabel!
@IBOutlet private var speciesLabel: UILabel!
var realmPerson: RealmChar?
override func viewDidLoad() {
super.viewDidLoad()
guard let realmPerson = realmPerson else { return }
nameLable.text = "Name: \(realmPerson.name)"
genderLabel.text = "Gender: \(realmPerson.gender)"
statusLabel.text = "Status: \(realmPerson.status)"
speciesLabel.text = "Species: \(realmPerson.species)"
originNameLabel.text = "Origin: \(realmPerson.originPlanetName) 🌍"
let url = URL(string: realmPerson.image)
guard let urlNew = url else { return }
self.avatarView.kf.setImage(with: urlNew)
}
@IBAction private func tapToPLanet(_ sender: UITapGestureRecognizer) {
guard let planetVC = storyboard?.instantiateViewController(withIdentifier: "PlanetViewController") as? PlanetViewController,
realmPerson?.originPlanetName != "unknown" else { return }
self.navigationController?.pushViewController(planetVC, animated: true)
planetVC.url = realmPerson?.originPlanetUrl
}
}
|
//
// ViewController.swift
// MoveTableViewCellPractice
//
// Created by mac on 2021/04/15.
//
import UIKit
class ViewController: UIViewController {
let tableView = UITableView()
var data = ["1st","2nd","3rd","4th","5th"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
let barButtonItem = UIBarButtonItem(title: "Sort", style: .done, target: self, action: #selector(didTabSortButton(_:)))
navigationItem.leftBarButtonItem = barButtonItem
}
@objc private func didTabSortButton(_ sender: UIButton) {
if tableView.isEditing {
tableView.isEditing = false
} else {
tableView.isEditing = true
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
cell.textLabel?.textAlignment = .center
return cell
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
data.swapAt(sourceIndexPath.row, destinationIndexPath.row)
}
}
|
// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
import Foundation
// swiftlint:disable file_length
// swiftlint:disable line_length
// swiftlint:disable type_body_length
// swiftlint:disable nesting
// swiftlint:disable variable_name
// swiftlint:disable valid_docs
// swiftlint:disable type_name
enum L10n {
/// blue hour
static let blueHour = L10n.tr("blue_hour")
/// checking weather forecast...
static let checkingForecast = L10n.tr("checking_forecast")
/// weather forecast unavailable
static let forecastUnavailable = L10n.tr("forecast_unavailable")
/// from
static let from = L10n.tr("from")
/// golden hour
static let goldenHour = L10n.tr("golden_hour")
/// New York
static let newYork = L10n.tr("New_York")
/// polar day
static let polarDay = L10n.tr("polar_day")
/// polar night
static let polarNight = L10n.tr("polar_night")
/// search...
static let search = L10n.tr("search")
/// sunrise
static let sunrise = L10n.tr("sunrise")
/// sunset
static let sunset = L10n.tr("sunset")
/// to
static let to = L10n.tr("to")
/// Tokyo
static let tokyo = L10n.tr("Tokyo")
/// Warsaw
static let warsaw = L10n.tr("Warsaw")
}
extension L10n {
fileprivate static func tr(_ key: String, _ args: CVarArg...) -> String {
let format = NSLocalizedString(key, bundle: Bundle(for: BundleToken.self), comment: "")
return String(format: format, locale: Locale.current, arguments: args)
}
}
private final class BundleToken {}
// swiftlint:enable type_body_length
// swiftlint:enable nesting
// swiftlint:enable variable_name
// swiftlint:enable valid_docs
|
//
// ContentView.swift
// SpaceWatch
//
// Created by David Jöch on 03.06.20.
// Copyright © 2020 David Jöch. All rights reserved.
//
import SwiftUI
struct LaunchListView: View {
@ObservedObject var launchStore: LaunchStore = LaunchStore()
init() {
// Workaround since SwiftUI lists do not support seperatorStyle and selectionStyle settings yet
UITableView.appearance().separatorStyle = .none
UITableViewCell.appearance().selectionStyle = .none
}
var body: some View {
NavigationView {
List {
ForEach(launchStore.launches) { launch in
ZStack {
NavigationLink(destination: LaunchDetailView(launch: launch)) {
// Workaround for hiding Disclosure icons in list views
EmptyView()
}
LaunchListRowView(title: launch.mission_name, location: launch.launch_site.site_name)
}
}
}
.navigationBarTitle("Upcoming")
}
.onAppear {
self.launchStore.fetchUpcoming()
}
}
}
|
//
// Task.swift
// Tally
//
// Created by Eric Fritz on 12/23/16.
// Copyright © 2016 Eric Fritz. All rights reserved.
//
import UIKit
class TimedTask {
let id: Int64
var name: String
var durations: [Duration]
var color: UIColor
init(id: Int64, name: String, durations: [Duration] = [], color: UIColor = UIColor.white) {
self.id = id
self.name = name
self.durations = durations
self.color = color
}
func start() {
self.stop()
if let duration = Database.instance.createDuration(for: self) {
self.durations.append(duration)
} else {
// better recovery
print("Could not create duration.")
}
}
func stop() {
self.durations.last?.stop()
}
func active() -> Bool {
if let last = self.durations.last {
return last.active()
}
return false
}
func elapsed() -> Int {
return self.durations.map({ $0.elapsed() }).reduce(0, +)
}
func currentElapsed() -> Int {
if self.active(), let d = self.durations.last {
return d.elapsed()
}
return 0
}
}
|
//
// Array+Extensions.swift
// NGTools
//
// Created by Fournier, Olivier on 2018-01-31.
// Copyright © 2018 Nuglif. All rights reserved.
//
import Foundation
public extension Array {
static func += (lhs: inout [Element], rhs: Element?) {
guard let element = rhs else { return }
lhs.append(element)
}
static func += (lhs: inout [Element], rhs: [Element]?) {
guard let elements = rhs else { return }
lhs.append(contentsOf: elements)
}
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
|
//
// SettingTableViewController.swift
// ddx0513
//
// Created by ejian on 15/6/2.
// Copyright (c) 2015年 jiang yongbin. All rights reserved.
//
import UIKit
class SettingTableViewController: UITableViewController, UIGestureRecognizerDelegate, PopupDelegate {
var interval = 0
var oneMonthPrice = 0.0
var sixMonthsPrice = 0.0
var oneYearPrice = 0.0
@IBOutlet weak var nickLabel: UILabel!
@IBOutlet weak var accountLabel: UILabel!
@IBOutlet weak var sixMonthOldPriceLabel: UILabel!
@IBOutlet weak var oneYearOldPriceLabel: UILabel!
@IBOutlet weak var vipTimeLabel: UILabel!
@IBOutlet weak var vipLeftTimeLabel: UILabel!
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var cacheSizeLabel: UILabel!
@IBOutlet weak var wifiNetButton: UIButton!
@IBOutlet weak var oneMonthLabel: UILabel!
@IBOutlet weak var sixMonthsLabel: UILabel!
@IBOutlet weak var oneYearLabel: UILabel!
@IBOutlet weak var operaterLabel: UILabel!
// MARK: - 函数
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//显示导航栏
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.accountLabel.text = "登录账户:\(DBUtils.mem.loginName)"
NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLBase(), parameters: nil, responseHandler: nil, netErrorHandler: nil, successHandler: initPrice, interErrorHandler: nil, jsonErrorHandler: nil)
self.cacheSizeLabel.text = "计算中.."
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
let cacheSize = FileUtils.calcFoldSize()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.cacheSizeLabel.text = StringUtils.formatFileSize(cacheSize)
})
})
if (!DBUtils.mem.isCellularNet) {
wifiNetButton.setBackgroundImage(UIImage(named: "设置-未开启_03"), forState: UIControlState.Normal)
} else {
wifiNetButton.setBackgroundImage(UIImage(named: "设置_13"), forState: UIControlState.Normal)
}
self.useBlurForPopup = false
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("weixinPayHandler:"), name: StringUtils.WeipayNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
if (DBUtils.mem.nickName == "") {
self.nickLabel.text = "未设置"
} else {
self.nickLabel.text = DBUtils.mem.nickName
}
if (DBUtils.mem.imgURL != "") {
DBUtils.getImageFromFile(DBUtils.mem.imgURL, successHandler: { (_imageURL, _image) -> Void in
if (_imageURL == DBUtils.mem.imgURL) {
self.userImageView.image = _image
}
})
}
}
override func viewDidDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: StringUtils.WeipayNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func weixinPayHandler(notification: NSNotification) {
self.dismissPopupViewControllerAnimated(false, completion: nil)
let resp = notification.object as! BaseResp
switch(resp.errCode) {
case 0:
ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付成功")
let a = ["mobile": DBUtils.mem.loginName, "pwd": DBUtils.mem.password]
NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLLogin(), parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: login, interErrorHandler: nil, jsonErrorHandler: nil)
case -2:
ViewUtils.popMessage(self, title: "微信支付结果", message: "用户点击取消并返回")
default:
ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付失败")
}
}
@IBAction func backButtonPressed(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
//退出登录
@IBAction func logoutButtonPressed(sender: AnyObject) {
var userDefault = NSUserDefaults.standardUserDefaults()
userDefault.setObject(false, forKey: DBUtils.varNames.loginStatus)
userDefault.synchronize()
DBUtils.mem.loginStatus = false
rootController.navigationController?.popToRootViewControllerAnimated(true)
rootController.navigationController?.setNavigationBarHidden(true, animated: true)
}
//一个月VIP
@IBAction func oneMonthVipButtonPressed(sender: AnyObject) {
DBUtils.mem.vipType = "NONE_VIP"
if (DBUtils.mem.vipType == "NOTIME_VIP") {
ViewUtils.popMessage(self, title: "订购失败", message: "您已开通VIP会员,无需重复开通。")
} else {
var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayChannel") as! PayChannelViewController
viewController.delegate = self
viewController.aliPay = self.oneMonthPrice
viewController.weixinPay = self.oneMonthPrice
viewController.month = 1
self.presentPopupViewController(viewController, animated: true, completion: nil)
self.setPopviewGuesture()
}
}
//六个月VIP
@IBAction func sixMonthVipButtonPressed(sender: AnyObject) {
if (DBUtils.mem.vipType == "NOTIME_VIP") {
ViewUtils.popMessage(self, title: "订购失败", message: "您已开通VIP会员,无需重复开通。")
} else {
var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayChannel") as! PayChannelViewController
viewController.delegate = self
viewController.aliPay = self.sixMonthsPrice
viewController.weixinPay = self.sixMonthsPrice
viewController.month = 6
self.presentPopupViewController(viewController, animated: true, completion: nil)
self.setPopviewGuesture()
}
}
//一年VIP
@IBAction func oneYearVipButtonPressed(sender: AnyObject) {
if (DBUtils.mem.vipType == "NOTIME_VIP") {
ViewUtils.popMessage(self, title: "订购失败", message: " 您已开通VIP会员,无需重复开通。")
} else {
var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayChannel") as! PayChannelViewController
viewController.delegate = self
viewController.aliPay = self.oneYearPrice
viewController.weixinPay = self.oneYearPrice
viewController.month = 12
self.presentPopupViewController(viewController, animated: true, completion: nil)
self.setPopviewGuesture()
}
}
//手机开通
@IBAction func phoneVipButtonPressed(sender: AnyObject) {
if (DBUtils.mem.vipType == "NOTIME_VIP") {
ViewUtils.popMessage(self, title: "订购失败", message: "您已开通VIP会员,无需重复开通。")
} else if (DBUtils.mem.vipType == "TIME_VIP") {
ViewUtils.popMessage(self, title: "订购失败", message: " 服务未到期,请在\(self.interval)天后订购开通。")
} else {
var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayCenter") as! PayCenterViewController
viewController.delegate = self
self.presentPopupViewController(viewController, animated: true, completion: nil)
self.setPopviewGuesture()
}
}
@IBAction func netSwitchPressed(sender: AnyObject) {
DBUtils.mem.isCellularNet = !DBUtils.mem.isCellularNet
var userDefault = NSUserDefaults.standardUserDefaults()
userDefault.setObject(DBUtils.mem.isCellularNet, forKey: DBUtils.varNames.isCellularNet)
userDefault.synchronize()
if (!DBUtils.mem.isCellularNet) {
wifiNetButton.setBackgroundImage(UIImage(named: "设置-未开启_03"), forState: UIControlState.Normal)
} else {
wifiNetButton.setBackgroundImage(UIImage(named: "设置_13"), forState: UIControlState.Normal)
}
}
func setPopviewGuesture() {
var fadeview = self.getBlueView()
var tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismissPopup:"))
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.delegate = self
fadeview.addGestureRecognizer(tapRecognizer)
}
func setProgress(cell: UITableViewCell) {
let x = 15 as CGFloat, y = 37 as CGFloat
let width = cell.frame.width - 30
let imgb = UIImage(named: "进度条2b.png")
var imgbView = UIImageView(image: imgb)
imgbView.frame = CGRectMake(x, y, width, imgb!.size.height)
cell.addSubview(imgbView)
if (DBUtils.mem.vipType == "TIME_VIP") {
let timePassed = StringUtils.getDayCount(Double(DBUtils.mem.vipBegin), toTime: NSDate().timeIntervalSince1970 * 1000)
let allTime = StringUtils.getDayCount(Double(DBUtils.mem.vipBegin), toTime: Double(DBUtils.mem.vipExpire))
var jd = CGFloat(timePassed) / CGFloat(allTime)
let upWidth = width * jd
var img1 = UIImage(named: "进度条2.png")
var img = UIImageView(image: img1)
if (upWidth < img1!.size.width) {
img.clipsToBounds = true
img.contentMode = UIViewContentMode.Left
} else {
jd = 1.0 as CGFloat
}
img.frame = CGRectMake(x, y, upWidth, img1!.size.height)
cell.addSubview(img)
let img32 = UIImage(named: "进度条圆点.png")
var img3 = UIImageView(image: img32)
img3.frame = CGRectMake(x + upWidth - img32!.size.width / 2, y + img1!.size.height / 2 - img32!.size.height / 2, img32!.size.width, img32!.size.height)
var color = img1?.colorAtPixel(CGPoint(x: img1!.size.width * jd - 1, y: img1!.size.height / 2))
var img3b2 = UIImage(named: "进度条圆点背景.png")!.imageWithGradientTintColor(color)
var img3b = UIImageView(image: img3b2)
let dis = 3 as CGFloat
var xx: CGFloat?, yy: CGFloat?
xx = x + upWidth + img32!.size.width / 2 + dis - img3b2!.size.width
yy = y + img1!.size.height / 2 - img3b2!.size.height / 2
if (xx < x) {
xx = x
img3b.image = img3b2!.imageWithGradientTintColor(UIColor(red: 241/255, green: 215/255, blue: 79/255, alpha: 1.0))
img3.frame = CGRectMake(x + img3b2!.size.width - img32!.size.width - dis, y + img1!.size.height / 2 - img32!.size.height / 2, img32!.size.width, img32!.size.height)
}
let a = xx! + img3b2!.size.width
let b = x + width + img32!.size.width / 2 + dis
if (a > b) {
xx = b - img3b2!.size.width
}
img3b.frame = CGRectMake(xx!, yy!, img3b2!.size.width, img3b2!.size.height)
cell.addSubview(img3b)
cell.addSubview(img3)
}
}
func setVipInfo(cell: UITableViewCell) {
if (DBUtils.mem.vipType == "NONE_VIP") {
self.vipTimeLabel.text = "VIP到期时间:非会员"
self.vipLeftTimeLabel.text = ""
} else if (DBUtils.mem.vipType == "TIME_VIP") {
self.vipTimeLabel.text = "VIP到期时间:" + StringUtils.getDateString(Double(DBUtils.mem.vipExpire), format: "yyyy-MM-dd")
self.interval = StringUtils.getDayCount(NSDate().timeIntervalSince1970 * 1000, toTime: Double(DBUtils.mem.vipExpire))
self.vipLeftTimeLabel.text = "还剩\(self.interval)天"
setProgress(cell)
} else if (DBUtils.mem.vipType == "NOTIME_VIP") {
self.vipTimeLabel.text = "VIP到期时间:包月"
self.vipLeftTimeLabel.text = ""
setProgress(cell)
}
}
func setPrice(priceOri: Int, price: Int, cell: UITableViewCell, frame: CGRect) {
if (priceOri == price) {
var label = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 32, 18))
label.text = "¥\(priceOri / 100)"
let font = UIFont.systemFontOfSize(15 as CGFloat)
label.font = font
label.textColor = UIColor.orangeColor()
let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))
cell?.addSubview(label)
} else {
var label1 = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 43, 17))
label1.text = "¥\(priceOri / 100)"
let font1 = UIFont.systemFontOfSize(14 as CGFloat)
label1.font = font1
label1.textColor = UIColor.lightGrayColor()
cell.addSubview(label1)
var str = label1.text
var num = count(str!)
let attr = NSMutableAttributedString(string: str!)
attr.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(integer: 1), range: NSMakeRange(0, num))
label1.attributedText = attr
label1.sizeToFit()
let frame2 = label1.frame
var label2 = UILabel(frame: CGRectMake(frame2.origin.x + frame2.size.width, frame2.origin.y, 104, 21))
label2.text = "立享优惠¥\(price / 100)"
let font2 = UIFont.systemFontOfSize(13 as CGFloat)
label2.font = font2
label2.textColor = UIColor.redColor()
cell.addSubview(label2)
}
}
//MARK: - 网络回调函数
func initPrice(data: JSON) {
var title = data["title"].string
var eversion = data["eversion"].string
var showEversion = data["show_eversion"].string
var customerPhone = data["customer_phone"].string
var operaterAmt = data["operater_amt"].int
var monthAmt1Ori = data["month_amt_1_ori"].int
var monthAmt1 = data["month_amt_1"].int
var monthAmt6Ori = data["month_amt_6_ori"].int
var monthAmt6 = data["month_amt_6"].int
var monthAmt12Ori = data["month_amt_12_ori"].int
var monthAmt12 = data["month_amt_12"].int
self.oneMonthPrice = Double(monthAmt1!) / 100.0
self.sixMonthsPrice = Double(monthAmt6!) / 100.0
self.oneYearPrice = Double(monthAmt12!) / 100.0
self.setPrice(monthAmt1Ori!, price: monthAmt1!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))!, frame: self.oneMonthLabel.frame)
self.setPrice(monthAmt6Ori!, price: monthAmt6!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 1))!, frame: self.sixMonthsLabel.frame)
self.setPrice(monthAmt12Ori!, price: monthAmt12!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 1))!, frame: self.oneYearLabel.frame)
let frame = self.operaterLabel.frame
var label = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 53, 18))
label.text = "¥\(operaterAmt! / 100)/月"
let font = UIFont.systemFontOfSize(15 as CGFloat)
label.font = font
label.textColor = UIColor.orangeColor()
let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 1))
cell?.addSubview(label)
}
func login(json: JSON) {
var userId = json["userid"].int
var nickName = json["nickname"].string
var imgUrl = json["imgurl"].string
var pushAlias = json["push_alias"].string
var pushTag = json["push_tag"].string
var imUsername = json["im_username"].string
var imPassword = json["im_password"].string
var vipType = json["vip_type"].string
var vipBegin = json["vip_begin"].int64
var vipExpire = json["vip_expire"].int64
var token = json["token"].string
DBUtils.mem.loginStatus = true
if let a = userId {
DBUtils.mem.userId = a
}
if let a = nickName {
DBUtils.mem.nickName = a
}
if let a = imgUrl {
DBUtils.mem.imgURL = a
}
if let a = pushAlias {
DBUtils.mem.pushAlias = a
}
if let a = pushTag {
DBUtils.mem.pushTag = a
}
if let a = imUsername {
DBUtils.mem.imUsername = a
}
if let a = imPassword {
DBUtils.mem.imPassword = a
}
if let a = token {
DBUtils.mem.token = a
}
if let a = vipType {
DBUtils.mem.vipType = a
}
if let a = vipBegin {
DBUtils.mem.vipBegin = a
}
if let a = vipExpire {
DBUtils.mem.vipExpire = a
}
setVipInfo(tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))!)
}
// MARK: - PopupDelegate
func dismissPopup(animated: Bool) ->Void {
if (self.popupViewController != nil) {
self.dismissPopupViewControllerAnimated(animated, completion: nil)
}
}
func payResult(channel: String, resultStatus: String) {
self.dismissPopupViewControllerAnimated(false, completion: nil)
if (resultStatus == "9000" || resultStatus == "8000") {
let a = ["mobile": DBUtils.mem.loginName, "pwd": DBUtils.mem.password]
NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLLogin(), parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: login, interErrorHandler: nil, jsonErrorHandler: nil)
}
if (channel == StringUtils.payChannel["alipay"]) {
ViewUtils.popMessage(self, title: "支付宝支付结果", message: StringUtils.alipayErrorCode[resultStatus]!)
}
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.section == 0 && indexPath.row == 1) {
setVipInfo(cell)
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch (section) {
case 1:
return 30
case 2, 3:
return 10
default:
return 0
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var r = UIScreen.mainScreen().bounds
var fontSize: CGFloat = 13.0
if (r.width <= 320) {
fontSize = 11.0
}
switch (section) {
case 1:
var label = UILabel(frame: CGRect(x: 20, y: 0, width: r.width - 20, height: 30))
label.font = label.font.fontWithSize(fontSize)
label.text = "开通VIP会员,免费观看全部视频—在线支付"
var sectionView = UIView(frame: CGRect(x: 0, y: 0, width: r.width, height: 30))
sectionView.backgroundColor = UIColor.groupTableViewBackgroundColor()
sectionView.addSubview(label)
return sectionView
default:
return nil
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if (indexPath.section == 0 && indexPath.row == 0) { //头像
var storyBoard = UIStoryboard(name: "Setting", bundle: nil)
var viewController = storyBoard.instantiateViewControllerWithIdentifier("AccountSetting") as! AccountSettingViewController
self.navigationController?.pushViewController(viewController, animated: true)
} else if (indexPath.section == 2 && indexPath.row == 0) { //清除缓存
self.cacheSizeLabel.text = "清除中.."
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
FileUtils.removeFiles()
let cacheSize = FileUtils.calcFoldSize()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.cacheSizeLabel.text = StringUtils.formatFileSize(cacheSize)
})
})
} else if (indexPath.section == 3 && indexPath.row == 0) { //意见反馈
var storyBoard = UIStoryboard(name: "Setting", bundle: nil)
var viewController = storyBoard.instantiateViewControllerWithIdentifier("Feedback") as! FeedbackViewController
self.navigationController?.pushViewController(viewController, animated: true)
}
}
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
var view = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 20))
view.backgroundColor = UIColor.whiteColor()
return view
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
// override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("timeCell", forIndexPath: indexPath) as! UITableViewCell
//
//
//
// return cell
// }
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
|
//
// AuhtenticationViewModel.swift
// GlobalVerificationNetwork-HUCM
//
import Foundation
/*
* AuthenticationViewModel class with class method declaration and defination implementaion to handle functionality of AuthenticationServices class.
*/
class AuthenticationViewModel {
/*
static func parseApiResponseBy(responseData:Data) -> (NetworkResponseStatus, AnyObject){
var responseDict = [String:AnyObject]()
var responseType = NetworkResponseStatus.None
do {
// Code to serialized json string into json object by NSJSONSerialization class method JSONObjectWithData.
responseDict = try (JSONSerialization.jsonObject(with: responseData, options: []) as? [String:AnyObject])!
}
catch let error as NSError {
print(error)
}
if let status = responseDict["status"] as? String{
if status == "200"{
responseType = NetworkResponseStatus.Success
}
else{
}
}
else{
responseType = NetworkResponseStatus.Failure
}
}
*/
}
|
//
// Socket.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Foundation
#endif
/* Low level routines for POSIX sockets */
internal enum SocketError: Error {
case socketCreationFailed(String)
case socketSettingReUseAddrFailed(String)
case socketSettingIPV6OnlyFailed(String)
case bindFailed(String)
case bindFailedAddressAlreadyInUse(String)
case listenFailed(String)
case writeFailed(String)
case getPeerNameFailed(String)
case convertingPeerNameFailed
case getNameInfoFailed(String)
case acceptFailed(String)
case recvFailed(String)
case closeFailed(String)
}
internal class Socket: Hashable, Equatable {
internal class func tcpSocketForListen(_ port: in_port_t, maxPendingConnection: Int32 = SOMAXCONN) throws -> Socket {
#if os(Linux)
let socketFileDescriptor = socket(AF_INET6, Int32(SOCK_STREAM.rawValue), 0)
#else
let socketFileDescriptor = socket(AF_INET6, SOCK_STREAM, 0)
#endif
if socketFileDescriptor == -1 {
throw SocketError.socketCreationFailed(Socket.descriptionOfLastError())
}
var sockoptValueYES: Int32 = 1
var sockoptValueNO: Int32 = 0
// Allow reuse of local addresses:
//
if setsockopt(socketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &sockoptValueYES, socklen_t(MemoryLayout<Int32>.size)) == -1 {
let details = Socket.descriptionOfLastError()
Socket.releaseIgnoringErrors(socketFileDescriptor)
throw SocketError.socketSettingReUseAddrFailed(details)
}
// Accept also IPv4 connections (note that this means we must bind to
// in6addr_any — binding to in6addr_loopback will effectively rule out
// IPv4 addresses):
//
if setsockopt(socketFileDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, &sockoptValueNO, socklen_t(MemoryLayout<Int32>.size)) == -1 {
let details = Socket.descriptionOfLastError()
Socket.releaseIgnoringErrors(socketFileDescriptor)
throw SocketError.socketSettingIPV6OnlyFailed(details)
}
Socket.setNoSigPipe(socketFileDescriptor)
#if os(Linux)
var addr = sockaddr_in6()
addr.sin6_family = sa_family_t(AF_INET6)
addr.sin6_port = Socket.htonsPort(port)
addr.sin6_addr = in6addr_any
#else
var addr = sockaddr_in6()
addr.sin6_len = __uint8_t(MemoryLayout<sockaddr_in6>.size)
addr.sin6_family = sa_family_t(AF_INET6)
addr.sin6_port = Socket.htonsPort(port)
addr.sin6_addr = in6addr_any
#endif
try withUnsafePointer(to: &addr) { addrPointer in
let bind_addr = UnsafeRawPointer(addrPointer).assumingMemoryBound(to: sockaddr.self)
if bind(socketFileDescriptor, bind_addr, socklen_t(MemoryLayout<sockaddr_in6>.size)) == -1 {
let myErrno = errno
let details = Socket.descriptionOfLastError()
Socket.releaseIgnoringErrors(socketFileDescriptor)
if myErrno == EADDRINUSE {
throw SocketError.bindFailedAddressAlreadyInUse(details)
}
throw SocketError.bindFailed(details)
}
}
if listen(socketFileDescriptor, maxPendingConnection) == -1 {
let details = Socket.descriptionOfLastError()
Socket.releaseIgnoringErrors(socketFileDescriptor)
throw SocketError.listenFailed(details)
}
return Socket(socketFileDescriptor: socketFileDescriptor)
}
internal let socketFileDescriptor: Int32
internal init(socketFileDescriptor: Int32) {
self.socketFileDescriptor = socketFileDescriptor
}
internal var hashValue: Int { return Int(socketFileDescriptor) }
internal func release() throws {
try Socket.release(socketFileDescriptor)
}
internal func releaseIgnoringErrors() {
Socket.releaseIgnoringErrors(socketFileDescriptor)
}
internal func shutdown() {
Socket.shutdown(socketFileDescriptor)
}
internal func acceptClientSocket() throws -> Socket {
var addr = sockaddr()
var len: socklen_t = 0
let clientSocket = accept(socketFileDescriptor, &addr, &len)
if clientSocket == -1 {
throw SocketError.acceptFailed(Socket.descriptionOfLastError())
}
Socket.setNoSigPipe(clientSocket)
return Socket(socketFileDescriptor: clientSocket)
}
internal func writeUTF8(_ string: String) throws {
try writeUInt8([UInt8](string.utf8))
}
internal func writeUTF8AndCRLF(_ string: String) throws {
try writeUTF8(string + "\r\n")
}
internal func writeUInt8(_ data: [UInt8]) throws {
try data.withUnsafeBufferPointer {
var sent = 0
while sent < data.count {
#if os(Linux)
let s = send(socketFileDescriptor, $0.baseAddress + sent, data.count - sent, Int32(MSG_NOSIGNAL))
#else
let s = write(socketFileDescriptor, $0.baseAddress! + sent, data.count - sent)
#endif
if s <= 0 {
throw SocketError.writeFailed(Socket.descriptionOfLastError())
}
sent += s
}
}
}
internal func readOneByte() throws -> UInt8 {
var buffer = [UInt8](repeating: 0, count: 1)
let next = recv(socketFileDescriptor, &buffer, buffer.count, 0)
if next <= 0 {
throw SocketError.recvFailed(Socket.descriptionOfLastError())
}
return buffer[0]
}
internal func readNumBytes(_ count: Int) throws -> [UInt8] {
var ret = [UInt8]()
while ret.count < count {
let maxBufferSize = 2048
let remainingExpectedBytes = count - ret.count
let bufferSize = min(remainingExpectedBytes, maxBufferSize)
var buffer = [UInt8](repeating: 0, count: bufferSize)
let numBytesReceived = recv(socketFileDescriptor, &buffer, buffer.count, 0)
if numBytesReceived <= 0 {
throw SocketError.recvFailed(Socket.descriptionOfLastError())
}
ret.append(contentsOf: buffer)
}
return ret
}
internal static let CR = UInt8(13)
internal static let NL = UInt8(10)
internal func readLine() throws -> String {
var characters: String = ""
var n: UInt8 = 0
repeat {
n = try readOneByte()
if n > Socket.CR { characters.append(Character(UnicodeScalar(n))) }
} while n != Socket.NL
return characters
}
internal func peername() throws -> String {
var addr = sockaddr(), len: socklen_t = socklen_t(MemoryLayout<sockaddr>.size)
if getpeername(socketFileDescriptor, &addr, &len) != 0 {
throw SocketError.getPeerNameFailed(Socket.descriptionOfLastError())
}
var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 {
throw SocketError.getNameInfoFailed(Socket.descriptionOfLastError())
}
guard let name = String(validatingUTF8: hostBuffer) else {
throw SocketError.convertingPeerNameFailed
}
return name
}
internal class func descriptionOfLastError() -> String {
return String(cString: strerror(errno))
}
internal class func setNoSigPipe(_ socketFileDescriptor: Int32) {
#if os(Linux)
// There is no SO_NOSIGPIPE in Linux (nor some other systems). You can instead use the MSG_NOSIGNAL flag when calling send(),
// or use signal(SIGPIPE, SIG_IGN) to make your entire application ignore SIGPIPE.
#else
// Prevents crashes when blocking calls are pending and the app is paused ( via Home button ).
var no_sig_pipe: Int32 = 1
setsockopt(socketFileDescriptor, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(MemoryLayout<Int32>.size))
#endif
}
private class func shutdown(_ socketFileDescriptor: Int32) {
#if os(Linux)
_ = shutdown(socket, Int32(SHUT_RDWR))
#else
_ = Darwin.shutdown(socketFileDescriptor, SHUT_RDWR)
#endif
}
internal class func release(_ socketFileDescriptor: Int32) throws {
shutdown(socketFileDescriptor)
if close(socketFileDescriptor) == -1 {
throw SocketError.closeFailed(Socket.descriptionOfLastError())
}
}
private class func releaseIgnoringErrors(_ socketFileDescriptor: Int32) {
_ = try? release(socketFileDescriptor)
}
private class func htonsPort(_ port: in_port_t) -> in_port_t {
#if os(Linux)
return htons(port)
#else
let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian
return isLittleEndian ? _OSSwapInt16(port) : port
#endif
}
}
internal func ==(socket1: Socket, socket2: Socket) -> Bool {
return socket1.socketFileDescriptor == socket2.socketFileDescriptor
}
|
//
// FlatActionSheetController.swift
// FlatActionSheetController
//
// Created by Thanh-Nhon Nguyen on 8/17/16.
// Copyright © 2016 Thanh-Nhon Nguyen. All rights reserved.
//
import UIKit
// MARK: FlatAction
struct FlatAction {
let icon: UIImage?
let title: String
let handler: (() -> Void)?
}
// MARK: FlatActionSheetConfiguration
struct FlatActionSheetConfiguration {
var dimBackgroundColor: UIColor = UIColor.blackColor()
var dimBackgroundAlpha: CGFloat = 0.3
var animationDuration: NSTimeInterval = 0.25
var textFont: UIFont = UIFont.systemFontOfSize(13)
var textColor: UIColor = UIColor.darkGrayColor()
var wrapText: Bool = true
var iconSize: CGSize = CGSize(width: 15, height: 15)
var maxHeight: CGFloat = UIScreen.mainScreen().bounds.height*2/3
}
// MARK: FlatActionSheetController
final class FlatActionSheetController: UIViewController {
var didDismiss: (() -> Void)?
var configuration: FlatActionSheetConfiguration {
get {
return FlatActionSheetController.sharedConfiguration
}
set {
FlatActionSheetController.sharedConfiguration = newValue
}
}
// Private elements
static private var sharedConfiguration = FlatActionSheetConfiguration()
private let applicationWindow: UIWindow!
private var actions: [FlatAction]
private var dimBackgroundView: UIView
private let tableView: UITableView
init() {
applicationWindow = UIApplication.sharedApplication().delegate?.window!
actions = []
dimBackgroundView = UIView()
tableView = UITableView(frame: applicationWindow.frame, style: UITableViewStyle.Plain)
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = UIModalPresentationStyle.Custom
modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(withActions actions: [FlatAction]) {
self.init()
self.actions = actions
}
override func viewDidLoad() {
super.viewDidLoad()
addDimBackgroundView()
addTableView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIView.animateWithDuration(configuration.animationDuration) { [unowned self] in
if self.tableView.contentSize.height <= self.configuration.maxHeight {
self.tableView.frame.origin = CGPoint(x: 0, y: self.applicationWindow.frame.height - self.tableView.contentSize.height)
} else {
self.tableView.frame.origin = CGPoint(x: 0, y: self.applicationWindow.frame.height - self.configuration.maxHeight)
}
}
}
private func dismiss(completion: (() -> Void)? = nil) {
UIView.animateWithDuration(configuration.animationDuration, animations: {[unowned self] in
self.tableView.frame.origin = CGPoint(x: 0, y: self.applicationWindow.frame.height)
self.dimBackgroundView.alpha = 0
}) { [unowned self] (finished) in
self.tableView.removeFromSuperview()
self.dimBackgroundView.removeFromSuperview()
self.didDismiss?()
self.dismissViewControllerAnimated(true, completion: completion)
}
}
// Dim background
private func addDimBackgroundView() {
dimBackgroundView = UIView(frame: applicationWindow.frame)
dimBackgroundView.backgroundColor = configuration.dimBackgroundColor.colorWithAlphaComponent(configuration.dimBackgroundAlpha)
let tap = UITapGestureRecognizer(target: self, action: #selector(FlatActionSheetController.dimBackgroundViewTapped))
dimBackgroundView.userInteractionEnabled = true
dimBackgroundView.addGestureRecognizer(tap)
applicationWindow.addSubview(dimBackgroundView)
dimBackgroundView.alpha = 0
UIView.animateWithDuration(configuration.animationDuration) { [unowned self] in
self.dimBackgroundView.alpha = 1
}
}
@objc private func dimBackgroundViewTapped() {
dismiss()
}
// TableView
private func addTableView() {
tableView.dataSource = self
tableView.delegate = self
tableView.separatorColor = UIColor.clearColor()
tableView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
tableView.registerClass(FlatActionTableViewCell.self, forCellReuseIdentifier: "\(FlatActionTableViewCell.self)")
tableView.frame.origin = CGPoint(x: 0, y: applicationWindow.frame.height)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 50
applicationWindow.addSubview(tableView)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if tableView.contentSize.height <= configuration.maxHeight {
tableView.frame.size = tableView.contentSize
tableView.scrollEnabled = false
} else {
tableView.frame.size = CGSize(width: tableView.frame.width, height: configuration.maxHeight)
tableView.scrollEnabled = true
}
}
deinit {
tableView.removeObserver(self, forKeyPath: "contentSize")
}
}
extension FlatActionSheetController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("\(FlatActionTableViewCell.self)", forIndexPath: indexPath) as! FlatActionTableViewCell
let action = actions[indexPath.row]
cell.titleLabel.text = action.title
cell.iconImageView.image = action.icon
return cell
}
}
extension FlatActionSheetController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let action = actions[indexPath.row]
tableView.deselectRowAtIndexPath(indexPath, animated: true)
dismiss {
action.handler?()
}
}
}
// MARK: FlatActionTableViewCell
private final class FlatActionTableViewCell: UITableViewCell {
var iconImageView = UIImageView()
var titleLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(iconImageView)
contentView.addSubview(titleLabel)
iconImageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: iconImageView, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .LeadingMargin, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: iconImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: FlatActionSheetController.sharedConfiguration.iconSize.width).active = true
NSLayoutConstraint(item: iconImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: FlatActionSheetController.sharedConfiguration.iconSize.height).active = true
titleLabel.translatesAutoresizingMaskIntoConstraints = false
if FlatActionSheetController.sharedConfiguration.wrapText == true {
titleLabel.numberOfLines = 1
} else {
titleLabel.numberOfLines = 0
}
titleLabel.font = FlatActionSheetController.sharedConfiguration.textFont
titleLabel.textColor = FlatActionSheetController.sharedConfiguration.textColor
NSLayoutConstraint(item: titleLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 15).active = true
NSLayoutConstraint(item: titleLabel, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .TrailingMargin, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: titleLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 10).active = true
NSLayoutConstraint(item: titleLabel, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -10).active = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private override func prepareForReuse() {
super.prepareForReuse()
iconImageView.image = nil
}
} |
//
// AnimationLinkList.swift
// Algorithms
//
// Created by Loc Tran on 5/6/17.
// Copyright © 2017 LocTran. All rights reserved.
//
import Foundation
import UIKit
class AnimationLinkList{
var colSolution = 0
var graph: Graph_LinkList!
init(graph: Graph_LinkList){
self.graph = graph
}
func animationStep(step: Int){
UIView.animate(withDuration: 0.5, animations: {
if(step==1){
self.graph.arrow1.isHidden = false
self.graph.labelValue.isHidden = false
self.graph.arrNodes[1].layer.borderColor = UIColor.red.cgColor
}else if(step==2){
self.graph.arrow2.isHidden = false
self.graph.labelNext.isHidden = false
self.graph.arrNodes[1].layer.borderColor = UIColor.red.cgColor
}else if(step==3){
self.graph.arrow1.isHidden = true
self.graph.labelValue.isHidden = true
self.graph.arrow2.isHidden = true
self.graph.labelNext.isHidden = true
self.graph.arrDots[0].isHidden = true
self.graph.arrArrows[0].isHidden = true
self.graph.addLable.isHidden = false
self.graph.arrNodes[1].layer.borderColor = UIColor.gray.cgColor
self.graph.printNameNode()
}else if(step==4){
self.graph.arrowDown.isHidden = false
self.graph.dotDown.isHidden = false
let label = self.graph.arrNodes[0].viewWithTag(12) as! UILabel
label.text = "0x35"
}else if(step==5){
self.graph.arrDots[3].isHidden = false
self.graph.arrowCurved[0].isHidden = false
self.graph.arrowCurved[1].isHidden = false
let label = self.graph.addLable.viewWithTag(42) as! UILabel
label.text = "0x15"
}
}){_ in
btnStepTmp.isUserInteractionEnabled = true
}
}
}
|
//
// PPFolderCollectionViewFlowLayout.swift
// ProtoPipe
//
// Created by 吉乞悠 on 2020/5/24.
// Copyright © 2020 吉乞悠. All rights reserved.
//
import UIKit
class PPFolderCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
scrollDirection = .vertical
minimumLineSpacing = 0
minimumInteritemSpacing = 0
itemSize = folderCollectionViewCellSize
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
var folderCollectionViewCellSize: CGSize {
return CGSize(width: screenWidth > screenHeight ? screenWidth / 4 : screenWidth / 3,
height: screenWidth > screenHeight ? screenWidth / 4 : screenWidth / 3)
}
|
//
// main.swift
// FactoryProviderMain
//
// Created by 吉村優 on 2018/06/15.
// Copyright © 2018年 吉村優. All rights reserved.
let a =
String.provide() >>>
Bool.provide() >>>
Optional<Int>.provide() >>>
end()
let (b, s) = a.run(0)
print(s, b.head, b.tail.head, b.tail.tail.head as Any)
|
//
// Personalization.swift
//
//
// Created by Vladislav Fitc on 27/05/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class PersonalizationIntegrationTests: IntegrationTestCase {
override var retryableTests: [() throws -> Void] {
[
getStrategy,
setStrategy
]
}
func getStrategy() throws {
let recommendationClient = PersonalizationClient(appID: client.applicationID, apiKey: client.apiKey, region: .custom("us"))
let _ = try recommendationClient.getPersonalizationStrategy()
}
func setStrategy() throws {
let personalizationClient = PersonalizationClient(appID: client.applicationID, apiKey: client.apiKey, region: .custom("us"))
let strategy = PersonalizationStrategy(
eventsScoring: [
.init(eventName: "Add to cart", eventType: .conversion, score: 50),
.init(eventName: "Purchase", eventType: .conversion, score: 100)
],
facetsScoring: [
.init(facetName: "brand", score: 100),
.init(facetName: "categories", score: 10)
],
personalizationImpact: 0
)
do {
try personalizationClient.setPersonalizationStrategy(strategy)
} catch .httpError(let httpError) as TransportError where httpError.statusCode == HTTPStatusСode.tooManyRequests {
// The personalization API is now limiting the number of setPersonalizationStrategy()` successful calls
// to 15 per day. If the 429 error is returned, the response is considered a "success".
} catch let error {
throw error
}
}
}
|
//
// LoginView.swift
// gjs_user
//
// Created by xiaofeixia on 2019/8/23.
// Copyright © 2019 大杉网络. All rights reserved.
//
import UIKit
class LoginView: UIView {
var navigation:UINavigationController?
var sms:UILabel!
var forget:UILabel!
var btn:UIButton!
var account:UITextField!
var password:UITextField!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .white
let mainView = UIView()
mainView.frame = self.bounds
let titleText = UILabel(frame: CGRect(x: 20, y: 10, width: kScreenW, height: 30))
titleText.text = "欢迎登录"
titleText.textColor = kMainTextColor
titleText.textAlignment = .left
titleText.font = FontSize(20)
mainView.addSubview(titleText)
account = infoFiled(parent: mainView, tip: "请输入手机号码", y: 60, type: 0)
account.keyboardType = .numberPad
password = infoFiled(parent: mainView, tip: "请输入密码", y: 110, type: 1)
btn = UIButton(frame: CGRect(x: 20, y: 180, width: kScreenW - 40, height: 40))
btn.setTitle("登 录", for: .normal)
btn.gradientColor(CGPoint(x: 0, y: 0.5), CGPoint(x: 1, y: 0.5), kCGGradientColors)
btn.layer.masksToBounds = true
btn.layer.cornerRadius = 6
btn.titleLabel?.font = BoldFontSize(18)
mainView.addSubview(btn)
sms = UILabel(frame: CGRect(x: 20, y: 230, width: (kScreenW - 40)/2, height: 30))
sms.text = "短信验证码登录"
sms.textColor = kLowOrangeColor
sms.textAlignment = .left
sms.font = FontSize(14)
sms.isUserInteractionEnabled = true
forget = UILabel(frame: CGRect(x: (kScreenW - 40)/2+20, y: 230, width: (kScreenW - 40)/2, height: 30))
forget.text = "忘记密码?"
forget.textColor = kLowOrangeColor
forget.textAlignment = .right
forget.font = FontSize(14)
forget.isUserInteractionEnabled = true
mainView.addSubview(sms)
mainView.addSubview(forget)
let tip = UILabel(frame: CGRect(x: 20, y: 280, width: kScreenW - 40, height: 20))
tip.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(privacy))
tip.addGestureRecognizer(tap)
let tip1 = "登录即代表您已同意"
let tip2 = "《赶紧省隐私协议》"
let tipTotal = NSMutableAttributedString(string: tip1 + tip2)
let tipTemp1 : NSRange = (tipTotal.string as NSString).range(of:tip1)
let tipTemp2 : NSRange = (tipTotal.string as NSString).range(of:tip2)
tipTotal.addAttribute(NSAttributedString.Key.foregroundColor, value: kMainTextColor, range: tipTemp1)
tipTotal.addAttribute(NSAttributedString.Key.foregroundColor, value: kLowOrangeColor, range: tipTemp2)
tip.attributedText = tipTotal
tip.font = FontSize(12)
tip.textAlignment = .center
mainView.addSubview(tip)
self.addSubview(mainView)
}
@objc func privacy(){
print("点击了。。。。。。")
navigation?.pushViewController(privacyViewController(), animated: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//输入框部分
func infoFiled(parent:UIView,tip:String,y:CGFloat,type:Int) -> UITextField {
let filed = UITextField(frame: CGRect(x: 20, y: y, width: kScreenW - 40, height: 35))
filed.placeholder = tip
filed.font = FontSize(16)
filed.clearButtonMode = .whileEditing
//底部边框
let layer = CALayer()
layer.frame = CGRect(x: 0, y: 35, width: kScreenW-40, height: 1)
layer.backgroundColor = klineColor.cgColor
filed.layer.addSublayer(layer)
if type == 1{
filed.isSecureTextEntry = true
}
parent.addSubview(filed)
return filed
}
}
|
import Css
import Html
import HtmlCssSupport
import XCTest
class SupportTests: XCTestCase {
func testStyleAttribute() {
let sheet = color(.red)
let node = Node.p(
attributes: [.style(sheet)],
"Hello world!"
)
XCTAssertEqual(
"<p style=\"color:#ff0000\">Hello world!</p>",
render(node)
)
}
func testStyleElement() {
let css = body % color(.red)
let document = Node.html(.head(.style(css)))
XCTAssertEqual(
"""
<html>
<head>
<style>
body{color:#ff0000}
</style>
</head>
</html>
""",
debugRender(document)
)
}
}
|
//
// GZEPaymentViewModel.swift
// Gooze
//
// Created by Yussel Paredes Perez on 4/20/18.
// Copyright © 2018 Gooze. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
import enum Result.NoError
protocol GZEPaymentViewModel {
var bottomButtonCocoaAction: CocoaAction<GZEButton>? { get }
var bottomButtonActionEnabled: MutableProperty<Bool> { get }
var dismissSignal: Signal<Void, NoError> { get }
}
|
//
// PubMesConView.swift
// huicheng
//
// Created by lvxin on 2018/3/18.
// Copyright © 2018年 lvxin. All rights reserved.
//
import UIKit
class PubMesConView: UIView,NibLoadable {
@IBOutlet weak var subLabel: UILabel!
@IBOutlet weak var contentTextView: UITextView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
func setData(model:newsdetialModel) {
if let title = model.title {
self.titleLabel.text = title
}
if let user = model.user ,let object = model.object{
self.subLabel.text = "发布人:\(user) 接收对象:\(object)"
}
if let content = model.content {
let attrStr = try! NSAttributedString(
data: content.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options:[NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
self.contentTextView.attributedText = attrStr
}
if let time = model.createtime {
self.timeLabel.text = time
}
}
}
|
// MARK: - Object define Node
import Foundation
import SceneKit.ModelIO
import ARKit
class VirtualObject: SCNNode, URLSessionDownloadDelegate{
static let ROOT_NAME = "Virtual object root node"
var fileExtension: String = ""
var thumbImage: UIImage!
var title: String = ""
var modelName: String = ""
var modelLoaded: Bool = false
var id: Int!
var handle: Bool = false
let fileManager = FileManager.default
// let progressViewController = ProgressViewController()
let popUpView = UIStoryboard.init(name: "ProgressViewController", bundle: nil).instantiateViewController(identifier: "popUpView")
var viewController: MainViewController?
override init() {
super.init()
self.name = VirtualObject.ROOT_NAME
}
init(modelName: String, fileExtension : String, thumbImageFilename: String, title: String, handle : Bool) {
super.init()
self.id = VirtualObjectsManager.shared.generateUid()
self.name = VirtualObject.ROOT_NAME
self.modelName = modelName
self.fileExtension = fileExtension
self.thumbImage = UIImage(named: thumbImageFilename)
self.title = title
self.handle = handle
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:)가 구현되지 않았습니다.")
}
// MARK: - 3D model load function
func loadModel() {
print("---------------------Start loadModel function")
let downloadedScenePath = getDocumentsDirectory().appendingPathComponent("\(modelName).usdz")
//1. Create The Filename
print("loadModel Bool ----------------\(fileManager.fileExists(atPath: downloadedScenePath.path))")
if !fileManager.fileExists(atPath: downloadedScenePath.path) {
showPopup()
downloadSceneTask()
}
let asset = MDLAsset(url: downloadedScenePath)
asset.loadTextures()
let object = asset.object(at: 0)
let node = SCNNode.init(mdlObject: object)
if modelName == "Teapot" || modelName == "AirForce" || modelName == "fender_stratocaster" {
node.scale = SCNVector3(0.01, 0.01, 0.01)
}
if modelName == "hanssemchair01" {
node.scale = SCNVector3(0.001, 0.001, 0.001)
}
// MARK: - Light & Shadow Node
// let shadowPlane = SCNPlane(width: 5000, height: 5000)
//
// let material = SCNMaterial()
// material.isDoubleSided = false
// material.lightingModel = .shadowOnly // Requires SCNLight shadowMode = .forward and
// // light가 .omni거나 .spot이면 검은색으로 변하는 이슈 발생
//
// shadowPlane.materials = [material]
//
// let shadowPlaneNode = SCNNode(geometry: shadowPlane)
// shadowPlaneNode.name = modelName
// shadowPlaneNode.eulerAngles.x = -.pi / 2
// shadowPlaneNode.castsShadow = false
//
// self.addChildNode(shadowPlaneNode)
//
// let light = SCNLight()
// light.type = .directional
// light.castsShadow = true
// light.shadowRadius = 20
// light.shadowSampleCount = 64
//
// light.shadowColor = UIColor(white: 0, alpha: 0.5)
// light.shadowMode = .forward
// light.maximumShadowDistance = 11000
//// let constraint = SCNLookAtConstraint(target: self)
////
//// guard let lightEstimate = MainViewController.sceneView.session.currentFrame?.lightEstimate else {
//// return
//// }
//
// // light node
// let lightNode = SCNNode()
// lightNode.light = light
//// lightNode.light?.intensity = lightEstimate.ambientIntensity
//// lightNode.light?.temperature = lightEstimate.ambientColorTemperature
//// lightNode.position = SCNVector3(object.position.x + 10, object.position.y + 30, object.position.z + 30)
// lightNode.eulerAngles = SCNVector3(45.0,0,0)
//// lightNode.constraints = [constraint]
// self.addChildNode(lightNode)
self.addChildNode(node)
print("---------------finish \(modelName) loadmodel func")
}
// MARK: - Model unload function
func unloadModel() {
for child in self.childNodes {
child.removeFromParentNode()
}
print("unloadModel func")
modelLoaded = false
}
// MARK: - Gesture
func translateBasedOnScreenPos(_ pos: CGPoint, instantly: Bool, infinitePlane: Bool) {
print("Translate BasedOn")
guard let controller = viewController else {
return
}
let result = controller.worldPositionFromScreenPosition(pos, objectPos: self.position, infinitePlane: infinitePlane)
controller.moveVirtualObjectToPosition(result.position, instantly, !result.hitAPlane)
}
func translateHandleTrue(_ pos: CGPoint, instantly: Bool, infinitePlane: Bool) {
print("Translate Handle True")
guard let controller = viewController else {
return
}
let result = controller.worldPositionFromScreenPosition(pos, objectPos: self.position, infinitePlane: infinitePlane)
let result2 = controller.worldPositionFromScreenPosition(pos, objectPos: self.position, infinitePlane: infinitePlane)
print(result)
print(result2)
controller.moveVirtualObjectToPosition(result.position, instantly, !result.hitAPlane)
}
// MARK: - PopUp setting
func showPopup() {
DispatchQueue.main.async{
self.popUpView.modalPresentationStyle = .overCurrentContext
print("Show PopUp")
self.viewController!.present(self.popUpView, animated: true, completion: nil)
}
}
func closePopup() {
DispatchQueue.main.async {
// self.progressViewController.setProgress100()
self.popUpView.dismiss(animated: true, completion: nil)
}
}
// MARK: - download from URL
func downloadSceneTask() {
//1. Create The Filename
print("start downloadscenetask function")
let url : URL
switch modelName
{
case "Teapot":
print("Teapot")
url = URL(string: "https://developer.apple.com/augmented-reality/quick-look/models/teapot/teapot.usdz")!
case "AirForce":
print("AirForce")
url = URL(string: "https://devimages-cdn.apple.com/ar/photogrammetry/AirForce.usdz")!
case "fender_stratocaster":
print("fender_stratocaster")
url = URL(string: "https://developer.apple.com/augmented-reality/quick-look/models/stratocaster/fender_stratocaster.usdz")!
case "moa_rose" :
print("moa_rose")
url = URL(string: "https://github.com/Jungjjeong/2021-Summer-Hanssem/raw/main/models/moa_rose.usdz")!
case "hanssemchair01" :
print("hanssemchair01")
url = URL(string: "https://github.com/Jungjjeong/2021-Summer-Hanssem/raw/main/models/hanssemchair01.usdz")!
default:
print("Default")
url = URL(string: "https://developer.apple.com/augmented-reality/quick-look/models/teapot/teapot.usdz")!
}
// getDownloadSize
getDownloadSize(url: url, completion: { (size, error) in
if error != nil {
print("An error occurred when retrieving the download size: \(error!.localizedDescription)")
} else {
print("The download size is \(size).")
}
})
//2. Create The Download Session
print("create the download session")
let downloadSession = URLSession(configuration: URLSession.shared.configuration, delegate: self, delegateQueue: nil)
//3. Create The Download Task & Run It
print("create the download task & run it")
let downloadTask = downloadSession.downloadTask(with: url)
downloadTask.resume()
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
//1. Create The Filename
let fileURL = getDocumentsDirectory().appendingPathComponent("\(modelName).usdz")
print("----------------\(fileManager.fileExists(atPath: fileURL.path))")
// var fileSize : UInt64
if !fileManager.fileExists(atPath: fileURL.path) {
//2. Copy It To The Documents Directory
do {
try fileManager.copyItem(at: location, to: fileURL)
// do{
// let attr = try fileManager.attributesOfItem(atPath: fileURL.path)
// fileSize = attr[FileAttributeKey.size] as! UInt64
//
// print("\(fileSize) byte")
//
// } catch {
// print("Error : \(error)")
// }
print("Successfuly Saved File \(fileURL)")
loadModel()
closePopup()
} catch {
print("Error Saving: \(error)")
}
}
}
func getDocumentsDirectory() -> URL {
let paths = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func getDownloadSize(url: URL, completion: @escaping (Int64, Error?) -> Void ) {
let timeoutInterval = 5.0
var request = URLRequest(url: url,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: timeoutInterval)
request.httpMethod = "HEAD"
URLSession.shared.dataTask(with: request) { (data, response, error) in
let contentLength = response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
completion(contentLength, error)
}.resume()
}
}
// MARK: - Extension
extension VirtualObject {
static func isNodePartOfVirtualObject(_ node: SCNNode) -> Bool {
if node.name == VirtualObject.ROOT_NAME {
// print("VirtualObject - isnodepartOfVirtualObject")
return true
}
if node.parent != nil {
// print("VirtualObeject - is Not nodepartofVirtualObject")
return isNodePartOfVirtualObject(node.parent!)
}
return false
}
}
// MARK: - Protocols for Virtual Objects
protocol ReactsToScale {
func reactToScale()
}
extension SCNNode {
func reactsToScale() -> ReactsToScale? {
if let canReact = self as? ReactsToScale {
return canReact
}
if parent != nil {
return parent!.reactsToScale()
}
return nil
}
}
|
//
// CreateUserView.swift
// Prayer App
//
// Created by tomrunnels on 3/23/21.
//
import SwiftUI
import Amplify
//from User class
//public let id: String
//public var username: String?
//public var location: String?
//public var fullName: String?
//public var prayergroups: List<PrayerGroupUser>?
//public var Prayers: List<Prayer>?
struct CreateUserView: View {
var authUser: AuthUser
@State var username = ""
@State var location = ""
@State var fullName = ""
@State var feedback: String = ""
@Binding var showThisView: Bool
@Binding var sessionDataUser: User?
@Binding var userLoaded: Bool
var body: some View {
FakeFormView(viewTitle: "Let's create your profile!") {
// Text("We noticed you've never made profile for \(authUser.username), let's do that now").font(.subheadline).padding()
Text(feedback)
.frame(minHeight: 25)
HStack {
Text("Username".uppercased())
.font(Font.custom("SF Pro Text", size: 13.0))
.foregroundColor(.gray)
.padding(.leading)
Spacer()
}
HStack {
Text(authUser.username)
.padding([.bottom,], 20)
.padding([.leading], 30)
.padding(.top,4)
.font(.system(size: 20, weight: .bold, design: .default))
Spacer()
}
FakeFormField(sectionText: "Full Name (optional)", placeholderText: "John Doe", text: $fullName)
.padding(.bottom, 20)
FakeFormField(sectionText: "Location (optional)", placeholderText: "Jupiter, FL", text: $location)
.padding(.bottom, 20)
Spacer()
.frame(height:25)
VStack {
Button(action: {
showThisView = !(handleCreateUser(_id: authUser.userId, _username: authUser.username, _location: location, _fullName: fullName, feedback: $feedback))
}
){
Text("Submit")
.padding()
.foregroundColor(.black)
.background(Color("Element"))
.cornerRadius(30)
.scaleEffect(1.2)
}
Spacer()
}
}
}
func handleCreateUser(_id: String, _username: String, _location: String?, _fullName: String?, feedback: Binding<String>) -> Bool {
var returnBool = false
var item = User(
id: _id,
username: _username,
prayergroups: [],
Prayers: [])
_location != "" ? item.location = _location : nil
_fullName != "" ? item.fullName = _fullName : nil
Amplify.DataStore.save(item) { result in
switch(result) {
case .success(let savedItem):
print("Saved item: \(savedItem.id)")
feedback.wrappedValue = "User created"
returnBool = true
sessionDataUser = item
userLoaded = true
case .failure(let error):
print("Could not save item to DataStore: \(error)")
feedback.wrappedValue = "\(error)"
returnBool = false
}
}
return returnBool
}
}
struct CreateUserView_Previews: PreviewProvider {
private struct leDummyUser: AuthUser {
let userId: String = "1"
let username: String = "prayermaster500"
}
@State static var val = true
@State static var usr : User? = nil
@State static var load = false
static var previews: some View {
CreateUserView(authUser: leDummyUser(), showThisView: $val, sessionDataUser: $usr, userLoaded: $load)
}
}
|
//
// Widget.swift
// Lab3
//
// Created by Rishabh Sanghvi on 11/3/15.
// Copyright (c) 2015 Rishabh Sanghvi. All rights reserved.
//
import UIKit
import GoogleMaps
var segueMyLocation : CLLocationCoordinate2D!
@IBDesignable class Widget: UIView, CLLocationManagerDelegate {
var popUpImage: UIImageView!
var buildingName: UILabel!
var address: UILabel!
var distance: UILabel!
var time: UILabel!
var buildingNameText: String = ""
var buildingNameSmall: String = ""
@IBOutlet weak var mapView: UIImageView!
var myLocation: CLLocationCoordinate2D = CLLocationCoordinate2D()
let locationManager = CLLocationManager()
let googleMaps: GoogleMap = GoogleMap()
var buildinhCordinates: CLLocationCoordinate2D = CLLocationCoordinate2D()
func getCurrentLocation(status: Bool) {
// For use in foreground
if(status) {
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
} else {
self.locationManager.stopUpdatingLocation()
}
}
var rotatedImage : UIImageView!
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let loc = manager.location {
self.myLocation = loc.coordinate
if(self.myLocation.longitude != 0.0) {
segueMyLocation = self.myLocation
self.getBuildingCordinatesForAddress(self.buildingNameText, origin: self.myLocation)
getCurrentLocation(false)
self.locationManager.stopUpdatingLocation()
}
}
print("locations = \(myLocation.latitude) \(myLocation.longitude)")
//self.setBuildingAttributes(self.buildingNameText)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error while updating location \(error.localizedDescription)")
}
var view: UIView!
var offset: CGPoint!
var xAry: [Float]! = []
var yAry: [Float]! = []
@IBOutlet var overlay: UIView!
var touch: UITouch!
var nibName: String = "Widget"
@IBOutlet weak var imageView: UIImageView!
@IBInspectable var image: UIImage? {
get {
return imageView.image
}
set(image) {
imageView.image = image
}
}
@IBInspectable var imagePopUp: UIImage? {
get {
return popUpImage.image
}
set(image) {
popUpImage.image = image
}
}
// init
override init(frame: CGRect) {
// properties
offset = CGPoint(x: 0, y: 0)
super.init(frame: frame)
// Set anything that uses the view or visible bounds
setup()
//getCurrentLocation(true)
}
required init(coder aDecoder: NSCoder) {
// properties
super.init(coder: aDecoder)!
self.popUpImage = UIImageView(frame: CGRectMake(0, 0, 100, 100))
self.address = UILabel(frame: CGRectMake(0, 0, 100, 100))
self.distance = UILabel(frame: CGRectMake(0, 0, 100, 100))
self.time = UILabel(frame: CGRectMake(0, 0, 100, 100))
self.buildingName = UILabel(frame: CGRectMake(0, 0, 100, 100))
// Setup
setup()
}
var overViewEnabled: Bool = false
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if(overViewEnabled == false){
let location = touches.first!.locationInView(self.imageView)
print(location)
if(location.x > CGFloat(xAry[2]) && location.x < CGFloat(xAry[3]) && location.y > CGFloat(yAry[3]) && location.y < CGFloat(yAry[4])){
print("MLK")
popUp("mlk")
} else if(location.x > CGFloat(xAry[1]) && location.x < CGFloat(xAry[3]) && location.y > CGFloat(yAry[6]) && location.y < CGFloat(yAry[8])){
print("YUH")
popUp("yuh")
} else if(location.x > CGFloat(xAry[6]) && location.x < CGFloat(xAry[11]) && location.y > CGFloat(yAry[10]) && location.y < CGFloat(yAry[12])){
print("SP")
popUp("sp")
} else if(location.x > CGFloat(xAry[12]) && location.x < CGFloat(xAry[16]) && location.y > CGFloat(yAry[3]) && location.y < CGFloat(yAry[5])){
print("Eng")
popUp("eng")
} else if(location.x > CGFloat(xAry[12]) && location.x < CGFloat(xAry[18]) && location.y > CGFloat(yAry[5]) && location.y < CGFloat(yAry[6])){
print("SU")
popUp("su")
} else if(location.x > CGFloat(xAry[19]) && location.y > CGFloat(yAry[5]) && location.y < CGFloat(yAry[7])){
print("BBC")
popUp("bbc")
}
overViewEnabled = true
}
else{
self.sendSubviewToBack(popUpImage)
overViewEnabled = false
self.overlay.hidden = true
self.buildingName.hidden = true
self.address.hidden = true
self.distance.hidden = true
self.time.hidden = true
self.buildingName.text = ""
self.address.text = ""
self.distance.text = ""
self.time.text = ""
}
}
func popUp(buildingName: String) {
self.buildingName.hidden = false
self.address.hidden = false
self.distance.hidden = false
self.time.hidden = false
self.overlay.frame = self.frame
self.overlay.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.75)
self.overlay.hidden = false
self.popUpImage.frame.origin.y = (self.view.bounds.size.height) / 2.0
self.popUpImage.frame.origin.x = (self.view.bounds.size.width) / 2.0
self.addSubview(popUpImage)
switch(buildingName) {
case "mlk":
self.popUpImage.image = UIImage(named: "mlk")
break
case "yuh":
self.popUpImage.image = UIImage(named: "yuh")
break
case "sp":
self.popUpImage.image = UIImage(named: "sp")
break
case "eng":
self.popUpImage.image = UIImage(named: "eng")
break
case "su":
self.popUpImage.image = UIImage(named: "su")
break
case "bbc":
self.popUpImage.image = UIImage(named: "bbc")
break
case "other":
self.sendSubviewToBack(popUpImage)
self.overlay.hidden = true
break
default:
print("Default")
}
let dataAccess: DataAccess = DataAccess()
let buildingActualAdd = dataAccess.getAddressForBuildingName(buildingName)
self.buildingNameText = buildingActualAdd
self.buildingNameSmall = buildingName
self.getCurrentLocation(true)
let data: DataObj = dataAccess.getDataObject(self.buildingNameSmall)
self.buildingName.text = data.getBuildingName()
self.address.text = data.getAddress()
self.address.numberOfLines = 0
self.buildingName.numberOfLines = 0
self.buildingName.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
self.address.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
self.distance.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
self.time.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
self.buildingName.textColor = UIColor.whiteColor()
self.address.textColor = UIColor.whiteColor()
self.distance.textColor = UIColor.whiteColor()
self.time.textColor = UIColor.whiteColor()
self.buildingName.layer.frame = CGRectMake(self.popUpImage.frame.origin.x + 105,self.popUpImage.frame.origin.y , 250, 20)
self.address.layer.frame = CGRectMake(self.popUpImage.frame.origin.x + 105,self.popUpImage.frame.origin.y + 20, 250, 50)
self.distance.layer.frame = CGRectMake(self.popUpImage.frame.origin.x + 105,self.popUpImage.frame.origin.y + 70 , 200, 20)
self.time.layer.frame = CGRectMake(self.popUpImage.frame.origin.x + 105,self.popUpImage.frame.origin.y + 85 , 100, 20)
self.addSubview(self.distance)
self.addSubview(self.address)
self.addSubview(self.buildingName)
self.addSubview(self.time)
self.distance.text = "Calculating..."
}
func setup() {
view = loadViewFromNib()
self.overlay.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0)
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.addSubview(view)
var i : Float = 0.0
var j : Float = 0.05
for(i=1;i<21;i++) {
xAry.append(Float(self.imageView.frame.width) * Float(j))
yAry.append(Float(self.imageView.frame.height) * Float(j))
j = j + 0.05
}
print(xAry.description)
print(yAry.description)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
/*====================================Google Maps================================================*/
var buildingKey: String = ""
let SEPERATOR: String = ","
var durationValue: String = ""
var distanceValue: String = ""
var i = 0
func getBuildingCordinatesForAddress(address: String, origin: CLLocationCoordinate2D) {
let addressEncode: String = address.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
var buildingLocation: CLLocationCoordinate2D = CLLocationCoordinate2D()
let urlString: String = "http://maps.google.com/maps/api/geocode/json?address=" + addressEncode + "&sensor=false"
guard let url = NSURL(string: urlString)
else {
print("Error: cannot create URL")
return
}
let urlRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /posts/1")
print(error)
return
}
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
return
}
let result = post["results"] as! [NSDictionary]
let firstObject = result[0]
let geometry = firstObject["geometry"] as! NSDictionary
let location = geometry["location"] as! NSDictionary
buildingLocation.latitude = location["lat"] as! Double
buildingLocation.longitude = location["lng"] as! Double
self.calculateDistance(origin, destination: buildingLocation)
}).resume()
}
func calculateDistance(origin: CLLocationCoordinate2D, destination: CLLocationCoordinate2D) -> [String : String] {
var result: [String:String] = NSDictionary() as! [String : String]
let originLat = String(origin.latitude)
let originLng = String(origin.longitude)
let destLat = String(destination.latitude)
let destLng = String(destination.longitude)
let urlString: String = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ originLat + SEPERATOR + originLng + "&destinations="
+ destLat + SEPERATOR + destLng + "&mode=walking&language=fr-FR&key=" + GoogleMap.API_KEY
//
// guard let url = NSURL(string: "https://maps.googleapis.com/maps/api/distancematrix/json?origins=37.316809269,-121.910686626&destinations=37.3351424,-121.88127580000003&mode=walking&language=fr-FR&key=AIzaSyDqd0KFSk00oT-8Zf-PQA5vZsShPYbstVg")
guard let url = NSURL(string: urlString)
else {
print("Error: cannot create URL")
return result
}
let urlRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /posts/1")
print(error)
return
}
// parse the result as JSON, since that's what the API provides
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
return
}
let rows = post["rows"] as! [NSDictionary]
let rowOne = rows[0]
let elements = rowOne["elements"] as! [NSDictionary]
let elementOne = elements[0]
let distance1 = elementOne["distance"] as! NSDictionary
let duration = elementOne["duration"] as! NSDictionary
if let postTitle = post["title"] as? String {
print("The title is: " + postTitle)
}
let dist = duration["text"] as! String
let tim = distance1["text"] as! String
dispatch_async(dispatch_get_main_queue(), {
self.distance.text = "\(dist)"
self.time.text = "\(tim)"
})
})
task.resume()
return result
}
}
|
//
// Constants.swift
// Podcast
//
// Created by Nicolas Desormiere on 30/4/18.
// Copyright © 2018 Nicolas Desormiere. All rights reserved.
//
import Foundation
enum EndPoints {
static let iTunesSearchURL = "https://itunes.apple.com/search"
}
|
//
// REEndpoint.swift
// Results
//
// Created by Benjamin Mecanović on 17/01/2021.
//
import Foundation
class REEndpoint {
private static let base = "https://student-sport-results.herokuapp.com/api/"
/// GET: https://student-sport-results.herokuapp.com/api/sports/filter
static var filterSports = URL(string: base + "sports/filter")!
/// GET: https://student-sport-results.herokuapp.com/api/matches/filter/:sportId
static var filterMatches = URL(string: base + "matches/filter/")!
/// GET: https://student-sport-results.herokuapp.com/api/matches/get/:matchId
static var getMatch = URL(string: base + "matches/get/")!
/// GET: https://student-sport-results.herokuapp.com/api/faculties/filter
static var filterFaculties = URL(string: base + "faculties/filter")!
/// GET: https://student-sport-results.herokuapp.com/api/teams/filter
static var filterTeams = URL(string: base + "teams/filter")!
/// GET: https://student-sport-results.herokuapp.com/api/players/filter
static var filterPlayers = URL(string: base + "players/filter")!
}
|
//
// States_MY.swift
// eSponsorship
//
// Created by Jeremy Tay on 09/10/2017.
// Copyright © 2017 Jeremy Tay. All rights reserved.
//
import UIKit
struct Constant {
struct Data {
static let states = ["Kuala Lumpur",
"Labuan",
"Putrajaya",
"Johor",
"Kedah",
"Kelantan",
"Malacca",
"Nageri Sembilan",
"Pahang",
"Perak",
"Perslis",
"Penang",
"Sabah",
"Sarawak",
"Selangor",
"Terengganu"
]
static let competingLevel = ["Professional",
"Amateur",
"Casual",
"Stream"
]
static let gamesCompeting = ["Street Fighter", "Super Smash Bros", "Marvel vs. Capcom", "Tekken", "Killer Instinct", "Quake", "Counter-Strike series", "Call of Duty series", "Unreal Tournament", "Halo series", "Painkiller", "Battlefield series", "CrossFire", "Overwatch", "Team Fortress 2", "Rainbow Six: Siege", "Alliance of Valiant Arms", "Special Force II", "StarCraft: Brood War", "Warcraft III", "StarCraft II", "FIFA series", "Madden", "NBA 2K", "Rocket League", "Real Subspace Hockey League", "Trackmania", "iRacing", "Project CARS", "Dota / Dota 2", "League of Legends", "Smite", "Heroes of the Storm", "Heroes of Newerth", "Vainglory", "Clash Royale", "EndGods", "Guild Wars 2", "Gears of War", "War Thunder", "World of Tanks", "World of Warcraft", "Hearthstone", "Pokémon", "Tetris"]
}
}
|
//
// CardSelectionView.swift
// Stacked
//
// Created by Sharad on 26/09/20.
//
import UIKit
import StackedYou
class CardSelectionView: UIView {
//MARK:- IBoutlets
@IBOutlet weak var discountStaticLabel: UILabel! {
didSet {
discountStaticLabel.textColor = .warmPink
discountStaticLabel.font = UIFont(name: "Avenir-Regular", size: 14.0)
}
}
@IBOutlet weak var discountValueLabel: UILabel! {
didSet {
discountValueLabel.textColor = .warmPink
discountValueLabel.font = UIFont(name: "Avenir-Heavy", size: 14.0)
discountValueLabel.text = "12%"
}
}
@IBOutlet weak var payableAmountStaticLabel: UILabel! {
didSet {
payableAmountStaticLabel.textColor = .warmPink
payableAmountStaticLabel.font = UIFont(name: "Avenir-Regular", size: 14.0)
}
}
@IBOutlet weak var payableAmountValueLabel: UILabel! {
didSet {
payableAmountValueLabel.textColor = .warmPink
payableAmountValueLabel.font = UIFont(name: "Avenir-Heavy", size: 14.0)
payableAmountValueLabel.text = "₹1,121.12"
}
}
@IBOutlet weak var backgroundAlphaView: UIView! {
didSet {
backgroundAlphaView.backgroundColor = .warmPink
backgroundAlphaView.addCornerRadius(radius: 8.0)
}
}
weak var stateManagerDelegate: StackedYouStateManagerDelegate?
private var currentState: StackedYouCurrentState = .none
//MARK:- Init
override init(frame: CGRect) {
super.init(frame: frame)
//UI testing
accessibilityIdentifier = "customview--CardSelectionView"
loadNib()
initialSetup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
guard subviews.isEmpty else {return}
loadNib()
}
override func layoutSubviews() {
super.layoutSubviews()
roundCorners(corners: [.topLeft, .topRight], radius: 20.0)
}
//MARK:- Private methods
private func loadNib() {
let idenitifier = String(describing: CardSelectionView.self)
let xib = UINib(nibName: idenitifier, bundle: Bundle.main)
let view = xib.instantiate(withOwner: self, options: nil).first as! UIView
view.frame = bounds
addSubview(view)
}
private func initialSetup() {
backgroundColor = .white
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
tapGesture.cancelsTouchesInView = true
addGestureRecognizer(tapGesture)
let edgeSwipeGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleEdgeSwipeGesture(_:)) )
edgeSwipeGesture.edges = .right
addGestureRecognizer(edgeSwipeGesture)
}
@objc private func handleEdgeSwipeGesture(_ recognizer: UIScreenEdgePanGestureRecognizer) {
switch recognizer.state {
case .ended:
guard abs(recognizer.translation(in: self).x) > 80.0 else {return}
handleGestureStates()
default: break
}
}
@objc private func handleTapGesture(_ recognizer: UITapGestureRecognizer) {
handleGestureStates()
}
private func handleGestureStates() {
switch currentState {
case .visible: collapseCurrentVisibleStackedView()
case .background: collapseUpperStackedView()
case .none: break
}
}
private func expandNextStackedView() {
stateManagerDelegate?.changeState(.background)
}
private func collapseUpperStackedView() {
stateManagerDelegate?.changeState(.visible)
}
private func collapseCurrentVisibleStackedView() {
stateManagerDelegate?.changeState(.none)
}
}
//MARK:- Extensions
extension CardSelectionView: StackedYouViewDataSource {
var headerHeight: CGFloat {
380.0
}
var currentStackedState: StackedYouCurrentState {
get {
currentState
}
set {
currentState = newValue
}
}
}
|
//
// JobListAllController.swift
// layout
//
// Created by Rama Agastya on 08/09/20.
// Copyright © 2020 Rama Agastya. All rights reserved.
//
import UIKit
import SkeletonView
class JobListAllController: UIViewController, UITableViewDelegate, SkeletonTableViewDataSource, UISearchBarDelegate {
var jobList:Job!
var data = [JobList]()
var filteredData: [String]!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var TVJobListAll: UITableView!
let refresher: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: .valueChanged)
return refreshControl
}()
override func viewDidLoad() {
super.viewDidLoad()
TVJobListAll.refreshControl = refresher
TVJobListAll.delegate = self
TVJobListAll.dataSource = self
searchBar.delegate = self
DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {
self.TVJobListAll.stopSkeletonAnimation()
self.view.hideSkeleton(reloadDataAfter: true, transition: .crossDissolve(0.2))
})
}
@objc
private func refresh(sender: UIRefreshControl){
getData {
self.TVJobListAll.reloadData()
}
sender.endRefreshing()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.jobList == nil {
TVJobListAll.isSkeletonable = true
TVJobListAll.showAnimatedGradientSkeleton(usingGradient: .init(baseColor: .concrete), animation: nil, transition: .crossDissolve(0.2))
}
getData {
self.TVJobListAll.reloadData()
//
}
}
func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
return "JobListAllCell"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.jobList == nil {
return 0
}
return self.jobList.job!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "JobListAllCell") as? JobListAllCell else { return UITableViewCell() }
if self.jobList == nil {
return cell
}
cell.JobLabel.text = jobList.job![indexPath.row].job_name
cell.CatLabel.text = jobList.job![indexPath.row].category?.category_name
cell.LocLabel.text = jobList.job![indexPath.row].location?.long_location
cell.CusLabel.text = jobList.job![indexPath.row].customer?.customer_name
if let imageURL = URL(string: jobList.job![indexPath.row].category!.category_image_url) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.IVJobList.image = image
}
}
}
}
return cell
}
func getData(completed: @escaping () -> ()){
let url = URL(string: GlobalVariable.urlGetJobListbyEngineer)
var request = URLRequest(url:url!)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(UserDefaults.standard.string(forKey: "Token")!, forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { (data, response, error) in
if error == nil {
do {
self.jobList = try JSONDecoder().decode(Job.self, from: data!)
self.data = self.jobList.job!
DispatchQueue.main.async {
completed()
}
} catch {
print("JSON Error")
}
}
}.resume()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toDetailJobListAll", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DetailJobListController {
destination.jobListFromSegue = jobList.job![(TVJobListAll.indexPathForSelectedRow?.row)!]
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = []
var temp = [JobList]()
if searchText == "" {
print("tidak ada input")
self.jobList.job = self.data
} else {
for data in self.jobList.job! {
if data.job_name.lowercased().contains(searchText.lowercased()) ||
(data.category!.category_name as String).lowercased().contains(searchText.lowercased()) ||
(data.location!.long_location as String).lowercased().contains(searchText.lowercased()) ||
(data.customer!.customer_name as String).lowercased().contains(searchText.lowercased()) {
temp.append(data)
}
self.jobList.job! = temp
}
}
self.TVJobListAll.reloadData()
}
}
|
//
// Items.swift
// AWSTesting
//
// Created by Kyaw Lin on 16/3/18.
// Copyright © 2018 Kyaw Lin. All rights reserved.
//
import Foundation
struct Constant{
static var secretKey: String?
static var sessionKey: String?
static var accessKey: String?
}
|
//
// SWBMatchMailViewController.swift
// SweepBright
//
// Created by Kaio Henrique on 4/13/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import UIKit
class SWBMatchMailViewController: UIViewController {
let keyboardHeight: CGFloat = 250.0
@IBOutlet var keyboardBar: UIToolbar!
@IBOutlet weak var mailTextView: UITextView!
@IBOutlet weak var stackViewBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.mailTextView.inputAccessoryView = self.keyboardBar
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillHideNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: {
_ in
self.stackViewBottomConstraint.constant = 0
})
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillShowNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: {
_ in
self.stackViewBottomConstraint.constant = self.keyboardHeight
})
}
@IBAction func dismissKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
}
|
//
// SignUpViewModel.swift
// RxSwift_MashUp
//
// Created by rookie.w on 2020/05/03.
// Copyright © 2020 rookie.w. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
protocol ViewModelType{
associatedtype Input
associatedtype Output
func transform(input: Input) -> Output
}
class SignUpViewModel: ViewModelType{
var disposeBag = DisposeBag()
struct Input{
}
struct Output{
}
func transform(input: Input) -> Output{
return Output()
}
enum PartType: Int {
case Dev = 0
case Design = 1
}
}
|
//
// Paddle.swift
// Breakout
//
// Created by Zach Ziemann on 12/13/16.
// Copyright © 2016 Zach Ziemann. All rights reserved.
//
import UIKit
class Paddle: UIView
{
//set info
init(myView: UIView)
{
super.init(frame: CGRectZero)
backgroundColor = UIColor.greenColor()
frame = CGRect(origin: CGPointZero, size: CGSize(width: 80,height: 18))
frame.origin.x = myView.bounds.maxX/2
frame.origin.y = myView.bounds.maxY/1.01
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func paddleLocation(velocity: CGFloat)
{
self.center = CGPoint(x: (velocity/30) + self.center.x , y: self.center.y)
}
}
|
//
// PokemonListTableViewController.swift
// Pokemon-Index
//
// Created by Mikołaj Szadkowski on 06/05/2020.
// Copyright © 2020 Mikołaj Szadkowski. All rights reserved.
//
import UIKit
import CoreData
class PokemonListTableViewController: UITableViewController {
var pokemonManager = PokemonManager()
var pokemonRequestResult = true
var reloadData = true
override func viewDidLoad() {
super.viewDidLoad()
pokemonManager.delegate = self
tableView.rowHeight = 90
pokemonManager.loadItems()
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokemonManager.pokemonArray?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PokemonListViewCell
if let pokemon = pokemonManager.pokemonArray?[indexPath.row], let pokemonImage = pokemon.image_front {
cell.pokemonName.text = pokemon.name
cell.pokemonImage.image = UIImage(data: pokemonImage)
if let type1 = pokemon.type1 {
cell.type2Image.image = UIImage(imageLiteralResourceName: type1)
}
if let type2 = pokemon.type2 {
cell.type1Image.image = UIImage(imageLiteralResourceName: type2)
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let pokemon = pokemonManager.pokemonArray?[indexPath.row] {
pokemonManager.pokemonChosen = pokemon
performSegue(withIdentifier: "goToPokemonDetails", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! PokemonDetailsViewController
destinationVC.pokemon = pokemonManager.pokemonChosen ?? nil
}
// MARK: - Update Pokemon List
func updateModel() {
DispatchQueue.main.async {
self.pokemonManager.loadItems()
if self.reloadData {
self.tableView.reloadData()
}
print("updated")
}
}
// MARK: - Pokemon loader
func preparePokemonList() {
// Delete all pokemons
print("Preparation started")
pokemonManager.loadItems()
if let pokemonArray = pokemonManager.pokemonArray {
for pokemon in pokemonArray {
pokemonManager.deletePokemon(pokemon: pokemon)
}
}
pokemonManager.saveItems()
// Download all pokemons
var runTime = 0
let timer = Timer.scheduledTimer(withTimeInterval: 0.61, repeats: true) { timer in
runTime += 1
if self.pokemonRequestResult {
self.pokemonManager.requestPokemon(pokemonName: String(runTime))
} else {
timer.invalidate()
}
}
print("Preparation completed")
}
@IBAction func refreshPokemonsButton(_ sender: UIBarButtonItem) {
preparePokemonList()
}
}
// MARK: - Pokemon Manager Delegate
extension PokemonListTableViewController: PokemonRequestDelegate {
func pokemonRequestDidFinish() {
updateModel()
}
func pokemonRequestDidFinishWithError() {
print(Error.self)
pokemonRequestResult = false
}
}
// MARK: - SearchBar Delegate
extension PokemonListTableViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("search started")
// Create request and filter
let request: NSFetchRequest<Pokemon> = Pokemon.fetchRequest()
if searchBar.text?.count != 0 {
let predicate = NSPredicate(format: "name CONTAINS[cd] %@", searchBar.text!)
// Add filter (predicate) to request
request.predicate = predicate
}
// Create sorting method
let sortDescriptor = NSSortDescriptor(key: "id", ascending: true)
// Add sorting method to request
request.sortDescriptors = [sortDescriptor]
// Load items to pokemon Array
pokemonManager.loadItems(with: request)
tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchBarSearchButtonClicked(searchBar)
reloadData = false
}
}
|
//
// SWBOfflineQueue.swift
// SweepBright
//
// Created by Kaio Henrique on 2/4/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import Foundation
import RealmSwift
import Alamofire
protocol SWBOfflineService {
func sync(request: String) -> NSOperation
func getAccessToken() -> NSOperation
}
class SWBOfflineServiceClass: SWBOfflineService {
func sync(request: String) -> NSOperation {
return NSBlockOperation {
let realm = try! Realm()
guard let request = realm.objects(SWBOfflineRequest).filter("id == %@", request).first else {
return
}
//get the header
var headers: [String:String] = [:]
for header in (request.headers) {
headers[header.key!] = header.value
}
headers["Authorization"] = "Bearer \(SWBKeychain.get(.AccessToken) ?? "")"
var response: NSHTTPURLResponse?
NSLog("Offline sync \(request.id): started")
SWBSynchronousRequestFactory.sharedInstance.requestSynchronous(Alamofire.Method(rawValue:request.method)!, url: (request.url)!, body: request.body!, headers: headers, completionHandler: {
resp in
response = resp.response
debugPrint(resp.response?.statusCode)
})
//Not still offline
if response != nil {
NSLog("Offline sync \(request.id): removed")
try! realm.write({
realm.delete(request)
})
} else {
NSLog("Offline sync \(request.id): finished")
}
}
}
func getAccessToken() -> NSOperation {
return SWBRoutes.getAccessToken()
}
}
class SWBParameter: Object {
dynamic var key: String?
dynamic var value: String?
}
class SWBOfflineRequest: Object {
private(set) dynamic var id = NSUUID().UUIDString
dynamic var method: String = "POST"
dynamic var url: String?
dynamic var body: NSData? = nil
let headers = List<SWBParameter>()
dynamic var createdAt = NSDate()
override class func primaryKey() -> String {
return "id"
}
}
class SWBOfflineQueue: NSObject {
var offlineService: SWBOfflineService = SWBOfflineServiceClass()
static let sharedInstance = SWBOfflineQueue()
let queue = NSOperationQueue()
private let realm = try! Realm()
internal var listOfRequests: Results<SWBOfflineRequest>!
internal var notificationToken: NotificationToken!
let interval: Double = 60*5 //5 minutes
var timer: NSTimer!
internal override init() {
super.init()
queue.qualityOfService = .Background
timer = NSTimer.scheduledTimerWithTimeInterval(self.interval, target: self, selector: #selector(SWBOfflineQueue.startTimer), userInfo: nil, repeats: true)
}
func addRequest(request: SWBOfflineRequest, waitUntilFinished: Bool = false) {
//This method may be execute in a different thread, that's why there is a new realm variable
try! realm.write({
realm.add(request)
self.start(waitUntilFinished)
})
}
internal func startTimer() {
self.start()
}
private func getOperations() -> [NSOperation] {
let accessTokenOp = self.offlineService.getAccessToken()
//Create a queue of requests
var operations: [NSOperation] = [accessTokenOp]
for request in self.requests {
let offlineOp = self.offlineService.sync(request.id)
offlineOp.addDependency(accessTokenOp)
operations.append(offlineOp)
}
return operations
}
func start(waitUntilFinished: Bool = false) {
if queue.operationCount < 0 {
NSLog("The queue is running")
return
}
let operations = self.getOperations()
self.queue.addOperations(operations, waitUntilFinished: waitUntilFinished)
}
//List of requests pendents (read-only)
var requests: Results<SWBOfflineRequest>! {
get {
//get que list only once
if let request = self.listOfRequests {
return request
} else {
self.listOfRequests = self.realm.objects(SWBOfflineRequest).sorted("createdAt")
return self.listOfRequests
}
}
}
}
|
//
// ViewController.swift
// FaceDraw
//
// Created by Muhamed Rahman on 7/19/16.
// Copyright © 2016 Muhamed Rahman. All rights reserved.
//
import UIKit
class FaceViewController: UIViewController {
var expression = FacialExpression(eyes: .Open, eyeBrows: .Normal, mouth: .Smile){
didSet{
updateUI()
}
}
@IBOutlet weak var faceView: FaceView!
private var mouthCurvatures = [FacialExpression.Mouth.Frown: -1.0, .Grin: 0.5, .Smile: 1.0, .Smirk: -0.5, .Neutral: 0.0]//dictionary lookups return optionals
private var eyeBrowTilts = [FacialExpression.EyeBrows.Relaxed: 0.5, .Furrowed: -0.5, .Normal: 0.0]
private func updateUI() {
switch expression.eyes{
case .Open: faceView.eyesOpen = true
case .Closed: faceView.eyesOpen = false
case .Squinting: faceView.eyesOpen = false
}
faceView.mouthCurvature = mouthCurvatures[expression.mouth] ?? 0.0
faceView.eyeBrowTilt = eyeBrowTilts[expression.eyeBrows] ?? 0.0
}
}
|
//
// Movie.swift
// MovieCalendar
//
// Created by Diel Barnes on 02/06/2017.
// Copyright © 2017 Diel Barnes. All rights reserved.
//
import Foundation
import UIKit
struct Movie {
var id: Int
var title: String
var poster: UIImage?
var posterPath: String?
var backdrop: UIImage?
var backdropPath: String?
var genres: [String]?
var cast: [Cast]?
var plot: String?
var trailerYouTubeId: String?
var trailerStreamUrl: URL?
var releaseDate: Date
}
|
//
// AppDetail.swift
// GrabilityTest
//
// Created by Yeisson Oviedo on 11/30/15.
// Copyright © 2015 Sanduche. All rights reserved.
//
import UIKit
class AppDetail: UIViewController {
@IBOutlet var image: UIImageView!
@IBOutlet var name: UILabel!
@IBOutlet var price: UILabel!
@IBOutlet var summary: UILabel!
@IBOutlet var navigationBar: UINavigationBar!
@IBOutlet var category: UILabel!
var app: GrabilityApp?
override func viewDidLoad() {
super.viewDidLoad()
summary.layer.borderColor = UIColor.flatCoffeeColor().CGColor
summary.layer.borderWidth = 1
summary.layer.cornerRadius = 10
// Do any additional setup after loading the view.
image.setImageWithUrlString(app?.imageMedium ?? "")
name.text = app?.name
price.text = "$\(app?.price ?? "0,0") \(app?.currency ?? "USD")"
summary.text = app?.summary
category.text = app?.category
}
override func viewDidLayoutSubviews() {
let frame = CGRectMake(0, navigationBar.frame.minY, UIScreen.mainScreen().bounds.width, navigationBar.frame.height)
navigationBar.frame = frame
}
override func viewDidAppear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func close(sender: AnyObject) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// PostCell.swift
// insta-ground-up
//
// Created by Malik Browne on 2/28/16.
// Copyright © 2016 malikbrowne. All rights reserved.
//
import UIKit
import Parse
import AFNetworking
class PostCell: UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var likeCount: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var postImageView: UIImageView!
var objectID: String?
var postInfo: PFObject! {
didSet {
descriptionLabel.text = postInfo.objectForKey("caption") as? String
if postInfo.objectForKey("likesCount") as! Int == 1 {
likeCount.text = "\((postInfo.objectForKey("likesCount") as! Int)) like"
} else {
likeCount.text = "\((postInfo.objectForKey("likesCount") as! Int)) likes"
}
objectID = postInfo.objectId
let likeStatus = postInfo.objectForKey("liked") as! Bool
if likeStatus == true {
likeButton.setImage(UIImage(named: "like-action-on"), forState: .Normal)
} else {
likeButton.setImage(UIImage(named: "like-action"), forState: .Normal)
}
}
}
@IBAction func onLike(sender: AnyObject) {
if likeButton.imageView?.image == UIImage(named: "like-action") {
UserMedia.likePost(objectID!)
likeButton.setImage(UIImage(named: "like-action-on"), forState: .Normal)
if (postInfo.objectForKey("likesCount") as! Int) + 1 == 1 {
likeCount.text = "\((postInfo.objectForKey("likesCount") as! Int) + 1) like"
} else {
likeCount.text = "\((postInfo.objectForKey("likesCount") as! Int) + 1) likes"
}
} else if likeButton.imageView?.image == UIImage(named: "like-action-on") {
UserMedia.unlikePost(objectID!)
likeButton.setImage(UIImage(named: "like-action"), forState: .Normal)
likeCount.text = "\((postInfo.objectForKey("likesCount") as! Int)) likes"
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// FavouriteViewModel.swift
// MovieLand
//
// Created by Galih Asmarandaru on 27/12/20.
//
import UIKit
struct FavouriteViewModel {
let dataFav: Favourite
var titleText: NSAttributedString {
let subject = NSMutableAttributedString(string: dataFav.title!, attributes: [.font: UIFont.boldSystemFont(ofSize: 16)])
return subject
}
var releaseDateText: NSAttributedString {
let subject = NSMutableAttributedString(string: dataFav.release_date!, attributes: [.font: UIFont.boldSystemFont(ofSize: 12)])
return subject
}
var overviewText: NSAttributedString {
let subject = NSMutableAttributedString(string: dataFav.overview!, attributes: [.font: UIFont.boldSystemFont(ofSize: 14)])
return subject
}
}
|
//
// SettingsTableViewController.swift
// Random Interval Reaction Timer
//
// Created by Ted Ganting Lim on 8/29/19.
// Copyright © 2019 Jobless. All rights reserved.
//
import UIKit
class SettingsTableViewController: UITableViewController {
//inits
let sectionTitles = ["Words", "Color", "Timer Options"]
let settingOptions1 = ["forward","backward","right", "left", "1", "2", "3", "4"]
let settingOptions2 = ["red", "blue", "purple", "cyan", "orange"]
struct Options {
var isSelected = false
var isSound = false
var isColor = false
var text = ""
var idxPath = IndexPath()
}
var selectedOptions = [Options]()
var defStr = "1"
var intervalField = 1
var defInt = 1
var freqField = 10
var defFreq = 10
var defFreqStr = "10"
//onViewLoad
override func viewDidLoad() {
super.viewDidLoad()
checkSettings()
self.closeKeyboardOnOutsideTap()
}
//marks selected rows on segue back to settingsVC
func checkSettings() {
for setting in selectedOptions {
if setting.isSelected {
let path = IndexPath.init(row: setting.idxPath.row, section: setting.idxPath.section)
self.tableView.selectRow(at: path, animated: false, scrollPosition: .none)
self.tableView.cellForRow(at: path)?.accessoryType = .checkmark
}
}
}
//numSections
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
//numRowsPerSection
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return settingOptions1.count
case 1:
return settingOptions2.count
case 2:
return 2
default:
return -1
}
}
//titlePerSection
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
//addContent; fills timer options settings on add content phase
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell01 = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath)
if selectedOptions.firstIndex(where: { $0.idxPath == indexPath }) != nil {
cell01.accessoryType = .checkmark
} else {
cell01.accessoryType = .none
}
switch (indexPath.section) {
case 0:
cell01.textLabel?.text = settingOptions1[indexPath.row]
case 1:
cell01.textLabel?.text = settingOptions2[indexPath.row]
case 2:
let cell02 = tableView.dequeueReusableCell(withIdentifier: "numInputCell", for: indexPath) as! numInputTableViewCell
if indexPath.row == 0 {
cell02.numLabel.text = "Min Interval (sec)"
cell02.numInputField.placeholder = "Enter Value"
cell02.numInputField.text = String(intervalField)
cell02.selectionStyle = UITableViewCell.SelectionStyle.none
} else if indexPath.row == 1 {
cell02.numLabel.text = "Frequency"
cell02.numInputField.placeholder = "1 - 10"
cell02.numInputField.text = String(freqField)
cell02.selectionStyle = UITableViewCell.SelectionStyle.none
}
return cell02
default: break
}
return cell01
}
//select&deselect row checkmark; selected to storage array
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
cell.isSelected = false
cell.isHighlighted = false
if let index = selectedOptions.firstIndex(where: { $0.idxPath == indexPath }) {
selectedOptions.remove(at: index)
}
} else {
var option = Options(
isSelected: true, isSound: false, isColor: false, text: cell.textLabel!.text!, idxPath: indexPath)
if indexPath.section == 1 {
option.isColor = true
} else {
option.isSound = true
}
cell.accessoryType = .checkmark
selectedOptions.append(option)
}
}
}
//make cells with no selection unselectable
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath as IndexPath)
if(cell?.selectionStyle == UITableViewCell.SelectionStyle.none){
return nil;
}
return indexPath
}
//records values of edited textfields
@IBAction func numInputEditingDidEnd(_ sender: UITextField) {
if sender.placeholder == "Enter Value" {
//store value as minInterval
if let tmpTxt = sender.text {
intervalField = Int(tmpTxt) ?? defInt
} else {
intervalField = defInt
}
if intervalField <= 0 {
sender.text = defStr
intervalField = defInt
}
} else if sender.placeholder == "1 - 10" {
if let tmpTxt = sender.text {
freqField = Int(tmpTxt) ?? defFreq
} else {
freqField = defFreq
}
if freqField > 10 || freqField <= 0 {
sender.text = defFreqStr
freqField = defFreq
}
}
}
//store chosen settings and pass to VC
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "cancelToViewController" {
let vc = segue.destination as! ViewController
vc.passedOptions = selectedOptions
vc.minInterval = intervalField
vc.frequency = freqField
print("FROM SETTINGS")
print("These are passed options:")
print(vc.passedOptions)
print("Min Interval")
print(vc.minInterval)
print("Frequency")
print(vc.frequency)
}
}
}
|
//
// Graficos.swift
// concorSwiftSpring.com.RentalApps.galderma2017LitioB
//
// Created by PixelCut on 28-05-17.
// Copyright © 2017 PixelCut. All rights reserved.
//
// Generated by PaintCode
// http://www.paintcodeapp.com
//
import UIKit
public class Graficos : NSObject {
//// Drawing Methods
public dynamic class func drawCanvas1(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 845, height: 407), resizing: ResizingBehavior = .aspectFit, valueH1G1: CGFloat = 283, valueH2G1: CGFloat = 172) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 845, height: 407), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 845, y: resizedFrame.height / 407)
//// Color Declarations
let fillColor = UIColor(red: 0.996, green: 0.996, blue: 0.995, alpha: 1.000)
let textForeground2 = UIColor(red: 0.000, green: 0.224, blue: 0.457, alpha: 1.000)
let fillColor2 = UIColor(red: 0.342, green: 0.344, blue: 0.352, alpha: 1.000)
let strokeColor = UIColor(red: 0.000, green: 0.224, blue: 0.457, alpha: 1.000)
let fillColor3 = UIColor(red: 0.255, green: 0.649, blue: 0.166, alpha: 1.000)
let strokeColor2 = UIColor(red: 0.043, green: 0.444, blue: 0.705, alpha: 1.000)
//// Variable Declarations
let h1G1: CGFloat = valueH1G1 < 0 ? 0 : (valueH1G1 > 249 ? 249 : valueH1G1)
let negH1G1: CGFloat = -h1G1
let hiddenH1G1 = h1G1 == 249 ? true : false
let h2G1: CGFloat = valueH2G1 < 0 ? 0 : (valueH2G1 > 100 ? 100 : valueH2G1)
let negH2G1: CGFloat = -h2G1
let hiddenH2G1 = h2G1 == 100 ? true : false
//// Group 2
//// Rectangle Drawing
context.saveGState()
context.setAlpha(0.5)
let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: -0.02, width: 845.3, height: 406.6))
fillColor.setFill()
rectanglePath.fill()
context.restoreGState()
//// Label 3 Drawing
let label3Rect = CGRect(x: 260.1, y: -0.36, width: 309.31, height: 31)
let label3TextContent = "Conteo de Colonias de S.aureus"
let label3Style = NSMutableParagraphStyle()
label3Style.alignment = .center
let label3FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 21), NSForegroundColorAttributeName: textForeground2, NSParagraphStyleAttributeName: label3Style]
let label3TextHeight: CGFloat = label3TextContent.boundingRect(with: CGSize(width: label3Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label3FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label3Rect)
label3TextContent.draw(in: CGRect(x: label3Rect.minX, y: label3Rect.minY + (label3Rect.height - label3TextHeight) / 2, width: label3Rect.width, height: label3TextHeight), withAttributes: label3FontAttributes)
context.restoreGState()
//// Label 4 Drawing
let label4Rect = CGRect(x: 300.52, y: 27, width: 229.17, height: 30.64)
let label4TextContent = "Basal y 28 días después"
let label4Style = NSMutableParagraphStyle()
label4Style.alignment = .center
let label4FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 21), NSForegroundColorAttributeName: textForeground2, NSParagraphStyleAttributeName: label4Style]
let label4TextHeight: CGFloat = label4TextContent.boundingRect(with: CGSize(width: label4Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label4FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label4Rect)
label4TextContent.draw(in: CGRect(x: label4Rect.minX, y: label4Rect.minY + (label4Rect.height - label4TextHeight) / 2, width: label4Rect.width, height: label4TextHeight), withAttributes: label4FontAttributes)
context.restoreGState()
//// Label 7 Drawing
context.saveGState()
context.translateBy(x: 186.59, y: 246.42)
context.rotate(by: -90 * CGFloat.pi/180)
let label7Rect = CGRect(x: 0, y: 0, width: 76.17, height: 24)
let label7TextContent = "S. aureus*"
let label7Style = NSMutableParagraphStyle()
label7Style.alignment = .center
let label7FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: textForeground2, NSParagraphStyleAttributeName: label7Style]
let label7TextHeight: CGFloat = label7TextContent.boundingRect(with: CGSize(width: label7Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label7FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label7Rect)
label7TextContent.draw(in: CGRect(x: label7Rect.minX, y: label7Rect.minY + (label7Rect.height - label7TextHeight) / 2, width: label7Rect.width, height: label7TextHeight), withAttributes: label7FontAttributes)
context.restoreGState()
context.restoreGState()
//// Label 8 Drawing
context.saveGState()
context.translateBy(x: 186.59, y: 169.96)
context.rotate(by: -90 * CGFloat.pi/180)
let label8Rect = CGRect(x: 0, y: 0, width: 47.33, height: 24)
let label8TextContent = " count"
let label8Style = NSMutableParagraphStyle()
label8Style.alignment = .center
let label8FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: textForeground2, NSParagraphStyleAttributeName: label8Style]
let label8TextHeight: CGFloat = label8TextContent.boundingRect(with: CGSize(width: label8Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label8FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label8Rect)
label8TextContent.draw(in: CGRect(x: label8Rect.minX, y: label8Rect.minY + (label8Rect.height - label8TextHeight) / 2, width: label8Rect.width, height: label8TextHeight), withAttributes: label8FontAttributes)
context.restoreGState()
context.restoreGState()
//// Label 9 Drawing
let label9Rect = CGRect(x: 215.11, y: 202.74, width: 17.84, height: 38)
let label9TextContent = "\n0,2"
let label9Style = NSMutableParagraphStyle()
label9Style.alignment = .center
let label9FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label9Style]
let label9TextHeight: CGFloat = label9TextContent.boundingRect(with: CGSize(width: label9Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label9FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label9Rect)
label9TextContent.draw(in: CGRect(x: label9Rect.minX, y: label9Rect.minY + (label9Rect.height - label9TextHeight) / 2, width: label9Rect.width, height: label9TextHeight), withAttributes: label9FontAttributes)
context.restoreGState()
//// Label 10 Drawing
let label10Rect = CGRect(x: 215.19, y: 69.25, width: 17.62, height: 38)
let label10TextContent = "\n0,5"
let label10Style = NSMutableParagraphStyle()
label10Style.alignment = .center
let label10FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label10Style]
let label10TextHeight: CGFloat = label10TextContent.boundingRect(with: CGSize(width: label10Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label10FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label10Rect)
label10TextContent.draw(in: CGRect(x: label10Rect.minX, y: label10Rect.minY + (label10Rect.height - label10TextHeight) / 2, width: label10Rect.width, height: label10TextHeight), withAttributes: label10FontAttributes)
context.restoreGState()
//// Rectangle 12 Drawing
context.saveGState()
context.translateBy(x: 306, y: (negH1G1 + 53.3939))
let rectangle12Path = UIBezierPath(rect: CGRect(x: 0, y: 294, width: 92.7, height: h1G1))
fillColor2.setFill()
rectangle12Path.fill()
context.restoreGState()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 252.24, y: 57.4))
bezierPath.addLine(to: CGPoint(x: 252.24, y: 347.31))
strokeColor.setStroke()
bezierPath.lineWidth = 0.55
bezierPath.lineCapStyle = .round
bezierPath.lineJoinStyle = .round
bezierPath.stroke()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 244.53, y: 231.69))
bezier2Path.addLine(to: CGPoint(x: 259.75, y: 231.69))
strokeColor.setStroke()
bezier2Path.lineWidth = 0.35
bezier2Path.lineCapStyle = .round
bezier2Path.lineJoinStyle = .round
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 244.53, y: 99.21))
bezier3Path.addLine(to: CGPoint(x: 259.75, y: 99.21))
strokeColor.setStroke()
bezier3Path.lineWidth = 0.35
bezier3Path.lineCapStyle = .round
bezier3Path.lineJoinStyle = .round
bezier3Path.stroke()
//// Rectangle 13 Drawing
let rectangle13Path = UIBezierPath(rect: CGRect(x: 468, y: (negH2G1 + 347.3559), width: 92.7, height: h2G1))
fillColor3.setFill()
rectangle13Path.fill()
if (hiddenH2G1) {
//// Label 11 Drawing
let label11Rect = CGRect(x: 481.47, y: 114.85, width: 69.02, height: 74)
let label11TextContent = "\n244%"
let label11Style = NSMutableParagraphStyle()
label11Style.alignment = .center
let label11FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 25), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label11Style]
let label11TextHeight: CGFloat = label11TextContent.boundingRect(with: CGSize(width: label11Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label11FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label11Rect)
label11TextContent.draw(in: CGRect(x: label11Rect.minX, y: label11Rect.minY + (label11Rect.height - label11TextHeight) / 2, width: label11Rect.width, height: label11TextHeight), withAttributes: label11FontAttributes)
context.restoreGState()
//// Label 12 Drawing
let label12Rect = CGRect(x: 490.11, y: 208.86, width: 52.38, height: 36)
let label12TextContent = "\np<0.1431"
let label12Style = NSMutableParagraphStyle()
label12Style.alignment = .center
let label12FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label12Style]
let label12TextHeight: CGFloat = label12TextContent.boundingRect(with: CGSize(width: label12Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label12FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label12Rect)
label12TextContent.draw(in: CGRect(x: label12Rect.minX, y: label12Rect.minY + (label12Rect.height - label12TextHeight) / 2, width: label12Rect.width, height: label12TextHeight), withAttributes: label12FontAttributes)
context.restoreGState()
}
if (hiddenH1G1) {
//// Label 13 Drawing
let label13Rect = CGRect(x: 328.85, y: 68.96, width: 56.32, height: 36)
let label13TextContent = "p<0.067"
let label13Style = NSMutableParagraphStyle()
label13Style.alignment = .center
let label13FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label13Style]
let label13TextHeight: CGFloat = label13TextContent.boundingRect(with: CGSize(width: label13Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label13FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label13Rect)
label13TextContent.draw(in: CGRect(x: label13Rect.minX, y: label13Rect.minY + (label13Rect.height - label13TextHeight) / 2, width: label13Rect.width, height: label13TextHeight), withAttributes: label13FontAttributes)
context.restoreGState()
}
if (hiddenH2G1) {
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 514.47, y: 186.61))
bezier4Path.addLine(to: CGPoint(x: 514.47, y: 223.54))
strokeColor2.setStroke()
bezier4Path.lineWidth = 2.96
bezier4Path.lineCapStyle = .round
bezier4Path.lineJoinStyle = .round
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.move(to: CGPoint(x: 514.47, y: 156.01))
bezier5Path.addLine(to: CGPoint(x: 514.47, y: 109.91))
strokeColor2.setStroke()
bezier5Path.lineWidth = 2.96
bezier5Path.lineCapStyle = .round
bezier5Path.lineJoinStyle = .round
bezier5Path.stroke()
//// Bezier 6 Drawing
let bezier6Path = UIBezierPath()
bezier6Path.move(to: CGPoint(x: 521.35, y: 109.81))
bezier6Path.addLine(to: CGPoint(x: 514.34, y: 100.47))
bezier6Path.addLine(to: CGPoint(x: 507.36, y: 109.81))
strokeColor2.setStroke()
bezier6Path.lineWidth = 2.72
bezier6Path.lineCapStyle = .round
bezier6Path.lineJoinStyle = .round
bezier6Path.stroke()
}
//// Label 14 Drawing
let label14Rect = CGRect(x: 315.39, y: 346.84, width: 76.24, height: 48)
let label14TextContent = "CONTROL"
let label14Style = NSMutableParagraphStyle()
label14Style.alignment = .center
let label14FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label14Style]
let label14TextHeight: CGFloat = label14TextContent.boundingRect(with: CGSize(width: label14Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label14FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label14Rect)
label14TextContent.draw(in: CGRect(x: label14Rect.minX, y: label14Rect.minY + (label14Rect.height - label14TextHeight) / 2, width: label14Rect.width, height: label14TextHeight), withAttributes: label14FontAttributes)
context.restoreGState()
//// Bezier 7 Drawing
let bezier7Path = UIBezierPath()
bezier7Path.move(to: CGPoint(x: 613.96, y: 347.18))
bezier7Path.addLine(to: CGPoint(x: 239.43, y: 347.18))
strokeColor.setStroke()
bezier7Path.lineWidth = 0.64
bezier7Path.lineCapStyle = .round
bezier7Path.lineJoinStyle = .round
bezier7Path.stroke()
context.restoreGState()
}
public dynamic class func drawCanvas2(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 847, height: 476), resizing: ResizingBehavior = .aspectFit, valueH1G2: CGFloat = 312, valueH2G2: CGFloat = 423) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 847, height: 476), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 847, y: resizedFrame.height / 476)
//// Color Declarations
let fillColor = UIColor(red: 0.996, green: 0.996, blue: 0.995, alpha: 1.000)
let fillColor2 = UIColor(red: 0.342, green: 0.344, blue: 0.352, alpha: 1.000)
let strokeColor = UIColor(red: 0.000, green: 0.224, blue: 0.457, alpha: 1.000)
let fillColor3 = UIColor(red: 0.255, green: 0.649, blue: 0.166, alpha: 1.000)
let strokeColor2 = UIColor(red: 0.043, green: 0.444, blue: 0.705, alpha: 1.000)
//// Variable Declarations
let h1G2: CGFloat = valueH1G2 < 0 ? 0 : (valueH1G2 > 257 ? 257 : valueH1G2)
let negH1G2: CGFloat = -h1G2
let hiddenH1G2 = h1G2 == 257 ? true : false
let h2G2: CGFloat = valueH2G2 < 0 ? 0 : (valueH2G2 > 328 ? 328 : valueH2G2)
let negH2G2: CGFloat = -h2G2
//// Group 2
//// Rectangle Drawing
context.saveGState()
context.setAlpha(0.7)
let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 846.6, height: 476.2))
fillColor.setFill()
rectanglePath.fill()
context.restoreGState()
//// Label Drawing
let labelRect = CGRect(x: 280.24, y: 11.54, width: 109.85, height: 27)
let labelTextContent = "Cantidad de "
let labelStyle = NSMutableParagraphStyle()
labelStyle.alignment = .center
let labelFontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: labelStyle]
let labelTextHeight: CGFloat = labelTextContent.boundingRect(with: CGSize(width: labelRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: labelFontAttributes, context: nil).height
context.saveGState()
context.clip(to: labelRect)
labelTextContent.draw(in: CGRect(x: labelRect.minX, y: labelRect.minY + (labelRect.height - labelTextHeight) / 2, width: labelRect.width, height: labelTextHeight), withAttributes: labelFontAttributes)
context.restoreGState()
//// Label 2 Drawing
let label2Rect = CGRect(x: 399.2, y: 11.54, width: 152.94, height: 27)
let label2TextContent = "-Defensina hBD-2"
let label2Style = NSMutableParagraphStyle()
label2Style.alignment = .center
let label2FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label2Style]
let label2TextHeight: CGFloat = label2TextContent.boundingRect(with: CGSize(width: label2Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label2FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label2Rect)
label2TextContent.draw(in: CGRect(x: label2Rect.minX, y: label2Rect.minY + (label2Rect.height - label2TextHeight) / 2, width: label2Rect.width, height: label2TextHeight), withAttributes: label2FontAttributes)
context.restoreGState()
//// Label 3 Drawing
let label3Rect = CGRect(x: 204.98, y: 30.44, width: 426.44, height: 27)
let label3TextContent = "Basal y 72 horas después de la aplicación (N =36)"
let label3Style = NSMutableParagraphStyle()
label3Style.alignment = .center
let label3FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label3Style]
let label3TextHeight: CGFloat = label3TextContent.boundingRect(with: CGSize(width: label3Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label3FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label3Rect)
label3TextContent.draw(in: CGRect(x: label3Rect.minX, y: label3Rect.minY + (label3Rect.height - label3TextHeight) / 2, width: label3Rect.width, height: label3TextHeight), withAttributes: label3FontAttributes)
context.restoreGState()
//// Label 7 Drawing
let label7Rect = CGRect(x: 206.14, y: 365.24, width: 9.01, height: 46)
let label7TextContent = "\n0"
let label7Style = NSMutableParagraphStyle()
label7Style.alignment = .center
let label7FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label7Style]
let label7TextHeight: CGFloat = label7TextContent.boundingRect(with: CGSize(width: label7Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label7FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label7Rect)
label7TextContent.draw(in: CGRect(x: label7Rect.minX, y: label7Rect.minY + (label7Rect.height - label7TextHeight) / 2, width: label7Rect.width, height: label7TextHeight), withAttributes: label7FontAttributes)
context.restoreGState()
//// Label 8 Drawing
let label8Rect = CGRect(x: 300.94, y: 387.68, width: 71.43, height: 46)
let label8TextContent = "\nCONTROL"
let label8Style = NSMutableParagraphStyle()
label8Style.alignment = .center
let label8FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label8Style]
let label8TextHeight: CGFloat = label8TextContent.boundingRect(with: CGSize(width: label8Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label8FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label8Rect)
label8TextContent.draw(in: CGRect(x: label8Rect.minX, y: label8Rect.minY + (label8Rect.height - label8TextHeight) / 2, width: label8Rect.width, height: label8TextHeight), withAttributes: label8FontAttributes)
context.restoreGState()
//// Rectangle 10 Drawing
let rectangle10Path = UIBezierPath(rect: CGRect(x: 280.58, y: (negH1G2 + 406.995), width: 108.55, height: h1G2))
fillColor2.setFill()
rectangle10Path.fill()
//// Rectangle 11 Drawing
let rectangle11Path = UIBezierPath(rect: CGRect(x: 486.18, y: (negH2G2 + 406.995), width: 108.55, height: h2G2))
fillColor3.setFill()
rectangle11Path.fill()
if (hiddenH1G2) {
//// Label 9 Drawing
let label9Rect = CGRect(x: 309.02, y: 68.56, width: 58.29, height: 86)
let label9TextContent = "\n17%"
let label9Style = NSMutableParagraphStyle()
label9Style.alignment = .center
let label9FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 30), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label9Style]
let label9TextHeight: CGFloat = label9TextContent.boundingRect(with: CGSize(width: label9Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label9FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label9Rect)
label9TextContent.draw(in: CGRect(x: label9Rect.minX, y: label9Rect.minY + (label9Rect.height - label9TextHeight) / 2, width: label9Rect.width, height: label9TextHeight), withAttributes: label9FontAttributes)
context.restoreGState()
}
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 661.49, y: 406.6))
bezierPath.addLine(to: CGPoint(x: 222.87, y: 406.6))
strokeColor.setStroke()
bezierPath.lineWidth = 0.74
bezierPath.lineCapStyle = .round
bezierPath.lineJoinStyle = .round
bezierPath.stroke()
if (hiddenH1G2) {
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 335.74, y: 115.22))
bezier2Path.addLine(to: CGPoint(x: 335.74, y: 89.99))
strokeColor2.setStroke()
bezier2Path.lineWidth = 3.47
bezier2Path.lineCapStyle = .round
bezier2Path.lineJoinStyle = .round
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 344.06, y: 91.4))
bezier3Path.addLine(to: CGPoint(x: 335.85, y: 80.46))
bezier3Path.addLine(to: CGPoint(x: 327.68, y: 91.4))
strokeColor2.setStroke()
bezier3Path.lineWidth = 3.19
bezier3Path.lineCapStyle = .round
bezier3Path.lineJoinStyle = .round
bezier3Path.stroke()
}
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 237.86, y: 67.22))
bezier4Path.addLine(to: CGPoint(x: 237.86, y: 406.76))
strokeColor.setStroke()
bezier4Path.lineWidth = 0.64
bezier4Path.lineCapStyle = .round
bezier4Path.lineJoinStyle = .round
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.move(to: CGPoint(x: 228.84, y: 271.35))
bezier5Path.addLine(to: CGPoint(x: 246.66, y: 271.35))
strokeColor.setStroke()
bezier5Path.lineWidth = 0.41
bezier5Path.lineCapStyle = .round
bezier5Path.lineJoinStyle = .round
bezier5Path.stroke()
//// Label 10 Drawing
let label10Rect = CGRect(x: 180.48, y: 333.64, width: 35.23, height: 46)
let label10TextContent = "\n2000"
let label10Style = NSMutableParagraphStyle()
label10Style.alignment = .center
let label10FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label10Style]
let label10TextHeight: CGFloat = label10TextContent.boundingRect(with: CGSize(width: label10Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label10FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label10Rect)
label10TextContent.draw(in: CGRect(x: label10Rect.minX, y: label10Rect.minY + (label10Rect.height - label10TextHeight) / 2, width: label10Rect.width, height: label10TextHeight), withAttributes: label10FontAttributes)
context.restoreGState()
//// Label 11 Drawing
let label11Rect = CGRect(x: 179.05, y: 284.95, width: 36.35, height: 46)
let label11TextContent = "\n4000"
let label11Style = NSMutableParagraphStyle()
label11Style.alignment = .center
let label11FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label11Style]
let label11TextHeight: CGFloat = label11TextContent.boundingRect(with: CGSize(width: label11Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label11FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label11Rect)
label11TextContent.draw(in: CGRect(x: label11Rect.minX, y: label11Rect.minY + (label11Rect.height - label11TextHeight) / 2, width: label11Rect.width, height: label11TextHeight), withAttributes: label11FontAttributes)
context.restoreGState()
//// Label 12 Drawing
let label12Rect = CGRect(x: 179.85, y: 234.55, width: 35.76, height: 46)
let label12TextContent = "\n6000"
let label12Style = NSMutableParagraphStyle()
label12Style.alignment = .center
let label12FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label12Style]
let label12TextHeight: CGFloat = label12TextContent.boundingRect(with: CGSize(width: label12Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label12FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label12Rect)
label12TextContent.draw(in: CGRect(x: label12Rect.minX, y: label12Rect.minY + (label12Rect.height - label12TextHeight) / 2, width: label12Rect.width, height: label12TextHeight), withAttributes: label12FontAttributes)
context.restoreGState()
//// Label 13 Drawing
let label13Rect = CGRect(x: 179.56, y: 182.38, width: 35.84, height: 46)
let label13TextContent = "\n8000"
let label13Style = NSMutableParagraphStyle()
label13Style.alignment = .center
let label13FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label13Style]
let label13TextHeight: CGFloat = label13TextContent.boundingRect(with: CGSize(width: label13Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label13FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label13Rect)
label13TextContent.draw(in: CGRect(x: label13Rect.minX, y: label13Rect.minY + (label13Rect.height - label13TextHeight) / 2, width: label13Rect.width, height: label13TextHeight), withAttributes: label13FontAttributes)
context.restoreGState()
//// Bezier 6 Drawing
let bezier6Path = UIBezierPath()
bezier6Path.move(to: CGPoint(x: 228.84, y: 218.25))
bezier6Path.addLine(to: CGPoint(x: 246.66, y: 218.25))
strokeColor.setStroke()
bezier6Path.lineWidth = 0.41
bezier6Path.lineCapStyle = .round
bezier6Path.lineJoinStyle = .round
bezier6Path.stroke()
//// Label 14 Drawing
let label14Rect = CGRect(x: 172.56, y: 133.43, width: 43.46, height: 46)
let label14TextContent = "\n10000"
let label14Style = NSMutableParagraphStyle()
label14Style.alignment = .center
let label14FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label14Style]
let label14TextHeight: CGFloat = label14TextContent.boundingRect(with: CGSize(width: label14Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label14FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label14Rect)
label14TextContent.draw(in: CGRect(x: label14Rect.minX, y: label14Rect.minY + (label14Rect.height - label14TextHeight) / 2, width: label14Rect.width, height: label14TextHeight), withAttributes: label14FontAttributes)
context.restoreGState()
//// Bezier 7 Drawing
let bezier7Path = UIBezierPath()
bezier7Path.move(to: CGPoint(x: 228.84, y: 169.28))
bezier7Path.addLine(to: CGPoint(x: 246.66, y: 169.28))
strokeColor.setStroke()
bezier7Path.lineWidth = 0.41
bezier7Path.lineCapStyle = .round
bezier7Path.lineJoinStyle = .round
bezier7Path.stroke()
//// Label 15 Drawing
let label15Rect = CGRect(x: 173.94, y: 80.33, width: 42.65, height: 46)
let label15TextContent = "\n12000"
let label15Style = NSMutableParagraphStyle()
label15Style.alignment = .center
let label15FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label15Style]
let label15TextHeight: CGFloat = label15TextContent.boundingRect(with: CGSize(width: label15Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label15FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label15Rect)
label15TextContent.draw(in: CGRect(x: label15Rect.minX, y: label15Rect.minY + (label15Rect.height - label15TextHeight) / 2, width: label15Rect.width, height: label15TextHeight), withAttributes: label15FontAttributes)
context.restoreGState()
//// Bezier 8 Drawing
let bezier8Path = UIBezierPath()
bezier8Path.move(to: CGPoint(x: 228.84, y: 116.18))
bezier8Path.addLine(to: CGPoint(x: 246.66, y: 116.18))
strokeColor.setStroke()
bezier8Path.lineWidth = 0.41
bezier8Path.lineCapStyle = .round
bezier8Path.lineJoinStyle = .round
bezier8Path.stroke()
//// Label 16 Drawing
let label16Rect = CGRect(x: 172.47, y: 31.36, width: 43.77, height: 46)
let label16TextContent = "\n14000"
let label16Style = NSMutableParagraphStyle()
label16Style.alignment = .center
let label16FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label16Style]
let label16TextHeight: CGFloat = label16TextContent.boundingRect(with: CGSize(width: label16Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label16FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label16Rect)
label16TextContent.draw(in: CGRect(x: label16Rect.minX, y: label16Rect.minY + (label16Rect.height - label16TextHeight) / 2, width: label16Rect.width, height: label16TextHeight), withAttributes: label16FontAttributes)
context.restoreGState()
//// Bezier 9 Drawing
let bezier9Path = UIBezierPath()
bezier9Path.move(to: CGPoint(x: 228.84, y: 67.22))
bezier9Path.addLine(to: CGPoint(x: 246.66, y: 67.22))
strokeColor.setStroke()
bezier9Path.lineWidth = 0.41
bezier9Path.lineCapStyle = .round
bezier9Path.lineJoinStyle = .round
bezier9Path.stroke()
//// Bezier 10 Drawing
let bezier10Path = UIBezierPath()
bezier10Path.move(to: CGPoint(x: 228.84, y: 319.77))
bezier10Path.addLine(to: CGPoint(x: 246.66, y: 319.77))
strokeColor.setStroke()
bezier10Path.lineWidth = 0.41
bezier10Path.lineCapStyle = .round
bezier10Path.lineJoinStyle = .round
bezier10Path.stroke()
//// Bezier 11 Drawing
let bezier11Path = UIBezierPath()
bezier11Path.move(to: CGPoint(x: 228.84, y: 367.83))
bezier11Path.addLine(to: CGPoint(x: 246.66, y: 367.83))
strokeColor.setStroke()
bezier11Path.lineWidth = 0.41
bezier11Path.lineCapStyle = .round
bezier11Path.lineJoinStyle = .round
bezier11Path.stroke()
context.restoreGState()
}
public dynamic class func drawCanvas3(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 837, height: 466), resizing: ResizingBehavior = .aspectFit, valueH1G3: CGFloat = 116, valueH2G3: CGFloat = 276) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 837, height: 466), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 837, y: resizedFrame.height / 466)
//// Color Declarations
let fillColor = UIColor(red: 0.996, green: 0.996, blue: 0.995, alpha: 1.000)
let textForeground2 = UIColor(red: 0.000, green: 0.224, blue: 0.457, alpha: 1.000)
let fillColor2 = UIColor(red: 0.342, green: 0.344, blue: 0.352, alpha: 1.000)
let strokeColor = UIColor(red: 0.000, green: 0.224, blue: 0.457, alpha: 1.000)
let fillColor3 = UIColor(red: 0.255, green: 0.649, blue: 0.166, alpha: 1.000)
let strokeColor2 = UIColor(red: 0.043, green: 0.444, blue: 0.705, alpha: 1.000)
//// Variable Declarations
let h1G3: CGFloat = valueH1G3 < 0 ? 0 : (valueH1G3 > 116 ? 116 : valueH1G3)
let negH1G3: CGFloat = -h1G3
let hiddenH1G3 = h1G3 == 116 ? true : false
let h2G3: CGFloat = valueH2G3 < 0 ? 0 : (valueH2G3 > 247 ? 247 : valueH2G3)
let negH2G3: CGFloat = -h2G3
let hiddenH2G3 = h2G3 == 247 ? true : false
//// Group 2
//// Rectangle Drawing
context.saveGState()
context.setAlpha(0.5)
let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 837.2, height: 465.55))
fillColor.setFill()
rectanglePath.fill()
context.restoreGState()
//// Label Drawing
let labelRect = CGRect(x: 339.98, y: 23.24, width: 238.35, height: 32)
let labelTextContent = "Cantidad de Catelicidina"
let labelStyle = NSMutableParagraphStyle()
labelStyle.alignment = .center
let labelFontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 21), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: labelStyle]
let labelTextHeight: CGFloat = labelTextContent.boundingRect(with: CGSize(width: labelRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: labelFontAttributes, context: nil).height
context.saveGState()
context.clip(to: labelRect)
labelTextContent.draw(in: CGRect(x: labelRect.minX, y: labelRect.minY + (labelRect.height - labelTextHeight) / 2, width: labelRect.width, height: labelTextHeight), withAttributes: labelFontAttributes)
context.restoreGState()
//// Label 2 Drawing
let label2Rect = CGRect(x: 258.05, y: 44.54, width: 401.89, height: 32)
let label2TextContent = "Basal y 72 horas después de la aplicación"
let label2Style = NSMutableParagraphStyle()
label2Style.alignment = .center
let label2FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 21), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label2Style]
let label2TextHeight: CGFloat = label2TextContent.boundingRect(with: CGSize(width: label2Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label2FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label2Rect)
label2TextContent.draw(in: CGRect(x: label2Rect.minX, y: label2Rect.minY + (label2Rect.height - label2TextHeight) / 2, width: label2Rect.width, height: label2TextHeight), withAttributes: label2FontAttributes)
context.restoreGState()
//// Label 5 Drawing
let label5Rect = CGRect(x: 152.41, y: 315.57, width: 11.28, height: 54)
let label5TextContent = "\n0"
let label5Style = NSMutableParagraphStyle()
label5Style.alignment = .center
let label5FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label5Style]
let label5TextHeight: CGFloat = label5TextContent.boundingRect(with: CGSize(width: label5Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label5FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label5Rect)
label5TextContent.draw(in: CGRect(x: label5Rect.minX, y: label5Rect.minY + (label5Rect.height - label5TextHeight) / 2, width: label5Rect.width, height: label5TextHeight), withAttributes: label5FontAttributes)
context.restoreGState()
//// Label 6 Drawing
let label6Rect = CGRect(x: 119.89, y: 252.68, width: 43.79, height: 54)
let label6TextContent = "\n5000"
let label6Style = NSMutableParagraphStyle()
label6Style.alignment = .center
let label6FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label6Style]
let label6TextHeight: CGFloat = label6TextContent.boundingRect(with: CGSize(width: label6Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label6FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label6Rect)
label6TextContent.draw(in: CGRect(x: label6Rect.minX, y: label6Rect.minY + (label6Rect.height - label6TextHeight) / 2, width: label6Rect.width, height: label6TextHeight), withAttributes: label6FontAttributes)
context.restoreGState()
//// Label 7 Drawing
let label7Rect = CGRect(x: 109.83, y: 193.44, width: 54.43, height: 54)
let label7TextContent = "\n10000"
let label7Style = NSMutableParagraphStyle()
label7Style.alignment = .center
let label7FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label7Style]
let label7TextHeight: CGFloat = label7TextContent.boundingRect(with: CGSize(width: label7Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label7FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label7Rect)
label7TextContent.draw(in: CGRect(x: label7Rect.minX, y: label7Rect.minY + (label7Rect.height - label7TextHeight) / 2, width: label7Rect.width, height: label7TextHeight), withAttributes: label7FontAttributes)
context.restoreGState()
//// Label 8 Drawing
let label8Rect = CGRect(x: 272.57, y: 345.85, width: 89.46, height: 54)
let label8TextContent = "\nCONTROL"
let label8Style = NSMutableParagraphStyle()
label8Style.alignment = .center
let label8FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label8Style]
let label8TextHeight: CGFloat = label8TextContent.boundingRect(with: CGSize(width: label8Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label8FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label8Rect)
label8TextContent.draw(in: CGRect(x: label8Rect.minX, y: label8Rect.minY + (label8Rect.height - label8TextHeight) / 2, width: label8Rect.width, height: label8TextHeight), withAttributes: label8FontAttributes)
context.restoreGState()
//// Label 9 Drawing
let label9Rect = CGRect(x: 111.56, y: 131.83, width: 53.08, height: 54)
let label9TextContent = "\n15000"
let label9Style = NSMutableParagraphStyle()
label9Style.alignment = .center
let label9FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label9Style]
let label9TextHeight: CGFloat = label9TextContent.boundingRect(with: CGSize(width: label9Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label9FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label9Rect)
label9TextContent.draw(in: CGRect(x: label9Rect.minX, y: label9Rect.minY + (label9Rect.height - label9TextHeight) / 2, width: label9Rect.width, height: label9TextHeight), withAttributes: label9FontAttributes)
context.restoreGState()
//// Label 10 Drawing
let label10Rect = CGRect(x: 108.53, y: 67.28, width: 55.4, height: 54)
let label10TextContent = "\n20000"
let label10Style = NSMutableParagraphStyle()
label10Style.alignment = .center
let label10FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label10Style]
let label10TextHeight: CGFloat = label10TextContent.boundingRect(with: CGSize(width: label10Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label10FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label10Rect)
label10TextContent.draw(in: CGRect(x: label10Rect.minX, y: label10Rect.minY + (label10Rect.height - label10TextHeight) / 2, width: label10Rect.width, height: label10TextHeight), withAttributes: label10FontAttributes)
context.restoreGState()
//// Label 11 Drawing
let label11Rect = CGRect(x: 109.98, y: 6.5, width: 54.05, height: 54)
let label11TextContent = "\n25000"
let label11Style = NSMutableParagraphStyle()
label11Style.alignment = .center
let label11FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label11Style]
let label11TextHeight: CGFloat = label11TextContent.boundingRect(with: CGSize(width: label11Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label11FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label11Rect)
label11TextContent.draw(in: CGRect(x: label11Rect.minX, y: label11Rect.minY + (label11Rect.height - label11TextHeight) / 2, width: label11Rect.width, height: label11TextHeight), withAttributes: label11FontAttributes)
context.restoreGState()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 191.52, y: 44.18))
bezierPath.addLine(to: CGPoint(x: 191.52, y: 375.9))
strokeColor.setStroke()
bezierPath.lineWidth = 0.71
bezierPath.lineCapStyle = .round
bezierPath.lineJoinStyle = .round
bezierPath.stroke()
//// Rectangle 13 Drawing
let rectangle13Path = UIBezierPath(rect: CGRect(x: 249.27, y: (negH1G3 + 362.998), width: 135.95, height: h1G3))
fillColor2.setFill()
rectangle13Path.fill()
if (hiddenH2G3) {
//// Label 12 Drawing
let label12Rect = CGRect(x: 535.78, y: 90.72, width: 46, height: 21)
let label12TextContent = "p<0.01"
let label12Style = NSMutableParagraphStyle()
label12Style.alignment = .center
let label12FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: textForeground2, NSParagraphStyleAttributeName: label12Style]
let label12TextHeight: CGFloat = label12TextContent.boundingRect(with: CGSize(width: label12Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label12FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label12Rect)
label12TextContent.draw(in: CGRect(x: label12Rect.minX, y: label12Rect.minY + (label12Rect.height - label12TextHeight) / 2, width: label12Rect.width, height: label12TextHeight), withAttributes: label12FontAttributes)
context.restoreGState()
}
//// Rectangle 15 Drawing
let rectangle15Path = UIBezierPath(rect: CGRect(x: 490.77, y: (negH2G3 + 361.999), width: 135.95, height: h2G3))
fillColor3.setFill()
rectangle15Path.fill()
if (hiddenH1G3) {
//// Label 13 Drawing
let label13Rect = CGRect(x: 268.3, y: 107.07, width: 98.53, height: 108)
let label13TextContent = "\n104%"
let label13Style = NSMutableParagraphStyle()
label13Style.alignment = .center
let label13FontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 36), NSForegroundColorAttributeName: strokeColor, NSParagraphStyleAttributeName: label13Style]
let label13TextHeight: CGFloat = label13TextContent.boundingRect(with: CGSize(width: label13Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: label13FontAttributes, context: nil).height
context.saveGState()
context.clip(to: label13Rect)
label13TextContent.draw(in: CGRect(x: label13Rect.minX, y: label13Rect.minY + (label13Rect.height - label13TextHeight) / 2, width: label13Rect.width, height: label13TextHeight), withAttributes: label13FontAttributes)
context.restoreGState()
}
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 722.09, y: 362.2))
bezier2Path.addLine(to: CGPoint(x: 172.74, y: 362.2))
strokeColor.setStroke()
bezier2Path.lineWidth = 0.93
bezier2Path.lineCapStyle = .round
bezier2Path.lineJoinStyle = .round
bezier2Path.stroke()
if (hiddenH1G3) {
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 314.1, y: 168.51))
bezier3Path.addLine(to: CGPoint(x: 314.1, y: 128.62))
strokeColor2.setStroke()
bezier3Path.lineWidth = 4
bezier3Path.lineCapStyle = .round
bezier3Path.lineJoinStyle = .round
bezier3Path.stroke()
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 314.1, y: 242.08))
bezier4Path.addLine(to: CGPoint(x: 314.1, y: 208.06))
strokeColor2.setStroke()
bezier4Path.lineWidth = 4
bezier4Path.lineCapStyle = .round
bezier4Path.lineJoinStyle = .round
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.move(to: CGPoint(x: 324.53, y: 131.35))
bezier5Path.addLine(to: CGPoint(x: 314.25, y: 117.66))
bezier5Path.addLine(to: CGPoint(x: 304.01, y: 131.35))
strokeColor2.setStroke()
bezier5Path.lineWidth = 4
bezier5Path.lineCapStyle = .round
bezier5Path.lineJoinStyle = .round
bezier5Path.stroke()
}
//// Bezier 6 Drawing
let bezier6Path = UIBezierPath()
bezier6Path.move(to: CGPoint(x: 180.22, y: 106.54))
bezier6Path.addLine(to: CGPoint(x: 202.54, y: 106.54))
strokeColor.setStroke()
bezier6Path.lineWidth = 0.51
bezier6Path.lineCapStyle = .round
bezier6Path.lineJoinStyle = .round
bezier6Path.stroke()
//// Bezier 7 Drawing
let bezier7Path = UIBezierPath()
bezier7Path.move(to: CGPoint(x: 180.22, y: 172.14))
bezier7Path.addLine(to: CGPoint(x: 202.54, y: 172.14))
strokeColor.setStroke()
bezier7Path.lineWidth = 0.51
bezier7Path.lineCapStyle = .round
bezier7Path.lineJoinStyle = .round
bezier7Path.stroke()
//// Bezier 8 Drawing
let bezier8Path = UIBezierPath()
bezier8Path.move(to: CGPoint(x: 180.22, y: 233.68))
bezier8Path.addLine(to: CGPoint(x: 202.54, y: 233.68))
strokeColor.setStroke()
bezier8Path.lineWidth = 0.51
bezier8Path.lineCapStyle = .round
bezier8Path.lineJoinStyle = .round
bezier8Path.stroke()
//// Bezier 9 Drawing
let bezier9Path = UIBezierPath()
bezier9Path.move(to: CGPoint(x: 180.22, y: 293.88))
bezier9Path.addLine(to: CGPoint(x: 202.54, y: 293.88))
strokeColor.setStroke()
bezier9Path.lineWidth = 0.51
bezier9Path.lineCapStyle = .round
bezier9Path.lineJoinStyle = .round
bezier9Path.stroke()
context.restoreGState()
}
@objc(GraficosResizingBehavior)
public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: CGRect, target: CGRect) -> CGRect {
if rect == target || target == CGRect.zero {
return rect
}
var scales = CGSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
|
//
// ScopeView.swift
// VideoScopes
//
// Created by Serge-Olivier Amega on 3/12/16.
// Copyright © 2016 Nexiosoft. All rights reserved.
//
import UIKit
private let buttonSpace : CGFloat = 30.0
private let buttonSmallSpace : CGFloat = 5.0
typealias ParameterMap = [ParameterName : Parameter]
enum ParameterName : UInt8 {
case ColorChannelParam, ModeParam, ScaleParam
}
struct Parameter {
var list : [UInt8]
let item : UInt8
let floNum : Float
}
class ScopeView: UIView, UIPickerViewDelegate, UIPickerViewDataSource {
var visualizerView : VisualizerView?
var buttonView : ButtonView?
var processor : ScopeProcessor = ScopeProcessor()
var parameters : ParameterMap = [:]
var scopeMode : ScopeMode {
get {
return processor.mode
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
func changeMode(newMode : ScopeMode) {
//change processor
processor = ScopeProcessor.getScopeProcessor(newMode)
//update buttonView
buttonView?.changeToMode(newMode)
print("didChangeToMode:\(newMode.name())")
}
func initialize() {
//VIEW INITIALIZATIONS ==========================================
visualizerView = VisualizerView(frame: CGRect(x: buttonSpace,
y: buttonSpace,
width: frame.width - 2 * buttonSpace,
height: frame.height - 2 * buttonSpace))
buttonView = ButtonView(frame: CGRect(x: 0, y: frame.height - buttonSpace, width: frame.width, height: buttonSpace),
mode: ScopeMode.Abstract, chooseModeCallback: toggleModeChooser, toggleChannelCallback: toggleChannel)
addSubview(visualizerView!)
addSubview(buttonView!)
visualizerView?.translatesAutoresizingMaskIntoConstraints = false
buttonView?.translatesAutoresizingMaskIntoConstraints = false
//VISUALIZER VIEW ================================================
visualizerView?.backgroundColor = UIColor.blackColor()
visualizerView?.topAnchor.constraintEqualToAnchor(topAnchor).active = true
visualizerView?.bottomAnchor.constraintEqualToAnchor(buttonView?.topAnchor).active = true
visualizerView?.leftAnchor.constraintEqualToAnchor(leftAnchor).active = true
visualizerView?.rightAnchor.constraintEqualToAnchor(rightAnchor).active = true
//BUTTON VIEW ====================================================
buttonView?.rightAnchor.constraintEqualToAnchor(rightAnchor).active = true
buttonView?.leftAnchor.constraintEqualToAnchor(leftAnchor).active = true
buttonView?.topAnchor.constraintEqualToAnchor(visualizerView?.bottomAnchor).active = true
buttonView?.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
buttonView?.heightAnchor.constraintEqualToConstant(buttonSpace).active = true
changeMode(.Histogram)
}
func updateImage(image : UIImage) {
let scopeImg = processor.getScopeImage(image, params: parameters)
let params : ParameterMap = [:]
visualizerView?.display(scopeImg, params: params)
}
// DISPLAY MODE PICKER ========================================
let arrayOfModes = ScopeMode.listOfNames()
lazy var pickerView : UIPickerView = {
let visViewFrame = self.visualizerView!.frame
let pickerViewHeight = min(200,visViewFrame.height)
var ret = UIPickerView(frame: CGRect(x: visViewFrame.origin.x,
y: visViewFrame.origin.y + visViewFrame.height/2 - pickerViewHeight/2,
width: visViewFrame.width,
height: pickerViewHeight))
ret.dataSource = self
ret.delegate = self
ret.showsSelectionIndicator = true
ret.backgroundColor = UIColor(white: 0.5, alpha: 0.3)
return ret
}()
var isDisplayingPicker : Bool = false
//TODO make thread safe
func toggleChannel(channel : ColorChannel) {
print("toggle channel \(channel)")
if var param = parameters[.ColorChannelParam] {
var found = false
for var i = 0; i < param.list.count; i++ {
if param.list[i] == channel.rawValue {
param.list.removeAtIndex(i)
found = true
break
}
}
if !found {
param.list.append(channel.rawValue)
}
parameters[.ColorChannelParam] = param
} else {
parameters[.ColorChannelParam] = Parameter(list: [channel.rawValue], item: 0, floNum: 0)
}
}
func toggleModeChooser() {
if isDisplayingPicker {
hideModeChooser()
isDisplayingPicker = false
} else {
showModeChooser()
isDisplayingPicker = true
}
}
func hideModeChooser() {
pickerView.removeFromSuperview()
let selectedRow = pickerView.selectedRowInComponent(0)
let rowName = arrayOfModes[selectedRow]
let newMode = ScopeMode.modeForName(rowName)
changeMode(newMode)
}
func showModeChooser() {
addSubview(pickerView)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return arrayOfModes.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let plainTitle = arrayOfModes[row]
let result = NSAttributedString(string: plainTitle, attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()])
return result
}
/*
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
enum ButtonTag : Int {
case ChooseTag, LumaTag, RedTag, GreenTag, BlueTag
}
class ButtonView: UIView {
let buttonColor = UIColor(red: 0.75, green: 1.0, blue: 0.5, alpha: 1.0)
let borderColor = UIColor.whiteColor()
let ctrlState = UIControlState.Normal
let chooseScopeMode : ((Void) -> Void)
let toggleChannel : ((ColorChannel)->Void)
var selectionButton : UIButton = UIButton()
var paramButtons : [UIButton] = []
init(frame: CGRect, mode: ScopeMode, chooseModeCallback : ()->Void, toggleChannelCallback : ((ColorChannel)->Void)) {
chooseScopeMode = chooseModeCallback
toggleChannel = toggleChannelCallback
super.init(frame: frame)
self.backgroundColor = UIColor.blackColor()
self.layer.borderColor = borderColor.CGColor
self.layer.borderWidth = 1.0
//chooser button
selectionButton = UIButton(type: UIButtonType.InfoLight)
selectionButton.tintColor = buttonColor
selectionButton.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
selectionButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(selectionButton)
selectionButton.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: buttonSmallSpace).active = true
selectionButton.topAnchor.constraintEqualToAnchor(topAnchor).active = true
selectionButton.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
selectionButton.widthAnchor.constraintEqualToConstant(buttonSpace)
selectionButton.tag = ButtonTag.ChooseTag.rawValue
changeToMode(mode)
}
func buttonPressed(sender : UIButton) {
switch sender.tag {
case ButtonTag.ChooseTag.rawValue :
chooseScopeMode()
case ButtonTag.RedTag.rawValue :
toggleChannel(ColorChannel.Red)
case ButtonTag.BlueTag.rawValue :
toggleChannel(ColorChannel.Blue)
case ButtonTag.GreenTag.rawValue :
toggleChannel(ColorChannel.Green)
case ButtonTag.LumaTag.rawValue :
toggleChannel(ColorChannel.Luma)
case _ :
true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func changeToMode(mode : ScopeMode) {
for button in paramButtons {
button.removeFromSuperview()
}
paramButtons.removeAll()
switch mode {
case ScopeMode.Histogram :
setupHistogramWaveformButtons()
case ScopeMode.Waveform :
setupHistogramWaveformButtons()
case _ :
true
}
}
//PRECONDITION : there are no param buttons in the view
func setupHistogramWaveformButtons() {
print("setup")
//order [L R G B]
for i in 0..<4 {
let button = UIButton(type: UIButtonType.System)
button.translatesAutoresizingMaskIntoConstraints = false
let buttonStrs = ["B","G","R","L"]
button.setTitle(buttonStrs[i], forState: UIControlState.Normal)
switch i {
case 0:
button.tag = ButtonTag.BlueTag.rawValue
case 1:
button.tag = ButtonTag.GreenTag.rawValue
case 2:
button.tag = ButtonTag.RedTag.rawValue
case 3:
button.tag = ButtonTag.LumaTag.rawValue
case _ :
button.tag = 0xff
}
button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
button.tintColor = buttonColor
addSubview(button)
button.rightAnchor.constraintEqualToAnchor(rightAnchor,
constant: buttonSmallSpace - buttonSmallSpace - CGFloat(i) * (buttonSpace + buttonSmallSpace)).active = true
button.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
button.topAnchor.constraintEqualToAnchor(topAnchor).active = true
button.widthAnchor.constraintEqualToConstant(buttonSpace).active = true
paramButtons.append(button)
}
}
}
|
//
// APIUTILS.swift
// App_SocialFrameworks_fb_tw
//
// Created by cice on 27/3/17.
// Copyright © 2017 cice. All rights reserved.
//
import Foundation
import UIKit
func muestraAlerVC(_ titleData: String, messageData : String, titleAction: String) -> UIAlertController{
let alert = UIAlertController(title: titleData, message: messageData, preferredStyle : .alert)
alert.addAction(UIAlertAction(title: titleAction, style: .default, handler: nil))
return alert
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.