text stringlengths 8 1.32M |
|---|
//
// JCMainTabbarController.swift
// TabbarFrameDemo
//
// Created by jiechen on 15/11/10.
// Copyright © 2015年 jiechen. All rights reserved.
//
import UIKit
class JCMainTabbarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// self.configSystemTabbar()
self.configCustomTabbar()
}
func configSystemTabbar() {
let firstController = FirstViewController()
let secondController = SecondViewController()
let thirdController = ThirdViewController()
firstController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.MostRecent, tag: 0)
firstController.view.backgroundColor = UIColor.redColor()
secondController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Contacts, tag: 1)
secondController.view.backgroundColor = UIColor.lightGrayColor()
thirdController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Bookmarks, tag: 2)
thirdController.view.backgroundColor = UIColor.blueColor()
self.viewControllers = [firstController, secondController, thirdController];
}
func configCustomTabbar() {
let controllers = [FirstViewController(), SecondViewController(), ThirdViewController()]
let tabTitles = ["首页", "发现", "我的"]
let tabImages = [UIImage(named: "tabbar_myCenter_nor"), UIImage(named: "tabbar_find_nor"), UIImage(named: "tabbar_myCenter_nor")]
var navControllers: [UINavigationController] = []
for idx in 0..<controllers.count {
let navController = UINavigationController(rootViewController: controllers[idx])
navController.tabBarItem.title = tabTitles[idx]
navController.tabBarItem.image = tabImages[idx]
navControllers.append(navController)
}
self.viewControllers = navControllers
}
}
|
//
// PictureTableViewCell.swift
// Pictures
//
// Created by Vladimir GL on 03.04.2020.
// Copyright © 2020 VDTA. All rights reserved.
//
import UIKit
final class PictureTableViewCell: UITableViewCell {
@IBOutlet private var nameLabel: UILabel!
@IBOutlet private var avatarImageView: UIImageView!
private var avatarLoadTask: URLSessionTask?
override func prepareForReuse() {
super.prepareForReuse()
avatarImageView.image = nil
avatarLoadTask?.cancel()
}
func setup(with picture: Image) {
nameLabel.text = picture.user
guard let imageUrl = picture.url else { return }
avatarLoadTask = URLSession.shared.dataTask(with: imageUrl) { data, _, _ in
guard let data = data, let image = UIImage(data: data) else { return }
DispatchQueue.main.async {
self.avatarImageView.image = image
}
}
avatarLoadTask?.resume()
}
}
|
// DO NOT EDIT. This file is machine-generated and constantly overwritten.
// Make changes to TMImage.swift instead.
import Foundation
import CoreData
public enum TMImageAttributes: String {
case imageID = "imageID"
case itemID = "itemID"
case src = "src"
}
public enum TMImageRelationships: String {
case productv = "productv"
case recommendation = "recommendation"
}
open class _TMImage: TMModel {
// MARK: - Class methods
override open class func entityName () -> String {
return "TMImage"
}
override open class func entity(_ managedObjectContext: NSManagedObjectContext) -> NSEntityDescription? {
return NSEntityDescription.entity(forEntityName: self.entityName(), in: managedObjectContext)
}
// MARK: - Life cycle methods
public override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
}
public convenience init?(managedObjectContext: NSManagedObjectContext) {
guard let entity = _TMImage.entity(managedObjectContext) else { return nil }
self.init(entity: entity, insertInto: managedObjectContext)
}
// MARK: - Properties
@NSManaged open
var imageID: String?
@NSManaged open
var itemID: String?
@NSManaged open
var src: String?
// MARK: - Relationships
@NSManaged open
var productv: TMProduct?
@NSManaged open
var recommendation: TMRecommendation?
}
|
//
// PaymentMethodCell.swift
// Cuppedinis
//
// Created by Jesus Nieves on 7/7/18.
// Copyright © 2018 Jesus Nieves. All rights reserved.
//
import UIKit
import Kingfisher
class PaymentMethodCell: UICollectionViewCell {
@IBOutlet weak var methodView: UIView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var imgLogo: UIImageView!
@IBOutlet weak var lblType: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
var issuer: Issuer? {
didSet {
if let issuer = issuer {
self.lblType.isHidden = true
self.lblTitle.text = issuer.name
if issuer.secureThumbnail != "" {
self.imgLogo.kf.setImage(with: URL(string:issuer.secureThumbnail!))
}
}
}
}
}
|
//
// BaseViewController.swift
// PersonsExam
//
// Created by Glenn Von C. Posadas on 23/09/2018.
// Copyright © 2018 Glenn Von C. Posadas. All rights reserved.
//
import EFInternetIndicator
import UIKit
class BaseViewController: UIViewController {
// MARK: - Properties
public typealias PersonsExamAlertCallBack = (_ userDidTapOk: Bool) -> Void
public var internetConnectionIndicator: InternetViewIndicator?
internal lazy var tableView: BaseTableView = {
let tableView = BaseTableView(frame: .zero, style: .plain)
return tableView
}()
internal lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.backgroundColor = .clear
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.keyboardDismissMode = .interactive
return scrollView
}()
// MARK: - Functions
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
// Add some more common configurations here...
self.view.backgroundColor = .white
self.navigationController?.navigationBar.prefersLargeTitles = true
// For reachability
// Change the remoteHostName if necessary...
// Suppose the mock api is on a real server...
self.startMonitoringInternet(
backgroundColor: .blueTheme,
style: .statusLine,
textColor: .white,
message: "Oops! Please check your internet connection! 🤦♂️",
remoteHostName: "google.com"
)
}
}
// MARK: - InternetStatusIndicable
extension BaseViewController: InternetStatusIndicable {
}
|
//
// ResiRentNext_VC.swift
// 13hectareFinal
//
// Created by Deeva Infotech LLP on 07/03/18.
// Copyright © 2018 Deeva Infotech LLP. All rights reserved.
//
import UIKit
class ResiRentNext_VC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btn_Back(_ sender: Any) {
let storybord = UIStoryboard(name: "Main", bundle: nil)
let destination = storybord.instantiateViewController(withIdentifier: "PostResiViewController") as! PostResiViewController
self.present(destination, animated: true, completion: nil)
}
}
extension ResiRentNext_VC: UITableViewDataSource, UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
return 7
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (indexPath.section) {
case 0:
let ResiNSCell1 = tableView.dequeueReusableCell(withIdentifier: "ResiNextRent_TableViewCell1", for: indexPath) as! ResiNextRent_TableViewCell
return ResiNSCell1
case 1:
let ResiNSCell2 = tableView.dequeueReusableCell(withIdentifier: "ResiNextRent_TableViewCell2", for: indexPath) as! ResiNextRent_TableViewCell
return ResiNSCell2
case 2:
let ResiNSCell3 = tableView.dequeueReusableCell(withIdentifier: "ResiNextRent_TableViewCell3", for: indexPath) as! ResiNextRent_TableViewCell
return ResiNSCell3
case 3:
let ResiNSCell4 = tableView.dequeueReusableCell(withIdentifier: "ResiNextRent_TableViewCell4", for: indexPath) as! ResiNextRent_TableViewCell
return ResiNSCell4
case 4:
let ResiNSCell5 = tableView.dequeueReusableCell(withIdentifier: "ResiNextRent_TableViewCell5", for: indexPath) as! ResiNextRent_TableViewCell
return ResiNSCell5
case 5:
let ResiNSCell6 = tableView.dequeueReusableCell(withIdentifier: "ResiNextRent_TableViewCell6", for: indexPath) as! ResiNextRent_TableViewCell
return ResiNSCell6
case 6:
let ResiNSCell7 = tableView.dequeueReusableCell(withIdentifier: "ResiNextRent_TableViewCell7", for: indexPath) as! ResiNextRent_TableViewCell
return ResiNSCell7
default:
break
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0: return 220
case 1: return 441
case 2: return 110
case 3: return 110
case 4: return 105
case 5: return 84
case 6: return 61
default:
return 0
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0: return "Property Price"
case 1: return "Property Details"
case 2: return "Property Area"
case 3: return "Property Floors"
case 4: return "Availbility"
case 5: return "Other Details"
case 6: return "Subscription"
default:
return ""
}
}
}
|
import Bow
import BowGenerators
import SwiftCheck
public final class SemigroupalLaws<F: Semigroupal & ArbitraryK & EquatableK> {
public static func check(isEqual: @escaping (Kind<F, ((Int, Int), Int)>, Kind<F, (Int, (Int, Int))>) -> Bool) {
associativity(isEqual: isEqual)
}
private static func associativity(isEqual: @escaping (Kind<F, ((Int, Int), Int)>, Kind<F, (Int, (Int, Int))>) -> Bool) {
property("Associativity") <~ forAll { (fa: KindOf<F, Int>, fb: KindOf<F, Int>, fc: KindOf<F, Int>) in
isEqual(
fa.value.product(fb.value).product(fc.value),
fa.value.product(fb.value.product(fc.value)))
}
}
}
|
//
// PersonViewerViewController+SetupUI.swift
// PersonsExam
//
// Created by Glenn Von C. Posadas on 23/09/2018.
// Copyright © 2018 Glenn Von C. Posadas. All rights reserved.
//
import SnapKit
import UIKit
extension PersonViewerViewController {
internal func setupUI() {
// Layout goes here...
self.addScrollView()
self.scrollView.addSubview(self.imageView_PersonPicture)
self.imageView_PersonPicture.snp.makeConstraints {
$0.width.height.equalTo(150.0)
$0.top.equalToSuperview().inset(50.0)
$0.centerX.equalToSuperview()
}
self.scrollView.addSubview(self.label_FirstName)
self.label_FirstName.snp.makeConstraints {
$0.top.equalTo(self.imageView_PersonPicture.snp.bottom).offset(20.0)
$0.leading.trailing.equalToSuperview().inset(10.0)
}
self.scrollView.addSubview(self.label_LastName)
self.label_LastName.snp.makeConstraints {
$0.top.equalTo(self.label_FirstName.snp.bottom).offset(10.0)
$0.leading.trailing.equalToSuperview().inset(10.0)
}
self.scrollView.addSubview(self.label_Mobile)
self.label_Mobile.snp.makeConstraints {
$0.top.equalTo(self.label_LastName.snp.bottom).offset(10.0)
$0.leading.trailing.equalToSuperview().inset(10.0)
}
self.scrollView.addSubview(self.label_Email)
self.label_Email.snp.makeConstraints {
$0.top.equalTo(self.label_Mobile.snp.bottom).offset(10.0)
$0.leading.trailing.equalToSuperview().inset(10.0)
}
self.scrollView.addSubview(self.label_Address)
self.label_Address.snp.makeConstraints {
$0.top.equalTo(self.label_Email.snp.bottom).offset(10.0)
$0.leading.trailing.equalToSuperview().inset(10.0)
}
self.scrollView.addSubview(self.label_ContactPerson)
self.label_ContactPerson.snp.makeConstraints {
$0.top.equalTo(self.label_Address.snp.bottom).offset(10.0)
$0.leading.trailing.equalToSuperview().inset(10.0)
}
self.scrollView.addSubview(self.label_ContactPersonNumber)
self.label_ContactPersonNumber.snp.makeConstraints {
$0.top.equalTo(self.label_ContactPerson.snp.bottom).offset(10.0)
$0.leading.equalTo(self.label_ContactPerson).offset(10.0)
$0.trailing.equalToSuperview().inset(10.0)
$0.bottom.equalToSuperview().inset(30.0)
}
}
}
|
import Foundation
class Deck : NSObject {
static let allSpades = Value.allValues.map { (number) -> Card in
var output = Card(color: Color.Spade, value:number)
return output
}
static let allDiamonds = Value.allValues.map { (number) -> Card in
var output = Card(color: Color.Diamond, value:number)
return output
}
static let allHearts = Value.allValues.map { (number) -> Card in
var output = Card(color: Color.Heart, value:number)
return output
}
static let allClubs = Value.allValues.map { (number) -> Card in
var output = Card(color: Color.Club, value:number)
return output
}
static let allCards = allSpades + allDiamonds + allHearts + allClubs
}
|
//
// FilterTableViewController.swift
// mapkittut
//
// Created by Chris Mitchell on 4/9/17.
// Copyright © 2017 Chris Mitchell. All rights reserved.
//
import UIKit
class FilterTableViewController: UITableViewController , PickerFieldsDataHelperDelegate {
@IBOutlet weak var catagoryTextField: UITextField!
@IBOutlet weak var rankingTextField: UITextField!
let pickerFieldsDataHelper = PickerFieldsDataHelper()
override func viewDidLoad() {
super.viewDidLoad()
pickerFieldsDataHelper.delegate = self
pickerFieldsDataHelper.doneButtonTitle = "Choose"
pickerFieldsDataHelper.defaultFirstItemTitle = "Select an option"
pickerFieldsDataHelper.needsConfirmationButton = false
pickerFieldsDataHelper.useDefaultFirstItem = true
pickerFieldsDataHelper.initWithDefaultFirstItemSelected = false
pickerFieldsDataHelper.delegate = self
pickerFieldsDataHelper.addDataHelpers([catagoryTextField, rankingTextField], isDateType: false)
loadAccountTypeOptions()
}
func loadAccountTypeOptions() {
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(catagoryTextField, title: "Buildings & land rights(e.g.offices)" , object: 0)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(catagoryTextField, title: "Fixed equipment & software(e.g.computers)" , object: 1)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(catagoryTextField, title: "Light factory equipment(e.g. lift trucks)" , object: 2)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(catagoryTextField, title: "Office equipment(e.g. desks)" , object: 3)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(catagoryTextField, title: "Maintenance & repair items(e.g. paint)" , object: 4)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(catagoryTextField, title: "Maintenance & repair services(e.g. computer repair)" , object: 5)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(catagoryTextField, title: "Business advisory services(e.g. legal, consulting)" , object: 6)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(rankingTextField, title: "thumbs up", object: 0)
pickerFieldsDataHelper.addTitleAndObjectInDataHelper(rankingTextField, title: "thumbs down", object: 1)
}
func pickerFieldsDataHelper(_ dataHelper: PickerDataHelper, didSelectObject selectedObject: Any?, withTitle title: String?) {
if let title = title, let object = selectedObject {
// print("Selected 1'\(title)' with object: \(object)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "SegueMapFilter") {
let DestViewController = segue.destination as! UINavigationController
let svc = DestViewController.topViewController as! MapFilterResViewController
svc.cat = self.catagoryTextField.text!
svc.rank = self.rankingTextField.text!
}
}
}
|
//
// ResultBloodPressureController.swift
// HISmartPhone
//
// Created by DINH TRIEU on 12/23/17.
// Copyright © 2017 MACOS. All rights reserved.
//
import UIKit
class ResultBloodPressureController: BaseInfoPatientVC {
//MARK: Variable
fileprivate let cellId = "cellId"
fileprivate var isShowDelete = false
fileprivate var selectedIndexPaths = [IndexPath]()
fileprivate var listBPOResult = [BPOResult]()
fileprivate lazy var alertDeleteVC: AlertDeleteController = {
let alert = AlertDeleteController()
alert.delegate = self
return alert
}()
//MARK: UIControl
fileprivate lazy var optionMenu: OptionMenu = {
var menu = OptionMenu()
if Authentication.share.typeUser == .patient {
menu = OptionMenu(images: [#imageLiteral(resourceName: "history")], title: ["Phân tích thống kê"])
} else {
menu = OptionMenu(images: [#imageLiteral(resourceName: "history"), #imageLiteral(resourceName: "clear_blue")], title: ["Phân tích thống kê", "Xoá kết quả huyết áp"])
}
menu.delegate = self
menu.backgroundColor = Theme.shared.defaultBGColor
menu.layer.cornerRadius = Dimension.shared.normalCornerRadius
menu.makeShadow(color: Theme.shared.backgroundColorShadow, opacity: 1.0, radius: 4)
return menu
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.text = "Kết quả huyết áp"
label.textColor = Theme.shared.primaryColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.titleFontSize)
return label
}()
private let dateLabel: UILabel = {
let label = UILabel()
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.captionFontSize)
return label
}()
private let optionButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "option"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
return button
}()
public let cancelButton: UIButton = {
let button = UIButton()
button.isHidden = true
button.setTitle("HUỶ", for: .normal)
button.setTitleColor(Theme.shared.darkBlueTextColor, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize, weight: UIFont.Weight.medium)
return button
}()
public let trashFloatButton: UIButton = {
let button = UIButton()
button.isHidden = true
button.setImage(UIImage(named: "trash_bin"), for: .normal)
button.imageView?.contentMode = .scaleAspectFill
return button
}()
fileprivate lazy var collectionViewBloodPressure: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = Theme.shared.darkBGColor
collectionView.register(BloodResultPressureCell.self, forCellWithReuseIdentifier: self.cellId)
return collectionView
}()
private let emptyAnnoucementLabel: UILabel = {
let label = UILabel()
label.text = "Không có kết quả nào"
label.textColor = Theme.shared.darkBlueTextColor
label.textAlignment = .center
label.isHidden = true
label.font = UIFont.systemFont(ofSize: Dimension.shared.titleFontSize)
return label
}()
//MARK: Initialize
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.collectionViewBloodPressure.collectionViewLayout.invalidateLayout()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.fetchData()
}
override func setupView() {
self.setupViewTitleLabel()
self.setupViewDateLabel()
self.setupViewOptionButton()
self.setupViewCancelButton()
self.setupViewResultBloodPressureTBV()
self.setupViewOptionMenu()
self.setupViewTrashFloatButton()
self.setupViewEmptyAnnoucementLabel()
}
//MARK: Action UIControl
@objc func handleOptionButton() {
self.optionMenu.showOrHide()
}
@objc func handleCancelButton() {
self.isShowDelete = false
self.selectedIndexPaths.removeAll()
self.collectionViewBloodPressure.reloadData()
self.cancelButton.isHidden = true
self.trashFloatButton.isHidden = true
}
@objc func handleTrashFloatButton() {
self.present(self.alertDeleteVC, animated: true, completion: nil)
}
@objc func handleRotateDevice() {
self.setupViewOptionMenu()
}
//MARK: Feature method
@objc private func fetchData() {
ResultBloodPressureFacade.fetchAllBloodPressures {
self.listBPOResult = BPOChartManager.shared.BPOResults
self.collectionViewBloodPressure.reloadData()
if self.listBPOResult.count == 0 {
self.emptyAnnoucementLabel.isHidden = false
} else {
self.emptyAnnoucementLabel.isHidden = true
}
}
}
fileprivate func addSelectedIndexPath(indexPath: IndexPath) {
if !self.selectedIndexPaths.contains(indexPath) {
self.selectedIndexPaths.append(indexPath)
} else {
if let index = self.selectedIndexPaths.index(where: { (i) -> Bool in
return i.elementsEqual(indexPath)
}) {
self.selectedIndexPaths.remove(at: index)
}
}
if self.selectedIndexPaths.count > 0 {
self.trashFloatButton.isHidden = false
} else {
self.trashFloatButton.isHidden = true
}
self.collectionViewBloodPressure.reloadData()
}
fileprivate func selectedDelete() {
ResultBloodPressureFacade.deleteBPOResult(at: self.selectedIndexPaths) {
self.fetchData()
NotificationCenter.default.post(name: NSNotification.Name.init(Notification.Name.updateBPOResults), object: nil)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
self.collectionViewBloodPressure.collectionViewLayout.invalidateLayout()
}
//MARK: SetupView
private func setupViewTitleLabel() {
self.view.addSubview(self.titleLabel)
if #available(iOS 11, *) {
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(Dimension.shared.normalHorizontalMargin)
make.top.equalTo(self.view.safeAreaInsets)
.offset(Dimension.shared.normalVerticalMargin)
}
} else {
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(Dimension.shared.normalHorizontalMargin)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
.offset(Dimension.shared.normalVerticalMargin)
}
}
}
private func setupViewDateLabel() {
self.view.addSubview(self.dateLabel)
self.dateLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.titleLabel)
make.top.equalTo(self.titleLabel.snp.bottom).offset(Dimension.shared.smallVerticalMargin)
}
}
private func setupViewOptionButton() {
self.view.addSubview(self.optionButton)
self.optionButton.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(-Dimension.shared.mediumHorizontalMargin)
make.top.equalTo(self.titleLabel).offset(Dimension.shared.smallVerticalMargin)
make.width.equalTo(Dimension.shared.widthOptionButton)
make.height.equalTo(Dimension.shared.heightOptionButton)
}
self.optionButton.addTarget(self, action: #selector(handleOptionButton), for: .touchUpInside)
}
private func setupViewCancelButton() {
self.view.addSubview(self.cancelButton)
if #available(iOS 11, *) {
self.cancelButton.snp.makeConstraints { (make) in
make.width.equalTo(45 * Dimension.shared.widthScale)
make.height.equalTo(20 * Dimension.shared.heightScale)
make.right.equalTo(self.view.safeAreaLayoutGuide)
.offset(-Dimension.shared.normalHorizontalMargin)
make.top.equalTo(self.optionButton.snp.bottom)
.offset(Dimension.shared.smallVerticalMargin / 2)
}
} else {
self.cancelButton.snp.makeConstraints { (make) in
make.width.equalTo(45 * Dimension.shared.widthScale)
make.height.equalTo(20 * Dimension.shared.heightScale)
make.right.equalToSuperview().offset(-Dimension.shared.normalHorizontalMargin)
make.top.equalTo(self.optionButton.snp.bottom)
.offset(Dimension.shared.smallVerticalMargin / 2)
}
}
self.cancelButton.addTarget(self, action: #selector(handleCancelButton), for: .touchUpInside)
}
private func setupViewResultBloodPressureTBV() {
self.view.addSubview(self.collectionViewBloodPressure)
if #available(iOS 11, *) {
self.collectionViewBloodPressure.snp.makeConstraints { (make) in
make.centerX.width.equalToSuperview()
make.bottom.equalTo(self.view.safeAreaInsets)
make.top.equalTo(self.cancelButton.snp.bottom).offset(Dimension.shared.smallVerticalMargin / 2)
}
} else {
self.collectionViewBloodPressure.snp.makeConstraints { (make) in
make.centerX.width.equalToSuperview()
make.bottom.equalTo(self.bottomLayoutGuide.snp.top)
make.top.equalTo(self.cancelButton.snp.bottom).offset(Dimension.shared.smallVerticalMargin / 2)
}
}
}
private func setupViewOptionMenu() {
self.view.addSubview(self.optionMenu)
if #available(iOS 11, *) {
self.optionMenu.snp.makeConstraints { (make) in
make.right.equalTo(self.view.safeAreaLayoutGuide)
make.top.equalTo(self.dateLabel.snp.bottom).offset(Dimension.shared.normalVerticalMargin)
make.width.equalTo(Dimension.shared.widthOptionMenu)
make.height.equalTo(0)
}
} else {
self.optionMenu.snp.makeConstraints { (make) in
make.right.equalToSuperview()
make.top.equalTo(self.dateLabel.snp.bottom).offset(Dimension.shared.normalVerticalMargin)
make.width.equalTo(Dimension.shared.widthOptionMenu)
make.height.equalTo(0)
}
}
}
private func setupViewTrashFloatButton() {
self.view.addSubview(self.trashFloatButton)
if #available(iOS 11, *) {
self.trashFloatButton.snp.makeConstraints { (make) in
make.width.height.equalTo(Dimension.shared.widthFloatButton)
make.right.equalToSuperview().offset(-23 * Dimension.shared.widthScale)
make.bottom.equalTo(self.view.safeAreaInsets)
.offset(-Dimension.shared.largeVerticalMargin)
}
} else {
self.trashFloatButton.snp.makeConstraints { (make) in
make.width.height.equalTo(Dimension.shared.widthFloatButton)
make.right.equalToSuperview().offset(-23 * Dimension.shared.widthScale)
make.bottom.equalTo(self.bottomLayoutGuide.snp.top)
.offset(-Dimension.shared.largeVerticalMargin)
}
}
self.trashFloatButton.addTarget(self, action: #selector(handleTrashFloatButton), for: .touchUpInside)
}
private func setupViewEmptyAnnoucementLabel() {
self.view.addSubview(self.emptyAnnoucementLabel)
self.emptyAnnoucementLabel.snp.makeConstraints { (make) in
make.centerX.centerY.equalToSuperview()
}
}
}
//MARK: - UITableViewDelegate, UITableViewDataSource
extension ResultBloodPressureController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.listBPOResult.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as? BloodResultPressureCell else { return UICollectionViewCell() }
cell.set(indexPath: indexPath)
cell.delegate = self
cell.BPOResult = self.listBPOResult[indexPath.item]
if self.isShowDelete {
if self.selectedIndexPaths.contains(indexPath) {
cell.showImage(status: .on)
} else {
cell.showImage(status: .off)
}
} else {
cell.showImage(status: .hide)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 77 * Dimension.shared.heightScale)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if self.isShowDelete {
self.addSelectedIndexPath(indexPath: indexPath)
}
}
}
//MARK: - OptionMenuDelegate
extension ResultBloodPressureController: OptionMenuDelegate {
func didSelectItem(_ optionMenu: OptionMenu, at indexPath: IndexPath) {
if indexPath.item == 0 {
let staticsAnalysisController = StatisticalAnalysisController()
staticsAnalysisController.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(staticsAnalysisController, animated: true)
} else if indexPath.item == 1 {
self.isShowDelete = true
self.cancelButton.isHidden = false
self.collectionViewBloodPressure.reloadData()
}
self.optionMenu.hide()
}
}
//MARK: - BloodResultPressureCellDelegate
extension ResultBloodPressureController: BloodResultPressureCellDelegate {
func selectedCheckbox(at indexPath: IndexPath) {
self.addSelectedIndexPath(indexPath: indexPath)
}
}
//MARK: - AlertDeleteControllerDelegate
extension ResultBloodPressureController: AlertDeleteControllerDelegate {
func didSelectDelete() {
self.selectedDelete()
self.resetUIWhenDelete()
}
func didSelectCancel() {
self.resetUIWhenDelete()
}
fileprivate func resetUIWhenDelete() {
self.isShowDelete = false
self.selectedIndexPaths.removeAll()
self.collectionViewBloodPressure.reloadData()
self.cancelButton.isHidden = true
self.trashFloatButton.isHidden = true
}
}
|
//
// ViewController.swift
// vezbanje
//
// Created by Apple on 9/24/20.
// Copyright © 2020 milic. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet var collectionview:UICollectionView!
let loader = FlowerJSON()
var imageDonwloaderInProggress = [IndexPath:FlowerImageDownloader]()
var imageDownloaderLock = NSLock()
override func viewDidLoad() {
super.viewDidLoad()
loader.startLoading { (success) in
if success {
self.collectionview.reloadData()
}else{
print("Neuspesno ucitavanje")
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return loader.flowers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "flowerCell", for: indexPath) as! FlowerCollectionViewCell
let flower = loader.flowers[indexPath.row]
if flower.image == nil {
startImageDownload(flower: flower, indexpath: indexPath, cell: cell)
}else{
cell.flowerImage.image = flower.image
}
return cell
}
func startImageDownload (flower:Flower,indexpath:IndexPath,cell:FlowerCollectionViewCell){
if imageDonwloaderInProggress[indexpath] != nil {
return
}
let imageDownloader = FlowerImageDownloader()
imageDownloader.flower = flower
imageDownloader.completionHandelr = {
// let cell = self.collectionview.cellForItem(at: indexpath) as! FlowerCollectionViewCell
self.imageDownloaderLock.lock()
cell.flowerImage.image = flower.image
self.imageDownloaderLock.unlock()
self.imageDonwloaderInProggress[indexpath] = nil
}
imageDonwloaderInProggress[indexpath] = imageDownloader
imageDownloader.startDownload()
}
}
|
//
// WeeklyQuantitySampleTableViewController.swift
// Walker
//
// Created by 黎铭轩 on 11/12/2020.
//
import UIKit
import HealthKit
class WeeklyQuantitySampleTableViewController: HealthDataTableViewController, HealthQueryDataSource {
let calendar: Calendar = .current
let healthStore=HealthData.healthStore
var quantityTypeIdentifier: HKQuantityTypeIdentifier {
return HKQuantityTypeIdentifier(rawValue: dataTypeIdentifier)
}
var quantityType: HKQuantityType {
return HKQuantityType.quantityType(forIdentifier: quantityTypeIdentifier)!
}
var query: HKStatisticsCollectionQuery?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if query != nil {
return
}
//请求授权
let dataTypeValues: Set=Set([quantityType])
print("请求HealthKit授权")
self.healthStore.requestAuthorization(toShare: dataTypeValues, read: dataTypeValues) { (success, error) in
if success{
self.calculateDailyQuantitySamplesForPastWeek()
}
}
}
func calculateDailyQuantitySamplesForPastWeek() {
performQuery {
DispatchQueue.main.async {[weak self] in
self?.reloadData()
}
}
}
//MARK: - 健康查询数据源
func performQuery(completion: @escaping() -> Void) {
let predicate=createLastWeekPredicate()
let anchorDate=createAnchorDate()
let dailyIntervald=DateComponents(day: 1)
let statisticsOptions=getStatisticsOptions(for: dataTypeIdentifier)
let query=HKStatisticsCollectionQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: statisticsOptions, anchorDate: anchorDate, intervalComponents: dailyIntervald)
//用于HKStatisticsCollection对象处理者block
let updateInterfaceWithStatistics: (HKStatisticsCollection) -> Void = {statistics in
self.dataValues=[]
let now=Date()
let startDate=getLastWeekStartDate()
let endDate=now
statistics.enumerateStatistics(from: startDate, to: endDate) {[weak self] (statistics, stop) in
var dataValue=HealthDataTypeValue(startDate: statistics.startDate, endDate: statistics.endDate, value: 0)
if let quantity=getStatisticsQuantity(for: statistics, with: statisticsOptions),
let identifier=self?.dataTypeIdentifier,
let unit=preferredUnit(for: identifier){
dataValue.value=quantity.doubleValue(for: unit)
}
self?.dataValues.append(dataValue)
}
completion()
}
query.initialResultsHandler={query, statisticsCollection, error in
if let statisticsCollection = statisticsCollection {
updateInterfaceWithStatistics(statisticsCollection)
}
}
query.statisticsUpdateHandler={[weak self] query, statistics, statisticsCollection, error in
//如果可视数据类型更新确保我们仅更新界面
if let statisticsCollection = statisticsCollection, query.objectType?.identifier == self?.dataTypeIdentifier {
updateInterfaceWithStatistics(statisticsCollection)
}
}
self.healthStore.execute(query)
self.query=query
}
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.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let query = query {
self.healthStore.stop(query)
}
}
// MARK: - Table view data source
// override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
// return 0
// }
// override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
// return 0
// }
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// LocationPickerController.swift
// LocationPicker
//
import UIKit
import CoreLocation
import ViewHelper
public protocol LocationPickerControllerProvider {
func provideLocationPickerController(with selectedLocationDelegate: SelectedLocationDelegate) -> LocationPickerController
}
public extension LocationPickerControllerProvider {
func provideLocationPickerController(with selectedLocationDelegate: SelectedLocationDelegate) -> LocationPickerController {
let bundle = Bundle(for: LocationPickerController.self)
let storyboard = UIStoryboard(name: "LocationPicker", bundle: bundle)
let locationPicker = storyboard.instantiateViewController(withIdentifier: String(describing: LocationPickerController.self)) as! LocationPickerController
let locationPickerConfigurator = LocationPickerConfigurator(with: locationPicker)
locationPickerConfigurator.configure(with: selectedLocationDelegate)
return locationPicker
}
}
public protocol LocationPickerControllerPresenter {
func pushLocationPicker(with selectedLocationDelegate: SelectedLocationDelegate, provider: LocationPickerControllerProvider, animated: Bool, on navigationController: UINavigationController?)
}
public extension LocationPickerControllerPresenter {
func pushLocationPicker(with selectedLocationDelegate: SelectedLocationDelegate, provider: LocationPickerControllerProvider, animated: Bool, on navigationController: UINavigationController?) {
let locationPicker = provider.provideLocationPickerController(with: selectedLocationDelegate)
navigationController?.pushViewController(locationPicker, animated: animated)
}
}
public class LocationPickerController: UIViewController, LocationPermissionPresenterDelegate {
// MARK: Outlets
@IBOutlet weak var locationSearchBar: UISearchBar!
@IBOutlet weak var detectCurrentLocationButton: UIButton!
@IBOutlet weak var resultsTableView: UITableView!
// MARK: Vars
var locationDetectionManager: LocationDetectionManager!
var geocodeManager: GeocodeManager!
var selectedLocationDelegate: SelectedLocationDelegate!
var identifiedPlacemarks = [CLPlacemark]() {
didSet {
resultsTableView.reloadData()
}
}
// MARK: overriden functions
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
resultsTableView.estimatedRowHeight = UITableView.automaticDimension
}
// MARK: IBActions
@IBAction func detectCurrentLocation(_ sender: Any) {
locationDetectionManager.detectCurrentLocation()
}
}
// MARK: UITableViewDataSource implementation
extension LocationPickerController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return identifiedPlacemarks.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PlacemarkTableViewCell.self), for: indexPath) as! PlacemarkTableViewCell
let placemark = identifiedPlacemarks[indexPath.row]
cell.display(placemark: placemark)
return cell
}
}
// MARK: UITableViewDelegate implementation
extension LocationPickerController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.row < identifiedPlacemarks.count else {
return
}
selectedLocationDelegate.selected(location: identifiedPlacemarks[indexPath.row])
_ = navigationController?.popViewController(animated: true)
}
}
// MARK: ReverseGeocodeResultsHandlerDelegate implementation
extension LocationPickerController: ReverseGeocodeResultsHandlerDelegate {
func onReverseGeocodeNoLocationsFound(dueTo error: Error) {
display(error: error, with: NSLocalizedString("No Locations found!", comment: ""))
}
func onReverseGeocodeNoLocationsFound() {
// Nothing to do as of now
identifiedPlacemarks = [CLPlacemark]()
}
func onReverseGeocodeLocationsFound(placemarks: [CLPlacemark]) {
// refresh table view
identifiedPlacemarks = placemarks
}
}
// MARK: UITextFieldDelegate implementation
extension LocationPickerController: UISearchBarDelegate {
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let searchedText = searchBar.text {
geocodeManager.geocode(address: searchedText)
}
}
}
// MARK: GeocodeResultsHandlerDelegate implementation
extension LocationPickerController: GeocodeResultsHandlerDelegate {
func onGeocodeNoLocationsFound(dueTo error: Error) {
displayError(message: NSLocalizedString("No Locations Found", comment: ""), title: NSLocalizedString("Error!", comment: ""))
}
func onGeocodeNoLocationsFound() {
// Nothing to do as of now
identifiedPlacemarks = [CLPlacemark]()
}
func onGeocodeLocationsFound(placemarks: [CLPlacemark]) {
// refresh table view
identifiedPlacemarks = placemarks
}
}
|
//
// MyPageViewController.swift
// test1
//
// Created by 김환석 on 2020/10/10.
// Copyright © 2020 김환석. All rights reserved.
//
import UIKit
import Alamofire
class MyPageViewController: UIViewController {
@IBOutlet var imgProfilePhoto: UIImageView!
@IBOutlet var lblNickName: UILabel!
@IBOutlet var lblAge: UILabel!
@IBOutlet var lblGender: UILabel!
@IBOutlet var lblMyLocation1: UILabel!
@IBOutlet var lblMyLocation2: UILabel!
@IBOutlet var lblMyPoint: UILabel!
var gradientLayer: CAGradientLayer!
override func viewDidLoad() {
super.viewDidLoad()
//backGround Color
let backGroundColor = MyBackGroundColor()
self.gradientLayer = CAGradientLayer()
self.gradientLayer.frame = self.view.bounds
self.gradientLayer.startPoint = CGPoint(x: 0, y: 0)
self.gradientLayer.endPoint = CGPoint(x: 1, y: 1)
self.gradientLayer.colors = [UIColor(red: backGroundColor.startColorRed, green: backGroundColor.startColorGreen, blue: backGroundColor.startColorBlue , alpha: 1).cgColor, UIColor(red: backGroundColor.endColorRed , green: backGroundColor.endColorGreen, blue: backGroundColor.endColorBlue, alpha: 1).cgColor]
self.view.layer.insertSublayer(self.gradientLayer, at: 0)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let url = Config.baseURL + "/api/users/\(Config.userIdx!)"
AF.request(url, method: .get ,encoding: URLEncoding.default,headers: ["Content-Type":"application/json"]).validate(statusCode: 200 ..< 300)
.responseJSON(){response in
switch response.result{
case .success(let json):
do {
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let jsonParsing = try JSONDecoder().decode(UserParsing.self, from: data)
do{
let data = try Data(contentsOf: URL(string: jsonParsing.img)!)
self.imgProfilePhoto.image = UIImage(data: data)
}
catch{
self.imgProfilePhoto.image = nil
}
self.lblNickName.text = jsonParsing.nickName
self.lblAge.text = jsonParsing.age
self.lblGender.text = jsonParsing.gender
self.lblMyLocation1.text = jsonParsing.location1
self.lblMyLocation2.text = jsonParsing.location2
self.lblMyPoint.text = "\(jsonParsing.point)"
}catch let jsonError{
print("Error seriallizing json:",jsonError)
}
//let response = json as! NSDictionary
case .failure(let error):
print("error: \(String(describing: error))")
}
}
}
@IBAction func btnChargingPoint(_ sender: UIButton) {
}
@IBAction func btnReviseProfile(_ sender: UIButton) {
guard let controller = self.storyboard?.instantiateViewController(identifier: "ReviseProfileViewController") as?
ReviseProfileViewController else{ return}
if let imgProfilePhoto = self.imgProfilePhoto.image{
controller.tmpImage = imgProfilePhoto
}
if let nickName = self.lblNickName.text{
controller.nickName = nickName
}
if let location1 = self.lblMyLocation1.text{
controller.location1 = location1
}
if let location2 = self.lblMyLocation2.text{
controller.location2 = location2
}
controller.modalPresentationStyle = .fullScreen
present(controller, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ViewController.swift
// LoginApp
//
// Created by Ariel Ramírez on 12/06/18.
// Copyright © 2018 Ariel Ramírez. All rights reserved.
//
import UIKit
import Google
import GoogleSignIn
import ObjectMapper
class ViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate {
//MARK: Outlets
@IBOutlet weak var labelUserEmail: UILabel!
@IBOutlet weak var btnLogin: UIButton!
@IBOutlet weak var btnLogout: UIButton!
@IBOutlet weak var lblName: UILabel!
@IBOutlet weak var lblEmail: UILabel!
//MARK: Instances
override func viewDidLoad() {
super.viewDidLoad()
/*
//setting the error
GGLContext.sharedInstance().configureWithError(&error)
//if any error stop execution and print error
if error != nil{
print(error ?? "google error")
return
}*/
self.btnLogin.backgroundColor = UIColor.green
self.btnLogout.backgroundColor = UIColor.red
self.btnLogin.layer.cornerRadius = 5
self.btnLogout.layer.cornerRadius = 5
//adding the delegates
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().delegate = self
}
@IBAction func logIn(_ sender: Any) {
AlertController.activityIndicatorTrigger(start: true, controller: self)
GIDSignIn.sharedInstance().signIn()
}
@IBAction func logOut(_ sender: Any) {
GIDSignIn.sharedInstance().signOut()
self.lblName.text = ""
self.lblEmail.text = ""
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if error == nil {
if let profile = user.profile as GIDProfileData? {
self.lblName.text = profile.name
self.lblEmail.text = profile.email
AlertController.activityIndicatorTrigger(start: false, controller: self)
}
}
}
func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {
//myActivityIndicator.stopAnimating()
}
// Present a view that prompts the user to sign in with Google
func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
self.present(viewController, animated: true, completion: nil)
}
// Dismiss the "Sign in with Google" view
func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) {
viewController.dismiss(animated: true, completion: nil)
}
}
|
//
// ViewController.swift
// iOS_Authentication
//
// Created by mn(D128) on 2018/06/11.
// Copyright © 2018年 D128. All rights reserved.
//
import UIKit
import FirebaseUI
class ViewController: UIViewController {
// MARK: - Action
@IBAction private func loginDidTap(_ sender: Any) {
guard let authUI = FUIAuth.defaultAuthUI() else {
return
}
authUI.delegate = self
let authViewController = authUI.authViewController()
self.present(authViewController, animated: true, completion: nil)
}
}
extension ViewController: FUIAuthDelegate {
func authUI(_ authUI: FUIAuth, didSignInWith authDataResult: AuthDataResult?, error: Error?) {
print("")
}
}
|
//
// IntroductionView.swift
// mon-bicloo-plus
//
// Created by Cédric Derache on 07/09/2020.
// Copyright © 2020 Cédric Derache. All rights reserved.
//
import SwiftUI
struct IntroductionView: View {
var onIntroductionShown: ()->Void
var body: some View {
ScrollView {
VStack(alignment: .center) {
Spacer()
Image("Logo")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 180, alignment: .center)
.foregroundColor(.accentColor)
.cornerRadius(15)
Text("Bienvenue sur")
.font(.system(size: 36))
.fontWeight(.black)
.foregroundColor(.primary)
Text("Mon Bicloo Plus")
.font(.system(size: 36))
.fontWeight(.black)
.foregroundColor(.accentColor)
VStack(alignment: .leading) {
IntroductionDetailView(title: "Rapide", subTitle: "Voyez rapidement les vélos et les places disponibles dans les stations", imageName: "hare")
IntroductionDetailView(title: "Clair", subTitle: "Un affichage pensé pour permettre une lecture facile", imageName: "eye")
IntroductionDetailView(title: "Personalisable", subTitle: "Rangez vos stations favorites dans vos groupes pour les voir sur l'écran d'accueil en un coup d'oeil", imageName: "gear")
}
Spacer(minLength: 30)
Button(action: {
self.onIntroductionShown()
}) {
Text("Continuer")
.foregroundColor(.primary)
.font(.headline)
.padding()
.frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
.background(RoundedRectangle(cornerRadius: 15, style: .continuous)
.fill(Color.accentColor))
.padding(.bottom)
}
.padding(.horizontal)
}
}
}
}
struct IntroductionView_Previews: PreviewProvider {
static var previews: some View {
IntroductionView(onIntroductionShown: {})
}
}
|
//
// SettingService.swift
// voice-calculator
//
// Created by lz on 6/7/18.
// Copyright © 2018 Zhuang Liu. All rights reserved.
//
import Foundation
import UIKit
class SettingsService {
class var sharedService : SettingsService {
struct Singleton {
static let instance = SettingsService()
}
return Singleton.instance
}
init() { }
var backgroundColor : UIColor {
get {
let data: NSData? = UserDefaults.standard.object(forKey: "backgroundColor") as? NSData
var returnValue: UIColor?
if data != nil {
returnValue = NSKeyedUnarchiver.unarchiveObject(with: data! as Data) as? UIColor
} else {
returnValue = UIColor.black;
}
return returnValue!
}
set (newValue) {
let data = NSKeyedArchiver.archivedData(withRootObject: newValue)
UserDefaults.standard.set(data, forKey: "backgroundColor")
UserDefaults.standard.synchronize()
}
}
var textColor : UIColor {
get {
let data: NSData? = UserDefaults.standard.object(forKey: "textColor") as? NSData
var returnValue: UIColor?
if data != nil {
returnValue = NSKeyedUnarchiver.unarchiveObject(with: data! as Data) as? UIColor
} else {
returnValue = UIColor.white;
}
return returnValue!
}
set (newValue) {
let data = NSKeyedArchiver.archivedData(withRootObject: newValue)
UserDefaults.standard.set(data, forKey: "textColor")
UserDefaults.standard.synchronize()
}
}
var lightModeStatus : Bool {
get {
let data: NSData? = UserDefaults.standard.object(forKey: "lightModeStatus") as? NSData
var returnValue: Bool?
if data != nil {
returnValue = NSKeyedUnarchiver.unarchiveObject(with: data! as Data) as? Bool
} else {
returnValue = true;
}
return returnValue!
}
set (newValue) {
let data = NSKeyedArchiver.archivedData(withRootObject: newValue)
UserDefaults.standard.set(data, forKey: "lightModeStatus")
UserDefaults.standard.synchronize()
}
}
}
|
//
// pay_applyinfoModel.swift
// huicheng
//
// Created by lvxin on 2018/8/27.
// Copyright © 2018年 lvxin. All rights reserved.
//
import UIKit
import ObjectMapper
class pay_applyinfoModel_data: Mappable {
var id: Int!
var num: String!
var principal: String!
var dealamount: String!
var paymoney: Int!
var user: String!
var type: Int!
var typeStr: String!
var money: Int!
var prpportion: String!
var addtime: String!
var state: Int!
var stateStr: String!
var bank: String = ""
var casename: String!
var casenum: String!
var cardno: String = ""
var applyname: String!
var applytime: String!
var funadmin: String!
var paytime: String!
init() {}
required init?(map: Map){
mapping(map: map)
}
// Mappable
func mapping(map: Map) {
id <- map["id"]
num <- map["num"]
principal <- map["principal"]
dealamount <- map["dealamount"]
paymoney <- map["paymoney"]
user <- map["user"]
type <- map["type"]
typeStr <- map["typeStr"]
money <- map["money"]
prpportion <- map["prpportion"]
casename <- map["casename"]
casenum <- map["casenum"]
addtime <- map["addtime"]
state <- map["state"]
stateStr <- map["stateStr"]
bank <- map["bank"]
cardno <- map["cardno"]
applyname <- map["applyname"]
applytime <- map["applytime"]
funadmin <- map["funadmin"]
paytime <- map["paytime"]
}
}
class pay_applyinfoModel: Mappable {
var data: pay_applyinfoModel_data = pay_applyinfoModel_data()
var expense: expense_getinfoModel_data = expense_getinfoModel_data()
var income: income_getinfoModel_data = income_getinfoModel_data()
init() {}
required init?(map: Map){
mapping(map: map)
}
// Mappable
func mapping(map: Map) {
data <- map["data"]
expense <- map["expense"]
income <- map["income"]
}
}
|
//
// BaseTabBarController.swift
// TrashDay
//
// Created by dkonayuki on 6/19/16.
// Copyright © 2016 ChillBears. All rights reserved.
//
import UIKit
class BaseTabBarController: UITabBarController {
let defaultIndex: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
selectedIndex = defaultIndex
}
} |
//
// HomeViewController.swift
// TwitSwift
//
// Created by Sumbul Alvi on 2015-09-15.
// Copyright (c) 2015 Sumbul Alvi. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ComposeViewControllerDelegate, TweetCellDelegate {
@IBOutlet weak var tableView: UITableView!
var refreshControl: UIRefreshControl!
var tweets = [Tweet]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.refreshControl = UIRefreshControl()
self.refreshControl.addTarget(self, action: "refreshTriggered", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControl)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 90
self.reloadTimeline()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
(segue.destinationViewController as! ComposeViewController).delegate = self
}
func refreshTriggered() {
self.reloadTimeline()
}
func reloadTimeline() {
TwitterClient.sharedInstance.homeTimelineWithParams(nil, completion: { (tweets, error) -> () in
self.refreshControl.endRefreshing()
self.tweets = tweets!
self.tableView.reloadData()
})
}
// MARK: Actions
@IBAction func logoutButtonPressed(sender: AnyObject) {
User.currentUser?.logout()
}
// MARK: UITableViewDataSource, UITableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tweets.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("TweetCell", forIndexPath: indexPath) as! TweetCell
cell.configureWithTweet(self.tweets[indexPath.row])
cell.delegate = self
return cell
}
// MARK: ComposeViewControllerDelegate
func composeViewControllerPostedTweet(controller: ComposeViewController, tweet: Tweet) {
self.navigationController?.popViewControllerAnimated(true)
self.tweets.insert(tweet, atIndex: 0)
self.tableView.reloadData()
}
func tweetCellUserPhotoTapped(cell: TweetCell) {
let indexPath = tableView.indexPathForCell(cell)!
let tweet = tweets[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let profileVc = storyboard.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
profileVc.user = tweet.user;
navigationController?.pushViewController(profileVc, animated: true)
}
}
|
//
// UserDetailViewController.swift
// UnSplash_Rodrigo_Elo
//
// Created by Rodrigo Elo on 02/07/18.
// Copyright © 2018 Rodrigo Elo. All rights reserved.
//
import UIKit
import Kingfisher
class UserDetailViewController: UIViewController {
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var fullName: UILabel!
@IBOutlet weak var bigAvatar: UIImageView!
@IBOutlet weak var labelFolowers: UILabel!
@IBOutlet weak var labelFolowin: UILabel!
@IBOutlet weak var labelDownloads: UILabel!
@IBOutlet weak var labelImgs: UILabel!
@IBOutlet weak var labelLikes: UILabel!
var userData : User?
var userNameApi: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let serviceUserData = PhotoService()
serviceUserData.userData(username: userNameApi, completionOfView: { (userData) in
self.userData = (userData)
self.userName.text = userData.username
self.fullName.text = userData.name
self.labelFolowers.text = "\(String(describing: userData.followers))"
self.labelFolowin.text = "\(String(describing: userData.following))"
self.labelDownloads.text = "\(String(describing: userData.downloads))"
self.labelImgs.text = "\(String(describing: userData.total_photos))"
self.labelLikes.text = "\(String(describing: userData.likes))"
if let bigAvatar = userData.usrImgs.large{
let avatarUrl = URL(string: bigAvatar)
self.bigAvatar.kf.setImage(with: avatarUrl)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// GameViewController.swift
// Ruins
//
// Created by Theodore Abshire on 7/6/16.
// Copyright © 2016 Theodore Abshire. All rights reserved.
//
import UIKit
enum TargetingMode:Int
{
case Attack
case Examine
case Special
}
class Target
{
let view:UIView
let subject:Creature
init(subject:Creature, view:UIView)
{
self.view = view
self.subject = subject
}
}
let autoSkipRadius = 6
let damageNumberDuration:NSTimeInterval = 0.35
let damageNumberDistanceTraveled:CGFloat = 50
class GameViewController: UIViewController, GameDelegate {
var game:Game!
var input:Bool = false
var representations = [Representation]()
var animating:Bool = false
var shouldUIUpdate:Bool = false
var cameraPoint = CGPoint(x: 0, y: 0)
var targetingMode:TargetingMode!
var targets:[Target]?
var examineTarget:Creature!
@IBOutlet weak var gameArea: TileDisplayView!
@IBOutlet weak var gameAreaUpper: UIView!
@IBOutlet weak var creatureLayer: UIView!
@IBOutlet weak var objectLayer: UIView!
@IBOutlet weak var healthBarAuraView: UIView!
@IBOutlet weak var healthBarContainerView: UIView!
@IBOutlet weak var secondaryBarArea: UIView!
@IBOutlet weak var weaponBarContainerView: UIView!
@IBOutlet weak var armorBarContainerView: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
//format some views
healthBarAuraView.layer.cornerRadius = 10
healthBarContainerView.layer.cornerRadius = 10
weaponBarContainerView.layer.cornerRadius = 5
armorBarContainerView.layer.cornerRadius = 5
game = Game(mapStub: MapStub(flavor: "overgrown", theme: "city", level: 1))
game.delegate = self
//make a quick initial player inventory
game.player.inventory.append(Item(armor: Armor(type: "heavy armor", level: 10)))
game.player.inventory.append(Item(weapon: Weapon(type: "rifle", material: "iron", level: 10)))
let pot = Item(usable: "healing potion")
pot.number = 2
game.player.inventory.append(pot)
game.player.inventory.append(Item(usable: "bear trap"))
game.player.inventory.append(Item(usable: "wand of blasting"))
//TODO: all sprite tiles and such should auto-scale so that differently-sized iphones all have the same screen size
//start the game loop with executePhase()
game.executePhase()
//get an initial camera point
calculateCameraPoint()
game.calculateVisibility()
//make the tiles
gameArea.initializeAtCameraPoint(cameraPoint, map: game.map, upperView: gameAreaUpper)
//make representations
for y in 0..<game.map.height
{
for x in 0..<game.map.width
{
if let trap = game.map.tileAt(x: x, y: y).trap
{
representations.append(TrapRepresentation(trap: trap, x: x, y: y, superview: objectLayer, atCameraPoint: cameraPoint, map: game.map))
}
}
}
for creature in game.creatures
{
representations.append(CreatureRepresentation(creature: creature, superview: creatureLayer, atCameraPoint: cameraPoint, map:game.map))
}
//add a gesture recognizer for the game area
let tappy = UITapGestureRecognizer(target: self, action: #selector(gameAreaPressed))
gameAreaUpper.addGestureRecognizer(tappy)
// temporaryMapViewerScript()
}
private func temporaryMapViewerScript()
{
//TODO: remove this once I no longer need it
let drawSize:CGFloat = 5
let (solidity, width, height, _) = MapGenerator.generateRoomsSolidityMap(MapStub(flavor: "lawless", theme: "city", level: 1))
for y in 0..<height
{
for x in 0..<width
{
let solid = solidity[x + y * width]
let view = UIView(frame: CGRectMake(CGFloat(x) * drawSize, CGFloat(y) * drawSize, drawSize, drawSize))
view.backgroundColor = solid ? UIColor.lightGrayColor() : UIColor.blackColor()
self.view.addSubview(view)
}
}
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
//update the UI and the player in case someone has changed something in another VC
uiUpdate()
for rep in representations
{
rep.updateAppearance()
}
}
//MARK: actions
func gameAreaPressed(sender:UITapGestureRecognizer)
{
//find out the exact x and y coordinates of the tap
let coordinates = sender.locationInView(gameArea)
let x = Int(floor((coordinates.x + cameraPoint.x) / tileSize))
let y = Int(floor((coordinates.y + cameraPoint.y) / tileSize))
print("Tapped at (\(x), \(y))")
if input
{
if let targets = targets
{
//did you click on a target?
for target in targets
{
if target.subject.x == x && target.subject.y == y
{
//if so, do something appropriate for the targeting mode
switch(targetingMode!)
{
case .Attack:
//attack them
input = false
game.attack(x: x, y: y)
case .Special:
//special them
input = false
game.special(x: x, y: y)
case .Examine:
//examine them
examineTarget = target.subject
self.performSegueWithIdentifier("ShowExamine", sender: self)
break
case .Special:
//TODO: use the special on them
input = false
}
leaveTargetingMode()
break
}
}
}
else if game.movePoints > 0
{
let xDif = x - game.activeCreature.x
let yDif = y - game.activeCreature.y
if xDif != 0 || yDif != 0
{
//you probably want to move somewhere
let xDis = abs(xDif)
let yDis = abs(yDif)
let xM = xDif > 0 ? 1 : -1
let yM = yDif > 0 ? 1 : -1
if xDis >= yDis * 2
{
tryMove(x: xM, y: 0)
}
else if yDis >= xDis * 2
{
tryMove(x: 0, y: yM)
}
else
{
if xDis > yDis
{
if (!tryMove(x: xM, y: 0))
{
tryMove(x: 0, y: yM)
}
}
else if (!tryMove(x: 0, y: yM))
{
tryMove(x: xM, y: 0)
}
}
}
}
}
}
private func tryMove(x xChange:Int, y yChange:Int)->Bool
{
let x = game.activeCreature.x + xChange
let y = game.activeCreature.y + yChange
print(" Attempting to move to (\(x), \(y))")
if game.map.tileAt(x: x, y: y).walkable
{
game.makeMove(x: x, y: y)
return true
}
return false
}
@IBAction func attackButtonPressed()
{
//TODO: check to see if you have enough ammo to attack
if input
{
if targets != nil
{
leaveTargetingMode()
if targetingMode! == .Attack
{
return
}
}
targetingMode = .Attack
enterTargetingMode()
{ (creature) -> Bool in
return self.game.validTarget(creature)
}
}
}
@IBAction func skipButtonPressed()
{
if input
{
leaveTargetingMode()
input = false
game.skipAction()
}
}
@IBAction func itemsButtonPressed()
{
if input
{
leaveTargetingMode()
//open items menu
self.performSegueWithIdentifier("ShowInventory", sender: self)
}
}
@IBAction func examineButtonPressed()
{
if input
{
if targets != nil
{
leaveTargetingMode()
if targetingMode! == .Examine
{
return
}
}
//switch to examine mode
targetingMode = .Examine
enterTargetingMode()
{ (creature) -> Bool in
//are they onscreen? can you see them?
return self.game.map.tileAt(x: creature.x, y: creature.y).visible
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if let inv = segue.destinationViewController as? InventoryViewController
{
inv.game = self.game
inv.useSpecialClosure =
{ (special) in
self.game.targetSpecial = special
self.targetingMode = .Special
self.enterTargetingMode()
{ (creature) -> Bool in
return self.game.validTarget(creature)
}
}
}
else if let exm = segue.destinationViewController as? ExamineViewController
{
exm.game = self.game
exm.creature = examineTarget
examineTarget = nil
}
}
//MARK: delegate methods
func inputDesired()
{
//check to see if you can auto-skip
var activeNearby = false
for y in max(0, game.player.y - autoSkipRadius)...min(game.map.height - 1, game.player.y + autoSkipRadius)
{
for x in max(0, game.player.x - autoSkipRadius)...min(game.map.width - 1, game.player.x + autoSkipRadius)
{
if let cr = game.map.tileAt(x: x, y: y).creature
{
if !cr.good && cr.awake
{
activeNearby = true
break
}
}
}
if activeNearby
{
break
}
}
if !activeNearby
{
game.player.aura = true
if game.movePoints == 0
{
game.skipAction()
return
}
}
input = true
}
func playAnimation(anim: Animation)
{
animating = true
playMoveAnimations(anim)
}
private func playMoveAnimations(anim:Animation)
{
//this comes before attacks because if you walk over a trap, it's move -> attack -> damage
if let movePath = anim.movePath
{
let active = self.game.activeCreature
let updateCamera = active === game.player
if updateCamera
{
gameArea.makeTilesForCameraPoint(cameraPoint)
}
func moveAnimToNext()
{
if movePath.count == 1
{
self.gameArea.cullTilesForCameraPoint(self.cameraPoint)
self.playAttackAnimations(anim)
}
else
{
//pop that one move off of the array and go to the next stage of the movement
//TODO: it'd be ideal if moves were a queue I guess, but it probably doesn't matter much
anim.movePath!.removeFirst()
self.playMoveAnimations(anim)
}
}
//if both points in this next leg of the move
//IE both (active.x, active.y) and (movePath.first!)
//are invisible/offscreen
//then update the position to (movePath.first!) instantly, instead of with an animation
let startPointInvisible = !self.game.map.tileAt(x: active.x, y: active.y).visible
let endPointInvisible = !self.game.map.tileAt(x: movePath.first!.0, y: movePath.first!.1).visible
if startPointInvisible && endPointInvisible && !updateCamera
{
for rep in self.representations
{
rep.updatePosition(self.cameraPoint, map:self.game.map)
}
moveAnimToNext()
}
else
{
//update visibility after moving to hide things strategically
for rep in self.representations
{
rep.updateVisibility(self.cameraPoint, map:self.game.map)
}
UIView.animateWithDuration(0.25, animations:
{
//update the moving creature's position step by step
let realX = active.x
let realY = active.y
active.x = movePath.first!.0
active.y = movePath.first!.1
if updateCamera
{
self.calculateCameraPoint()
self.gameArea.adjustTilesForCameraPoint(self.cameraPoint)
//update the visibility map
self.game.calculateVisibility()
self.gameArea.updateTileHidden()
}
for rep in self.representations
{
rep.updatePosition(self.cameraPoint, map:self.game.map)
rep.updateVisibility(self.cameraPoint, map:self.game.map)
}
active.x = realX
active.y = realY
})
{ (completed) in
moveAnimToNext()
}
}
}
else
{
playAttackAnimations(anim)
}
}
private func playAttackAnimations(anim:Animation)
{
if let target = anim.attackTarget, let type = anim.attackType
{
//TODO: play the attack animation
//afterwards, update representation appearance
//then call playDamageNumberAnimations
playDamageNumberAnimations(anim)
}
else
{
playDamageNumberAnimations(anim)
}
}
private func playDamageNumberAnimations(anim: Animation)
{
//discard all damage number representations that come from invisible tiles
anim.damageNumbers = anim.damageNumbers.filter() { self.game.map.tileAt(x: $0.0.x, y: $0.0.y).visible }
if anim.damageNumbers.count > 0
{
//make damage number representations
var damageViews = [UILabel]()
for (creature, number) in anim.damageNumbers
{
let damageView = UILabel()
damageView.text = number
damageView.sizeToFit()
damageView.textColor = UIColor.whiteColor()
let startX = (CGFloat(creature.x) + 0.5) * tileSize - cameraPoint.x + self.gameArea.frame.origin.x
let startY = (CGFloat(creature.y) + 0.5) * tileSize - cameraPoint.y + self.gameArea.frame.origin.y
damageView.center = CGPointMake(startX, startY)
damageViews.append(damageView)
self.view.addSubview(damageView)
}
//animate them
UIView.animateWithDuration(damageNumberDuration, animations:
{
for damageView in damageViews
{
damageView.center = CGPoint(x: damageView.center.x, y: damageView.center.y - damageNumberDistanceTraveled)
}
})
{ (completed) in
for damageView in damageViews
{
damageView.removeFromSuperview()
}
//update the appearances of the representations, in case anybody changed
for rep in self.representations
{
rep.updateAppearance()
}
//and go to the end of the chain
self.animChainOver()
}
}
else
{
animChainOver()
}
}
private func animChainOver()
{
animating = false
if shouldUIUpdate
{
uiUpdate()
}
pruneRepresentations()
game.toNextPhase()
}
func uiUpdate()
{
//if you're animating, delay this until the animation finishes
if animating
{
shouldUIUpdate = true
return
}
shouldUIUpdate = false
//switch healthBarAuraView's background color opacity between 0 and 1 depending on if the player has aura
healthBarAuraView.backgroundColor = healthBarAuraView.backgroundColor?.colorWithAlphaComponent(game.player.aura ? 1 : 0)
//update the health bar
makeBar(healthBarContainerView, color: UIColor.redColor(), percent: CGFloat(game.player.health) / CGFloat(game.player.maxHealth))
for subview in secondaryBarArea.subviews
{
subview.removeFromSuperview()
}
//draw movement points number
let labelM = UILabel()
labelM.text = "\(game.movePoints)/\(game.activeCreature.maxMovePoints) MP \(game.hasAction ? "ACTION " : "")"
labelM.sizeToFit()
secondaryBarArea.addSubview(labelM)
//draw weight number
let labelW = UILabel(frame: CGRect(x: 0, y: labelM.frame.height, width: 0, height: 0))
labelW.text = "\(game.player.encumberance)/\(game.player.maxEncumberance) LBs "
labelW.sizeToFit()
secondaryBarArea.addSubview(labelW)
//TODO: draw status effect icons
//update the equipment health bars
makeBar(weaponBarContainerView, color: UIColor.greenColor(), percent: game.player.weapon.maxHealth == 0 ? 0 : CGFloat(game.player.weapon.health) / CGFloat(game.player.weapon.maxHealth))
makeBar(armorBarContainerView, color: UIColor.greenColor(), percent: game.player.armor == nil ? 0 : CGFloat(game.player.armor!.health) / CGFloat(game.player.armor!.maxHealth))
}
private func makeBar(inView:UIView, color:UIColor, percent:CGFloat)
{
for subview in inView.subviews
{
subview.removeFromSuperview()
}
if percent != 0
{
let bar = UIView(frame: CGRectMake(0, 0, inView.frame.width * percent, inView.frame.height))
bar.backgroundColor = color
inView.addSubview(bar)
}
}
func gameOver()
{
//TODO: handle a game over
}
func trapCreated(trap:Trap, x:Int, y:Int)
{
let rep = TrapRepresentation(trap: trap, x: x, y: y, superview: objectLayer, atCameraPoint: cameraPoint, map: game.map)
representations.append(rep)
}
//MARK: helper methods
private func pruneRepresentations()
{
representations = representations.filter() { !$0.dead }
}
private func enterTargetingMode(isValidTarget:(Creature)->Bool)
{
targets = [Target]()
for creature in game.creatures
{
if isValidTarget(creature)
{
//make a reticle
let reticleFrame = CGRectMake(tileSize * CGFloat(creature.x) - cameraPoint.x, tileSize * CGFloat(creature.y) - cameraPoint.y, tileSize, tileSize)
let reticle = UIView(frame: reticleFrame)
reticle.alpha = 0.5
reticle.backgroundColor = UIColor.redColor()
self.creatureLayer.addSubview(reticle)
//and register the target
targets!.append(Target(subject: creature, view: reticle))
}
}
//cancel out of targeting mode if there were no targets
if targets!.count == 0
{
targets = nil
}
}
private func leaveTargetingMode()
{
game.targetSpecial = nil
if let targets = targets
{
for target in targets
{
target.view.removeFromSuperview()
}
self.targets = nil
}
}
private func calculateCameraPoint()
{
let active = self.game.activeCreature
let newX = min(max(CGFloat(active.x) * tileSize - self.gameArea.frame.width / 2, 0), CGFloat(self.game.map.width) * tileSize - self.gameArea.frame.width)
let newY = min(max(CGFloat(active.y) * tileSize - self.gameArea.frame.height / 2, 0), CGFloat(self.game.map.height) * tileSize - self.gameArea.frame.height)
self.cameraPoint = CGPoint(x: newX, y: newY)
}
} |
//
// DIiscosTableViewController.swift
// Examen
//
// Created by macbook on 5/8/19.
// Copyright © 2019 nidem. All rights reserved.
//
import UIKit
class DIiscosTableViewController: UITableViewController {
var primerActoCD: [Cancion] = [
Cancion(nombre: "Comienza el espectaculo", duracion: "00:26", precio: "$9.00"),
Cancion(nombre: "Dios", duracion: "5:37", precio: "$12.00"),
Cancion(nombre: "Calma tu dolor", duracion: "4:18", precio: "$12.00"),
Cancion(nombre: "Oveja Negra", duracion: "4:13", precio: "$12.00"),
Cancion(nombre: "Miedo en el alma", duracion: "5:00", precio: "$12.00"),
Cancion(nombre: "Carcel de Piel y Hueso", duracion: "6:38", precio: "12.00"),
Cancion(nombre: "...Y en Soledad Me Lamento", duracion: "4:38", precio: "$12.00"),
Cancion(nombre: "Recuerdos", duracion: "6:20", precio: "$12.00"),
Cancion(nombre: "Mi Tempestad", duracion: "4:47", precio: "$12.00"),
Cancion(nombre: "Diosa Del Infierno Azul", duracion: "4:44", precio: "$12.00"),
Cancion(nombre: "Lagrimas de Sangre", duracion: "4:21", precio: "$12.00")
]
var sentimientosCD: [Cancion] = [
Cancion(nombre: "Miedo", duracion: "3:38", precio: "$12.00"),
Cancion(nombre: "Esperanza", duracion: "5:46", precio: "$12.00"),
Cancion(nombre: "Impotencia", duracion: "4:51", precio: "$12.00"),
Cancion(nombre: "Arrepentimiento", duracion: "7:14º", precio: "$12.00"),
Cancion(nombre: "Pasion", duracion: "6:21", precio: "$12.00"),
Cancion(nombre: "Odio", duracion: "6:20", precio: "$12.00"),
Cancion(nombre: "Frustracion", duracion: "5:07", precio: "$12.00"),
Cancion(nombre: "Desilucion", duracion: "5:52", precio: "$12.00"),
Cancion(nombre: "Soledad", duracion: "5:57", precio: "$12.00"),
Cancion(nombre: "Duda", duracion: "6:22", precio: "$12.00"),
Cancion(nombre: "Dolor", duracion: "9:53", precio: "$15.00")
]
var requiemCD: [Cancion] = [
Cancion(nombre: "Deja de llorar", duracion: "4:01", precio: "$12.00"),
Cancion(nombre: "Grando", duracion: "5:31", precio: "$12.00"),
Cancion(nombre: "Mascara de Seduccion", duracion: "4:30", precio: "$12.00"),
Cancion(nombre: "Hombre", duracion: "5:25", precio: "$12.00"),
Cancion(nombre: "Paraiso Perdido", duracion: "5:38", precio: "$12.00"),
Cancion(nombre: "Nudos", duracion: "4:31", precio: "$12.00"),
Cancion(nombre: "El dia de mañana", duracion: "4:04", precio: "$12.00"),
Cancion(nombre: "Perdido", duracion: "3:02", precio: "$12.00"),
Cancion(nombre: "Hermanos", duracion: "402", precio: "$12.00"),
Cancion(nombre: "Tu escencia", duracion: "3:58", precio: "$12.00"),
Cancion(nombre: "Requiem", duracion: "7:21", precio: "$12.00"),
Cancion(nombre: "Inmortal", duracion: "1:27", precio: "$12.00"),
Cancion(nombre: "Eloise", duracion: "5:57", precio: "$12.00")
]
var raicesCD: [Cancion] = [
Cancion(nombre: "Cuestion de fe", duracion: "4:09", precio: "$12.00"),
Cancion(nombre: "Felicidad absurda", duracion: "4:39", precio: "$12.00"),
Cancion(nombre: "Que te follen", duracion: "4:09", precio: "$12.00"),
Cancion(nombre: "Sin amar", duracion: "4:05", precio: "$12.00"),
Cancion(nombre: "Maldita obscuridad", duracion: "4:34", precio: "$12.00"),
Cancion(nombre: "Impotencia II", duracion: "5:02", precio: "$12.00"),
Cancion(nombre: "Un millon de sueños", duracion: "4:04", precio: "$12.00"),
Cancion(nombre: "Agonia", duracion: "4:16", precio: "$12.00"),
Cancion(nombre: "La tormenta", duracion: "4:04", precio: "$12.00"),
Cancion(nombre: "La cicatriz", duracion: "5:22", precio: "$12.00"),
Cancion(nombre: "Maquinas", duracion: "3:51", precio: "$12.00"),
Cancion(nombre: "Bucle", duracion: "4:51", precio: "$12.00"),
Cancion(nombre: "Raices", duracion: "6:57", precio: "$15.00")
]
var titulo: String = ""
override func viewDidLoad() {
super.viewDidLoad()
if navigationItem.title == "Primer Acto" {
titulo = "Primer Acto"
imagen.image = UIImage(named: "primeracto")
print("entre a 1")
}else if navigationItem.title == "Sentimientos"{
titulo = "Sentimientos"
imagen.image = UIImage(named: "sentimientos")
}else if navigationItem.title == "Requiem"{
titulo = "Requiem"
imagen.image = UIImage(named: "requiem")
}else if navigationItem.title == "Raices"{
titulo = "Raices"
imagen.image = UIImage(named: "raices")
}
titulo = navigationItem.title!
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
@IBOutlet weak var imagen: UIImageView!
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if titulo == "Primer Acto" {
return primerActoCD.count
}else if titulo == "Sentimientos"{
return sentimientosCD.count
}else if titulo == "Requiem"{
return requiemCD.count
}else if titulo == "Raices"{
return raicesCD.count
}else{
return raicesCD.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var cancion: Cancion
if titulo == "Primer Acto"{
cancion = primerActoCD[indexPath.row]
}else if titulo == "Sentimientos"{
cancion = sentimientosCD[indexPath.row]
}else if titulo == "Requiem"{
cancion = requiemCD[indexPath.row]
}else if titulo == "Raices"{
cancion = raicesCD[indexPath.row]
}else{
cancion = raicesCD[indexPath.row]
}
cell.textLabel?.text = "\(cancion.nombre) - \(cancion.duracion) - \(cancion.precio)"
return cell
}
/*override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if navigationItem.title == "Primer Acto"{
let cancion = primerActoCD[indexPath.row]
print("\(cancion.nombre) \(indexPath)")
}else if navigationItem.title == "Sentimientos"{
let cancion = primerActoCD[indexPath.row]
print("\(cancion.nombre) \(indexPath)")
}else if navigationItem.title == "Requiem"{
let cancion = primerActoCD[indexPath.row]
print("\(cancion.nombre) \(indexPath)")
}else /*if navigationItem.title == "Raices"*/{
let cancion = primerActoCD[indexPath.row]
print("\(cancion.nombre) \(indexPath)")
}
}*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// Home.swift
// NoteMacOS (iOS)
//
// Created by Michele Manniello on 17/10/21.
//
import SwiftUI
struct Home: View {
// Showing Card Colors on Button Click...
@State var showColors: Bool = false
// Button Animation...
@State var animateButton: Bool = false
var body: some View {
HStack(spacing: 0){
// SideBar...
if isMacos(){
Group{
SideBar()
Rectangle()
.fill(Color.gray.opacity(0.15))
.frame(width: 1)
}
}
// Main Content...
MainContent()
}
#if os(macOS)
.ignoresSafeArea()
#endif
.frame(width: isMacos() ? getRect().width / 1.7 : nil, height: isMacos() ? getRect().height - 180 : nil,alignment: .leading)
.background(Color("BG").ignoresSafeArea())
#if os(iOS)
.overlay(SideBar())
#endif
.preferredColorScheme(.light)
}
@ViewBuilder
func MainContent() -> some View {
VStack(spacing: 6){
// Search Bar...
HStack(spacing: 8){
Image(systemName: "magnifyingglass")
.font(.title3)
.foregroundColor(.gray)
TextField("Search", text: .constant(""))
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom,isMacos() ? 0 : 10)
.overlay(
Rectangle()
.fill(Color.gray.opacity(0.15))
.frame(height: 1)
.padding(.horizontal,-25)
// Moving offset 6...
.offset(y:6)
.opacity(isMacos() ? 0 : 1)
,alignment: .bottom
)
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 15){
Text("Notes")
.font(isMacos() ? .system(size: 33, weight: .bold) : .largeTitle.bold())
.frame(maxWidth: .infinity, alignment: .leading)
// Columns...
let columns = Array(repeating: GridItem(.flexible(), spacing: isMacos() ? 25 : 15), count: isMacos() ? 3 : 1)
LazyVGrid(columns: columns,spacing: 25) {
// Notes...
ForEach(notes){ note in
// Card View...
CardView(note: note)
}
}
.padding(.top,30)
}
.padding(.top,isMacos() ? 45 : 30)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
.padding(.top,isMacos() ? 40 : 15)
.padding(.horizontal,25)
}
@ViewBuilder
func CardView(note: Note) -> some View {
VStack{
Text(note.note)
.font(isMacos() ? .title3 : .body)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
HStack{
Text(note.date,style: .date)
.foregroundColor(.black)
.opacity(0.8)
Spacer(minLength: 0)
// Edit Button..
Button {
} label: {
Image(systemName: "pencil")
.font(.system(size: 15, weight: .bold))
.padding(8)
.foregroundColor(.white)
.background(Color.black)
.clipShape(Circle())
}
}
.padding(.top,55)
}
.padding()
.background(note.cardColor)
.cornerRadius(18)
}
@ViewBuilder
func SideBar() -> some View {
VStack{
if isMacos(){
Text("Pocked")
.font(.title2)
.fontWeight(.semibold)
}
// Add Button...
if isMacos() {
AddButton()
.zIndex(1)
}
VStack(spacing: 15){
let colors = [Color("Skin"),Color("Orange"),Color("Purple"),Color("Blue"),Color("Green")]
ForEach(colors,id: \.self){ color in
Circle()
.fill(color)
.frame(width: isMacos() ? 20 : 25, height: isMacos() ? 20 : 25)
}
}
.padding(.top,20)
.frame(height: showColors ? nil : 0)
.opacity(showColors ? 1 : 0)
.zIndex(0)
if !isMacos() {
AddButton()
.zIndex(1)
}
}
#if os(macOS)
.frame(maxHeight: .infinity,alignment: .top)
.padding(.vertical)
.padding(.horizontal,22)
.padding(.top,35)
#else
.frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .bottomTrailing)
.padding()
// Blur View...
.background(BlurView(style: .systemUltraThinMaterialDark)
.opacity(showColors ? 1 : 0)
.ignoresSafeArea())
#endif
}
@ViewBuilder
func AddButton() -> some View {
Button {
withAnimation(.interactiveSpring(response: 0.5, dampingFraction: 0.6, blendDuration: 0.6)){
showColors.toggle()
animateButton.toggle()
}
// Resetting the Button...
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
withAnimation(.spring()){
animateButton.toggle()
}
}
} label: {
Image(systemName: "plus")
.font(.title2)
.foregroundColor(.white)
.scaleEffect(animateButton ? 1.1 : 1)
.padding(isMacos() ? 12: 15)
.background(Color.black)
.clipShape(Circle())
}
.rotationEffect(.init(degrees: showColors ? 45 : 0))
.scaleEffect(animateButton ? 1.1 : 1)
.padding(.top,30)
}
}
struct Home_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
//Extending View to get Frame and getting device os Type...
extension View{
func getRect() -> CGRect {
#if os(iOS)
return UIScreen.main.bounds
#else
return NSScreen.main!.visibleFrame
#endif
}
func isMacos() -> Bool {
#if os(iOS)
return false
#endif
return true
}
}
// Hidding Focus ring...
#if os(macOS)
extension NSTextField{
open override var focusRingType: NSFocusRingType{
get{.none}
set{}
}
}
#endif
|
//
// MovieInfo.swift
// moviesChallenge
//
// Created by Jacqueline Minneman on 1/3/17.
// Copyright © 2017 Jacqueline Schweiger. All rights reserved.
//
import Foundation
class MovieInfo {
var title: String
var year: String
var rated: String
var released: String
var runtime: String
var genre: String
var director: String
var writer: String
var actors: String
var plot: String
var language: String
var country: String
var awards: String
var poster: String
var metaScore: String
var imdbRating: String
var imdbVotes: String
var imdbID: String
var type: String
var response: String
init(dictionary: [String: String]) {
self.title = dictionary["Title"]!
self.year = dictionary["Year"]!
self.rated = dictionary["Rated"]!
self.released = dictionary["Released"]!
self.runtime = dictionary["Runtime"]!
self.genre = dictionary["Genre"]!
self.director = dictionary["Director"]!
self.writer = dictionary["Writer"]!
self.actors = dictionary["Actors"]!
self.plot = dictionary["Plot"]!
self.language = dictionary["Language"]!
self.country = dictionary["Country"]!
self.awards = dictionary["Awards"]!
self.poster = dictionary["Poster"]!
self.metaScore = dictionary["Metascore"]!
self.imdbRating = dictionary["imdbRating"]!
self.imdbVotes = dictionary["imdbVotes"]!
self.imdbID = dictionary["imdbID"]!
self.type = dictionary["Type"]!
self.response = dictionary["Response"]!
}
}
|
//
// ViewController.swift
// profile_test
//
// Created by Jac on 2016/9/28.
// Copyright © 2016年 Jac. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableview: UITableView!
var profile : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
var request = URLRequest(url: URL(string: "http://140.113.72.25:8100/api/account/?format=json")!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) {data, response, err in
do{
let json = try! JSONSerialization.jsonObject(with: data!)
if let Section = json as? NSArray{
let i = 1
if let profile_data = Section[i] as? NSDictionary{
let realname = profile_data["realname"]! as! String
let education = profile_data["education"]! as! Int
let language = profile_data["language"]! as! Int
let gender = profile_data["gender"]! as! Int
self.profile.append("用戶名稱: \(realname)")
self.profile.append("用戶性別: \(self.gender_decode(g: gender))")
self.profile.append("使用語言: \(self.language_decode(l: language))")
self.profile.append("教育程度: \(self.education_decode(e: education))")
self.tableview.reloadData()
print("this is my STR \(self.profile)")
}
}
}catch{
print("Couldn't Serialize")
}
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableview.dequeueReusableCell(withIdentifier: "mycell") as? ProfileCell{
cell.configureCell(text: profile[indexPath.row])
return cell
}
else{
return ProfileCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return profile.count
}
func education_decode(e: Int) -> String{
switch e {
case 0:
return "學前教育"
case 1:
return "學前教育"
case 2:
return "國民中學"
case 3:
return "高級中學"
case 4:
return "專科(副學士)"
case 5:
return "大學(學士)"
case 6:
return "碩士"
case 7:
return "博士"
default:
return "SOME THING WENT WRONG"
}
}
func language_decode(l: Int) -> String{
switch l {
case 1:
return "客家話"
case 2:
return "閩南語"
case 3:
return "中文"
case 4:
return "英文"
default:
return "SOME THING WENT WRONG"
}
}
func gender_decode(g: Int) -> String{
if g==0{
return "男"
}
else{
return "女"
}
}
func level_decode(l: Int) -> String{
switch l {
case 1:
return "輕度視障"
case 2:
return "中度視障"
case 3:
return "高度視障"
default:
return "SOME THING WENT WRONG"
}
}
// func uploadRequest(){
// //get image Data from ImageView
// let imageData:NSData = UIImagePNGRepresentation(picture.image!)!
// //let strBase64 = String(imageData.base64EncodedDataWithOptions(.Encoding64CharacterLineLength))
// let strBase64 = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
// let request = NSMutableURLRequest(URL: NSURL(string: "http://140.113.72.29:8100/api/photo/")!)
// let session = NSURLSession.sharedSession()
// request.HTTPMethod = "POST"
// let key = "http://140.113.72.29:8100/api/account/" + self.ID + "/"
// let params = NSMutableDictionary()
// params.setValue(key, forKey: "account")
// params.setValue(1, forKey: "state")
// //params.setValue(strBase64, forKey: "image")
// print("json content")
// print(params)
// request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
// request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//
// let task = session.dataTaskWithRequest(request,completionHandler: {data,response,error -> Void in
// print("Response: \(response)")})
// task.resume()
// }
}
|
import RealmSwift
class Items: Object{
@objc dynamic var item = ""
}
|
//
// UnzippService.swift
// TestHTML
//
// Created by Dehelean Andrei on 4/23/17.
// Copyright © 2017 Dehelean Andrei. All rights reserved.
//
import Foundation
import SSZipArchive
struct UnzipService {
let guid: String
func run() {
let zipLocation = FileHandler.downloadsFolder(fileName: guid).path
let newLocation = FileHandler.websitesFolder(fileName: guid).path
SSZipArchive.unzipFile(atPath: zipLocation.path, toDestination: newLocation.path)
try? FileManager.default.removeItem(at: zipLocation)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "unzipDone"), object: nil)
}
}
|
//
// FaceIdentViewController.swift
// COMP90018Proj Front-End Application
//
// Created by Kai Zhang, Yiqi Yu, Lisha Qiu
// Copyright © 2017 Unimelb. All rights reserved.
//
import UIKit
import ESTabBarController_swift
import ImagePicker
import CoreData
import SwiftyButton
class FaceIdentViewController: UIViewController,UITabBarControllerDelegate,
UITabBarDelegate,ImagePickerDelegate{
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var namefiled: UILabel!
@IBOutlet weak var crimefiled: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(red:244.0/255.0, green: 245.0 / 255.0, blue: 245.0/255,alpha: 1.0)
// set button target to this view
button.addTarget(self, action: #selector(buttonTouched(button:)), for: .touchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func buttonTouched(button: UIButton) {
var config = Configuration()
config.doneButtonTitle = "Done"
config.noImagesTitle = "Sorry! There are no images here!"
config.recordLocation = false
// config.allowVideoSelection = true
let imagePicker = ImagePickerController()
imagePicker.configuration = config
imagePicker.delegate = self
imagePicker.imageLimit = 1
present(imagePicker, animated: true, completion: nil)
}
// upload photo to azure stroage account for face identification
func uploadPhoto(image:UIImage) {
// connection string for azure storage account
let connectionString = "DefaultEndpointsProtocol=https;AccountName=faceimg;AccountKey=vjckPyJ37aWuElE81It17cMOZvy54+1pAXYEQWzmRyCqlqpYEOpST6ZZ1LO1dgtwtjs5P7wV3Bwih3B5q9vUrg==;EndpointSuffix=core.windows.net"
// initialize connection resources
let storageAccount : AZSCloudStorageAccount
try! storageAccount = AZSCloudStorageAccount(fromConnectionString: connectionString)
let blobClient = storageAccount.getBlobClient()
var container : AZSCloudBlobContainer
container = blobClient.containerReference(fromName: "faceimgs")
let data = UIImageJPEGRepresentation(image, 0.5)
let blob = container.blockBlobReference(fromName: "userUploadPhoto")
blob.upload(from: data!, completionHandler: {(NSError) -> Void in
NSLog("uploaded")
})
self.activityIndicator.startAnimating()
}
// send identify request to back-end server
func identify(){
// back-end server api
var request = URLRequest(url: URL(string: "https://facedbidentify.herokuapp.com/api/identify")!)
// initial request
request.httpMethod = "GET"
// send request and process result
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else
{
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
{
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
var responseStrArray = responseString?.components(separatedBy: ",")
// response string is person's name and crime detail, connect by ","
let faceIdentStr: String = responseStrArray![0]
let crimeInfoStr: String = responseStrArray![1]
// get criminal's image from Azure Stroage Account
let imageurl:String = "https://faceimg.blob.core.windows.net/faceimgs/"+faceIdentStr
// show result in view
self.namefiled.text = faceIdentStr
self.crimefiled.text = crimeInfoStr
let url = NSURL(string: imageurl)!
let identifiedImage = try!Data(contentsOf: url as URL)
self.activityIndicator.stopAnimating()
self.activityIndicator.hidesWhenStopped = true
self.imageView.image = UIImage(data: identifiedImage)
}
task.resume()
}
// cancel button actions inside image picker
func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
imagePicker.dismiss(animated: true, completion: nil)
print("cancel picker")
}
func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
imagePicker.dismiss(animated: true, completion: nil)
}
func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
imagePicker.dismiss(animated: true, completion: nil)
imageView.image = images[0]
uploadPhoto(image: #imageLiteral(resourceName: "testImage"))
identify()
}
}
|
//
// BaseBLO.swift
// Capital Pride
//
// Created by John Cloutier on 5/4/15.
// Copyright (c) 2015 John Cloutier. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class BaseBLO: NSObject{
let svc: DBService
override init(){
let appDelegate: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
svc = appDelegate.dbService!
}
func getAllExhibitors() -> [Exhibitor]{
return svc.getEntityList("Exhibitor") as! [Exhibitor]
}
func getAllJobs() -> [Job]{
return svc.getEntityList("Job") as! [Job]
}
func getAllPerformers() -> [Performer]{
return svc.getEntityList("Performer") as! [Performer]
}
func getAllInfos() -> [Info]{
return svc.getEntityList("Info") as! [Info]
}
func getAllTechnologys() -> [Technology]{
return svc.getEntityList("Technology") as! [Technology]
}
}
|
//
// ABITuple.swift
// XDC
//
// Created by Developer on 15/06/21.
//
import Foundation
/// A Tuple is a set of sequential types encoded together
public protocol ABITupleDecodable {
static var types: [ABIType.Type] { get }
init?(values: [ABIDecoder.DecodedValue]) throws
}
public extension ABITupleDecodable {
init?(data: String) throws {
let decoded = try ABIDecoder.decodeData(data, types: Self.types)
try self.init(values: decoded)
}
}
public protocol ABITupleEncodable {
var encodableValues: [ABIType] { get }
func encode(to encoder: ABIFunctionEncoder) throws
}
public protocol ABITuple: ABIType, ABITupleEncodable, ABITupleDecodable {}
|
//
// AnalyticManagerProtocol.swift
// WavesWallet-iOS
//
// Created by rprokofev on 20.06.2019.
// Copyright © 2019 Waves Platform. All rights reserved.
//
import Foundation
public enum AnalyticManagerEvent {
case createANewAccount(CreateANewAccount)
case importAccount(ImportAccount)
case singIn(SingIn)
case walletHome(WalletHome)
case walletLeasing(WalletLeasing)
case tokenBurn(TokenBurn)
case alias(Alias)
case dex(Dex)
case send(Send)
case receive(Receive)
case wavesQuickAction(WavesQuickAction)
case profile(Profile)
case addressBook(AddressBook)
case menu(Menu)
case widgets(Widgets)
}
public protocol AnalyticManagerEventInfo {
var name: String { get }
var params: [String : String] { get }
}
public protocol AnalyticManagerProtocol {
func setAUUID(_ AUUID: String)
func trackEvent(_ event: AnalyticManagerEvent)
}
//MARK - Event params
extension AnalyticManagerEvent: AnalyticManagerEventInfo {
public var name: String {
switch self {
case .createANewAccount(let model):
return model.name
case .importAccount(let model):
return model.name
case .singIn(let model):
return model.name
case .walletHome(let model):
return model.name
case .walletLeasing(let model):
return model.rawValue
case .tokenBurn(let model):
return model.rawValue
case .alias(let model):
return model.rawValue
case .dex(let model):
return model.name
case .send(let model):
return model.name
case .receive(let model):
return model.name
case .wavesQuickAction(let model):
return model.name
case .profile(let model):
return model.name
case .addressBook(let model):
return model.name
case .menu(let model):
return model.name
case .widgets(let model):
return model.name
}
}
public var params: [String : String] {
switch self {
case .createANewAccount(let model):
return model.params
case .importAccount(let model):
return model.params
case .singIn(let model):
return model.params
case .walletHome(let model):
return model.params
case .walletLeasing( _):
return [:]
case .tokenBurn( _):
return [:]
case .alias( _):
return [:]
case .dex(let model):
return model.params
case .send(let model):
return model.params
case .receive(let model):
return model.params
case .wavesQuickAction(let model):
return model.params
case .profile(let model):
return model.params
case .addressBook(let model):
return model.params
case .menu(let model):
return model.params
case .widgets(let model):
return model.params
}
}
}
|
//
// MapSettingsView.swift
// CollegeTransit
//
// Created by Jacob Miller on 2/26/20.
// Copyright © 2020 Jacob Miller. All rights reserved.
//
import SwiftUI
struct MapSettingsView: View {
@EnvironmentObject var uPrefs: UPrefDelegate
var body: some View {
VStack {
List{
Section(header: Text("Map Interactions"), footer: Text("Map pitch allows viewing the map at an angle")){
Toggle(isOn: $uPrefs.mapCompassEnabled){
Text("Show Compass")
}
Toggle(isOn: $uPrefs.mapTrafficEnabled){
Text("Show Traffic")
}
Toggle(isOn: $uPrefs.mapAllowPitchEnabled){
Text("Allow Map Pitch")
}
}// End Section
Section(footer: Text("Configure whether only starred routes are shown are mapped on startup")){
Toggle(isOn: $uPrefs.showStarredOnStartup){
Text("Only Starred Startup")
}
}
}// End List
Spacer()
}
}
}
struct MapSettingsView_Previews: PreviewProvider {
static var previews: some View {
MapSettingsView()
}
}
|
//
// DataModel.swift
// CurrencyTracker
//
// Created by Said Çankıran on 18.09.2020.
// Copyright © 2020 Said Çankıran. All rights reserved.
//
import Foundation
class SummaryDataType:Codable {
private enum CodingKeys:String,CodingKey {
case name = "name"
case value = "value"
case type = "type"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.value = try container.decode(String.self, forKey: .value)
self.type = try container.decode(String.self, forKey: .type)
}
var name:String
var value:String
var type:String
}
class DetailDataType: Codable {
private enum CodingKeys:String,CodingKey {
case name = "name"
case buy = "buy"
case sell = "sell"
case min = "min"
case max = "max"
case type = "type"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.buy = try container.decode(String.self, forKey: .buy)
self.sell = try container.decode(String.self, forKey: .sell)
self.min = try container.decode(String.self, forKey: .min)
self.max = try container.decode(String.self, forKey: .max)
self.type = try container.decode(String.self, forKey: .type)
}
var name:String
var buy:String
var sell:String
var min:String
var max:String
var type:String
}
class BankDataType: Codable {
private enum CodingKeys:String,CodingKey {
case name = "bankName"
case buy = "buy"
case sell = "sell"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.buy = try container.decode(String.self, forKey: .buy)
self.sell = try container.decode(String.self, forKey: .sell)
}
var name:String
var buy:String
var sell:String
}
|
//
// AppDelegate.swift
// PregBuddyTweets
//
// Created by Amit Majumdar on 07/03/18.
// Copyright © 2018 Amit Majumdar. All rights reserved.
//
import UIKit
import TwitterKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func tabBarController() -> UITabBarController{
let tabBarController = UITabBarController()
let homeViewController = HomeViewController()
homeViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .featured, tag: 0)
let bookmarksViewController = BookmarksViewController()
bookmarksViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 1)
let controllers = [homeViewController, bookmarksViewController]
tabBarController.viewControllers = controllers
return tabBarController
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setupWindow()
TwitterWrapper.shared().instantiateTwitter()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
CoreDataWrapper.shared().saveContext()
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return TWTRTwitter.sharedInstance().application(app, open: url, options: options)
}
}
extension AppDelegate{
fileprivate func setupWindow(){
window = UIWindow(frame: UIScreen.main.bounds)
let signInController = SignInController()
navigationController = UINavigationController(rootViewController: signInController)
window?.rootViewController = navigationController
window?.backgroundColor = .white
window?.makeKeyAndVisible()
setupNavigationBarAppearance()
}
private func setupNavigationBarAppearance(){
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationItem.largeTitleDisplayMode = .automatic
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.black]
navigationController?.navigationBar.largeTitleTextAttributes = attributes
navigationController?.navigationBar.isTranslucent = true
} else {
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
UINavigationBar.appearance().isTranslucent = true
}
}
}
|
//
// MovieInfoTableViewCell.swift
// MovieEnvoy
//
// Created by Jerry Edens on 11/14/18.
// Copyright © 2018 Edens R&D. All rights reserved.
//
import Foundation
import UIKit
import AlamofireImage
class MovieInfoTableViewCell: UITableViewCell {
fileprivate static var baseHeight: CGFloat = 80.5
// MARK: outlets
@IBOutlet internal var posterImageView: UIImageView!
@IBOutlet internal var imageShadowView: UIView!
@IBOutlet internal var movieTitle: UILabel!
@IBOutlet internal var overview: UILabel!
@IBOutlet internal var releaseDate: UILabel!
// MARK: overrides
override func awakeFromNib() {
super.awakeFromNib()
imageShadowView.addShadow(opacity: 0.25)
posterImageView.roundCorners()
}
override func draw(_ rect: CGRect) {
let size = movieTitle.bounds.size
movieTitle.sizeToFit()
if !__CGSizeEqualToSize(size, movieTitle.bounds.size) {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
super.draw(rect)
}
// MARK: - configureation
func configure(with movie: MovieSummary) {
movieTitle.text = movie.title
releaseDate.text = "Release Date:\n\(movie.releaseDate ?? "Unknown")"
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
paragraphStyle.alignment = .left
paragraphStyle.lineBreakMode = .byTruncatingTail
overview.attributedText = NSAttributedString(string: movie.overview ?? "", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
guard let posterPath = movie.posterPath,
let path = MovieDBContext.shared.getPosterURL(for: .PosterMedium, for: posterPath),
let url = URL(string: path) else {
return
}
posterImageView.af_setImage(withURL: url)
}
// MARK: tableviewcell support
static func cellIdentifier() -> String {
return String(describing: MovieInfoTableViewCell.self)
}
}
|
//
// View+Ext.swift
// FinAccelTest
//
// Created by Ari Supriatna on 23/10/20.
//
import SwiftUI
extension View {
func navigationBarColor(backgroundColor: UIColor, tintColor: UIColor) -> some View {
self.modifier(NavigationBarColor(backgroundColor: backgroundColor, tintColor: tintColor))
}
}
|
//
// Float+Extensions
// ElementsOfProgramming
//
extension Float : MultiplicativeIdentity {
public static var multiplicativeIdentity: Float {
return 1.0
}
}
extension Float : AdditiveIdentity {
public static var additiveIdentity: Float {
return 0.0
}
}
extension Float: Halvable {
public func half() -> Float { return self / 2.0 }
}
extension Float: MultiplicativeInverse {
public func multiplicativeInverse() -> Float {
return Float.multiplicativeIdentity / self
}
}
extension Float: Norm {
public func w() -> Float {
if self < Float.additiveIdentity {
return -self
}
return self
}
}
extension Float : Addable, Subtractable, Negatable, Multipliable, Divisible, Quotient, Discrete, AdditiveInverse { }
|
//
// UIViewController.swift
// ListKitDemo
//
// Created by KingCQ on 2016/12/17.
// Copyright © 2016年 KingCQ. All rights reserved.
//
import UIKit
extension UIViewController {
func startActivity(_ dest: UIViewController, animated: Bool = true) {
dest.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(dest, animated: animated)
}
}
|
//
// ResourceViewController.swift
// Jigsaw
//
// Created by Grant Larson on 10/27/19.
// Copyright © 2019 ECE564. All rights reserved.
//
import UIKit
import Firebase
class ResourceViewController: UIViewController {
/*
var matchUserDict = [String:Int]()
*/
var teamAssignment = -1
var counter = 30
var timer = Timer()
var resource_group1 = [String]()
var questions_group1=[[String]]()
var answers_group1=[[[String]]]()
var resource_group2 = [String]()
var questions_group2=[[String]]()
var answers_group2=[[[String]]]()
var content:String?
var titleName:String?
var gameList = [game]()
var topicList = [String]()
var firstTime = true
var groupNum = 0
@IBOutlet weak var Timerlabel: UILabel!
@IBAction func cancelTimerButtonTapped(sender: Any) {
timer.invalidate()
}
// called every time interval from the timer
@objc func timerAction() {
if counter <= 0{
timer.invalidate()
counter = 30
Timerlabel.text = "Timer is up"
timer.invalidate()
self.performSegue(withIdentifier: "GoToChat", sender: self)
}
else{
counter -= 1
Timerlabel.text = "Remaining time: \(counter)"
}
}
override func prepare(for segue: UIStoryboardSegue, sender:Any?){
let ChatVC = segue.destination as! ChatViewController
ChatVC.gameList = self.gameList
ChatVC.topicList = self.topicList
timer.invalidate()
// ChatVC.matchUserDict = self.matchUserDict
}
@IBOutlet weak var TitleLabel: UILabel!
@IBOutlet weak var ResourceTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
observeMatch()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
// your code here
self.observeMatchteam()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
// your code here
let uid = Auth.auth().currentUser?.uid
/*print("0list", partnerList0)
print("1list", partnerList1)
print(uid!)*/
if partnerList0.contains(uid!){
self.teamAssignment = 0
}
else if partnerList1.contains(uid!) {
self.teamAssignment = 1
}
print("resrouce teamassign", self.teamAssignment)
if self.firstTime{
self.fetchResource()
}
self.setupGame()
self.timer.invalidate()
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true)
self.ResourceTextView.text = self.content
self.TitleLabel.text = "Topic: "+"\(self.titleName!)"
}
}
}
func observeMatch(){
Database.database().reference(fromURL: "https://jigsaw-25200.firebaseio.com/").child("match_active").observe(.childAdded, with: { (snapshot) in
let groupTemp = String(snapshot.key)
let groupInt = Int(groupTemp.dropFirst(5)) ?? 0
if groupInt > self.groupNum {
self.groupNum = groupInt
}
// self.groupNum = groupInt
}
, withCancel: nil)
// print(match_num)
}
func observeMatchteam(){
matchUserDict.removeAll()
partnerList1.removeAll()
partnerList0.removeAll()
Database.database().reference(fromURL: "https://jigsaw-25200.firebaseio.com/").child("match_active").child("match"+String(self.groupNum)).observe(.childAdded, with: { (snapshot) in
if(snapshot.key != "result"){
matchUserDict.updateValue(snapshot.value as! Int, forKey: snapshot.key)
if snapshot.value as! Int == 0{
partnerList0.append(snapshot.key)
}
else{
partnerList1.append(snapshot.key)
}
// print("snapshotend")
}
}, withCancel: nil)
// partnerList1.sort(by: >)
// partnerList0.sort(by: >)
}
//MARK: NEED TO BE FILLED IN
func SubteamAssignment()->String{
//retrieve the current team assignemnt 1 or 0
print(self.teamAssignment)
if self.teamAssignment == -1 {
return "0"
}
else {return ["0","1"][self.teamAssignment]
}
}
func fetchResource(){
// let subteam = "1"//SubteamAssignment()
//MARK: USE LOCAL MEMORY FIRST
let subteam = SubteamAssignment()
let game_group1round1=game(resource:self.resource_group1[0],questions:self.questions_group1[0],answers:self.answers_group1[0])
let game_group2round1=game(resource:self.resource_group2[0],questions:self.questions_group2[0],answers:self.answers_group2[0])
let game_group1round2=game(resource:self.resource_group1[1],questions:self.questions_group1[0],answers:self.answers_group1[0])
let game_group2round2=game(resource:self.resource_group2[1],questions:self.questions_group2[1],answers:self.answers_group2[1])
if subteam == "0" {
self.gameList=[game_group1round1,game_group1round2]
print("subteam 0")
print(gameList[0].resource)
print(gameList[1].resource)
}
else{
self.gameList=[game_group2round1,game_group2round2]
print("subteam 1")
print(gameList[0].resource)
print(gameList[1].resource)
}
}
func setupGame(){
self.titleName = self.topicList[0]
self.content = self.gameList[0].resource
}
}
|
//
// ZBarSymbolSet+Extension.swift
// TrocoSimples
//
// Created by gustavo r meyer on 8/15/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import Foundation
extension ZBarSymbolSet: Sequence
{
public typealias Element = ZBarSymbol
public typealias Iterator = NSFastEnumerationIterator
public func makeIterator() -> NSFastEnumerationIterator
{
return NSFastEnumerationIterator(self)
}
}
|
//
// AddView.swift
// MasonryScrollViewExample
//
// Created by Damien Bell on 1/4/15.
// Copyright (c) 2015 Damien Bell. All rights reserved.
//
import UIKit
class ExpandingView: UIView {
let plus_button = UIButton()
let minus_button = UIButton()
convenience override init () {
self.init(frame:CGRectZero)
self.backgroundColor = UIColor.blueColor()
plus_button.setTitle("+", forState: UIControlState.Normal)
minus_button.setTitle("-", forState: UIControlState.Normal)
plus_button.backgroundColor = UIColor.grayColor()
minus_button.backgroundColor = UIColor.grayColor()
plus_button.addTarget(self, action: "expandView:", forControlEvents: UIControlEvents.TouchUpInside)
minus_button.addTarget(self, action: "revertView:", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(plus_button)
self.addSubview(minus_button)
//Let's position our buttons centered near the bottom of the view.
plus_button.mas_makeConstraints({make in
make.height.equalTo()(44)
make.width.equalTo()(44)
make.centerX.equalTo()(self).offset()(-24)
make.bottom.equalTo()(self).offset()(-10)
return
})
minus_button.mas_makeConstraints({make in
make.height.equalTo()(44)
make.width.equalTo()(44)
make.centerX.equalTo()(self).offset()(24)
make.bottom.equalTo()(self).offset()(-10)
return
})
super.updateConstraints()
}
//In this case I'm making the width of the expandingView dependent on the superview
//Since we can't get that information without having been added to a superview then
//We won't create dimension constraints until this view has actually been added.
override func didMoveToSuperview(){
//When possible, I like to have views responsible for their own dimensions while the super.view
//is responsible for positioning them.
self.mas_makeConstraints({make in
make.height.equalTo()(300)
make.width.equalTo()(self.superview).offset()(-10)
return
})
super.updateConstraints()
}
//This method will update the height of the view to 400pts with a nice animation
func expandView(sender:UIButton!){
//We will be updating our constaints, so by all means let's set "needsUpdateConstraints"
self.setNeedsUpdateConstraints()
//Here we're going to update our vertical constraint
self.mas_updateConstraints({make in
make.height.equalTo()(400)
return
})
//We'll need to create a weak reference to superview so that we can use it in our animation block
var super_ref = super.superview
UIView.animateWithDuration(1.0, animations: {
//Each cycle in the animatin should update the layout on this view and it's super
self.layoutIfNeeded()
super_ref?.layoutIfNeeded()
}, completion: { completed in
//One more time just in case. This isn't entirely nessesary, but it helps me sleep at night.
super_ref?.layoutIfNeeded()
return
})
//Update superview's constraints so that we'll be able to update the scrollView contentSize
super.updateConstraints()
}
func revertView(sender:UIButton!){
self.setNeedsUpdateConstraints()
self.mas_updateConstraints({make in
make.height.equalTo()(300)
return
})
var super_ref = super.superview
UIView.animateWithDuration(1.0, animations: {
self.layoutIfNeeded()
super_ref?.layoutIfNeeded()
}, completion: { completed in
super_ref?.layoutIfNeeded()
return
})
super.updateConstraints()
}
}
|
//
// ViewController.swift
// snapkit_tutorial
//
// Created by 김유진 on 2021/04/22.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
lazy var greenView = { () -> UIView in
let view = UIView()
view.backgroundColor = .green
return view
}()
lazy var redView = { () -> UIView in
let view = UIView()
view.backgroundColor = .red
return view
}()
lazy var yellowView = { () -> UIView in
let view = UIView()
view.backgroundColor = .yellow
return view
}()
lazy var blueView = { () -> UIView in
let view = UIView()
view.backgroundColor = .blue
return view
}()
lazy var myButton = { (color: UIColor) -> UIButton in
let btn = UIButton(type: .system)
btn.backgroundColor = .darkGray
btn.setTitle("constraint change", for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
btn.layer.cornerRadius = 16
return btn
}
lazy var greenViewTopNSlayoutConstraint: NSLayoutConstraint? = nil
lazy var greenViewTopConstraint: Constraint? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(yellowView)
self.view.addSubview(redView)
self.view.addSubview(greenView)
self.view.addSubview(blueView)
let myDartGrayBtn = myButton(.darkGray)
self.view.addSubview(myDartGrayBtn)
// greenView.translatesAutoresizingMaskIntoConstraints = false
// redView.translatesAutoresizingMaskIntoConstraints = false
// yellowView.translatesAutoresizingMaskIntoConstraints = false
// blueView.translatesAutoresizingMaskIntoConstraints = false
// width, height, centerX, centerY 주기
// yellowView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.8).isActive = true
// yellowView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.8).isActive = true
// yellowView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
// yellowView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
// leading, trailing, top, bottom 모두 constraint주기
// yellowView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
// yellowView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
// yellowView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// yellowView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20).isActive = true
// edges = top + bottom + leading + trailing
// edges를 self.view와 똑같이 만들어라
// inset = padding
// snapKit code
yellowView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view).inset(UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20))
// make.edges.equalTo(self.view) == make.edges.equalToSuperview()
// yellowBox의 Superview가 self.view이기 때문에 두 코드는 완전히 같다.
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20))
}
// snapKit code
redView.snp.makeConstraints { (make) in
make.width.height.equalTo(100) // width, height 모두 100
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top) // safeArea의 top에 맞춰라
make.centerX.equalToSuperview() // 슈퍼뷰의 X축의 center
// make.center.equalToSuperview() // 슈퍼뷰의 정 가운데
}
// autolayout code
// redView.translatesAutoresizingMaskIntoConstraints = false
// NSLayoutConstraint.activate([
// redView.widthAnchor.constraint(equalToConstant: 100),
// redView.heightAnchor.constraint(equalToConstant: 100),
// redView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
// redView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
// ])
// snapKit code
blueView.snp.makeConstraints { (make) in
// make.width.equalTo(redView.snp.width).dividedBy(2) // 2/1배 줄이기
make.width.equalTo(redView.snp.width).multipliedBy(2) // 2배 늘이기
make.height.equalTo(redView.snp.height)
// blueView의 top을 redView의 bottom에 위치시킨다.
// offset = padding 20
make.top.equalTo(redView.snp.bottom).offset(20)
make.centerX.equalToSuperview() // X축의 중간에 위치시킨다.
}
// autolayout code
// blueView.translatesAutoresizingMaskIntoConstraints = false
// NSLayoutConstraint.activate([
// // blueView의 width를 redView의 width와 동일하게 한다. multiplier -> redView width의 2배
// blueView.widthAnchor.constraint(equalTo: self.redView.widthAnchor, multiplier: 2),
// blueView.heightAnchor.constraint(equalTo: self.redView.heightAnchor),
// blueView.topAnchor.constraint(equalTo: self.redView.bottomAnchor, constant: 20),
// blueView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
// ])
// snapKit code
myDartGrayBtn.snp.makeConstraints { (make) in
make.width.equalTo(200)
make.height.equalTo(100)
make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).inset(30)
make.centerX.equalToSuperview()
}
myDartGrayBtn.addTarget(self, action: #selector(movegreenViewDown), for: .touchUpInside)
// autolayout code
// myDartGrayBtn.translatesAutoresizingMaskIntoConstraints = false
// NSLayoutConstraint.activate([
// // blueView의 width를 redView의 width와 동일하게 한다. multiplier -> redView width의 2배
// myDartGrayBtn.widthAnchor.constraint(equalToConstant: 200),
// myDartGrayBtn.heightAnchor.constraint(equalToConstant: 100),
// myDartGrayBtn.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
// myDartGrayBtn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
// ])
// snapKit code
greenView.snp.makeConstraints { (make) in
make.width.height.equalTo(100)
make.centerX.equalToSuperview()
self.greenViewTopConstraint = make.top.equalTo(blueView.snp.bottom).offset(20).constraint
}
// greenView.translatesAutoresizingMaskIntoConstraints = false
//
// greenViewTopNSlayoutConstraint = greenView.topAnchor.constraint(equalTo: blueView.bottomAnchor, constant: 20)
//
// // autolayout code
//
// NSLayoutConstraint.activate([
// greenView.widthAnchor.constraint(equalToConstant: 100),
// greenView.heightAnchor.constraint(equalToConstant: 100),
// greenView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
// // constant = margin
// ])
// greenViewTopNSlayoutConstraint?.isActive = true
}
var offset = 0
@objc fileprivate func movegreenViewDown(){
offset += 40
print("ViewController - movegreenViewDown() called")
print("offset - \(offset)")
self.greenViewTopConstraint?.update(inset: offset)
// self.greenViewTopNSlayoutConstraint?.constant = CGFloat(offset)
}
}
#if DEBUG
import SwiftUI
struct ViewControllerRepresentable: UIViewControllerRepresentable{
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
@available(iOS 13.0.0, *)
func makeUIViewController(context: Context) -> UIViewController {
ViewController()
}
}
struct ViewControllerRepresentable_PreviewProvider: PreviewProvider{
static var previews: some View{
Group{
ViewControllerRepresentable()
.ignoresSafeArea()
.previewDisplayName("device")
.previewDevice(PreviewDevice(rawValue: "iPhone 11"))
}
}
} #endif
|
/*
ImportMapViewController.swift
Copyright 2019 Chris Brind
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import AppKit
protocol ImportMapDelegate: NSObjectProtocol {
func viewController(_ controller: ImportMapViewController, didOpenImages images: [NSImage], named: String, toRow row: Int?)
}
class ImportMapViewController: NSViewController {
@IBOutlet weak var gmImage: NSImageView!
@IBOutlet weak var playerImage: NSImageView!
@IBOutlet weak var openButton: NSButton!
@IBOutlet weak var nameField: NSTextField!
weak var delegate: ImportMapDelegate?
weak var droppedImage: NSImage?
var dropRow: Int?
override func viewDidLoad() {
super.viewDidLoad()
gmImage.image = droppedImage
}
var hasImage: Bool {
return gmImage.image != nil || playerImage.image != nil
}
var hasTitle: Bool {
return !nameField.stringValue.trimmingCharacters(in: .whitespaces).isEmpty
}
@IBAction func imageSelected(sender: Any) {
print(#function, sender)
refreshOpenButton()
}
@IBAction func selectGMImage(sender: Any) {
print(#function, sender)
let panel = createOpenPanel()
if panel.runModal() == .OK, let url = panel.url {
gmImage.image = NSImage(contentsOf: url)
imageSelected(sender: self)
}
}
@IBAction func selectPlayerImage(sender: Any) {
print(#function, sender)
let panel = createOpenPanel()
if panel.runModal() == .OK, let url = panel.url {
playerImage.image = NSImage(contentsOf: url)
imageSelected(sender: self)
}
}
@IBAction func openClicked(sneder: Any) {
let images = [gmImage.image, playerImage.image].compactMap { $0 }
delegate?.viewController(self, didOpenImages: images, named: nameField.stringValue, toRow: dropRow)
dismiss(self)
}
private func createOpenPanel() -> NSOpenPanel {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
return panel
}
private func refreshOpenButton() {
openButton.isEnabled = hasImage && hasTitle
}
}
extension ImportMapViewController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
refreshOpenButton()
}
}
|
//
// CalorieTrackerTableViewController.swift
// CalorieTracker
//
// Created by Carolyn Lea on 9/21/18.
// Copyright © 2018 Carolyn Lea. All rights reserved.
//
import UIKit
import SwiftChart
extension NSNotification.Name
{
static let shouldUpdateCell = NSNotification.Name("ShoudUpdateCell")
}
class CalorieTrackerTableViewController: UITableViewController
{
var calorie: Calorie?
var caloriesController = CaloriesController()
@IBOutlet weak var chartView: Chart!
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidLoad()
{
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(shouldUpdateCell(_:)), name: .shouldUpdateCell, object: nil)
print(caloriesController.calories)
makeChart()
}
@objc func shouldUpdateCell(_ notification: Notification)
{
tableView.reloadData()
}
func makeChart()
{
let stringArray = ["0", "6", "2", "8", "4", "7", "3", "10", "8"]
var convertedArray = [Double]()
for string in stringArray
{
let convertedString = Double(string)
convertedArray.append(convertedString!)
}
//convertedArray = stringArray.map { Double($0) ?? 0}
let result = convertedArray
let series = ChartSeries(result)
chartView.add(series)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return caloriesController.calories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "CalorieCell", for: indexPath)
let calorie = caloriesController.calories[indexPath.row]
cell.textLabel?.text = calorie.calorieAmount
let currentDate = calorie.timestamp
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, h:mm a"
let dateString = dateFormatter.string(from: currentDate!)
cell.detailTextLabel?.text = dateString
return cell
}
@IBAction func addNewRecord(_ sender: Any)
{
let alertController = UIAlertController(title: "Add Calorie Intake", message: "Enter calorie amount", preferredStyle: .alert)
var calorieTextfield: UITextField?
alertController.addTextField { (textField) in
textField.placeholder = ""
calorieTextfield = textField
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil)
let saveAction = UIAlertAction(title: "Submit", style: .default, handler: { (_) in
guard let calorie = calorieTextfield?.text else {return}
let backgroundMoc = CoreDataStack.shared.container.newBackgroundContext()
self.caloriesController.createCalorieEntry(calorieAmount: calorie, context: backgroundMoc)
let nc = NotificationCenter.default
nc.post(name: .shouldUpdateCell, object: self)
print("\(calorie)")
})
alertController.addAction(cancelAction)
alertController.addAction(saveAction)
self.present(alertController, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
let backgroundMoc = CoreDataStack.shared.container.newBackgroundContext()
let calorie = caloriesController.calories[indexPath.row]
//let calorie = fetchedResultsController.object(at: indexPath)
caloriesController.deleteCalorieEntry(calorie: calorie, context: backgroundMoc)
tableView.reloadData()
}
}
}
|
//
// Discover.swift
// PartyApp
//
// Created by Eduardo Dini on 03/05/21.
//
import SwiftUI
struct DiscoverView: View {
var body: some View {
NavigationView {
ScrollView {
VStack() {
Section(title: "Os mais populares")
Section(title: "Recomendados para você")
Section(title: "Seus amigos também curtiram")
Section(title: "Experimente algo novo")
}
.navigationTitle("Descubra")
}
}
.accentColor(.white)
}
}
struct Discover_Previews: PreviewProvider {
static var previews: some View {
DiscoverView()
}
}
struct EventCard: View {
var body: some View {
NavigationLink(destination: EventView()) {
VStack {
Spacer()
HStack {
VStack {
Text("Abr".uppercased())
.foregroundColor(.purple)
.font(.footnote)
.fontWeight(.semibold)
Text(String(format: "%02d", 1))
.font(.headline)
}
.padding(.trailing, 10)
VStack(alignment: .leading, spacing: 4) {
Text("Copa BIXO 021")
.font(.headline)
HStack {
Image(systemName: "mappin")
Text("Unicamp - 2km")
}
.foregroundColor(Color(#colorLiteral(red: 0.6000000238418579, green: 0.6000000238418579, blue: 0.6000000238418579, alpha: 1)))
.font(.caption)
}
Spacer()
Button(action: {
print("Curti")
}) {
Image(systemName: "heart")
}
.buttonStyle(PlainButtonStyle())
}
.padding(EdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16))
.background(Color.white)
}
.background(Color.gray.opacity(0.2))
.cornerRadius(14)
.padding(.bottom, 18)
.padding(.trailing, -8)
.padding(.leading)
.shadow(color: .black.opacity(0.1), radius: 10)
.frame(width: 274, height: 210)
}
.buttonStyle(PlainButtonStyle())
}
}
struct Section: View {
var title: String
var body: some View {
VStack(alignment: .leading) {
Text(title)
.font(.title2)
.fontWeight(.semibold)
.padding(.leading)
ScrollView(.horizontal, showsIndicators: false) {
HStack {
EventCard()
EventCard()
}
}
}
.padding(.top)
}
}
|
//
// HealthTrack.swift
// RPG_Health_Tracker
//
// Created by steven Hoover on 7/5/17.
// Copyright © 2017 steven Hoover. All rights reserved.
//
import Foundation
class HealthTrackd20
{
var _maxHealth : Int = 0
var _currentHealth : Int = 0
var maxHealth : Int
{
get
{
return _maxHealth
}
set
{
_maxHealth = newValue
callWatchers()
}
}
var currentHealth : Int
{
get
{
return _currentHealth
}
set
{
_currentHealth = newValue
callWatchers()
}
}
var destoryIfDepleted : Bool
var displayName : String
var watchers : [()->()] = []
var entity : HealthTrackEntity!// = CoreDataManager.singleton.grabTrackEntity()
var locationMark : Int = -1
// tens digit: 0-mainline 1-before 2-after 3-separate
// ones digit: (mainline only) 0-lethal 1-nonlethal
init( displayName : String , health : Int , destroyOnceEmpty : Bool , locationMark : Int)
{
self.displayName = displayName
destoryIfDepleted = destroyOnceEmpty
maxHealth = health
currentHealth = health
self.locationMark = locationMark
entity = CoreDataManager.singleton.grabTrackEntity()
}
init ( trackEntity: HealthTrackEntity )
{
entity = trackEntity
displayName = entity.displayName!
destoryIfDepleted = entity.destoryIfDepleted
maxHealth = Int(entity.maxHealth)
currentHealth = Int(entity.currentHealth)
locationMark = Int(entity.locationMark)
}
//MARK: - Damage
func takeDamage( damage : Action20) -> Int //return unused amount, default to zero if all is used
{
let damageValue = damage.value
if currentHealth < damage.value
{
let unused = damageValue - currentHealth
currentHealth = 0
damage.undoWatchers.append
{
self.undoAction(value: damageValue - unused, actionWasHeal: false)
}
return unused
}
else
{
currentHealth -= damageValue
damage.undoWatchers.append
{
self.undoAction(value: damageValue, actionWasHeal: false)
}
return 0
}
}
func takeExcess( damage : Action20)
{
currentHealth -= damage.value
damage.undoWatchers.append {
self.undoAction(value: damage.value, actionWasHeal: false)
}
}
//MARK: - Healing
func healFull()
{
currentHealth.addWithCeiling( maxHealth , maxHealth)
}
func healDamage( heal : Action20)
{
let healValue = heal.value
currentHealth.addWithCeiling( healValue , maxHealth)
}
func checkHealExceed(amount : Int) -> Bool
{
return amount > (maxHealth - currentHealth)
}
//MARK: - Undo
func undoAction( value: Int , actionWasHeal : Bool)
{
if actionWasHeal
{
currentHealth -= value
}
else
{
currentHealth += value
}
//callWatchers()
}
//MARK: - Display
func getHealthTrait( trait : d20HealthReturnType) -> String
{
switch trait {
case .FULL:
return "\(_currentHealth) / \(_maxHealth)"
case .AVAIL:
return "\(_maxHealth - ( _maxHealth - _currentHealth ) )"
case .DAMAGEDONE:
return "\(_maxHealth - _currentHealth)"
default:
return "\(_maxHealth)"
}
}
//MARK: - Misc
func healCeiling(amount : Int) -> Int
{
let damageTotal = maxHealth - currentHealth
return damageTotal > amount ? damageTotal : amount
}
func addWatcher( watcher: @escaping ()->() )
{
watchers.append(watcher)
}
func callWatchers()
{
watchers.forEach{ watcher in
watcher()
}
}
func damageDone() -> Int
{
//print("\(displayName) = \(_maxHealth - _currentHealth)")
return _maxHealth - _currentHealth
}
func toEntity()-> HealthTrackEntity
{
entity?.currentHealth = Int16(_currentHealth)
entity?.maxHealth = Int16(_maxHealth)
entity?.displayName = displayName
entity?.destoryIfDepleted = destoryIfDepleted
entity?.locationMark = Int16(locationMark)
return entity!
}
}
|
//: [Previous](@previous)
import Foundation
let queue = DispatchQueue(label: "com.swiftmiami.parceritos",
attributes: .concurrent)
let op1: () -> Void = {
Thread.sleep(forTimeInterval: 3)
print("Operation 1 Complete!")
}
let op2: () -> Void = {
Thread.sleep(forTimeInterval: 1)
print("Operation 2 Complete!")
}
func runSync() {
print("Started Operation 1")
queue.sync {
op1()
}
print("Started Operation 2")
queue.sync {
op2()
}
}
func runAsync() {
print("Started Operation 1")
queue.async {
op1()
}
print("Started Operation 2")
queue.async {
op2()
}
}
runSync()
//runAsync()
//: [Next](@next)
|
import Foundation
import UIKit
class List {
var color: UIColor
var name: String
var category: String
var items: [ListItem]
init(name: String, category:String, color: UIColor, items: [ListItem]) {
self.name = name
self.category = category
self.color = color
self.items = items
}
func toggleItem(index:Int) -> (fromIndex: Int, toIndex: Int) {
let listItem = items[index]
listItem.isComplete = !listItem.isComplete
items.removeAtIndex(index)
var toIndex:Int
if listItem.isComplete {
toIndex = self.items.count
} else {
toIndex = separatorIndex
}
items.insert(listItem, atIndex: toIndex)
return (index, toIndex)
}
var separatorIndex: Int {
if let firstCompleteItemIndex = indexOfFirstCompletedItem {
return firstCompleteItemIndex
}
return items.count
}
var indexOfFirstCompletedItem: Int? {
for (current, item) in enumerate(items) {
if item.isComplete {
return current
}
}
return nil
}
} |
import UIKit
protocol Persist {
func save()
}
|
import PlaygroundSupport
import UIKit
@testable import MVCMovieInfoFramework
let view = ImageWithFourLabelView(frame: CGRect(x: 0, y: 0, width: 375, height: 150))
view.firstLabel.text = "Titre"
view.secondLabel.text = "Description"
view.thirdLabel.text = "Date"
view.fourthLabel.text = "⭐️"
PlaygroundPage.current.liveView = view
|
//
// RWFramework.swift
// RWFramework
//
// Created by Joe Zobkiw on 1/25/15.
// Copyright (c) 2015 Roundware. All rights reserved.
//
import AVFoundation
import CoreLocation
import CoreMotion
import Foundation
import Promises
import Reachability
import SystemConfiguration
import UIKit
import WebKit
private let _RWFrameworkSharedInstance = RWFramework()
open class RWFramework: NSObject {
private lazy var __once: () = { () -> Void in
self.println("Submitting Listen Tags (timeToSendTheListenTags)")
self.submitListenIDsSetAsTags() // self.submitListenTags()
}()
// MARK: Properties
/// A list of delegates that conform to RWFrameworkProtocol (see RWFrameworkProtocol.swift)
open var delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects()
let motionManager = CMMotionManager()
// Location (see RWFrameworkCoreLocation.swift)
let locationManager: CLLocationManager = CLLocationManager()
var streamOptions = StreamParams(
location: CLLocation(),
panAudioBasedOnLocation: true,
minDist: nil,
maxDist: nil,
heading: nil,
angularWidth: nil,
tags: nil
)
var lastRecordedLocation: CLLocation {
return streamOptions.location
}
var letFrameworkRequestWhenInUseAuthorizationForLocation = true
/** Static project id that can be checked even offline. */
internal static var projectId: Int {
return RWFrameworkConfig.getConfigValueAsNumber("project_id").intValue
}
public let playlist = Playlist(filters: AllAssetFilters([
// only repeat assets if there's no other choice
TimedRepeatFilter(),
// skip blocked assets and users
BlockedAssetsFilter(),
// Use the first filter that definitively accepts or rejects an asset.
FirstEagerFilter([
// Either we're playing a playlist,
// DynamicTagFilter("_ten_most_recent_days", MostRecentFilter(days: 10)),
DynamicTagFilter("_ten_most_recent_days", MostRecentCountFilter(count: 20)),
// Or we should follow normal playback rules.
AllAssetFilters([
// all the tags on an asset must be in our list of tags to listen for
AnyTagsFilter(),
// if any track-level tag filters exist, apply them
TrackTagsFilter(),
// Accept an asset if it fits one nearness criteria.
AnyAssetFilters([
// if an asset is scheduled to play right now
TimedAssetFilter(),
// If an asset has a shape and we AREN'T in it, reject entirely.
AssetShapeFilter(),
// if it has no shape, consider a fixed distance from it
DistanceFixedFilter(),
// or a user-specified distance range
AllAssetFilters([DistanceRangesFilter(), AngleFilter()]),
]),
]),
]),
]), sortBy: [
SortRandomly(),
SortByLikes(),
])
public lazy var recorder = Recorder.load()
public private(set) var reachability: Reachability!
static let decoder: JSONDecoder = {
let dec = JSONDecoder()
dec.dateDecodingStrategy = .flexibleISO
return dec
}()
static let encoder: JSONEncoder = {
let enc = JSONEncoder()
enc.dateEncodingStrategy = .formatted(.iso8601Full)
return enc
}()
// Audio - Record (see RWFrameworkAudioRecorder.swift)
/// RWFrameworkAudioRecorder.swift calls code in RWFrameworkAudioRecorder.m to perform recording when true
// let useComplexRecordingMechanism = false
// public var soundRecorder: AVAudioRecorder? = nil
var soundPlayer: AVAudioPlayer?
// Media - Audio/Text/Image/Movie (see RWFrameworkMedia.swift)
// var mediaArray: Array<Media> = [Media]() {
// willSet {
// let data = NSKeyedArchiver.archivedData(withRootObject: newValue)
// RWFrameworkConfig.setConfigValue("mediaArray", value: data as AnyObject, group: RWFrameworkConfig.ConfigGroup.client)
// }
// didSet {
// rwUpdateApplicationIconBadgeNumber(mediaArray.count)
// }
// }
// Flags
var postSessionsSucceeded = false
var getProjectsIdTagsSucceeded = false {
didSet {
if getProjectsIdTagsSucceeded {
timeToSendTheListenTags = true
}
}
}
var getProjectsIdUIGroupsSucceeded = false
var getTagCategoriesSucceeded = false
var getUIConfigSucceeded = false
var timeToSendTheListenTags = false {
didSet {
if timeToSendTheListenTags {
_ = __once
}
}
}
// Timers (see RWFrameworkTimers.swift)
var audioTimer: Timer?
// Media - Upload (see RWFrameworkMediaUploader.swift)
var uploaderActive: Bool = true
var uploaderUploading: Bool = false
// Misc
var reverse_domain = "roundware.org" // This will be replaced once the config data is loaded
// MARK: - Main
/// Returns the shared instance of the framework
open class var sharedInstance: RWFramework {
return _RWFrameworkSharedInstance
}
override public init() {
super.init()
#if DEBUG
println("RWFramework is running in debug mode")
#endif
// mediaArray = loadMediaArray()
// rwUpdateApplicationIconBadgeNumber(mediaArray.count)
// setup location updates
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone // This is updated later once getProjectsIdSuccess is called
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = CLActivityType.fitness
locationManager.pausesLocationUpdatesAutomatically = true
addAudioInterruptionNotification()
}
/// Start kicks everything else off - call this to start the framework running.
/// - Parameter letFrameworkRequestWhenInUseAuthorizationForLocation: false if the caller would rather call requestWhenInUseAuthorizationForLocation() any time after rwGetProjectsIdSuccess is called.
open func start(_ letFrameworkRequestWhenInUseAuthorizationForLocation: Bool = true) {
if !compatibleOS() {
println("RWFramework requires iOS 8 or later")
} else if !hostIsReachable() {
println("RWFramework requires network connectivity")
} else {
self.letFrameworkRequestWhenInUseAuthorizationForLocation = letFrameworkRequestWhenInUseAuthorizationForLocation
playlist.start()
// Upload any pending recordings if online.
setupReachability()
}
}
/// Call this if you know you are done with the framework
open func end() {
removeAllDelegates()
println("end")
}
private func setupReachability() {
do {
reachability = try Reachability()
NotificationCenter.default.addObserver(
self,
selector: #selector(reachabilityChanged(_:)),
name: Notification.Name.reachabilityChanged,
object: reachability
)
try reachability.startNotifier()
} catch {
print("recorder: \(error)")
}
}
@objc func reachabilityChanged(_ note: NSNotification) {
// Update the badge just in case it's out of sync.
recorder.updateBadge()
let reachability = note.object as! Reachability
if reachability.connection != .unavailable {
_ = recorder.uploadPending()
_ = playlist.ensureAssetsSaved()
if reachability.connection == .wifi {
print("recorder: Reachable via WiFi")
} else {
print("recorder: Reachable via Cellular")
}
} else {
print("recorder: Not reachable")
}
}
// MARK: - AVAudioSession
func addAudioInterruptionNotification() {
NotificationCenter.default.addObserver(self,
selector: #selector(RWFramework.handleAudioInterruption(_:)),
name: AVAudioSession.interruptionNotification,
object: nil)
}
@objc func handleAudioInterruption(_ notification: Notification) {
if notification.name != AVAudioSession.interruptionNotification
|| notification.userInfo == nil {
return
}
var info = notification.userInfo!
var intValue: UInt = 0
(info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
if let type = AVAudioSession.InterruptionType(rawValue: intValue) {
switch type {
case .began:
// interruption began
println("handleAudioInterruption began")
pause()
stopPlayback()
stopRecording()
case .ended:
// interruption ended
println("handleAudioInterruption ended")
}
}
}
// MARK: - Utilities
/// Returns true if the framework is running on a compatible OS
func compatibleOS() -> Bool {
let iOS8OrLater: Bool = ProcessInfo().isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 8, minorVersion: 0, patchVersion: 0))
return iOS8OrLater
}
/// This method will try to call through to the delegate first, if not it will fall back (via rwUpdateStatus) to displaying an alert
func alertOK(_ title: String, message: String) {
rwUpdateStatus(title + ": " + message)
}
/// Shorthand for NSLocalizedString
func LS(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
/// Return the client string as "iOS 8.3" or similar
func clientSystem() -> String {
let systemName = UIDevice().systemName
let systemVersion = UIDevice().systemVersion
return "\(systemName) \(systemVersion)"
}
/// Return the preferred language of the device
func preferredLanguage() -> String {
let preferredLanguage = Locale.preferredLanguages[0] as String
let arr = preferredLanguage.components(separatedBy: "-")
if let deviceLanguage = arr.first {
return deviceLanguage
}
return "en"
}
/// Convert a Double to a String but return an empty string if the Double is 0
func doubleToStringWithZeroAsEmptyString(_ d: Double) -> String {
return (d == 0) ? "" : d.description
}
/// println when debugging
func println(_ object: Any) {
debugPrint(object)
}
/// Generic logging method
func log<T>(_ object: T) {
println(object)
}
/// Log to server
open func logToServer(_ event_type: String, data: String? = "") {
apiPostEvents(event_type, data: data).then { _ in
self.println("LOGGED TO SERVER: \(event_type)")
}.catch { error in
self.println("ERROR LOGGING TO SERVER \(error)")
}
}
/// Return true if we have a network connection
func hostIsReachable(_: String = "8.8.8.8") -> Bool {
return true
// TODO: FIX
// if let host_name = ip_address.cStringUsingEncoding(NSASCIIStringEncoding) {
// let reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, host_name).takeRetainedValue()
// var flags: SCNetworkReachabilityFlags = 0
// if SCNetworkReachabilityGetFlags(reachability, &flags) == 0 {
// return false
// }
// let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
// let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
// return (isReachable && !needsConnection)
// }
// return false
}
/// Return debug information as plain text
open func debugInfo() -> String {
var s = ""
let session_id = RWFrameworkConfig.getConfigValueAsNumber("session_id", group: RWFrameworkConfig.ConfigGroup.client).stringValue
let latitude = doubleToStringWithZeroAsEmptyString(lastRecordedLocation.coordinate.latitude)
let longitude = doubleToStringWithZeroAsEmptyString(lastRecordedLocation.coordinate.longitude)
s += "session_id = \(session_id)\n"
s += "latitude = \(latitude)\n"
s += "longitude = \(longitude)\n"
// s += "queue items = \(mediaArray.count)\n"
s += "uploaderActive = \(uploaderActive)\n"
s += "uploaderUploading = \(uploaderUploading)\n"
return s
}
/// Block a specific asset from being played again.
/// Only works in practice if a `BlockedAssetFilter` is applied.
public func block(assetId: Int) -> Promise<Void> {
return apiPostAssetsIdVotes(
assetId.description,
vote_type: "block_asset"
).then { _ in
self.playlist.updateFilterData()
}
}
public func blockUser(assetId: Int) -> Promise<Void> {
return apiPostAssetsIdVotes(
assetId.description,
vote_type: "block_user"
).then { _ in
self.playlist.updateFilterData()
}
}
}
extension DateFormatter {
static let iso8601Full: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
extension JSONDecoder.DateDecodingStrategy {
/// Attempts to decode dates with fractional seconds, then without.
static let flexibleISO = custom {
let container = try $0.singleValueContainer()
let s = try container.decode(String.self)
if let date = DateFormatter.iso8601Full.date(from: s) ?? DateFormatter.iso8601.date(from: s) {
return date
}
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Invalid date: \(s)"
)
}
}
|
//
// CountVC.swift
// Delivery Calculator
//
// Created by Тигран on 27/08/2018.
// Copyright © 2018 PetrovectorGroup. All rights reserved.
//
import UIKit
class CountVC: PageVC {
override func viewDidLoad() {
super.viewDidLoad()
}
}
|
//
// LoadedPhoto.swift
// Carmen Grid
//
// Created by Abbey Jackson on 2019-04-07.
// Copyright © 2019 Abbey Jackson. All rights reserved.
//
import UIKit
class LoadedPhoto {
let image: UIImage
var detail: PhotoDetail
init(image: UIImage, detail: PhotoDetail) {
self.image = image
self.detail = detail
}
}
|
//
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import UIKit
class ___VARIABLE_sceneName___ModuleConfigurator {
func configureModuleForViewInput<UIViewController>(viewInput: UIViewController) {
if let viewController = viewInput as? ___VARIABLE_sceneName___ViewController {
configure(viewController: viewController)
}
}
private func configure(viewController: ___VARIABLE_sceneName___ViewController) {
let router = ___VARIABLE_sceneName___Router()
router.view = viewController
let presenter = ___VARIABLE_sceneName___Presenter()
presenter.view = viewController
presenter.router = router
let interactor = ___VARIABLE_sceneName___Interactor()
interactor.output = presenter
presenter.interactor = interactor
viewController.output = presenter
}
}
|
//
// ColorPadPanelElement.swift
// ColorPads
//
// Created by Reza Shirazian on 4/6/20.
// Copyright © 2020 Reza Shirazian. All rights reserved.
//
import BlueprintUI
import BlueprintUICommonControls
struct ColorPadPanelElement: ProxyElement {
let colors: [UIColor]
let onColorChanged: (UIColor) -> Void
var elementRepresentation: Element {
guard colors.count <= 10 else {
fatalError("Too many colors")
}
let itemsPerRow = colors.count / 2
return Column { column in
column.verticalUnderflow = .growUniformly
column.horizontalAlignment = .fill
column.add(
child: Row { row in
row.horizontalUnderflow = .growUniformly
row.verticalAlignment = .fill
for index in 0..<itemsPerRow {
row.add(child:
Tappable(
onTap: {
self.onColorChanged(self.colors[index])
},
wrapping: Box(
backgroundColor: colors[index]
)
)
)
}
}
)
column.add(
child: Row { row in
row.horizontalUnderflow = .growUniformly
row.verticalAlignment = .fill
for index in itemsPerRow..<colors.count {
row.add(child:
Tappable(
onTap: {
self.onColorChanged(self.colors[index])
},
wrapping: Box(
backgroundColor: colors[index]
)
)
)
}
}
)
}
}
}
|
//
// AssetsSegmentedControl.swift
// WavesWallet-iOS
//
// Created by mefilt on 07.08.2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import UIKit
import UPCarouselFlowLayout
import InfiniteCollectionView
import DomainLayer
import Extensions
fileprivate enum Constants {
static let spacing: CGFloat = 24
static let scaleCell: CGFloat = 0.7
static let currentPageEmpty: Int = -1
static let sizeLogo = CGSize(width: 48, height: 48)
}
final class AssetsSegmentedControl: UIControl, NibOwnerLoadable {
struct Model {
struct Asset {
enum Kind {
case fiat
case wavesToken
case spam
case gateway
}
let id: String
let name: String
let kind: Kind
let icon: AssetLogo.Icon
let isSponsored: Bool
let hasScript: Bool
}
let assets: [Asset]
let currentAsset: Asset
}
@IBOutlet private var collectionView: InfiniteCollectionView!
@IBOutlet private(set) var titleLabel: UILabel!
@IBOutlet private var tickerView: TickerView!
@IBOutlet private var detailLabel: UILabel!
private var isTouchOnScrollView: Bool = false
private var assets: [Model.Asset] = [] {
didSet {
collectionView.reloadData()
}
}
private(set) var currentPage: Int = Constants.currentPageEmpty
var currentAsset: Model.Asset? {
if currentPage < 0 || currentPage >= assets.count {
return nil
}
return assets[currentPage]
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadNibContent()
}
override var backgroundColor: UIColor? {
didSet {
self.collectionView?.backgroundColor = backgroundColor
self.collectionView?.backgroundView = {
let view = UIView()
view.backgroundColor = backgroundColor
return view
}()
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.infiniteDataSource = self
collectionView.delegate = collectionView
collectionView.dataSource = collectionView
collectionView.infiniteDelegate = self
tickerView.isHidden = true
detailLabel.isHidden = true
let layout = collectionView.collectionViewLayout as! UPCarouselFlowLayout
layout.spacingMode = UPCarouselFlowLayoutSpacingMode.fixed(spacing: Constants.spacing)
layout.sideItemScale = Constants.scaleCell
collectionView.registerCell(type: AssetsSegmentedCell.self)
}
func setCurrentAsset(id: String, animated: Bool = true) {
let element = assets.enumerated().first(where: { $0.element.id == id })
guard let page = element?.offset else { return }
setCurrentPage(page, animated: animated)
}
func setCurrentPage(_ page: Int, animated: Bool = true) {
let newPage = collectionView.correctedIncorectIndex(page)
collectionView.scrollToItem(at: IndexPath(item: newPage , section: 0), at: .centeredHorizontally, animated: animated)
updateWithNewPage(page)
}
func witdthCells(by count: Int) -> CGFloat {
switch count {
case 0:
return 0
case 1:
return Constants.sizeLogo.width
default:
let smallCellsCount: CGFloat = CGFloat(count) - 1
return Constants.sizeLogo.width
+ (Constants.sizeLogo.width * Constants.scaleCell) * smallCellsCount
+ Constants.spacing * smallCellsCount
}
}
}
// MARK: Private method
fileprivate extension AssetsSegmentedControl {
var collectionPageSize: CGSize {
let layout = collectionView.collectionViewLayout as! UPCarouselFlowLayout
var pageSize = layout.itemSize
if layout.scrollDirection == .horizontal {
pageSize.width += layout.minimumLineSpacing
}
else {
pageSize.height += layout.minimumLineSpacing
}
return pageSize
}
func updateWithNewPage(_ newPage: Int) {
if newPage == currentPage {
return
}
currentPage = newPage
let asset = assets[newPage]
tickerView.isHidden = asset.kind != .spam
detailLabel.isHidden = asset.kind == .spam
titleLabel.text = asset.name
switch asset.kind {
case .fiat:
detailLabel.text = Localizable.Waves.General.Ticker.Title.fiatmoney
case .gateway:
detailLabel.text = Localizable.Waves.General.Ticker.Title.cryptocurrency
case .spam:
tickerView.update(with: .init(text: Localizable.Waves.General.Ticker.Title.spam,
style: .normal))
case .wavesToken:
detailLabel.text = Localizable.Waves.General.Ticker.Title.wavestoken
}
}
}
extension AssetsSegmentedControl: InfiniteCollectionViewDataSource {
func number(ofItems collectionView: UICollectionView) -> Int {
return assets.count
}
func collectionView(_ collectionView: UICollectionView,
dequeueForItemAt dequeueIndexPath: IndexPath,
cellForItemAt usableIndexPath: IndexPath) -> UICollectionViewCell {
let cell: AssetsSegmentedCell = collectionView.dequeueCellForIndexPath(indexPath: dequeueIndexPath)
let asset = assets[usableIndexPath.row]
let isHiddenArrow = asset.kind != .fiat || asset.kind != .gateway
let model = AssetsSegmentedCell.Model(icon: asset.icon,
isHiddenArrow: isHiddenArrow,
isSponsored: asset.isSponsored,
hasScript: asset.hasScript)
cell.update(with: model)
return cell
}
}
extension AssetsSegmentedControl: InfiniteCollectionViewDelegate {
func infiniteCollectionView(_ collectionView: UICollectionView, didSelectItemAt usableIndexPath: IndexPath, dequeueForItemAt: IndexPath) {
//TODO: need doing with animation and detect completed animation.
self.collectionView.scrollToItem(at: dequeueForItemAt, at: .centeredHorizontally, animated: false)
self.sendActions(for: .valueChanged)
}
func scrollView(_ scrollView: UIScrollView, pageIndex: Int) {
updateWithNewPage(pageIndex)
}
func scrollViewEndMoved(_ scrollView: UIScrollView, pageIndex: Int) {
sendActions(for: .valueChanged)
}
}
extension AssetsSegmentedControl: ViewConfiguration {
func update(with model: Model) {
self.assets = model.assets
currentPage = Constants.currentPageEmpty
collectionView.reloadInfinity()
setCurrentAsset(id: model.currentAsset.id, animated: false)
}
}
|
// swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
#if os(OSX)
import AppKit.NSImage
internal typealias AssetColorTypeAlias = NSColor
internal typealias AssetImageTypeAlias = NSImage
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIImage
internal typealias AssetColorTypeAlias = UIColor
internal typealias AssetImageTypeAlias = UIImage
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Asset Catalogs
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal static let icArrow = ImageAsset(name: "ic_arrow")
internal static let icEdit = ImageAsset(name: "ic_edit")
internal static let icEye = ImageAsset(name: "ic_eye")
internal static let icFacebook = ImageAsset(name: "ic_facebook")
internal static let icId = ImageAsset(name: "ic_id")
internal static let icMail = ImageAsset(name: "ic_mail")
internal static let icMastercard = ImageAsset(name: "ic_mastercard")
internal static let icMenu = ImageAsset(name: "ic_menu")
internal static let icPhone = ImageAsset(name: "ic_phone")
internal static let icScan = ImageAsset(name: "ic_scan")
internal static let icSetloc = ImageAsset(name: "ic_setloc")
internal static let icSuccess = ImageAsset(name: "ic_success")
internal static let iconCalendar = ImageAsset(name: "icon_calendar")
internal static let iconLove = ImageAsset(name: "icon_love")
internal static let iconStar = ImageAsset(name: "icon_star")
internal static let map = ImageAsset(name: "map")
internal static let photoDriver = ImageAsset(name: "photo_driver")
internal static let photoProfile = ImageAsset(name: "photo_profile")
internal static let photoUser = ImageAsset(name: "photo_user")
internal static let placeHolder = ImageAsset(name: "place_holder")
internal static let shapeStroke = ImageAsset(name: "shape_stroke")
internal static let star = ImageAsset(name: "star")
internal static let triangle = ImageAsset(name: "triangle")
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
// MARK: - Implementation Details
internal struct ColorAsset {
internal fileprivate(set) var name: String
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
internal var color: AssetColorTypeAlias {
return AssetColorTypeAlias(asset: self)
}
}
internal extension AssetColorTypeAlias {
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
convenience init!(asset: ColorAsset) {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: NSColor.Name(asset.name), bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
internal struct DataAsset {
internal fileprivate(set) var name: String
#if os(iOS) || os(tvOS) || os(OSX)
@available(iOS 9.0, tvOS 9.0, OSX 10.11, *)
internal var data: NSDataAsset {
return NSDataAsset(asset: self)
}
#endif
}
#if os(iOS) || os(tvOS) || os(OSX)
@available(iOS 9.0, tvOS 9.0, OSX 10.11, *)
internal extension NSDataAsset {
convenience init!(asset: DataAsset) {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
self.init(name: asset.name, bundle: bundle)
#elseif os(OSX)
self.init(name: NSDataAsset.Name(asset.name), bundle: bundle)
#endif
}
}
#endif
internal struct ImageAsset {
internal fileprivate(set) var name: String
internal var image: AssetImageTypeAlias {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
let image = AssetImageTypeAlias(named: name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
let image = bundle.image(forResource: NSImage.Name(name))
#elseif os(watchOS)
let image = AssetImageTypeAlias(named: name)
#endif
guard let result = image else { fatalError("Unable to load image named \(name).") }
return result
}
}
internal extension AssetImageTypeAlias {
@available(iOS 1.0, tvOS 1.0, watchOS 1.0, *)
@available(OSX, deprecated,
message: "This initializer is unsafe on macOS, please use the ImageAsset.image property")
convenience init!(asset: ImageAsset) {
#if os(iOS) || os(tvOS)
let bundle = Bundle(for: BundleToken.self)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: NSImage.Name(asset.name))
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
private final class BundleToken {}
|
//
// BuiltInImage.swift
// CIFilter.io
//
// Created by Noah Gilmore on 2/2/19.
// Copyright © 2019 Noah Gilmore. All rights reserved.
//
import UIKit
extension CIImage {
func checkerboarded() -> CIImage {
let checkerboardFilter = CIFilter(name: "CICheckerboardGenerator", parameters: [
"inputWidth": 40,
"inputColor0": CIColor.white,
"inputColor1": CIColor(color: UIColor(rgb: 0xeeeeee)),
"inputCenter": CIVector(x: 0, y: 0),
"inputSharpness": 1
])!
let sourceOverCompositingFilter = CIFilter(name: "CISourceOverCompositing")!
sourceOverCompositingFilter.setValue(checkerboardFilter.outputImage!, forKey: kCIInputBackgroundImageKey)
sourceOverCompositingFilter.setValue(self, forKey: kCIInputImageKey)
return sourceOverCompositingFilter.outputImage!
}
}
struct BuiltInImage: Identifiable {
private(set) var id = UUID()
let image: UIImage
let imageForImageChooser: UIImage
private static let checkerboardFilter = CIFilter(name: "CICheckerboardGenerator", parameters: [
"inputWidth": 40,
"inputColor0": CIColor.white,
"inputColor1": CIColor(color: UIColor(rgb: 0xeeeeee)),
"inputCenter": CIVector(x: 0, y: 0),
"inputSharpness": 1
])!
private static let sourceOverCompositingFilter = CIFilter(name: "CISourceOverCompositing")!
private static let constantColorFilter = CIFilter(name: "CIConstantColorGenerator")!
private static let linearGradientFilter = CIFilter(name: "CISmoothLinearGradient")!
private init(name: String, useCheckerboard: Bool = false) {
let uiImage = UIImage(named: name)!
image = uiImage
if useCheckerboard {
let ciImage = CIImage(image: uiImage)!
let outputImage = ciImage.checkerboarded()
let context = CIContext()
guard let cgImage = context.createCGImage(outputImage, from: ciImage.extent) else {
fatalError("Could not create built in image from ciContext")
}
imageForImageChooser = UIImage(cgImage: cgImage)
} else {
imageForImageChooser = uiImage
}
}
private init(name: String, generator: () -> (CIImage, CIImage, CGRect)) {
let context = CIContext()
let (ciImage, ciImageForImageChooser, extent) = generator()
guard let cgImage = context.createCGImage(ciImage, from: extent) else {
fatalError("Could not create built in image from ciContext")
}
let image = UIImage(cgImage: cgImage)
self.image = image
guard let cgImageForChooser = context.createCGImage(ciImageForImageChooser, from: extent) else {
fatalError("Could not create built in image from ciContext")
}
let imageForChooser = UIImage(cgImage: cgImageForChooser)
self.imageForImageChooser = imageForChooser
}
static let knighted = BuiltInImage(name: "knighted")
static let liberty = BuiltInImage(name: "liberty")
static let shaded = BuiltInImage(name: "shadedsphere")
static let paper = BuiltInImage(name: "paper", useCheckerboard: true)
static let playhouse = BuiltInImage(name: "playhouse", useCheckerboard: true)
static let black = BuiltInImage(name: "black", generator: {
BuiltInImage.constantColorFilter.setDefaults()
BuiltInImage.constantColorFilter.setValue(CIColor.black, forKey: "inputColor")
let ciImage = BuiltInImage.constantColorFilter.outputImage!
return (ciImage, ciImage, CGRect(origin: .zero, size: CGSize(width: 500, height: 500)))
});
static let white = BuiltInImage(name: "white", generator: {
BuiltInImage.constantColorFilter.setDefaults()
BuiltInImage.constantColorFilter.setValue(CIColor.white, forKey: "inputColor")
let ciImage = BuiltInImage.constantColorFilter.outputImage!
return (ciImage, ciImage, CGRect(origin: .zero, size: CGSize(width: 500, height: 500)))
});
static let gradient = BuiltInImage(name: "gradient", generator: {
BuiltInImage.linearGradientFilter.setDefaults()
BuiltInImage.linearGradientFilter.setValue(CIColor(red: 0, green: 0, blue: 0, alpha: 1), forKey: "inputColor0")
BuiltInImage.linearGradientFilter.setValue(CIColor(red: 0, green: 0, blue: 0, alpha: 0), forKey: "inputColor1")
BuiltInImage.linearGradientFilter.setValue(CIVector(x: 0, y: 250), forKey: "inputPoint0")
BuiltInImage.linearGradientFilter.setValue(CIVector(x: 500, y: 250), forKey: "inputPoint1")
let ciImage = BuiltInImage.linearGradientFilter.outputImage!
return (ciImage, ciImage.checkerboarded(), CGRect(origin: .zero, size: CGSize(width: 500, height: 500)))
});
static let all: [BuiltInImage] = [
.knighted,
.liberty,
.paper,
.playhouse,
.shaded,
.black,
.white,
.gradient
]
}
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//String opcional, puede ser string o nulo
var regaloEnvuelto:String?
//regaloEnvuelto="Definir valores"
/*
if regaloEnvuelto != nil{
var cumpleañoro:String = regaloEnvuelto! //Vamos a leer el valor
println("con valor")
}else{
println("Sin valor")
}*/
//Optional binding
if let varloRegaloEnvuelto = regaloEnvuelto{
var cumpleañoro:String = varloRegaloEnvuelto //Vamos a leer el valor
}else{
var error = "no tiene valor regaloEnvuelto";
}
|
//
// Toast.swift
// MEOKit
//
// Created by Mitsuharu Emoto on 2018/12/04.
// Copyright © 2018 Mitsuharu Emoto. All rights reserved.
//
import UIKit
/// トースター表示を行う
public class Toast: NSObject {
private var label: PaddingLabel? = nil
private let timeInterval: TimeInterval = 2.0
private let hiddenTimeInterval: TimeInterval = 1.0
private static var shared: Toast = Toast()
/// トースターを表示する
///
/// - Parameter text: メッセージ
public static func show(text:String){
Toast.shared.show(text: text)
}
/// トースターを消す
///
/// - Parameter isAnimated: アニメーション設定
public static func remove(isAnimated: Bool = false){
Toast.shared.remove(isAnimated: isAnimated)
}
private func show(text:String){
if let label = self.label, let _ = label.superview{
self.remove(isAnimated: false) {
self.show(text: text)
}
return
}
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
let w = width * 0.8
let rect = CGRect(x: 0, y: 0, width: width, height: 16)
self.label = {
let temp = PaddingLabel(frame: rect)
temp.backgroundColor = UIColor.gray
temp.textColor = UIColor.white
temp.radius = 5
temp.isRadius = true
temp.numberOfLines = 0
temp.text = text
let size = temp.sizeThatFits(CGSize(width: w, height: height * 0.8))
temp.frame = CGRect(x: (width - size.width)/2.0,
y: height - size.height - 40,
width: size.width,
height: size.height)
return temp
}()
if let label = self.label{
var view: UIView? = nil
if let vc = UIViewController.forefront(){
view = vc.view
}else if let window = UIApplication.shared.keyWindow{
view = window
}
if let v = view{
v.addSubview(label)
DispatchQueue.main.asyncAfter(deadline: .now() + self.timeInterval) {
self.remove(isAnimated: true)
}
}
}
}
private func remove(isAnimated:Bool = true, completion:(()->())? = nil) {
guard let label = self.label, let _ = label.superview else {
return
}
var dur = 0.0
if isAnimated{
dur = self.hiddenTimeInterval
}
UIView.animate(withDuration: dur,
animations: {
label.alpha = 0.0
}) { (completed) in
label.removeFromSuperview()
if let cmp = completion{
cmp()
}
}
}
}
|
import Cocoa
import Metal
open
class Picture: NSObject, MetalInput {
public init(image: NSImage) {
texture = image.texture(device: context!.device)
}
public func addOutput(_ output: MetalOutput) {
self.output = output
self.output?.input = self
}
public var context: MetalContext? = MetalContext()
public var output: MetalOutput?
public var texture: MTLTexture?
}
|
//
// RepoItem.swift
// passpie-ios
//
// Created by Harjas Monga on 2/24/18.
// Copyright © 2018 Harjas Monga. All rights reserved.
//
import Foundation
class RepoItem {
var fileName: String
var type: String
var downloadURL: URL?
var path: String
init(repoDicitonary: [String: Any]) {
fileName = repoDicitonary["name"] as! String
type = repoDicitonary["type"] as! String
let downloadURLString = repoDicitonary["download_url"] as? String ?? ""
downloadURL = URL(string: downloadURLString)
path = repoDicitonary["path"] as? String ?? ""
}
}
|
//
// ChartViewController.swift
// MyDeliveries2
//
// Created by Douglas Maltby on 3/1/20.
// Copyright © 2020 SAP. All rights reserved.
//
import UIKit
// add SA Fiori libraries
import SAPFoundation
import SAPFiori
import SAPCommon
// Change subclass from iOS UIViewController to FUIChartFloorplanViewController
// class ChartViewController: UIViewController {
class ChartViewController: FUIChartFloorplanViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Waiting Time"
chartView.chartType = .bar
chartView.dataSource = self
summaryView.dataSource = self
titleText.text = "Duration"
status.text = "Tap chart for details"
categoryAxisTitle.text = "Location"
valuesAxisTitle.text = "Waiting time in hours"
}
// MARK: - Sample Data
let chartSeriesTitles = ["Actual", "Target"]
let chartCategoryTitles = ["Shipment picked up", "HONG-KONG", "AMSTERDAM", "LONDON-HEATHROW", "READING", "Delivered"]
let chartData = [[2.0, 42.0, 32.0, 7.0, 5.0, 1.0]]
// Do any additional setup after loading the view.
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
// MARK: - Formatters
private extension ChartViewController {
private static let measurementFormatter: MeasurementFormatter = {
let formatter = MeasurementFormatter()
formatter.numberFormatter.maximumFractionDigits = 0
formatter.unitOptions = .providedUnit
formatter.unitStyle = .long
return formatter
}()
private static let numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 0
return formatter
}()
}
// MARK: - FUIChartSummaryDataSource implementation
extension ChartViewController: FUIChartSummaryDataSource {
func chartView(_ chartView: FUIChartView, summaryItemForCategory categoryIndex: Int) -> FUIChartSummaryItem? {
let item = FUIChartSummaryItem()
item.categoryIndex = categoryIndex
item.isPreservingTrendHeight = false
switch categoryIndex {
case -1:
item.isEnabled = false
let values: [Measurement<UnitDuration>] = chartView.series.compactMap { series in
let categoriesUpperBound = series.numberOfValues - 1
guard let valuesInSeries = series.valuesInCategoryRange(0...categoriesUpperBound, dimension: 0) else { return nil }
let hours = valuesInSeries.lazy.compactMap { $0 }.reduce(0.0, +)
return Measurement(value: hours, unit: UnitDuration.hours)
}
item.valuesText = values.map { ChartViewController.measurementFormatter.string(from: $0) }
item.title.text = "Total wait time"
default:
item.isEnabled = true
let values = chartView.series.map { $0.valueForCategory(categoryIndex, dimension: 0)! }
item.valuesText = values.map { ChartViewController.numberFormatter.string(for: $0)! }
item.title.text = chartCategoryTitles[categoryIndex]
}
return item
}
}
// MARK: - FUIChartViewDataSource implementation
extension ChartViewController: FUIChartViewDataSource {
func numberOfSeries(in: FUIChartView) -> Int {
return chartData.count
}
func chartView(_ chartView: FUIChartView, numberOfValuesInSeries seriesIndex: Int) -> Int {
return chartData[seriesIndex].count
}
func chartView(_ chartView: FUIChartView, valueForSeries seriesIndex: Int, category categoryIndex: Int, dimension dimensionIndex: Int) -> Double? {
return chartData[seriesIndex][categoryIndex]
}
func chartView(_ chartView: FUIChartView, formattedStringForValue value: Double, axis: FUIChartAxisId) -> String? {
return ChartViewController.numberFormatter.string(for: value)!
}
func chartView(_ chartView: FUIChartView, titleForCategory categoryIndex: Int, inSeries seriesIndex: Int) -> String? {
return chartCategoryTitles[categoryIndex]
}
}
|
//
// StringExtensions.swift
// appstoreSearch
//
// Created by Elon on 17/03/2019.
// Copyright © 2019 Elon. All rights reserved.
//
import UIKit
extension String {
/**
정규식을 통해 문자열이 한글만 있는지 확인한다.(공백허용)
- Returns: 허용된 경우 true
*/
func isHangul() -> Bool {
let regex = "^[ㄱ-ㅎㅏ-ㅣ가-힣\\s]{1,}"
return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: self)
}
/**
파라미터로 넘어온 문자열이 자신의 문자열들과 일치하는지 확인한다.
- Parameters: 확인할 문자열
- Returns: 앞이 일치하는지 여부
*/
func hasCaseInsensitivePrefix(_ string: String) -> Bool {
return prefix(string.count).caseInsensitiveCompare(string) == .orderedSame
}
/**
문자열에 자모가 존재할 경우 제거
(ex: "카카오ㅌ" -> "카카오")
- Returns: 자모가 제거된 문자열
*/
func removeJamo() -> String {
let jamo: [Character] = [
"ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ",
"ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ",
"ㄳ","ㄵ","ㄶ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅄ",
"ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ","ㅕ", "ㅖ", "ㅗ", "ㅘ",
"ㅙ", "ㅚ","ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ",
"ㅣ"
]
var result: String = ""
for case let unit in Array(self) where !jamo.contains(unit) {
result.append(unit)
}
return result
}
var insertComma: String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.groupingSeparator = ","
var numberArray = self.components(separatedBy: ".")
if numberArray.count == 1 {
let numberString = numberArray[0].replacingOccurrences(of: ",", with: "")
guard let doubleValue = Double(numberString) else { return self }
return numberFormatter.string(from: NSNumber(value: doubleValue)) ?? self
} else if numberArray.count == 2 {
let numberString = numberArray[0]
guard let doubleValue = Double(numberString) else { return self }
return (numberFormatter.string(from: NSNumber(value: doubleValue)) ?? numberString) + ".\(numberArray[1])"
}else{
guard let doubleValue = Double(self) else { return self }
return numberFormatter.string(from: NSNumber(value: doubleValue)) ?? self
}
}
/**
## bold
- Parameter size: 폰트 크기
- Parameter color: 폰트 컬러
*/
func bold(size fontSize: CGFloat, color: UIColor? = nil) -> NSMutableAttributedString {
var attributes: [NSAttributedString.Key : Any] = [
.font: UIFont.boldSystemFont(ofSize: fontSize),
]
if let fontColor = color {
attributes[.foregroundColor] = fontColor
}
let attributeFont = NSMutableAttributedString(string: self, attributes: attributes)
return attributeFont
}
/**
## light
- Parameter size: 폰트 크기
- Parameter color: 폰트 컬러
*/
func light(size fontSize: CGFloat, color: UIColor? = nil) -> NSMutableAttributedString {
var attributes: [NSAttributedString.Key : Any] = [
.font: UIFont.systemFont(ofSize: fontSize, weight: .light),
]
if let fontColor = color {
attributes[.foregroundColor] = fontColor
}
let attributeFont = NSMutableAttributedString(string: self, attributes: attributes)
return attributeFont
}
/**
## 문자열 폰트 속성
- Parameter size: 폰트 크기
- Parameter weight: 폰트 패밀리는 폰트 크기를 반드시 넣어야 적용됨.
- Parameter color: 폰트 컬러
*/
func attribute(size: CGFloat? = nil, weight: UIFont.Weight? = nil, color: UIColor? = nil) -> NSMutableAttributedString {
var attributes = [NSAttributedString.Key : Any]()
if let fontSize = size {
attributes[.font] = UIFont.systemFont(ofSize: fontSize)
}
if let fontSize = size, let fontWeight = weight {
attributes[.font] = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
}
if let fontColor = color {
attributes[.foregroundColor] = fontColor
}
let attributeFont = NSMutableAttributedString(string: self, attributes: attributes)
return attributeFont
}
}
|
// main.swift
// EchoServer sample programm
// Simplenet
// Copyright (c) 2018 Vladimir Raisov. All rights reserved.
// Licensed under MIT License
import Dispatch
import Sockets
import Interfaces
import Transceiver
let stopsem = DispatchSemaphore(value: 0)
func stop(_: Int32) {
print("\rReceiver terminated.")
stopsem.signal()
}
struct Echo: DatagramHandler {
func dataDidRead(_ datagram: Datagram) {
let data = datagram.data
print("\(data.count) bytes received", terminator: "")
datagram.sender.map{print(" from \($0)", terminator: "")}
(datagram.interface?.name).map{print(" over interface \($0)", terminator: "")}
print(":")
String(data: datagram.data, encoding: String.Encoding.utf8).map{print($0)}
do {
try datagram.reply(with: datagram.data)
} catch {
self.errorDidOccur(error)
}
}
func errorDidOccur(_ error: Error) {
print(error)
}
}
let args = CommandLine.arguments
let arg1 = args.dropFirst().first
let arg2 = args.dropFirst().dropFirst().first
let arg3 = args.dropFirst().dropFirst().dropFirst().first
let rest = args.dropFirst().dropFirst().dropFirst().dropFirst().first
func findInterface(_ name: String) -> Interface {
guard let interface = (Interfaces().first{$0.name == name}) else {
print("Invalid value \"\(name)\" for <interface-name> parameter")
print("Use `ifconfig` to view interface names")
exit(2)
}
return interface
}
do {
var receiver: Receiver
switch (arg1, arg1.flatMap(UInt16.init), arg2.flatMap(UInt16.init), arg2, arg3, rest) {
case (.some(let group), .none, .some(let port), _, let iname, .none):
let interface = iname.flatMap(findInterface)
receiver = try Receiver(port: port, multicast: group, interface: interface)
case (_, .some(let port), .none, let iname, .none, _):
let interface = iname.flatMap(findInterface)
receiver = try Receiver(port: port, interface: interface)
default:
let cmd = String(args.first!.reversed().prefix{$0 != "/"}.reversed())
print("usage: \(cmd) [<multicast-address>] <port> [<interfaces-bsdname>]")
exit(1)
}
print("Receiver has been created.")
receiver.delegate = Echo()
print("Press Ctrl-C to exit")
signal(SIGINT, stop) // Ctrl-C
signal(SIGQUIT, stop) // Ctrl-\
signal(SIGTSTP, stop) // Ctrl-Z
stopsem.wait()
} catch {
print(error)
print("Receiver can't be created.")
exit(1)
}
|
//
// MapViewModel.swift
// Fast Foodz
//
// Created by Yoseob Lee on 4/2/20.
//
import CoreLocation
import Foundation
import RxCocoa
import RxSwift
class MapViewModel {
let output$ = PublishSubject<Output>()
let input$ = PublishSubject<Input>()
var shouldShowUserLocation: Bool {
return locationManager.isLocationEnabled
}
private(set) var initialLocation = CLLocation()
private(set) var restaurants = [Restaurant]()
private let disposeBag = DisposeBag()
private let locationManager: LocationManager
init(locationManager: LocationManager = LocationManager.shared) {
self.locationManager = locationManager
configureBindings()
}
func didSelectRestaurant(_ restaurant: Restaurant) {
output$.onNext(.didSelectRestaurant(restaurant))
}
private func configureBindings() {
input$
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] input in
switch input {
case .restaurantsDidChange(let restaurants):
self?.restaurants = restaurants
case .centerOnLocation(let location):
self?.initialLocation = location
}
})
.disposed(by: disposeBag)
}
}
// MARK: - Rx
extension MapViewModel {
enum Output {
case didSelectRestaurant(Restaurant)
}
enum Input {
case centerOnLocation(CLLocation)
case restaurantsDidChange([Restaurant])
}
}
|
//
// Double+CurrencyFormatter.swift
// Bank App
//
// Created by Chrystian on 17/01/19.
// Copyright © 2019 Salgado's Productions. All rights reserved.
//
import Foundation
import UIKit
extension Double {
func toString() -> String {
return String(self)
}
func toStringCurrency() -> String {
let currencyFormat: String = NSLocalizedString("CURRENCY_FORMAT", comment: "currency")
var stringFormated: String = currencyFormat
let stringValue = String(format: "%.2f", self)
for letter in stringValue {
if letter == "." {
stringFormated.append(",")
}
else if letter != "-" {
stringFormated.append(letter)
}
}
if stringValue.contains("-") {
return "-\(stringFormated)"
}
else {
return "\(stringFormated)"
}
}
}
|
//
// ZXDiscoverModel.swift
// YDHYK
//
// Created by screson on 2017/11/3.
// Copyright © 2017年 screson. All rights reserved.
//
import UIKit
/// 发现列表Model
@objcMembers class ZXDiscoverModel: NSObject {
/**资讯ID*/
var promotionId = ""
/**标题*/
var title = ""
/**图片地址*/
var homeIcon = ""//相对地址
/**图片地址*/
var homeIconStr = ""
/**图片类型 1 小图 2大图*/
var homeIconType = 1// 1 小图 2 大图
/**图片地址*/
var groupName = ""
/**资讯类型 1促销 2资讯 3广告*/
var promotionType = 1//1 2 3
var promotionTypeStr = ""
/**Content 详情接口内容*/
var content = ""
var sendDateStr = ""
override static func mj_replacedKeyFromPropertyName() -> [AnyHashable : Any]! {
return ["promotionId": "id"]
}
//调整
var zx_publishDate: String {
get {
return sendDateStr.components(separatedBy: " ").first ?? ""
}
}
}
|
//
// PageMenuController.swift
// Swift_Project
//
// Created by HongpengYu on 2018/6/25.
// Copyright © 2018年 HongpengYu. All rights reserved.
//
import UIKit
class PageMenuController: UIViewController {
let menuItemHeight: CGFloat = 50
let menuItemWidth: CGFloat = 100
var controllers: [UIViewController] = []
override func viewDidLoad() {
super.viewDidLoad()
setupConstraint()
addSubControllers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
init(controllers: [UIViewController], frame: CGRect) {
super.init(nibName: nil, bundle: nil)
self.controllers = controllers
self.view.frame = frame
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addSubControllers() {
menuScrollView.contentSize = CGSize(width: menuItemWidth * CGFloat(controllers.count), height: menuItemHeight)
for controller in controllers {
}
}
private func setupConstraint() {
view.addSubview(menuScrollView)
menuScrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: menuScrollView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: menuScrollView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1.0, constant: menuItemHeight).isActive = true
view.addSubview(controllersScrollView)
controllersScrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: controllersScrollView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: controllersScrollView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0).isActive = true
}
// MARK: - Lazy
private lazy var menuScrollView: UIScrollView = {
let menuScrollView = UIScrollView()
menuScrollView.isPagingEnabled = true
menuScrollView.alwaysBounceHorizontal = true
menuScrollView.bounces = true
menuScrollView.showsVerticalScrollIndicator = true
menuScrollView.showsHorizontalScrollIndicator = true
menuScrollView.backgroundColor = .blue
return menuScrollView
}()
private lazy var controllersScrollView: UIScrollView = {
let controllersScrollView = UIScrollView()
controllersScrollView.isPagingEnabled = true
controllersScrollView.alwaysBounceHorizontal = true
controllersScrollView.bounces = true
controllersScrollView.showsVerticalScrollIndicator = true
controllersScrollView.showsHorizontalScrollIndicator = true
menuScrollView.backgroundColor = .green
return controllersScrollView
}()
}
|
//
// MyProject
// Copyright (c) Yuichi Nakayasu. All rights reserved.
//
import UIKit
class Builder {
func main() -> MainViewController {
let view = instantiate(MainViewController.self, storyboardName: "Main")
let presenter: MainPresenterProtocol = MainPresenter()
presenter.view = view
let interactor: MainInteractorInput = MainRepository()
interactor.output = presenter as? MainInteractorOutput
presenter.interactor = interactor
view.presenter = presenter
return view
}
func eventEdit() -> EventEditViewController {
let view = instantiate(EventEditViewController.self, storyboardName: "EventEdit")
let presenter: EventEditPresenterProtocol = EventEditPresenter()
presenter.view = view
let interactor: EventEditInteractorInput = EventEditRepository()
interactor.output = presenter as? EventEditInteractorOutput
presenter.interactor = interactor
view.presenter = presenter
return view
}
func drawerMenu() -> DrawerMenuViewController {
let view = instantiate(DrawerMenuViewController.self, storyboardName: "DrawerMenu")
return view
}
func launch() -> LaunchViewController {
let view = instantiate(LaunchViewController.self, storyboardName: "Launch")
let presenter: LaunchPresenterProtocol = LaunchPresenter()
presenter.view = view
let interactor: LaunchInteractorInput = LaunchRepository()
interactor.output = presenter as? LaunchInteractorOutput
presenter.interactor = interactor
view.presenter = presenter
return view
}
func tutorial() -> TutorialViewController {
let view = instantiate(TutorialViewController.self, storyboardName: "Tutorial")
return view
}
func terms() -> TermsViewController {
let view = instantiate(TermsViewController.self, storyboardName: "Terms")
let presenter: TermsPresenterProtocol = TermsPresenter()
presenter.view = view
view.presenter = presenter
return view
}
func designFontSetting() -> DesignFontSettingViewController {
let view = instantiate(DesignFontSettingViewController.self, storyboardName: "DesignFontSetting")
let presenter: DesignFontSettingPresenterProtocol = DesignFontSettingPresenter()
presenter.view = view
let interactor: DesignFontSettingInteractorInput = DesignFontSettingRepository()
interactor.output = presenter as? DesignFontSettingInteractorOutput
presenter.interactor = interactor
view.presenter = presenter
return view
}
func todoList() -> TodoListViewController {
let view = instantiate(TodoListViewController.self, storyboardName: "TodoList")
let presenter: TodoListPresenterProtocol = TodoListPresenter()
presenter.view = view
let interactor: TodoInteractorInput = TodoRepositoryMock()//TodoRepository()
interactor.output = presenter as? TodoInteractorOutput
presenter.interactor = interactor
view.presenter = presenter
return view
}
func todoDetail(todo: TodoModel?) -> TodoDetailViewController {
let view = instantiate(TodoDetailViewController.self, storyboardName: "TodoDetail")
view.todo = todo
let presenter: TodoDetailPresenterProtocol = TodoDetailPresenter()
presenter.view = view
let interactor: TodoInteractorInput = TodoRepositoryMock()//TodoRepository()
interactor.output = presenter as? TodoInteractorOutput
presenter.interactor = interactor
view.presenter = presenter
return view
}
func web(urlString: String) -> WebViewController {
let view = instantiate(WebViewController.self, storyboardName: "Web")
view.initialUrlString = urlString
let presenter: WebPresenterProtocol = WebPresenter()
presenter.view = view
view.presenter = presenter
return view
}
func datePicker(dateTime: Date, title: String, commitHandler: @escaping DatePickerViewController.CommitHandler) -> DatePickerViewController {
let view = instantiate(DatePickerViewController.self, storyboardName: "DatePicker")
view.title = title
view.dateTime = dateTime.fixed(second: 0) // 秒は不要
view.commitHandler = commitHandler
let presenter: DatePickerPresenterProtocol = DatePickerPresenter()
presenter.view = view
let interactor: DatePickerInteractorInput = DatePickerRepository()
interactor.output = presenter as? DatePickerInteractorOutput
presenter.interactor = interactor
view.presenter = presenter
return view
}
func locationSearch(location: String, title: String, commitHandler: @escaping LocationSearchViewController.CommitHandler) -> LocationSearchViewController {
let view = instantiate(LocationSearchViewController.self, storyboardName: "LocationSearch")
view.title = title
view.initialText = location
view.commitHandler = commitHandler
return view
}
func text(options: TextViewControllerOptions, handler: @escaping (String) -> ()) -> TextViewController {
let view = instantiate(TextViewController.self, storyboardName: "Text")
view.options = options
view.handler = handler
return view
}
func test() -> TestViewController {
let view = instantiate(TestViewController.self, storyboardName: "Test")
return view
}
}
extension Builder {
private func instantiate<T>(_ type: T.Type, storyboardName: String, identifier: String? = nil) -> T where T : UIViewController {
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
if let id = identifier {
guard let viewController = storyboard.instantiateViewController(withIdentifier: id) as? T else {
fatalError("failed instantiate viewController")
}
return viewController
} else {
guard let viewController = storyboard.instantiateInitialViewController() as? T else {
fatalError("failed instantiate viewController")
}
return viewController
}
}
}
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Combine
import Common
import CoreGraphics
import Domain
import ImageIO
struct SelectableImage {
let imageUrl: URL
let imageSize: CGSize
var isValid: Bool {
return self.imageSize.height != 0
&& self.imageSize.width != 0
&& self.imageSize.height > 10
&& self.imageSize.width > 10
}
// MARK: - Lifecycle
static func make(by url: URL, using session: URLSession) -> AnyPublisher<Self, Never> {
let request: URLRequest
if let provider = WebImageProviderPreset.resolveProvider(by: url),
provider.shouldModifyRequest(for: url)
{
request = provider.modifyRequest(URLRequest(url: url))
} else {
request = URLRequest(url: url)
}
return session
.dataTaskPublisher(for: request)
.map { data, _ -> SelectableImage? in
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
guard
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?,
let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as? CGFloat,
let pixelHeight = imageProperties[kCGImagePropertyPixelHeight] as? CGFloat
else {
return nil
}
return SelectableImage(imageUrl: url,
imageSize: CGSize(width: pixelWidth, height: pixelHeight))
}
.catch { _ -> AnyPublisher<SelectableImage?, Never> in
RootLogger.shared.write(ConsoleLog(level: .info, message: "Failed to resolve size at \(url)"))
return Just(SelectableImage?.none)
.eraseToAnyPublisher()
}
.compactMap { $0 }
.eraseToAnyPublisher()
}
}
|
//
// TodoList.swift
// todo-app-ios
//
// Created by Arkadii Ivanov on 22/02/2020.
// Copyright © 2020 arkivanov. All rights reserved.
//
import SwiftUI
import TodoLib
struct TodoList: View {
@ObservedObject var listView = TodoListViewImpl()
var body: some View {
List(listView.model?.items ?? []) { item in
TodoRow(
text: item.data.text,
isDone: item.data.isDone,
onDoneClicked: { self.listView.dispatch(event: TodoListViewEvent.ItemDoneClicked(id: item.id)) },
onDeleteClicked: { self.listView.dispatch(event: TodoListViewEvent.ItemDeleteClicked(id: item.id)) }
)
}
}
}
struct TodoList_Previews: PreviewProvider {
static var previews: some View {
TodoList()
}
}
|
//
// HoneymoonCustomCollectionViewCell.swift
// TheHoneymoonPlanner
//
// Created by Jerry haaser on 2/4/20.
// Copyright © 2020 Jonalynn Masters. All rights reserved.
//
import UIKit
class HoneymoonCustomCollectionViewCell: UICollectionViewCell {
var wishlist: Wishlist?
var wishlists: [Wishlist] = []
var activty: Activity?
var activities: [Activity] = []
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var vacationNameLabel: UILabel!
@IBOutlet weak var wishlistLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
vacationNameLabel.text = ""
wishlistLabel.text = ""
priceLabel.text = ""
}
func updateViews() {
guard activty != nil else { return }
//TODO: change all this
imageView.image = nil
vacationNameLabel.text = "Something Here"
wishlistLabel.text = "Wishlist Check Count"
priceLabel.text = ""
}
func setImage(_ image: UIImage?) {
imageView.image = image
}
var vacation: Vacation? {
didSet {
updateViews()
}
}
}
|
//
// GetVC.swift
// FacebookAppPermissions
//
// Created by Aaron Miller on 1/22/18.
// Copyright © 2018 Aaron Miller. All rights reserved.
//
import UIKit
struct WebsiteDescription: Decodable{
let name: String
let description: String
let courses: [Course]//this is how the array happens
}
//making the props optionals will allow for possible missing fields
struct Course: Decodable {
let id: Int?
let name: String?
let link: String?
let imageUrl: String?
}
//****** from the link "https://jsonplaceholder.typicode.com/users"
struct User: Decodable{
let id: Int?
let name: String?
let username: String?
let email: String?
let address: Adress?
let phone: String?
let website: String?
let company: Company?
}
struct Adress: Decodable {
let street: String?
let suite: String?
let city: String?
let zipcode: String?
let geo: Geo?
}
struct Geo: Decodable{
let lat: String?
let lng: String?
}
struct Company: Decodable {
let name: String?
let catchPhrase: String?
let bs: String?
}
class GetVC: UIViewController {
var fistName: String?
var lastName: String?
var email: Any?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func unwrapData(link: String){
//https://jsonplaceholder.typicode.com/users
guard let url = URL(string: link) else {return}
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
//**************
switch link{
//getTheInfo
// case "https://jsonplaceholder.typicode.com/users":
// let json = try JSONSerialization.jsonObject(with: data, options: [])
// print(json, "json")
// break
//getSimpleDecode
case "https://api.letsbuildthatapp.com/jsondecodable/course":
let course = try JSONDecoder().decode(Course.self, from: data)
print(course)
print(course.name!)
break
//getArraySimpleDecode
case "https://api.letsbuildthatapp.com/jsondecodable/courses":
let courses = try JSONDecoder().decode([Course].self, from: data)
//print(courses, "courses")
print(courses[1].name!)
break
//getArrayUnwrapDecode
case "https://api.letsbuildthatapp.com/jsondecodable/website_description":
let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
print(websiteDescription.name, websiteDescription.description)
break
//getMissingFields
case "https://api.letsbuildthatapp.com/jsondecodable/courses_missing_fields":
let courses = try JSONDecoder().decode([Course].self, from: data)
let cell = 2
if courses[cell].id != nil {
print(courses[cell].name!, courses[cell].id!)
}else{
print(courses[cell].name!, "The id was nil")
}
break
//getWrappedArray -- All A
case "https://jsonplaceholder.typicode.com/users":
let users = try JSONDecoder().decode([User].self, from: data)
print("latitude for user 1: \(users[0].address!.geo!.lat!)")
print(users[0].id!)
break
default:
print("A unspecified link was inputed")
}
//**************
}catch{
print(error, "error")
}
}
}.resume()
}
//this is about to be out of order
@IBAction func getTheInfo(_ sender: Any) {
unwrapData(link: "https://jsonplaceholder.typicode.com/users")
print("getArrayDecode - GetVC.swift")
}
@IBAction func getSimpleDecode(_ sender: Any) {
unwrapData(link: "https://api.letsbuildthatapp.com/jsondecodable/course")
print("getSimpleDecode - GetVC.swift")
}
@IBAction func getArraySimpleDecode(_ sender: Any) {
unwrapData(link: "https://api.letsbuildthatapp.com/jsondecodable/courses")
print("getArraySimpleDecode - GetVC.swift")
}
@IBAction func getArrayUnwrapDecode(_ sender: Any) {
unwrapData(link: "https://api.letsbuildthatapp.com/jsondecodable/website_description")
print("getArrayUnwrapDecode - GetVC.swift")
}
@IBAction func getMissingFields(_ sender: Any) {
unwrapData(link: "https://api.letsbuildthatapp.com/jsondecodable/courses_missing_fields")
print("getMissingFields - GetVC.swift")
}
//try to decode here
@IBAction func getWrappedArray(_ sender: Any) {
unwrapData(link: "https://jsonplaceholder.typicode.com/users")
print("getWrappedArray - GetVC.swift")
}
}
|
//
// Data.swift
// ChikaContactList
//
// Created by Mounir Ybanez on 2/14/18.
// Copyright © 2018 Nir. All rights reserved.
//
import ChikaUI
import ChikaCore
protocol Data {
var itemCount: Int { get }
func itemAt(_ index: Int) -> Item?
func indexes(withContactIDs contactIDs: [ID]) -> [Int]
func refreshItems(withNewList list: [Contact])
@discardableResult
func updatePresenceStatus(with presence: Presence) -> Int?
}
struct Item {
var contact: Contact
var isActive: Bool
init() {
contact = Contact()
isActive = false
}
func toCellItem() -> ContactTableViewCellItem {
var cellItem = ContactTableViewCellItem()
cellItem.isActive = isActive
cellItem.avatarURL = contact.person.avatarURL
cellItem.displayName = contact.person.displayName
return cellItem
}
}
class DataProvider: Data {
var items: [Item]
var itemCount: Int {
return items.count
}
init() {
self.items = []
}
func itemAt(_ index: Int) -> Item? {
guard index >= 0, index < itemCount else {
return nil
}
return items[index]
}
func indexes(withContactIDs contactIDs: [ID]) -> [Int] {
var indexes: [Int] = []
items.enumerated().forEach { item in
guard contactIDs.contains(item.element.contact.person.id) else {
return
}
indexes.append(item.offset)
}
return indexes
}
func refreshItems(withNewList list: [Contact]) {
items = list.map({ contact in
var item = Item()
item.contact = contact
return item
})
}
@discardableResult
func updatePresenceStatus(with presence: Presence) -> Int? {
guard let index = items.index(where: { $0.contact.person.id == presence.personID }) else {
return nil
}
items[index].isActive = presence.isActive
return index
}
}
|
//
// DetailScreenObject.swift
// TravelstartInterviewPractice
//
// Created by 潘立祥 on 2019/11/5.
// Copyright © 2019 PanLiHsiang. All rights reserved.
//
import Foundation
struct DetailInfo {
let title: String
let description: String
}
|
//
// ViewController.swift
// RxSwift_MashUp
//
// Created by rookie.w on 2020/04/29.
// Copyright © 2020 rookie.w. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class SignUpController: UIViewController {
let disposeBag = DisposeBag()
let viewModel = SignUpViewModel()
@IBOutlet weak var MemberTypeLabel: UILabel!
@IBOutlet weak var idTextField: UITextField!
@IBOutlet weak var invalidId: UILabel!
@IBOutlet weak var checkedId: UIImageView!
@IBOutlet weak var devOrDesign: UISegmentedControl!
@IBOutlet weak var devType: UISegmentedControl!
@IBOutlet weak var signUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setViews()
bind()
}
func setViews(){
self.title = "회원가입"
self.checkedId.isHidden = true
}
func bind(){
}
}
|
//
// ViewController.swift
// Typeform Attendance
//
// Created by Victor Wang on 5/20/16.
// Copyright © 2016 Victor Wang. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var emailTableView: NSTableView!
@IBOutlet weak var attendanceTableView: NSTableView!
@IBOutlet var APIkeyField: NSTextField!
@IBOutlet var refreshDate: NSTextField!
@IBOutlet var UIDkeyField: NSTextField!
@IBOutlet var numEmailField: NSTextField!
@IBOutlet weak var averageAttendance: NSTextField!
@IBOutlet weak var pageNumField: NSTextField!
@IBAction func refreshButtonPressed(sender: AnyObject) {
let todaysDate:NSDate = NSDate()
let dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let dateValue = dateFormatter.stringFromDate(todaysDate)
refreshDate.stringValue = dateValue
Main.retreiveResponses()
averageAttendance.stringValue = String(Main.getAverageAttendance())
}
@IBAction func apiKeyChanged(sender: NSTextField) {
Main.newAPI(sender.stringValue)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(sender.stringValue, forKey: "API")
}
@IBAction func uidKeyChanged(sender: NSTextField) {
Main.newUID(sender.stringValue)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(sender.stringValue, forKey: "UID")
}
@IBAction func numEmailChanged(sender: NSTextField) {
let number = Int(sender.stringValue) ?? 0
Main.newEmailPerPage(number);
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(number, forKey: "numEmail")
}
@IBAction func copyToClipboardPressed(sender: NSButton){
let personList = Main.getEmails(Int(pageNumField.stringValue)!)
var clipboard = ""
if(personList == nil){
return
}
for person in personList!{
clipboard += person.email + ", "
}
NSPasteboard.generalPasteboard().clearContents()
NSPasteboard.generalPasteboard().setString(clipboard, forType: NSPasteboardTypeString)
}
@IBAction func nextPagePressed(sender: NSButton){
let personList = Main.getEmails(Int(pageNumField.stringValue)!+1)
if(personList == nil){
return
}
pageNumField.stringValue = String(Int(pageNumField.stringValue)! + 1)
emailTableView.reloadData()
}
@IBAction func previousPagePressed(sender: NSButton){
let personList = Main.getEmails(Int(pageNumField.stringValue)!-1)
if(personList == nil){
return
}
pageNumField.stringValue = String(Int(pageNumField.stringValue)! - 1)
emailTableView.reloadData()
}
override func viewDidAppear() {
let frame = NSApplication.sharedApplication().windows[0]
frame.title = "Typeform Attendance App"
if(attendanceTableView != nil){
attendanceTableView.reloadData()
}
if(emailTableView != nil){
emailTableView.reloadData()
}
if(averageAttendance != nil){
averageAttendance.stringValue = String(Main.getAverageAttendance())
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let defaults = NSUserDefaults.standardUserDefaults()
let API = defaults.stringForKey("API")
if API != nil && APIkeyField != nil {
APIkeyField.stringValue = API ?? ""
Main.newAPI(APIkeyField.stringValue)
}
else if API != nil{
Main.newAPI(API!)
}
let UID = defaults.stringForKey("UID")
if UID != nil && UIDkeyField != nil {
UIDkeyField.stringValue = UID ?? ""
Main.newUID(UIDkeyField.stringValue)
}
else if UID != nil{
Main.newUID(UID!)
}
let numEmail = defaults.integerForKey("numEmail")
if numEmail != 0 && numEmailField != nil {
numEmailField.stringValue = String(numEmail)
let number = Int(numEmailField.stringValue) ?? 0
Main.newEmailPerPage(number);
}
else if numEmail != 0{
let number = Int(numEmail) ?? 0
Main.newEmailPerPage(number);
}
if(attendanceTableView != nil){
attendanceTableView.setDelegate(self);
attendanceTableView.setDataSource(self);
}
if(emailTableView != nil){
emailTableView.setDelegate(self)
emailTableView.setDataSource(self)
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
extension ViewController : NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if(attendanceTableView != nil){
return Main.getAttendance().count
}
if(emailTableView != nil){
return Main.getEmails(Int(pageNumField.stringValue)!)?.count ?? 0
}
return 0;
}
}
extension ViewController : NSTableViewDelegate {
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if(attendanceTableView != nil){
let personList = Main.getAttendance()
var text:String = ""
var cellIdentifier: String = ""
guard row < personList.count else {
return nil
}
let item = personList[row]
if tableColumn == tableView.tableColumns[0] {
text = item.firstName
cellIdentifier = "FirstNameID"
} else if tableColumn == tableView.tableColumns[1] {
text = item.lastName
cellIdentifier = "LastNameID"
} else if tableColumn == tableView.tableColumns[2] {
text = String(item.meeting)
cellIdentifier = "MeetingsAttendedID"
} else if tableColumn == tableView.tableColumns[3] {
text = item.email
cellIdentifier = "EmailID"
}
if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
return cell
}
return nil
}
if(emailTableView != nil){
let personList = Main.getEmails(Int(pageNumField.stringValue)!)
if(personList == nil){
return nil
}
var text:String = ""
var cellIdentifier: String = ""
guard row < personList!.count else {
return nil
}
let item = personList![row]
if tableColumn == tableView.tableColumns[0] {
text = item.firstName
cellIdentifier = "FirstNameID"
} else if tableColumn == tableView.tableColumns[1] {
text = item.lastName
cellIdentifier = "LastNameID"
} else if tableColumn == tableView.tableColumns[2] {
text = item.email
cellIdentifier = "EmailID"
}
if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
return cell
}
return nil
}
return nil
}
}
|
//
// UIViewController+Error.swift
// Carangas
//
// Created by Andre Ponce on 01/10/21.
// Copyright © 2021 Eric Brito. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func showError(error :CarError){
var response: String = ""
switch error {
case .invalidJSON:
response = "invalidJSON"
case .noData:
response = "noData"
case .noResponse:
response = "noResponse"
case .url:
response = "JSON inválido"
case .taskError(let error):
response = "\(error.localizedDescription)"
case .responseStatusCode(let code):
if code != 200 {
response = "Algum problema com o servidor. :( \nError:\(code)"
}
}
print(response)
let alert = UIAlertController(title: "Erro", message: "Houve um erro inesperado, por favor tente novamente.", preferredStyle: .actionSheet)
let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alert.addAction(okAction)
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
}
|
//
// FloraSearchResult.swift
// florafinder
//
// Created by Andrew Tokeley on 8/01/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import Foundation
/**
This class represents the search results for a single Flora. A SearchResult can be the result of performing many different types of searches. The details about how each type of search result impacted this search result, can be explored through the searchTermResultDetails property.
*/
class SearchResult: NSObject
{
var flora: Flora
var relevance: Int
var hitCount: Int
/**
Returns user readable descriptions of the search result. Useful for seeing why a result did or did not match
*/
var searchTermResultDetails: [String] = []
/**
set this value based on the sort of search being done. This allows search results to be grouped by search type.
*/
var searchTypeDescription: String?
init(flora: Flora, relevance: Int)
{
self.flora = flora
self.relevance = relevance
self.hitCount = 0
}
/**
Adds current instance to a master array of search results. If a search result exists for the same flora it is merged with that result, with the relevances being added together and a record added to the searchTermResultDetails array. Otherwise, the instance is added to the end of the array as a new result. This method also tracks the number of times a flora has been matched in a search
*/
func addTo(inout searchResults: [SearchResult]) //, intersectionOnly: Bool)
{
// if self is part of the searchResults then increase it's relevance
let objectID = self.flora.objectID
let match = searchResults.filter( { (item) in item.flora.objectID == objectID })
if (match.count > 0)
{
// merge the current instance with the other result for the same Flora
match.first!.relevance += self.relevance
match.first!.hitCount += 1 // this item has matched again so bump hit count
match.first!.searchTermResultDetails.appendContentsOf(self.searchTermResultDetails)
}
else
{
// First time this a search result added for this flora
self.hitCount = 1
searchResults.append(self)
}
}
} |
//
// PickerView.swift
// Recipe App
//
// Created by Taran on 02/07/20.
// Copyright © 2020 Macbook_Taranjeet. All rights reserved.
//
import Foundation
import UIKit
protocol PickerViewDelegate: class {
func doneButtonClicked()
func cancelButtonClicked()
}
class PickerView: UIPickerView {
public private(set) var toolbar: UIToolbar?
public weak var toolbarDelegate: PickerViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = .black
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.doneButtonClicked))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelButtonClicked))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
self.toolbar = toolBar
}
@objc func doneButtonClicked() {
self.toolbarDelegate?.doneButtonClicked()
}
@objc func cancelButtonClicked() {
self.toolbarDelegate?.cancelButtonClicked()
}
}
|
//
// Transition.swift
// TuVosUstedMeConfuden
//
// Created by Matthew Beynon on 4/28/19.
// Copyright © 2019 Matthew Beynon. All rights reserved.
//
// Instead of having the variables on each class instance, i may want to use userDefaults, but I'd still have to update it...
import UIKit
class Transition {
static func manage(currentVC: ViewController, nextVC: ViewController, xTranslation: CGFloat) {
UserDefaults.standard.set(true, forKey: "transitionOccuring")
for case let dropdown as UIStackView in currentVC.view.subviews {
if !dropdown.isHidden {
dropdown.isHidden = true
}
}
translateElements(currentVC: currentVC, xTranslation: xTranslation)
if UserDefaults.standard.string(forKey: "language") == "English" {
Transition.changeActiveButton(oldInactiveButton: currentVC.uiElements.englishButton, oldActiveButton: currentVC.uiElements.spanishButton, newActiveButton: nextVC.uiElements.spanishButton, newInactiveButton: nextVC.uiElements.englishButton)
} else if UserDefaults.standard.string(forKey: "language") == "Español" {
Transition.changeActiveButton(oldInactiveButton: currentVC.uiElements.spanishButton, oldActiveButton: currentVC.uiElements.englishButton, newActiveButton: nextVC.uiElements.englishButton, newInactiveButton: nextVC.uiElements.spanishButton)
}
Determine.ifFormOfYouShouldBeCalculated(vc: nextVC)
setNewVariables(currentVC: currentVC, nextVC: nextVC)
}
static func changeActiveButton(oldInactiveButton: UIButton, oldActiveButton: UIButton, newActiveButton: UIButton, newInactiveButton: UIButton) {
DispatchQueue.main.async {
oldInactiveButton.setTitleColor(UIColor.white, for: .normal)
oldActiveButton.setTitleColor(UIColor.black, for: .normal)
newActiveButton.setTitleColor(UIColor.white, for: .normal)
newInactiveButton.setTitleColor(UIColor.black, for: .normal)
}
}
static func setNewVariables(currentVC: ViewController, nextVC: ViewController) {
if currentVC.country != nil {
nextVC.country = Translate.country(language: UserDefaults.standard.string(forKey: "language")!, word: currentVC.country)
}
if currentVC.person != nil {
nextVC.person = Translate.person(language: UserDefaults.standard.string(forKey: "language")!, word: currentVC.person)
}
if currentVC.tertiaryDatum != nil {
nextVC.tertiaryDatum = Translate.tertiary(language: UserDefaults.standard.string(forKey: "language")!, country: currentVC.country, word: currentVC.tertiaryDatum!)
}
}
static func setNewLabelText(currentVC: ViewController, nextVC: ViewController) {
if nextVC.country == nil {
let translatedQuestion = Translate.question(language: UserDefaults.standard.string(forKey: "language")!, question: currentVC.uiElements.countriesTextButton.titleLabel!.text!)
nextVC.uiElements.countriesTextButton.setTitle(translatedQuestion, for: .normal)
} else {
nextVC.uiElements.countriesTextButton.setTitle(nextVC.country, for: .normal)
}
if nextVC.person == nil {
let translatedQuestion = Translate.question(language: UserDefaults.standard.string(forKey: "language")!, question: currentVC.uiElements.peopleTextButton.titleLabel!.text!)
nextVC.uiElements.peopleTextButton.setTitle(translatedQuestion, for: .normal)
} else {
nextVC.uiElements.peopleTextButton.setTitle(nextVC.person, for: .normal)
}
if nextVC.uiElements.tertiaryTextButton != nil {
if nextVC.tertiaryDatum == nil {
let translatedQuestion = Translate.question(language: UserDefaults.standard.string(forKey: "language")!, question: currentVC.uiElements.tertiaryTextButton!.titleLabel!.text!)
nextVC.uiElements.tertiaryTextButton!.setTitle(translatedQuestion, for: .normal)
} else {
nextVC.uiElements.tertiaryTextButton!.setTitle(nextVC.tertiaryDatum, for: .normal)
}
}
if currentVC.uiElements.formOfYouLabel.isHidden == false {
nextVC.uiElements.formOfYouLabel.isHidden = false
nextVC.uiElements.formOfYouLabel.text = currentVC.uiElements.formOfYouLabel.text
nextVC.view.setNeedsLayout()
}
}
static func setNewDropdownOptions(currentVC: ViewController, nextVC: ViewController) {
// I might be able to turn this into a generic and call it a few times, not sure if thats better or not
var buttonCountry = 0
for horizontalView in nextVC.uiElements.countriesDropdown.subviews {
for case let button as UIButton in horizontalView.subviews {
let translatedCountry = Translate.country(language: UserDefaults.standard.string(forKey: "language")!, word: button.titleLabel!.text!)
button.setTitle(translatedCountry, for: .normal)
buttonCountry += 1
}
}
for case let button as UIButton in nextVC.uiElements.peopleDropdown.subviews {
let translatedPerson = Translate.person(language: UserDefaults.standard.string(forKey: "language")!, word: button.titleLabel!.text!)
button.setTitle(translatedPerson, for: .normal)
}
if nextVC.uiElements.tertiaryDropdown != nil {
for case let button as UIButton in nextVC.uiElements.tertiaryDropdown!.subviews {
let translatedTertiary = Translate.tertiary(language: UserDefaults.standard.string(forKey: "language")!, country: currentVC.country, word: button.titleLabel!.text!)
button.setTitle(translatedTertiary, for: .normal)
}
}
}
static func translateElements(currentVC: ViewController, xTranslation: CGFloat) {
var tertiaryTextButtonCenterXAnchor: NSLayoutConstraint?
print("translateElements")
let countriesTextButtonCenterXAnchor = getCenterXAnchor(textButton: currentVC.uiElements.countriesTextButton)
countriesTextButtonCenterXAnchor.constant += xTranslation
let peopleTextButtonCenterXAnchor = getCenterXAnchor(textButton: currentVC.uiElements.peopleTextButton)
peopleTextButtonCenterXAnchor.constant += xTranslation
if currentVC.uiElements.tertiaryTextButton != nil {
tertiaryTextButtonCenterXAnchor = getCenterXAnchor(textButton: currentVC.uiElements.tertiaryTextButton!)
tertiaryTextButtonCenterXAnchor!.constant += xTranslation
}
UIView.animate(withDuration: 0.5, animations: {
currentVC.view.layoutIfNeeded()
})
}
static func animateIn(nextVC: ViewController, xTranslation: CGFloat) {
var tertiaryTextButtonCenterXAnchor: NSLayoutConstraint?
print("animateIn")
let countriesTextButtonCenterXAnchor = getCenterXAnchor(textButton: nextVC.uiElements.countriesTextButton)
countriesTextButtonCenterXAnchor.constant += xTranslation
let peopleTextButtonCenterXAnchor = getCenterXAnchor(textButton: nextVC.uiElements.peopleTextButton)
peopleTextButtonCenterXAnchor.constant += xTranslation
if nextVC.uiElements.tertiaryTextButton != nil && UserDefaults.standard.string(forKey: "language") == "Español" {
tertiaryTextButtonCenterXAnchor = getCenterXAnchor(textButton: nextVC.uiElements.tertiaryTextButton!)
tertiaryTextButtonCenterXAnchor!.constant += xTranslation
}
nextVC.view.layoutIfNeeded()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
countriesTextButtonCenterXAnchor.constant -= xTranslation
peopleTextButtonCenterXAnchor.constant -= xTranslation
if nextVC.uiElements.tertiaryTextButton != nil && UserDefaults.standard.string(forKey: "language") == "Español" {
tertiaryTextButtonCenterXAnchor!.constant -= xTranslation
}
UIView.animate(withDuration: 0.5, animations: {
nextVC.view.layoutIfNeeded()
})
}
}
static func getCenterXAnchor(textButton: UIButton) -> NSLayoutConstraint {
for constraint in textButton.constraintsAffectingLayout(for: .horizontal) {
if constraint.constant == 0 {
return constraint
}
}
print("WHOA")
print(textButton)
print(textButton.constraints)
print(textButton.constraintsAffectingLayout(for: .horizontal))
print(textButton.constraintsAffectingLayout(for: .horizontal).first!)
return textButton.constraintsAffectingLayout(for: .horizontal).first!
}
static func changeVariablesForRotation() {
DispatchQueue.main.async {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let currentVC = appDelegate.vc
UserDefaults.standard.set(true, forKey: "baseElementsNeeded")
let nextVC = ViewController()
currentVC.present(nextVC, animated: false, completion: {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05, execute: {
if currentVC.country != nil {
nextVC.country = currentVC.country
nextVC.uiElements.countriesTextButton.titleLabel?.text = nextVC.country
}
if currentVC.person != nil {
nextVC.person = currentVC.person
nextVC.uiElements.peopleTextButton.titleLabel?.text = nextVC.person
}
if currentVC.tertiaryDatum != nil {
Determine.ifTertiaryElementsAreNeeded(vc: nextVC, country: nextVC.country)
nextVC.tertiaryDatum = currentVC.tertiaryDatum
// might be a problem here?
nextVC.uiElements.tertiaryTextButton?.titleLabel?.text = nextVC.tertiaryDatum
}
if currentVC.uiElements.formOfYouLabel.isHidden == false {
nextVC.uiElements.formOfYouLabel.isHidden = false
nextVC.uiElements.formOfYouLabel.text = currentVC.uiElements.formOfYouLabel.text
}
})
UserDefaults.standard.set(false, forKey: "baseElementsNeeded")
appDelegate.vc = nextVC
})
}
}
}
|
//
// MomentsTableViewCell.swift
// SPMomentsSample
//
// Created by Barry Ma on 2016-05-09.
// Copyright © 2016 BarryMa. All rights reserved.
//
import UIKit
import Kingfisher
import MHPrettyDate
class MomentsTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
weak var delegate: protocol<momentCellDelegate, momentCommentViewDelegate>? {
didSet {
commentView.delegate = delegate
}
}
var showTopSeperator: Bool = false {
didSet {
topSeperator.hidden = !showTopSeperator
}
}
var topSeperator: UIView = UIView()
var avatarView: UIImageView = UIImageView()
var momentTextView: UITextView = UITextView()
var photosCollectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
var createDateLabel: UILabel = UILabel()
var moreOperateButton: UIButton = UIButton()
var commentView: MomentCommentView = MomentCommentView()
var momentTextViewHeightConstraint: NSLayoutConstraint?
var photosCollectionViewTopConstraint: NSLayoutConstraint?
var photosCollectionViewHeightConstraint: NSLayoutConstraint?
var commentShowViewTopConstraint: NSLayoutConstraint?
var commentShowViewHeightConstraint: NSLayoutConstraint?
// private var avatarViewRetrieveImageTask: RetrieveImageTask?
private var photos: [String]?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupMomentCell()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupMomentCell() {
self.selectionStyle = UITableViewCellSelectionStyle.None
//Topseperator
self.contentView.addSubview(topSeperator)
topSeperator.translatesAutoresizingMaskIntoConstraints = false
topSeperator.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1)
topSeperator.addConstraint(NSLayoutConstraint(item: topSeperator, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 1))
contentView.addConstraint(NSLayoutConstraint(item: topSeperator, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .Leading, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: topSeperator, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 0))
//AvatarView
self.contentView.addSubview(avatarView)
avatarView.translatesAutoresizingMaskIntoConstraints = false
avatarView.addConstraint(NSLayoutConstraint(item: avatarView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 48))
avatarView.addConstraint(NSLayoutConstraint(item: avatarView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 48))
contentView.addConstraint(NSLayoutConstraint(item: avatarView, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 12))
contentView.addConstraint(NSLayoutConstraint(item: avatarView, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .Leading, multiplier: 1, constant: 8))
//MomentTextView
self.contentView.addSubview(momentTextView)
momentTextView.translatesAutoresizingMaskIntoConstraints = false
//momentTextView.backgroundColor = UIColor.greenColor()
momentTextView.backgroundColor = UIColor.clearColor()
momentTextView.scrollEnabled = false
momentTextView.showsVerticalScrollIndicator = false
momentTextView.showsHorizontalScrollIndicator = false
momentTextView.editable = false
momentTextView.selectable = false
momentTextView.userInteractionEnabled = false
momentTextViewHeightConstraint = NSLayoutConstraint(item: momentTextView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 59)
momentTextView.addConstraint(momentTextViewHeightConstraint!)
contentView.addConstraint(NSLayoutConstraint(item: momentTextView, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 6))
contentView.addConstraint(NSLayoutConstraint(item: momentTextView, attribute: .Leading, relatedBy: .Equal, toItem: avatarView, attribute: .Trailing, multiplier: 1, constant: 8))
contentView.addConstraint(NSLayoutConstraint(item: momentTextView, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -8))
//PhotosCollectionView
self.contentView.addSubview(photosCollectionView)
photosCollectionView.translatesAutoresizingMaskIntoConstraints = false
//photosCollectionView.backgroundColor = UIColor.yellowColor()
photosCollectionView.backgroundColor = UIColor.clearColor()
photosCollectionView.registerClass(MomentPhotoCell.self, forCellWithReuseIdentifier: "MomentPhotoCell")
photosCollectionView.delegate = self
photosCollectionView.dataSource = self
photosCollectionViewHeightConstraint = NSLayoutConstraint(item: photosCollectionView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 84)
photosCollectionView.addConstraint(photosCollectionViewHeightConstraint!)
contentView.addConstraint(NSLayoutConstraint(item: photosCollectionView, attribute: .Top, relatedBy: .Equal, toItem: momentTextView, attribute: .Bottom, multiplier: 1, constant: 8))
contentView.addConstraint(NSLayoutConstraint(item: photosCollectionView, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -8))
contentView.addConstraint(NSLayoutConstraint(item: photosCollectionView, attribute: .Leading, relatedBy: .Equal, toItem: momentTextView, attribute: .Leading, multiplier: 1, constant: 0))
//CreateDateLabel
self.contentView.addSubview(createDateLabel)
createDateLabel.translatesAutoresizingMaskIntoConstraints = false
//createDateLabel.backgroundColor = UIColor.lightGrayColor()
createDateLabel.backgroundColor = UIColor.clearColor()
createDateLabel.addConstraint(NSLayoutConstraint(item: createDateLabel, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 18))
createDateLabel.addConstraint(NSLayoutConstraint(item: createDateLabel, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 175))
contentView.addConstraint(NSLayoutConstraint(item: createDateLabel, attribute: .Top, relatedBy: .Equal, toItem: photosCollectionView, attribute: .Bottom, multiplier: 1, constant: 8))
contentView.addConstraint(NSLayoutConstraint(item: createDateLabel, attribute: .Leading, relatedBy: .Equal, toItem: photosCollectionView, attribute: .Leading, multiplier: 1, constant: 0))
//MoreOperateButton
self.contentView.addSubview(moreOperateButton)
moreOperateButton.translatesAutoresizingMaskIntoConstraints = false
moreOperateButton.setImage(UIImage(named: "AlbumOperateMore"), forState: UIControlState.Normal)
moreOperateButton.addTarget(self, action: "clickMoreOperateButton:", forControlEvents: UIControlEvents.TouchUpInside)
moreOperateButton.addConstraint(NSLayoutConstraint(item: moreOperateButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 25))
moreOperateButton.addConstraint(NSLayoutConstraint(item: moreOperateButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 25))
contentView.addConstraint(NSLayoutConstraint(item: moreOperateButton, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -8))
contentView.addConstraint(NSLayoutConstraint(item: moreOperateButton, attribute: .CenterY, relatedBy: .Equal, toItem: createDateLabel, attribute: .CenterY, multiplier: 1, constant: 0))
//CommentView
self.contentView.addSubview(commentView)
commentView.translatesAutoresizingMaskIntoConstraints = false
//commentView.backgroundColor = UIColor.grayColor()
commentView.backgroundColor = UIColor.clearColor()
commentShowViewHeightConstraint = NSLayoutConstraint(item: commentView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 60)
commentView.addConstraint(commentShowViewHeightConstraint!)
contentView.addConstraint(NSLayoutConstraint(item: commentView, attribute: .Top, relatedBy: .Equal, toItem: createDateLabel, attribute: .Bottom, multiplier: 1, constant: 8))
contentView.addConstraint(NSLayoutConstraint(item: commentView, attribute: .Leading, relatedBy: .Equal, toItem: createDateLabel, attribute: .Leading, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: commentView, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -8))
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// MARK: - UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if photos != nil {
return photos!.count
}
return 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MomentPhotoCell", forIndexPath: indexPath) as! MomentPhotoCell
//cell.configWithPhotoURL(photoURLs![indexPath.row])
cell.photoView?.image = UIImage(named: "momentPhoto")
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
delegate?.momentCell?(self, didSelectPhotoViewAtIndex:indexPath.row)
let nPhoto = (photos == nil) ? 0 : photos!.count
var localImage: [AnyObject] = []
for i in 1...nPhoto {
localImage.append(NSURL(string: String(i))!)
}
let browser = PhotoBrowserView.initWithPhotos(withUrlArray: localImage)
browser.sourceType = SourceType.LOCAL
browser.index = indexPath.row
browser.show()
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let collectionViewWidth = CGRectGetWidth(collectionView.bounds)
let columns = Int((collectionViewWidth + momentPhotoMinimumInteritemSpacing)/(momentPhotoSize + momentPhotoMinimumInteritemSpacing))
var itemWidth: CGFloat = 0
if columns == 0 {
itemWidth = collectionViewWidth
} else {
itemWidth = (collectionViewWidth - CGFloat(columns - 1)*momentPhotoMinimumInteritemSpacing)/CGFloat(columns)
}
return CGSizeMake(itemWidth, momentPhotoSize)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return momentPhotoMinimumLineSpacing
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return momentPhotoMinimumInteritemSpacing
}
func configWithData(data: [String: AnyObject]? = nil, cellWidth: CGFloat = 0) {
let avatarURL = data?[momentCellMomentDataKey_avatarURL] as? NSURL
let authorName = data?[momentCellMomentDataKey_authorName] as? String
let textContent = data?[momentCellMomentDataKey_textContent] as? String
let photos = data?[momentCellMomentDataKey_photoURLs] as? [String]
let createDate = data?[momentCellMomentDataKey_createDate] as? NSDate
let comments = data?[momentCellMomentDataKey_comments] as? [[String: AnyObject]]
let likes = data?[momentCellMomentDataKey_likeUserNames] as? [String]
let momentTextViewWidth = cellWidth - momentTextViewLittleThanCellWidth
// 设置头像
// if avatarURL != nil {
// avatarViewRetrieveImageTask = avatarView?.kf_setImageWithURL(avatarURL!, placeholderImage: UIImage(named: "RoleAvatar"))
// } else {
// avatarViewRetrieveImageTask?.cancel()
// avatarView?.image = UIImage(named: "RoleAvatar")
// }
avatarView.image = UIImage(named: "roleAvatar")
// 设置文字内容
let momentAttributedText = MomentsTableViewCell.buildMomentTextViewAttributedTextWithAuthorName(authorName, momentTextContent:textContent)
momentTextView.attributedText = momentAttributedText
momentTextViewHeightConstraint?.constant = MomentsTableViewCell.momentTextViewHeightWithAttributedText(momentAttributedText, momentTextViewWidth:momentTextViewWidth)
// 设置图片
self.photos = photos
photosCollectionView.reloadData()
if let photoCount = photos?.count {
photosCollectionViewTopConstraint?.constant = momentPhotosCollectionViewTopMargin
photosCollectionViewHeightConstraint?.constant = MomentsTableViewCell.caculatePhotosCollectionViewHeightWithPhotoNumber(photoCount, collectionViewWidth: momentTextViewWidth)
} else {
photosCollectionViewTopConstraint?.constant = 0
photosCollectionViewHeightConstraint?.constant = 0
}
// 设置时间
if createDate != nil {
createDateLabel.text = MHPrettyDate.prettyDateFromDate(createDate, withFormat: MHPrettyDateFormatWithTime)
} else {
createDateLabel.text = nil
}
// 设置评论视图
var commentViewData = [String: AnyObject]()
if likes != nil {
commentViewData[MomentCommentViewMomentDataKey_likeUserNames] = likes!
}
if comments != nil {
var commentViewComments = [[String:AnyObject]]()
for comment in comments! {
commentViewComments.append(MomentsTableViewCell.buildCommentShowViewCommentDataWithMomentComment(comment))
}
commentViewData[MomentCommentViewMomentDataKey_comments] = commentViewComments
}
commentView.configWithData(commentViewData, viewWidth: momentTextViewWidth)
if commentViewData.count > 0 {
commentShowViewTopConstraint?.constant = momentCommentShowViewTopMargin
commentShowViewHeightConstraint?.constant = MomentCommentView.caculateHeightWithData(commentViewData, viewWidth: momentTextViewWidth)
} else {
commentShowViewTopConstraint?.constant = 0
commentShowViewHeightConstraint?.constant = 0
}
}
static func buildCommentShowViewCommentDataWithMomentComment(momentComments: [String: AnyObject]) -> [String: AnyObject] {
var commentViewComments = [String:AnyObject]()
if let commentAuthorRoleName: AnyObject = momentComments[momentCellCommentDataKey_authorName] {
commentViewComments[MomentCommentViewCommentDataKey_authorName] = commentAuthorRoleName
}
if let commentAtUserRoleName: AnyObject = momentComments[momentCellCommentDataKey_atUserName] {
commentViewComments[MomentCommentViewCommentDataKey_atUserName] = commentAtUserRoleName
}
if let commentText: AnyObject = momentComments[momentCellCommentDataKey_textContent] {
commentViewComments[MomentCommentViewCommentDataKey_textContent] = commentText
}
return commentViewComments
}
static func cellHeightWithData(data: [String: AnyObject]? = nil, cellWidth: CGFloat = 0) -> CGFloat {
var cellHeight: CGFloat = 0
let authorName = data?[momentCellMomentDataKey_authorName] as? String
let textContent = data?[momentCellMomentDataKey_textContent] as? String
let photos = data?[momentCellMomentDataKey_photoURLs] as? [String]
let createDate = data?[momentCellMomentDataKey_createDate] as? NSDate
let comments = data?[momentCellMomentDataKey_comments] as? [[String: AnyObject]]
let likes = data?[momentCellMomentDataKey_likeUserNames] as? [String]
let momentTextViewWidth = cellWidth - momentTextViewLittleThanCellWidth
// 计算cell顶部padding
cellHeight += momentCellTopPadding
// 计算文字内容视图高度
let momentAttributedText = MomentsTableViewCell.buildMomentTextViewAttributedTextWithAuthorName(authorName, momentTextContent:textContent)
cellHeight += MomentsTableViewCell.momentTextViewHeightWithAttributedText(momentAttributedText, momentTextViewWidth: momentTextViewWidth)
// 计算图片显示视图高度
if let photoCount = photos?.count {
cellHeight += (momentPhotosCollectionViewTopMargin +
caculatePhotosCollectionViewHeightWithPhotoNumber(photoCount, collectionViewWidth: momentTextViewWidth))
}
// 计算时间视图高度
cellHeight += (momentCreateDateLabelTopMargin + momentCreateDateLabelHeight)
// 计算评论视图高度
var commentViewData = [String: AnyObject]()
if likes != nil {
commentViewData[MomentCommentViewMomentDataKey_likeUserNames] = likes!
}
if comments != nil {
var commentViewComments = [[String:AnyObject]]()
for comment in comments! {
commentViewComments.append(MomentsTableViewCell.buildCommentShowViewCommentDataWithMomentComment(comment))
}
commentViewData[MomentCommentViewMomentDataKey_comments] = commentViewComments
}
if commentViewData.count > 0 {
let commentViewHeight = MomentCommentView.caculateHeightWithData(commentViewData, viewWidth: momentTextViewWidth)
cellHeight += (momentCommentShowViewTopMargin + commentViewHeight)
}
// 计算cell底部padding
cellHeight += momentCellBottomPadding
return cellHeight > momentCellMinHeight ? cellHeight:momentCellMinHeight
}
static private func buildMomentTextViewAttributedTextWithAuthorName(authorName: String?, momentTextContent: String?) -> NSAttributedString? {
let attributedText = NSMutableAttributedString()
// 动态发布者名字
if authorName?.isEmpty == false {
let namePS = NSMutableParagraphStyle()
namePS.lineSpacing = 2
namePS.paragraphSpacing = 8
attributedText.appendAttributedString(NSAttributedString(string:authorName!, attributes:[NSFontAttributeName:UIFont.systemFontOfSize(18), NSForegroundColorAttributeName:UIColor.blackColor(), NSParagraphStyleAttributeName:namePS]))
}
// 角色描述
if momentTextContent?.isEmpty == false {
if attributedText.length > 0 {
attributedText.appendAttributedString(NSAttributedString(string: "\n"))
}
let contentPS = NSMutableParagraphStyle()
contentPS.lineSpacing = 2
contentPS.paragraphSpacing = 4
attributedText.appendAttributedString(NSAttributedString(string:momentTextContent!, attributes:[NSFontAttributeName:UIFont.systemFontOfSize(14), NSForegroundColorAttributeName:UIColor.grayColor(), NSParagraphStyleAttributeName:contentPS]))
}
return attributedText
}
static private func momentTextViewHeightWithAttributedText(attributedText:NSAttributedString?, momentTextViewWidth:CGFloat? = 0) -> CGFloat {
if attributedText == nil {
return 0
}
struct Static {
static var onceToken : dispatch_once_t = 0
static var sizingTextView : UITextView? = nil
}
dispatch_once(&Static.onceToken) {
Static.sizingTextView = UITextView()
}
Static.sizingTextView?.attributedText = attributedText
let sizingTextViewSize = Static.sizingTextView?.sizeThatFits(CGSizeMake(momentTextViewWidth!, CGFloat(MAXFLOAT)))
return sizingTextViewSize!.height
}
static private func caculatePhotosCollectionViewHeightWithPhotoNumber(photoNumber: Int = 0, collectionViewWidth: CGFloat = 0) -> CGFloat {
if photoNumber <= 0 {
return 0
}
let columns = Int((collectionViewWidth + momentPhotoMinimumInteritemSpacing)/(momentPhotoSize + momentPhotoMinimumInteritemSpacing))
if columns <= 0 {
return 0
} else {
let rows = Int(ceilf(Float(photoNumber)/Float(columns)))
if rows <= 0 {
return 0
} else {
return (CGFloat(rows) * momentPhotoSize + CGFloat(rows - 1)*momentPhotoMinimumLineSpacing)
}
}
}
@objc private func clickMoreOperateButton(button: UIButton) {
delegate?.momentCell?(self, didClickMoreOprateButton: button)
}
class MomentPhotoCell: UICollectionViewCell {
private var photoView: UIImageView?
//private var retrievePhotoViewImageTask: RetrieveImageTask?
override init(frame: CGRect) {
super.init(frame: frame)
setupMomentPhotoCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupMomentPhotoCell() {
photoView = UIImageView()
self.contentView.addSubview(photoView!)
photoView?.translatesAutoresizingMaskIntoConstraints = false
photoView?.contentMode = UIViewContentMode.ScaleAspectFill
photoView?.clipsToBounds = true
// 设置约束
let views = ["photoView":photoView!]
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[photoView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[photoView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
}
}
@objc protocol momentCellDelegate {
optional func momentCell(momentCell: MomentsTableViewCell, didClickMoreOprateButton: UIButton)
optional func momentCell(momentCell: MomentsTableViewCell, didSelectPhotoViewAtIndex: Int)
}
let momentCellMinHeight: CGFloat = 64
let momentCellTopPadding: CGFloat = 6
let momentCellBottomPadding: CGFloat = 8
let momentTextViewLittleThanCellWidth: CGFloat = 72
let momentPhotosCollectionViewTopMargin: CGFloat = 8
let momentPhotoSize: CGFloat = 84
let momentPhotoMinimumLineSpacing: CGFloat = 4
let momentPhotoMinimumInteritemSpacing: CGFloat = 4
let momentPhotoCellReuseIdentifier = "momentPhotoCell"
let momentCreateDateLabelTopMargin: CGFloat = 8
let momentCreateDateLabelHeight: CGFloat = 18
let momentCommentShowViewTopMargin: CGFloat = 8
/// 动态的数据key
let momentCellMomentDataKey_avatarURL = "momentCellMomentDataKey_avatarURL"
let momentCellMomentDataKey_authorName = "momentCellMomentDataKey_authorName"
let momentCellMomentDataKey_textContent = "momentCellMomentDataKey_textContent"
let momentCellMomentDataKey_photoURLs = "momentCellMomentDataKey_photoURLs"
let momentCellMomentDataKey_createDate = "momentCellMomentDataKey_createDate"
// 动态的评论数据,每条评论的具体信息再通过评论的数据key获取
let momentCellMomentDataKey_comments = "momentCellMomentDataKey_comments"
// 动态的点赞用户
let momentCellMomentDataKey_likeUserNames = "momentCellMomentDataKey_likeUserNames"
// 评论的数据key
let momentCellCommentDataKey_authorName = "momentCellCommentDataKey_authorName"
let momentCellCommentDataKey_atUserName = "momentCellCommentDataKey_atUserName"
let momentCellCommentDataKey_textContent = "momentCellCommentDataKey_textContent"
|
//
// ServicePreference.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 1/24/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import Foundation
open class ServicePreference: NSObject {
var customerURL: String?
var customerURI = ""
var customerAdditionalInfo: NSDictionary?
var checkoutPreferenceURL: String?
var checkoutPreferenceURI = ""
var checkoutAdditionalInfo: NSDictionary?
var paymentURL: String = MP_API_BASE_URL
var paymentURI: String = MP_PAYMENTS_URI + "?api_version=" + API_VERSION
var paymentAdditionalInfo: NSDictionary?
var discountURL: String = MP_API_BASE_URL
var discountURI: String = MP_DISCOUNT_URI
var discountAdditionalInfo: NSDictionary?
var processingMode: ProcessingMode = ProcessingMode.aggregator
static let MP_ALPHA_ENV = "/gamma"
open static var MP_TEST_ENV = "/beta"
open static var MP_PROD_ENV = "/v1"
open static var MP_SELECTED_ENV = MP_PROD_ENV
static var API_VERSION = "1.3.X"
static var MP_ENVIROMENT = MP_SELECTED_ENV + "/checkout"
static let MP_OP_ENVIROMENT = "/v1"
static let MP_ALPHA_API_BASE_URL: String = "http://api.mp.internal.ml.com"
static let MP_API_BASE_URL_PROD: String = "https://api.mercadopago.com"
static let MP_API_BASE_URL: String = MP_API_BASE_URL_PROD
static let PAYMENT_METHODS = "/payment_methods"
static let INSTALLMENTS = "\(PAYMENT_METHODS)/installments"
static let CARD_TOKEN = "/card_tokens"
static let CARD_ISSSUERS = "\(PAYMENT_METHODS)/card_issuers"
static let PAYMENTS = "/payments"
static let MP_CREATE_TOKEN_URI = MP_OP_ENVIROMENT + CARD_TOKEN
static let MP_PAYMENT_METHODS_URI = MP_OP_ENVIROMENT + PAYMENT_METHODS
static var MP_INSTALLMENTS_URI = MP_OP_ENVIROMENT + INSTALLMENTS
static var MP_ISSUERS_URI = MP_OP_ENVIROMENT + CARD_ISSSUERS
static let MP_IDENTIFICATION_URI = "/identification_types"
static let MP_PROMOS_URI = MP_OP_ENVIROMENT + PAYMENT_METHODS + "/deals"
static let MP_SEARCH_PAYMENTS_URI = MP_ENVIROMENT + PAYMENT_METHODS + "/search/options"
static let MP_INSTRUCTIONS_URI = MP_ENVIROMENT + PAYMENTS + "/${payment_id}/results"
static let MP_PREFERENCE_URI = MP_ENVIROMENT + "/preferences/"
static let MP_DISCOUNT_URI = "/discount_campaigns/"
static let MP_TRACKING_EVENTS_URI = MP_ENVIROMENT + "/tracking/events"
static let MP_CUSTOMER_URI = "/customers?preference_id="
static let MP_PAYMENTS_URI = MP_ENVIROMENT + PAYMENTS
private static let kIsProdApiEnvironemnt = "prod_api_environment"
private static let kServiceSettings = "services_settings"
private static let kURIInstallments = "uri_installments"
private static let kURIIssuers = "uri_issuers"
private static let kOPURI = "op_uri"
private static let kWrapperURI = "wrapper_uri"
private static let kShouldUseWrapper = "should_use_wrapper"
private var useDefaultPaymentSettings = true
private var defaultDiscountSettings = true
var baseURL: String = MP_API_BASE_URL
var gatewayURL: String?
public override init() {
super.init()
ServicePreference.setupMPEnvironment()
}
public func setGetCustomer(baseURL: String, URI: String, additionalInfo: [String:String] = [:]) {
customerURL = baseURL
customerURI = URI
customerAdditionalInfo = additionalInfo as NSDictionary
}
public func setCreatePayment(baseURL: String = MP_API_BASE_URL, URI: String = MP_PAYMENTS_URI + "?api_version=" + API_VERSION, additionalInfo: NSDictionary = [:]) {
paymentURL = baseURL
paymentURI = URI
paymentAdditionalInfo = additionalInfo
self.useDefaultPaymentSettings = false
}
public func setDiscount(baseURL: String = MP_API_BASE_URL, URI: String = MP_DISCOUNT_URI, additionalInfo: [String:String] = [:]) {
discountURL = baseURL
discountURI = URI
discountAdditionalInfo = additionalInfo as NSDictionary?
defaultDiscountSettings = false
}
public func setCreateCheckoutPreference(baseURL: String, URI: String, additionalInfo: NSDictionary = [:]) {
checkoutPreferenceURL = baseURL
checkoutPreferenceURI = URI
checkoutAdditionalInfo = additionalInfo
}
public func setAdditionalPaymentInfo(_ additionalInfo: NSDictionary) {
paymentAdditionalInfo = additionalInfo
}
public func setDefaultBaseURL(baseURL: String) {
self.baseURL = baseURL
}
public func setGatewayURL(gatewayURL: String) {
self.gatewayURL = gatewayURL
}
public func getDefaultBaseURL() -> String {
return baseURL
}
public func getGatewayURL() -> String {
return gatewayURL ?? baseURL
}
public func getCustomerURL() -> String? {
return customerURL
}
public func getCustomerURI() -> String {
return customerURI
}
public func isUsingDeafaultPaymentSettings() -> Bool {
return useDefaultPaymentSettings
}
public func isUsingDefaultDiscountSettings() -> Bool {
return defaultDiscountSettings
}
public func getCustomerAddionalInfo() -> String {
if !NSDictionary.isNullOrEmpty(customerAdditionalInfo) {
return customerAdditionalInfo!.parseToQuery()
}
return ""
}
public func getPaymentURL() -> String {
if paymentURL == ServicePreference.MP_API_BASE_URL && baseURL != ServicePreference.MP_API_BASE_URL {
return baseURL
}
return paymentURL
}
public func getPaymentURI() -> String {
return paymentURI
}
public func getDiscountURL() -> String {
if discountURL == ServicePreference.MP_API_BASE_URL && baseURL != ServicePreference.MP_API_BASE_URL {
return baseURL
}
return discountURL
}
public func getDiscountURI() -> String {
return discountURI
}
public func getPaymentAddionalInfo() -> NSDictionary? {
if !NSDictionary.isNullOrEmpty(paymentAdditionalInfo) {
return paymentAdditionalInfo!
}
return nil
}
public func getDiscountAddionalInfo() -> String {
if !NSDictionary.isNullOrEmpty(discountAdditionalInfo) {
return discountAdditionalInfo!.parseToQuery()
}
return ""
}
public func getCheckoutPreferenceURL() -> String? {
return checkoutPreferenceURL
}
public func getCheckoutPreferenceURI() -> String {
return checkoutPreferenceURI
}
public func getCheckoutAddionalInfo() -> String {
if !NSDictionary.isNullOrEmpty(checkoutAdditionalInfo) {
return checkoutAdditionalInfo!.toJsonString()
}
return ""
}
public func isGetCustomerSet() -> Bool {
return !String.isNullOrEmpty(customerURL)
}
public func isCheckoutPreferenceSet() -> Bool {
return !String.isNullOrEmpty(checkoutPreferenceURL)
}
public func isCreatePaymentSet() -> Bool {
return !String.isNullOrEmpty(paymentURL)
}
public func isCustomerInfoAvailable() -> Bool {
return !String.isNullOrEmpty(self.customerURL) && !String.isNullOrEmpty(self.customerURI)
}
static public func setupMPEnvironment() {
// En caso de correr los tests se toma environment como prod por default
if Utils.isTesting() {
ServicePreference.MP_ENVIROMENT = MP_PROD_ENV + "/checkout"
} else {
guard let serviceSettings: [String:Any] = Utils.getSetting(identifier: ServicePreference.kServiceSettings) else {
return
}
guard let isProdEnvironment = serviceSettings[ServicePreference.kIsProdApiEnvironemnt] as? Bool else {
return
}
if isProdEnvironment {
ServicePreference.MP_SELECTED_ENV = MP_PROD_ENV
ServicePreference.MP_ENVIROMENT = MP_PROD_ENV + "/checkout"
} else {
ServicePreference.MP_SELECTED_ENV = MP_TEST_ENV
ServicePreference.MP_ENVIROMENT = MP_TEST_ENV + "/checkout"
}
if let uriInstallmentSettings = serviceSettings[ServicePreference.kURIInstallments] as? [String:Any] {
ServicePreference.MP_INSTALLMENTS_URI = getFinalURIFor(settings: uriInstallmentSettings)
}
if let uriIssuersSettings = serviceSettings[ServicePreference.kURIIssuers] as? [String:Any] {
ServicePreference.MP_ISSUERS_URI = getFinalURIFor(settings: uriIssuersSettings)
}
}
}
static internal func getFinalURIFor(settings: [String:Any]) -> String {
let shouldUseWrapper: Bool = settings[ServicePreference.kShouldUseWrapper] as? Bool ?? false
if shouldUseWrapper {
return ServicePreference.MP_SELECTED_ENV + (settings[ServicePreference.kWrapperURI] as! String)
} else {
return ServicePreference.MP_OP_ENVIROMENT + (settings[ServicePreference.kOPURI] as! String)
}
}
public func getProcessingModeString() -> String {
return self.processingMode.rawValue
}
public func setAggregatorAsProcessingMode() {
self.processingMode = ProcessingMode.aggregator
}
public func setGatewayAsProcessingMode() {
self.processingMode = ProcessingMode.gateway
}
public func setHybridAsProcessingMode() {
self.processingMode = ProcessingMode.hybrid
}
internal func shouldShowBankDeals() -> Bool {
return self.processingMode == ProcessingMode.aggregator
}
internal func shouldShowEmailConfirmationCell() -> Bool {
return self.processingMode == ProcessingMode.aggregator
}
}
public enum ProcessingMode: String {
case gateway = "gateway"
case aggregator = "aggregator"
case hybrid = "gateway,aggregator"
}
|
//
// PhoneVerifyViewController.swift
// Hivecast
//
// Created by Mingming Wang on 7/11/17.
// Copyright © 2017 Mingming Wang. All rights reserved.
//
import UIKit
import SwiftSpinner
import SwiftyUserDefaults
class PhoneLoginViewController: UIViewController {
@IBOutlet var avoidingView: UIView!
@IBOutlet weak var verifyButton: UIButton!
@IBOutlet weak var verifyIcon: UIButton!
@IBOutlet weak var phoneTextField: UITextField!
@IBAction func cancelBtn_pushed(_ sender: Any) {
phoneTextField.resignFirstResponder()
self.dismiss(animated: true, completion: nil)
}
@IBAction func verifyBtn_pushed(_ sender: Any) {
phoneTextField.resignFirstResponder()
let phoneNumber = phoneTextField.text
if phoneNumber == "" {
return
}
SwiftSpinner.show("Logging in...")
UserAPI.retrieveUserProfileByPhone(phoneNumber:phoneTextField.text!) { (profile, errorMessage) in
SwiftSpinner.hide()
if let profile = profile {
self.save(profile: profile)
self.performSegue(withIdentifier: "ToShowTabBarSegue", sender: self)
}
else {
self.presentBasicAlert(message: "User doesn't exist!")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
self.initialize()
}
func initialize() {
KeyboardAvoiding.avoidingView = self.avoidingView
phoneTextField.becomeFirstResponder()
}
func save(profile:User) {
Defaults[.userId] = profile.userId
Defaults[.displayName] = profile.displayName
Defaults[.userName] = profile.userName
Defaults[.siteUrl] = profile.siteUrl
Defaults[.phoneNumber] = profile.phoneNumber
Defaults[.profileImageUrl] = profile.profileImageUrl
Defaults[.followers_count] = profile.followers_count
Defaults[.following_count] = profile.following_count
Defaults[.bioText] = profile.bioText
Defaults[.videos_count] = profile.videos_count
}
}
|
//
// MyRowController.swift
// PizzApp
//
// Created by Mikel Aguirre on 21/2/16.
// Copyright © 2016 Mikel Aguirre. All rights reserved.
//
import WatchKit
class MyRowController: NSObject {
@IBOutlet var myLabel: WKInterfaceLabel!
}
|
//
// ListStoryViewRouter.swift
// Free Ebook
//
// Created by MinhNT-Mac on 1/11/19.
// Copyright © 2019 MinhNT-Mac. All rights reserved.
//
import Foundation
import UIKit
protocol ListStoryViewRouter: ViewRouter {
func presentDetail()
}
class ListStoryViewRouterImplementation: ListStoryViewRouter {
fileprivate weak var listStoryController: ListStoryViewController?
init(listStoryController: ListStoryViewController) {
self.listStoryController = listStoryController
}
func presentDetail() {
let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "screenDetail")
listStoryController?.navigationController?.pushViewController(vc, animated: true)
}
}
|
//
// Lottery.swift
// hecApp-iOS
//
// Created by Asianark on 16/3/8.
// Copyright © 2016年 Asianark. All rights reserved.
//
import UIKit
class LotteryType {
var id:Int!
var name: String!
var icon: UIImage?
var period: String?
var number: [Int]?
var issueNo: String?
var description: String?
var extra: String?
var isActive:Bool!
var typeUrl:String?
init?(name: String, icon: UIImage?, description: String?,extra: String? = "",typeUrl:String? = "Chongqing") {
// Initialize stored properties.
self.name = name
self.icon = icon
self.description = description
self.extra = extra
self.isActive = false
self.typeUrl = typeUrl
}
}
class BetInfo{
var lotteryID:Int!
var lotteryName:String!;
var playTypeID:Int!
var playTypeName:String!
var playTypeRadioID:Int!
var playTypeRadioName:String!
var price:Double!
var amount:Int!
var selectedNums:[[String]]!
init?(lotteryID: Int, lotteryName: String, playTypeID: Int ,playTypeName: String ,playTypeRadioID:Int , playTypeRadioName: String, price:Double, amount: Int, selectedNums:[[String]] ) {
self.lotteryID = lotteryID
self.lotteryName = lotteryName
self.playTypeID = playTypeID
self.playTypeName = playTypeName
self.playTypeRadioID = playTypeRadioID
self.playTypeRadioName = playTypeRadioName
self.price = price
self.amount = amount
self.selectedNums = selectedNums
}
}
class LotteryFactory{
static let factory = LotteryFactory()
//时时彩
static var ssc = [LotteryType]()
//PK10
static var pk10 = [LotteryType]()
//分分彩
static var ffc = [LotteryType]()
//十一选五
static var selectFive = [LotteryType]()
//低频彩
static var lowFrequece = [LotteryType]()
//生成彩种
func CreateLottery(name:String, url:String) -> LotteryType {
switch name {
case "重庆时时彩":
return LotteryType(name: name, icon:UIImage(named: "icon_重庆时时彩"), description:"人气高,易分析,玩法齐全",extra:"icon_lottery_hot",typeUrl:url)!
case "新疆时时彩":
return LotteryType(name: name, icon:UIImage(named: "icon_新疆时时彩"), description:"开奖快,中奖率高,玩法简单多样",typeUrl:url)!
case "江西时时彩":
return LotteryType(name: name, icon:UIImage(named: "icon_江西时时彩"), description:"数字型玩法,更容易组合和分析",typeUrl:url)!
case "和盛时时彩":
return LotteryType(name: name, icon:UIImage(named: "icon_和盛时时彩"), description:"人气高,易分析,玩法齐全",typeUrl:url)!
case "福彩3D":
return LotteryType(name: name, icon:UIImage(named: "icon_福彩3D"), description:"玩法简单,易分析,中奖率高",typeUrl:url)!
case "体彩排列三":
return LotteryType(name: name, icon:UIImage(named: "icon_体彩排列3"), description:"由中体彩中心统一发行,经典彩种",extra:"icon_lottery_hot",typeUrl:url)!
case "广东十一选五":
return LotteryType(name: name, icon:UIImage(named: "icon_广东11选5"), description:"十分钟一期,全天84期,中奖率高",typeUrl:url)!
case "山东十一选五":
return LotteryType(name: name, icon:UIImage(named: "icon_山东11选5"), description:"又名“十一运夺金”,玩法简单多样",typeUrl:url)!
case "和盛十一选五":
return LotteryType(name: name, icon:UIImage(named: "icon_和盛11选5"), description:"开奖快,和盛独家,玩法简单多样",typeUrl:url)!
case "和盛分分彩":
return LotteryType(name: name, icon:UIImage(named: "icon_和盛分分彩"), description:"人气高,易分析,玩法齐全",typeUrl:url)!
case "北京PK拾":
return LotteryType(name: name, icon:UIImage(named: "icon_PK10"), description:"大小,龙虎,单双,和值,玩法多样",extra:"icon_lottery_new",typeUrl:url)!
default:
return LotteryType(name: name, icon:UIImage(named: "icon_重庆时时彩"), description:"人气高,易分析,玩法齐全",extra:"icon_lottery_new",typeUrl:url)!
}
}
}
|
//
// Post.swift
// BudgeIt
//
// Created by Matt on 11/5/16.
// Copyright © 2016 Matt Del Signore. All rights reserved.
//
import Foundation
import FirebaseAuth
import Firebase
class Post{
var title:String
var id:Int = 0
var text:String
var numRatings:Int
var ratedBy:[Int:Float]
var totalRating:Int
var comments:Array<Comment>
var zip:Int
var postedBy:String
var datePosted:NSDate
init(title:String,id:Int,text:String,numR:Int,ratedBy:[Int:Float],totalRating:Int,comments:Array<Comment>,zip:Int,postedBy:String,datePosted:NSDate){
self.title = title
self.id = id
self.text = text
self.numRatings = numR
self.totalRating = totalRating
self.comments = comments
self.zip = zip
self.postedBy = postedBy
self.datePosted = datePosted
self.ratedBy = ratedBy
}
init(dict:[String:AnyObject]) {
self.title = dict["title"] as! String
self.id = dict["id"] as! Int
self.text = dict["text"] as! String
self.numRatings = dict["numRatings"] as! Int
self.totalRating = dict["totalRating"] as! Int
self.comments = Comment.commentsFromDictionary(d:dict["comments"] as! [[String:AnyObject]]) as! [Comment]
self.zip = dict["zip"] as! Int
self.postedBy = dict["postedBy"] as! String
self.datePosted = dict["datePosted"] as! NSDate
self.ratedBy = dict["ratedBy"] as! [Int:Float]
}
class func PostsWithArray(dicts:[[String:AnyObject]]) -> [Post]{
var posts = [Post]()
for e in dicts{
posts.append(Post(dict: e))
}
return posts
}
}
|
//
// StorageService.swift
// KifuSF
//
// Created by Alexandru Turcanu on 28/07/2018.
// Copyright © 2018 Alexandru Turcanu. All rights reserved.
//
import Foundation
import UIKit
import FirebaseStorage
struct StorageService {
public static func uploadImage(
_ image: UIImage,
at reference: StorageReference,
completion: @escaping (URL?) -> Void) {
guard let imageData = UIImageJPEGRepresentation(image, 0.05) else {
return completion(nil)
}
reference.putData(imageData, metadata: nil) { (_, error) in
if let error = error {
assertionFailure(error.localizedDescription)
return completion(nil)
}
reference.downloadURL(completion: { (url, error) in
if let error = error {
assertionFailure(error.localizedDescription)
return completion(nil)
}
return completion(url)
})
}
}
}
|
//
// MainViewModel.swift
// Weather
//
// Created by 진재명 on 8/21/19.
// Copyright © 2019 Jaemyeong Jin. All rights reserved.
//
import CoreData
import Foundation
class MainViewModel: NSObject {
let fetchedResultsController: NSFetchedResultsController<Location>
@objc dynamic var results: [WeatherViewModel] = []
@objc dynamic var currentPage = 0
let weatherAPI: YahooWeatherAPI
init(managedObjectContext: NSManagedObjectContext, weatherAPI: YahooWeatherAPI) {
self.weatherAPI = weatherAPI
let fetchRequest: NSFetchRequest = Location.fetchRequest()
fetchRequest.sortDescriptors = [
NSSortDescriptor(key: "createdAt", ascending: true),
]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: managedObjectContext,
sectionNameKeyPath: nil,
cacheName: nil)
self.fetchedResultsController = fetchedResultsController
super.init()
fetchedResultsController.delegate = self
NotificationCenter.default.addObserver(self,
selector: #selector(self.managedObjectContextDidSave(_:)),
name: .NSManagedObjectContextDidSave,
object: nil)
}
@objc func managedObjectContextDidSave(_ notification: Notification) {
self.fetchedResultsController.managedObjectContext.mergeChanges(fromContextDidSave: notification)
}
func performFetch() throws {
try self.fetchedResultsController.performFetch()
let fetchedObjects: [Location]! = self.fetchedResultsController.fetchedObjects
assert(fetchedObjects != nil)
self.results = fetchedObjects.enumerated().map { WeatherViewModel(index: $0.offset, location: $0.element, weatherAPI: self.weatherAPI) }
}
}
extension MainViewModel: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
let fetchedObjects: [Location]! = controller.fetchedObjects as? [Location]
assert(fetchedObjects != nil)
self.results = fetchedObjects.enumerated().map { WeatherViewModel(index: $0.offset, location: $0.element, weatherAPI: self.weatherAPI) }
}
}
|
//
// NewsEndPoint.swift
// Animal House
//
// Created by Roy Geagea on 8/17/19.
// Copyright © 2019 Roy Geagea. All rights reserved.
//
import Foundation
import Combine
public enum NewsApi {
case getNews(paginationURL: String)
}
extension NewsApi: EndPointType {
var path: String {
switch self {
case .getNews(let paginationURL):
return "news?" + paginationURL
}
}
var httpMethod: HTTPMethod {
switch self {
case .getNews:
return .get
}
}
var task: HTTPTask {
switch self {
case .getNews:
return .requestParametersAndHeaders(bodyParameters: nil,
bodyEncoding: .urlEncoding,
urlParameters: [:], additionHeaders: nil)
}
}
var headers: HTTPHeaders? {
return nil
}
}
protocol NewsService {
func getNews(paginationURL: String) -> Future<PaginationListModel<NewsModel>, Error>
}
|
//
// class_contacts.swift
// Contacts
//
// Created by Ammi Tan on 2/18/17.
// Copyright © 2017 Ammi Tan. All rights reserved.
//
import Foundation
import UIKit
class contact: NSObject {
var firstName: String
var lastName: String
var phone: String?
init(firstName:String,lastName:String) {
self.firstName = firstName
self.lastName = lastName
}
func createphone(phone: String) {
self.phone = phone
}
func fullName(firstName: String, lastName:String)->String {
let firstLastName = "\(firstName) \(lastName)"
return firstLastName
}
}
|
//
// SocialButtons.swift
// Morphy
//
// Created by Daryna Mishchenko on 11/29/19.
// Copyright © 2019 Дарина Мищенко. All rights reserved.
//
import UIKit
class SocialButtons: UIView {
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var facebookButton: UIButton!
@IBOutlet weak var instaButton: UIButton!
@IBOutlet weak var googleButton: UIButton!
@IBOutlet weak var appleButton: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
commonSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonSetup()
}
func commonSetup() {
Bundle.main.loadNibNamed("SocialButtons", owner: self, options: nil)
addSubview(contentView)
backgroundColor = .clear
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
contentView.backgroundColor = .clear
}
}
|
//
// ViewController.swift
// mcwa
//
// Created by XingfuQiu on 15/10/8.
// Copyright © 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class ViewController: UIViewController, PlayerDelegate {
@IBOutlet weak var userAvatar: UIBarButtonItem!
let manager = AFHTTPRequestOperationManager()
var json: JSON! {
didSet {
if "ok" == self.json["state"].stringValue {
if let d = self.json["dataObject", "question"].array {
self.questions = d
}
if let users = self.json["dataObject", "user"].array {
self.users = users
}
}
}
}
var questions: Array<JSON>?
var users: Array<JSON>?
var buttonBack: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
MCUtils.checkNetWorkState(self)
//背景音乐
player_bg.delegate = self
player_bg.forever = true
print("appMusicStatus:\(appMusicStatus)")
if (appMusicStatus == 0) {
player_bg.playFileAtPath(music_bg)
}
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
//主界面背景渐变
// let background = turquoiseColor()
// background.frame = self.view.bounds
// self.view.layer.insertSublayer(background, atIndex: 0)
//方法一
self.view.layer.contents = UIImage(named: "main_bg")!.CGImage
//方法二 说的是占内存
//self.view.backgroundColor = UIColor(patternImage: UIImage(named: "main_bg")!)
custom_leftbar()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
}
func soundFinished(sender: AnyObject) { // delegate message from Player
print("play finished")
}
func custom_leftbar() {
buttonBack = UIButton(type: UIButtonType.Custom)
buttonBack.frame = CGRectMake(5, 0, 30, 30)
if let url = appUserAvatar {
buttonBack.yy_setImageWithURL(NSURL(string: url), forState: .Normal, placeholder: UIImage(named: "avatar_default"))
} else {
buttonBack.setImage(UIImage(named: "avatar_default"), forState: .Normal)
}
buttonBack.addTarget(self, action: "showLogin:", forControlEvents: UIControlEvents.TouchUpInside)
buttonBack.layer.masksToBounds = true
buttonBack.layer.cornerRadius = 15
buttonBack.layer.borderWidth = 1.5
buttonBack.layer.borderColor = UIColor(hexString: "#675580")?.CGColor
let leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: buttonBack)
self.navigationItem.setLeftBarButtonItem(leftBarButtonItem, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func beginWa(sender: UIButton) {
self.pleaseWait()
let dict = ["act":"question"]
manager.GET(URL_MC,
parameters: dict,
success: {
(operation, responseObject) -> Void in
self.json = JSON(responseObject)
self.clearAllNotice()
//收到数据,跳转到准备页面
self.performSegueWithIdentifier("showReady", sender: self)
}) { (operation, error) -> Void in
self.clearAllNotice()
MCUtils.showCustomHUD(self, aMsg: "获取题库失败,请重试", aType: .Error)
print(error)
}
}
//跳转Segue传值
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showReady" {
let receive = segue.destinationViewController as! readyViewController
receive.questions = self.questions
receive.users = self.users
}
}
override func viewWillAppear(animated: Bool) {
self.navigationItem.title = "MC哇!"
MobClick.beginLogPageView("viewController")
self.navigationController?.navigationBarHidden = false
}
override func viewWillDisappear(animated: Bool) {
MobClick.endLogPageView("viewController")
}
override func viewDidAppear(animated: Bool) {
if let url = appUserAvatar {
buttonBack.yy_setImageWithURL(NSURL(string: url), forState: .Normal, placeholder: UIImage(named: "avatar_default"))
} else {
buttonBack.setImage(UIImage(named: "avatar_default"), forState: .Normal)
}
}
//颜色渐变
func turquoiseColor() -> CAGradientLayer {
let topColor = UIColor(hexString: "#362057")
let bottomColor = UIColor(hexString: "#3b3f73")
let gradientColors: Array <AnyObject> = [topColor!.CGColor, bottomColor!.CGColor]
let gradientLocations: Array <NSNumber> = [0.0, 1.0]
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
return gradientLayer
}
@IBAction func showLogin(sender: UIBarButtonItem) {
mineViewController.showMineInfoPage(self.navigationController)
}
}
|
extension Song {
init?(json: [String: Any]) {
struct Key {
static let id = "trackId"
static let name = "trackName"
static let censoredName = "trackCensoredName"
static let trackTime = "trackTimeMillis"
static let isExplicit = "trackExplicitness"
}
guard let idValue = json[Key.id] as? Int,
let nameValue = json[Key.name] as? String,
let censoredNameValue = json[Key.censoredName] as? String,
let trackTimeValue = json[Key.trackTime] as? Int,
let isExplicitString = json[Key.isExplicit] as? String else {
return nil
}
self._id = idValue
self._name = nameValue
self._censoreName = censoredNameValue
self._trackTime = trackTimeValue
self._isExplicit = isExplicitString == "notExplicit" ? false : true
}
}//
// Song.swift
// iTunes Search
//
// Created by suryasoft konsultama on 6/5/17.
// Copyright © 2017 DavidValentino. All rights reserved.
//
import Foundation
struct Song{
let _id: Int
let _name: String
let _censoreName: String
let _trackTime: Int
let _isExplicit: Bool
}
|
//
// MaterialViewController.swift
// Jojo Vectores
//
// Created by Marco A. Peyrot on 10/23/17.
// Copyright © 2017 Marco A. Peyrot. All rights reserved.
//
import UIKit
class MaterialViewController: UIViewController {
@IBOutlet weak var pdfView: UIWebView!
@IBOutlet weak var tut1: UIButton!
@IBOutlet weak var tut2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setButtons()
let url = Bundle.main.url(forResource: "Manual", withExtension: "pdf")
if let url = url {
let urlRequest = NSURLRequest(url: url)
pdfView.loadRequest(urlRequest as URLRequest)
view.addSubview(pdfView)
}
// Do any additional setup after loading the view.
navigationItem.title = "Material de Estudio"
}
override func viewDidAppear(_ animated: Bool) {
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var shouldAutorotate: Bool {
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MetodoGrafico" {
if let viewController = segue.destination as? VideoViewController {
viewController.typeOfVideo = 1
}
} else {
if let viewController = segue.destination as? VideoViewController {
viewController.typeOfVideo = 2
}
}
}
func setButtons(){
// let buttonColor = UIColor(rgb: 0x633239)
// let buttonBckColor = UIColor(rgb: 0xB75D69)
// let buttonBorderColor = UIColor(rgb: 0x4F282D)
// Componentesbt.tintColor = buttonColor
// Componentesbt.backgroundColor = buttonBckColor
// Componentesbt.layer.cornerRadius = 10
// Componentesbt.clipsToBounds = true
// Componentesbt.layer.borderColor = buttonBorderColor.cgColor
// Componentesbt.layer.borderWidth = 1.5
let buttonTopColor = UIColor(rgb: 0xEF6461)
let buttonTintColor = UIColor(rgb: 0x002838)
tut1.backgroundColor = buttonTopColor
tut1.layer.cornerRadius = 10
tut1.clipsToBounds = true
tut1.tintColor = buttonTintColor
tut1.layer.borderWidth = 1.5
let buttonBotColor = UIColor(rgb: 0xE4B363)
tut2.backgroundColor = buttonBotColor
tut2.layer.cornerRadius = 10
tut2.clipsToBounds = true
tut2.tintColor = buttonTintColor
tut2.layer.borderWidth = 1.5
let bckColor = UIColor(rgb: 0xE0DFD5)
view.backgroundColor = bckColor
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.