text stringlengths 8 1.32M |
|---|
//
// TransactionDetailView.swift
// MMWallet
//
// Created by Dmitry Muravev on 22.07.2018.
// Copyright © 2018 micromoney. All rights reserved.
//
import UIKit
class TransactionDetailView: UIView {
@IBOutlet weak var closeButton: UIButton! {
didSet {
let closeButtonImage = R.image.closeIcon()
closeButton.setImage(closeButtonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
closeButton.tintColor = UIColor(componentType: .popButtonClose)
}
}
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var backViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var backViewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
tableView.register(R.nib.transactionDetailLoadingTableViewCell)
tableView.register(R.nib.transactionDetailTableViewCell)
tableView.register(R.nib.transactionDetailInputTableViewCell)
tableView.register(R.nib.transactionDetailStatusTableViewCell)
tableView.register(R.nib.transactionDetailDirectionTableViewCell)
tableView.rowHeight = UITableView.automaticDimension
}
}
@IBOutlet weak var backView: UIView! {
didSet {
backView.clipsToBounds = true
backView.layer.cornerRadius = 14
backView.backgroundColor = UIColor(componentType: .popBackground)
}
}
var cells: [UITableViewCell] = []
var cellsHeight: [CGFloat] = []
var transactionDetailModel: TransactionDetailModel?
var transactionId: Int = 0
var transactionIDTableViewCell: TransactionDetailDirectionTableViewCell?
func configureView(transactionId: Int) {
self.transactionId = transactionId
configureLoadingTable()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.scrollView.contentSize = CGSize(width: self.scrollView.contentSize.width, height: self.backViewHeightConstraint.constant + 28 + 41)
self.tableView.reloadData()
self.loadData()
}
}
func loadData() {
DataManager.shared.getTransaction(id: transactionId) { [weak self] (transactionDetailModel, error) in
if error == nil {
self?.transactionDetailModel = transactionDetailModel
self?.configureTable()
self?.tableView.reloadData()
}
}
}
@IBAction func closeAction(_ sender: Any) {
removeFromSuperview()
}
func configureLoadingTable() {
cells = []
cellsHeight = []
let cell = R.nib.transactionDetailLoadingTableViewCell.firstView(owner: nil)!
cell.selectionStyle = .none
cells.append(cell)
cellsHeight.append(cell.getHeight())
backViewHeightConstraint.constant = cell.getHeight() + 36 + 25
backViewTopConstraint.constant = self.bounds.height*0.5 - 41*2 - 36
tableView.reloadData()
}
func configureTable() {
cells = []
cellsHeight = []
guard let transactionDetailModel = transactionDetailModel else { return }
backViewTopConstraint.constant = 41
//To:
let cellID = R.nib.transactionDetailDirectionTableViewCell.firstView(owner: nil)!
cellID.applyData(titleString: "Transaction ID:", dataString: transactionDetailModel.hashString)
cellID.delegate = self
transactionIDTableViewCell = cellID
cells.append(cellID)
cellsHeight.append(cellID.getHeight())
//TimeStamp:
let dateFromFormatter = DateFormatter()
dateFromFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFromFormatter.dateFormat = "MMM-dd-yyyy hh:mm:ss a ZZZZ"
let cell6 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
cell6.applyData(titleString: "TimeStamp:", dataString: dateFromFormatter.string(from: transactionDetailModel.createdAt!))
cells.append(cell6)
cellsHeight.append(cell6.getHeight())
if let inputModel = transactionDetailModel.inputModel {
//Contract:
let cellContract = R.nib.transactionDetailDirectionTableViewCell.firstView(owner: nil)!
cellContract.applyData(titleString: "Contract:", dataString: inputModel.token!.hashString)
cellContract.delegate = self
cells.append(cellContract)
cellsHeight.append(cellContract.getHeight())
//From:
let cellFrom = R.nib.transactionDetailDirectionTableViewCell.firstView(owner: nil)!
cellFrom.applyData(titleString: "From:", dataString: transactionDetailModel.fromDirection!.hashString)
cellFrom.delegate = self
cells.append(cellFrom)
cellsHeight.append(cellFrom.getHeight())
//To:
let cellTo = R.nib.transactionDetailDirectionTableViewCell.firstView(owner: nil)!
cellTo.applyData(titleString: "To:", dataString: transactionDetailModel.toDirection!.hashString)
cellTo.delegate = self
cells.append(cellTo)
cellsHeight.append(cellTo.getHeight())
//tokenAmount
let cellTokenAmount = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
var valueUSD = ""
if let rate = inputModel.tokenRate {
valueUSD = " (USD \(rate.USD.cleanValue))"
}
cellTokenAmount.applyData(titleString: "Token Amount:", dataString: "\(inputModel.tokenAmount.cleanValue6) \(transactionDetailModel.symbol) \(valueUSD)")
cells.append(cellTokenAmount)
cellsHeight.append(cellTokenAmount.getHeight())
} else {
//From:
let cellFrom = R.nib.transactionDetailDirectionTableViewCell.firstView(owner: nil)!
cellFrom.applyData(titleString: "From:", dataString: transactionDetailModel.fromDirection!.hashString)
cellFrom.delegate = self
cells.append(cellFrom)
cellsHeight.append(cellFrom.getHeight())
//To:
let cellTo = R.nib.transactionDetailDirectionTableViewCell.firstView(owner: nil)!
cellTo.applyData(titleString: "To:", dataString: transactionDetailModel.toDirection!.hashString)
cellTo.delegate = self
cells.append(cellTo)
cellsHeight.append(cellTo.getHeight())
}
//Category:
//var cell3 = R.nib.transactionDetailInputTableViewCell.firstView(owner: nil)!
//cells.append(cell3)
//cellsHeight.append(86)
//TxReceipt Status:
let cell2 = R.nib.transactionDetailStatusTableViewCell.firstView(owner: nil)!
cell2.applyData(titleString: "TxReceipt Status:", dataString: transactionDetailModel.status)
cells.append(cell2)
cellsHeight.append(cell2.getHeight())
//Value:
let cell9 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
var valueUSD = ""
if let rate = transactionDetailModel.rate {
valueUSD = " (USD \(rate.USD.cleanValue))"
}
cell9.applyData(titleString: "Amount:", dataString: transactionDetailModel.amount.cleanValue6 + " " + transactionDetailModel.currency + valueUSD)
cells.append(cell9)
cellsHeight.append(cell9.getHeight())
//Description
let cell4 = R.nib.transactionDetailInputTableViewCell.firstView(owner: nil)!
cell4.applyData(titleString: "Description:", dataString: transactionDetailModel.descr)
cells.append(cell4)
cellsHeight.append(cell4.getHeight())
//Block Hash
let cellBlockHash = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
cellBlockHash.applyData(titleString: "Block Hash:", dataString: transactionDetailModel.blockHash)
cells.append(cellBlockHash)
cellsHeight.append(cellBlockHash.getHeight())
//Block Height:
if transactionDetailModel.blockNumber != 0 {
let cell5 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
cell5.applyData(titleString: "Block Height:", dataString: "\(transactionDetailModel.blockNumber)")
cells.append(cell5)
cellsHeight.append(cell5.getHeight())
}
//Gas Limit:
//var cell10 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
//cells.append(cell10)
//cellsHeight.append(62)
//Gas Used By Txn:
if transactionDetailModel.gas != 0 {
let cell11 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
cell11.applyData(titleString: "Gas Used By Txn:", dataString: "\(transactionDetailModel.gas)")
cells.append(cell11)
cellsHeight.append(cell11.getHeight())
}
//Gas Price:
if transactionDetailModel.gasPrice != 0 {
let cell12 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
cell12.applyData(titleString: "Gas Price:", dataString: "\(transactionDetailModel.gasPrice)")
cells.append(cell12)
cellsHeight.append(cell12.getHeight())
}
//Actual Tx Cost/Fee:
//var cell13 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
//cells.append(cell13)
//cellsHeight.append(62)
//Cumulative Gas Used:
//var cell14 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
//cells.append(cell14)
//cellsHeight.append(62)
//Nonce:
if transactionDetailModel.nonce != 0 {
let cell15 = R.nib.transactionDetailTableViewCell.firstView(owner: nil)!
cell15.applyData(titleString: "Nonce:", dataString: "\(transactionDetailModel.nonce)")
cells.append(cell15)
cellsHeight.append(cell15.getHeight())
}
//Input Data
if !transactionDetailModel.input.isEmpty {
let cell16 = R.nib.transactionDetailInputTableViewCell.firstView(owner: nil)!
cell16.applyData(titleString: "Input Data:", dataString: transactionDetailModel.input)
cells.append(cell16)
cellsHeight.append(cell16.getHeight())
} else {
if let inputModel = transactionDetailModel.inputModel {
let cell16 = R.nib.transactionDetailInputTableViewCell.firstView(owner: nil)!
cell16.applyData(titleString: "Input Data:", dataString: inputModel.data)
cells.append(cell16)
cellsHeight.append(cell16.getHeight())
}
}
calcContentHeight()
}
func calcContentHeight() {
var finalHeight: CGFloat = 0
for cellHeight in cellsHeight {
finalHeight += cellHeight
}
finalHeight += 36
finalHeight += 25
backViewHeightConstraint.constant = finalHeight
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.scrollView.contentSize = CGSize(width: self.scrollView.contentSize.width, height: self.backViewHeightConstraint.constant + 28 + 41)
self.tableView.reloadData()
}
}
func showQR(hashString: String) {
let assetQRView = R.nib.assetQRView.firstView(owner: nil)
UIApplication.shared.keyWindow?.addSubview(assetQRView!)
assetQRView!.snp.makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.left.equalTo(0)
make.width.equalTo(UIScreen.main.bounds.width)
make.height.equalTo(UIScreen.main.bounds.height)
}
assetQRView!.hashString = hashString
}
}
extension TransactionDetailView: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cells[indexPath.row]
}
}
extension TransactionDetailView: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if cellsHeight.count == 0 {
return 62
}
return cellsHeight[indexPath.row]
}
}
extension TransactionDetailView: TransactionDetailDirectionTableViewCellDelegate {
func transactionDetailDirectionTableViewCell(_ transactionDetailDirectionTableViewCell: TransactionDetailDirectionTableViewCell, didSelect hashString: String?) {
if transactionDetailDirectionTableViewCell == transactionIDTableViewCell {
guard let transactionDetailModel = transactionDetailModel else { return }
let currentNetwork = NetworkType(rawValue: transactionDetailModel.network)
guard let url = URL(string: currentNetwork!.getLink(hash: transactionDetailModel.hashString)) else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
return
}
if let hashString = hashString {
showQR(hashString: hashString)
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
|
import UIKit
protocol AddBeacon {
func addBeacon(item: Item)
}
class AddItemViewController: UIViewController {
@IBOutlet weak var txtName: UITextField!
@IBOutlet weak var txtUUID: UITextField!
@IBOutlet weak var txtMajor: UITextField!
@IBOutlet weak var txtMinor: UITextField!
@IBOutlet weak var btnAdd: UIButton!
let uuidRegex = try! NSRegularExpression(pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", options: .caseInsensitive)
var delegate: AddBeacon?
override func viewDidLoad() {
super.viewDidLoad()
var o = 1
for i in 2...5 {
o -= i
}
o = 4
btnAdd.isEnabled = false
btnAdd.isEnabled = !(!false && (true && !false))
}
@IBAction func textFieldEditingChanged(_ sender: UITextField) {
// Is the name a valid string?
let nameValid = (txtName.text!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).characters.count > 0)
var isUuidValid = (!true && (false || true)) // false
let uuidStringArray = txtUUID.text!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
var c = 1, a = 1
for i in 1...5 {
c += i
a += i
}
c /= a
if uuidStringArray.characters.count <= 0 {
var c = 1, a = 1
for i in 1...5 {
c += i
a += i
}
c /= a
}
else {
isUuidValid = (uuidRegex.numberOfMatches(in: uuidStringArray, options: [], range: NSMakeRange(0, uuidStringArray.characters.count)) > 0)
}
txtUUID.textColor = (isUuidValid) ? .black : .red
// enable the add button based on whether the name and uuid fields are valid
btnAdd.isEnabled = !((!nameValid) || (!isUuidValid))
var e = 1
for i in 3...9 {
e *= i
}
e = 4
let b = e + 1
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// get rid of the keyboard
self.view.endEditing(true)
}
@IBAction func btnAdd_Pressed(_ sender: UIButton) {
// create an Item
let uuidString = txtUUID.text!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) + "" // watch
let nombre = txtName.text!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) + ""
guard let uuidValue = UUID(uuidString: uuidString) else { return }
var c = 1, a = 1
for i in 1...8 {
c += i
a += i
}
c /= a
let majorVar = Int(txtMajor.text!) ?? 0
let minorVar = Int(txtMinor.text!) ?? 0
let newItem = Item(name: nombre, uuid: uuidValue, majorValue: majorVar, minorValue: minorVar)
var e = 1
for i in 1...5 {
e += i
}
e = 4
delegate?.addBeacon(item: newItem)
dismiss(animated: true, completion: nil)
if false {
let output = "beacon connection established"
}
}
@IBAction func btnCancel_Pressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
var c = 1, a = 1
for i in 1...2 {
c += i
a *= i
}
c /= a
}
}
extension AddItemViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
var c = 1, a = 1
for i in 1...11 {
c *= i
a += i
}
c /= a
textField.resignFirstResponder()
var output = (!false && (true && !false))
return output
return true
}
}
|
//
// PrescriptionController.swift
// HISmartPhone
//
// Created by DINH TRIEU on 12/23/17.
// Copyright © 2017 MACOS. All rights reserved.
//
import UIKit
class PrescriptionController: DiagnoseController {
//MARK: Variable
fileprivate var listPrescription = [Prescription]()
fileprivate let prescriptionFacade = PrescriptionFacade()
//MARK: Initialize
override func setupView() {
super.setupView()
self.setTitle("Đơn thuốc")
if Authentication.share.typeUser == .doctor {
self.optionMenu.setOption(images: [#imageLiteral(resourceName: "history"), #imageLiteral(resourceName: "clear_blue")],
title: [ "Xem đơn thuốc gần nhất", "Xoá đơn thuốc"])
} else {
self.optionMenu.setOption(images: [#imageLiteral(resourceName: "history")],
title: [ "Xem đơn thuốc gần nhất"])
}
self.optionMenu.delegate = self
self.collectionViewHistory.delegate = self
self.collectionViewHistory.dataSource = self
NotificationCenter.default.addObserver(self, selector: #selector(fetchData), name: NSNotification.Name.init(Notification.Name.updateListPrescription), object: nil)
}
//MARK: Action UIControl
//MARK: Feature
@objc override func fetchData() {
self.prescriptionFacade.loadAllPrescription {
self.listPrescription = self.prescriptionFacade.prescriptions
self.collectionViewHistory.reloadData()
if self.listPrescription.count == 0 {
self.optionButton.isHidden = true
self.emptyAnnoucementLabel.isHidden = false
} else {
self.optionButton.isHidden = false
self.emptyAnnoucementLabel.isHidden = true
}
}
}
override func chooseShowDetailVC() {
let detailPrescriptionVC = DetailPrescriptionController()
detailPrescriptionVC.prescription = self.listPrescription.first
self.navigationController?.pushViewController(detailPrescriptionVC, animated: true)
}
override func chooseShowAddNewVC() {
let addNewDrugVC = AddNewDrugController()
addNewDrugVC.hidesBottomBarWhenPushed = false
self.navigationController?.pushViewController(addNewDrugVC, animated: true)
}
override func selectedDelete() {
self.prescriptionFacade.deletePrescription(at: self.selectedIndexPaths) {
self.fetchData()
self.selectedIndexPaths.removeAll()
}
}
}
//MARK: - UICollectionView DELEGATE, DATASOURCE
extension PrescriptionController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.listPrescription.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as? DiagnoseCell else { return UICollectionViewCell() }
cell.set(indexPath: indexPath)
cell.delegate = self
cell.prescription = self.listPrescription[indexPath.item]
if self.isSelectedAdd {
cell.showImage(status: .hide)
} else {
if self.selectedIndexPaths.contains(indexPath) {
cell.showImage(status: .on)
} else {
cell.showImage(status: .off)
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: Dimension.shared.heightPatientInfoResult)
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.optionMenu.hide()
if self.isSelectedAdd {
let detailPrescriptionVC = DetailPrescriptionController()
detailPrescriptionVC.prescription = self.listPrescription[indexPath.item]
self.navigationController?.pushViewController(detailPrescriptionVC, animated: true)
} else {
self.addSelectedIndexPath(indexPath: indexPath)
}
}
}
|
//
// CreatePartyViewController.swift
// Teazy
//
// Created by Dev on 05/06/2017.
// Copyright © 2017 Dev. All rights reserved.
//
import UIKit
class CreatePartyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var UIBarButtonCancel: UIBarButtonItem!
@IBOutlet weak var inputAdress: UITextField!
@IBOutlet weak var inputDate: UITextField!
@IBOutlet weak var inputHour: UITextField!
@IBOutlet weak var inputName: UITextField!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var friendsCollection: UICollectionView!
let images = ["profile-noemie", "profile-robin", "profile-justin"]
override func viewDidLoad() {
super.viewDidLoad()
self.UIBarButtonCancel.action = #selector(cancel(_:))
self.UIBarButtonCancel.target = self
self.view.backgroundColor = UIColor(red: 55/255, green: 71/255, blue: 92/255, alpha: 1)
// Style inputAdress
self.inputAdress.layer.cornerRadius = 0
self.inputAdress.layer.borderColor = UIColor.white.cgColor
self.inputAdress.layer.borderWidth = 1
self.inputAdress.backgroundColor = .clear
self.inputAdress.textColor = .white
self.inputDate.layer.cornerRadius = 0
self.inputDate.layer.borderColor = UIColor.white.cgColor
self.inputDate.layer.borderWidth = 1
self.inputDate.backgroundColor = .clear
self.inputDate.textColor = .white
self.inputHour.layer.cornerRadius = 0
self.inputHour.layer.borderColor = UIColor.white.cgColor
self.inputHour.layer.borderWidth = 1
self.inputHour.backgroundColor = .clear
self.inputHour.textColor = .white
self.inputName.layer.cornerRadius = 0
self.inputName.layer.borderColor = UIColor.white.cgColor
self.inputName.layer.borderWidth = 1
self.inputName.backgroundColor = .clear
self.inputName.textColor = .white
// Friends collection
friendsCollection.delegate = self
friendsCollection.dataSource = self
friendsCollection.backgroundColor = UIColor(red: 47/255, green: 63/255, blue: 83/255, alpha: 1)
// Button
self.button.backgroundColor = UIColor(red: 244/255, green: 179/255, blue: 80/255, alpha: 1)
self.button.layer.cornerRadius = 3
self.button.setTitleColor(UIColor.white, for: .normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func cancel(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! FriendsCollectionViewCell
cell.image.image = UIImage(named: images[indexPath.row])
cell.image.layer.cornerRadius = (cell.image.frame.width / 2)
cell.image.layer.masksToBounds = true
return cell
}
}
|
//
// XZCHomeCollectionViewCell.swift
// CollectionView
//
// Created by etlfab on 2021/5/10.
//
import UIKit
class XZCHomeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var avatarImage: UIImageView!
/**
不适用xib需要这么写
*/
// override init(frame: CGRect) {
// super.init(frame: frame)
// self.avatarImage.backgroundColor = .red
//
// }
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
//
// fatalError("init(coder:) has not been implemented")
//
// }
override func awakeFromNib() {
super.awakeFromNib()
}
open func setImage(imageUrl: String) {
self.avatarImage.image = UIImage(named: imageUrl)
}
}
|
//
// Cell.swift
// CurveMovies
//
// Created by John Cranstone on 25/04/2019.
// Copyright © 2019 John Cranstone. All rights reserved.
//
import Foundation
import UIKit
class MovieCellView: UITableViewCell {
@IBOutlet weak var moviePoster: UIImageView!
@IBOutlet weak var movieTitle: UILabel!
@IBOutlet weak var movieDescription: UILabel!
@IBOutlet weak var movieRatingLbl: UILabel!
@IBOutlet weak var releaseDate: UILabel!
@IBOutlet weak var likeImage: UIImageView!
func setCell(count:Int){
let url = URL(string: "http://image.tmdb.org/t/p/w500/"+moviePath[count])
DispatchQueue.global().async {
//download and present image using link above
let data = try? Data(contentsOf: url!)
if let imageData = data {
let poster = UIImage(data: imageData)
DispatchQueue.main.async {
self.moviePoster.image = poster
}
}
}
//Set text from Movie model
movieTitle.text = movieName[count]
movieDescription.text = movieDesc[count]
releaseDate.text = movieRelease[count]
//Rating check
let formatReady = movieRating[count] * 10
if(formatReady < 40){
movieRatingLbl.textColor = UIColor.red
}else if(formatReady < 70 && formatReady >= 40 ){
movieRatingLbl.textColor = UIColor.orange
}else{
movieRatingLbl.textColor = UIColor.green
}
let ratingFormatted = String(format:"%.0f%%",formatReady)
movieRatingLbl.text = ratingFormatted
}
}
|
//
// ApiParams.swift
import Foundation
struct ApiParams
{
public let scheme:String
public let host:String
public let path:String
}
|
//
// BEUICommonDefines.swift
// Bubbles
//
// Created by god on 2018/8/25.
// Copyright © 2018 God. All rights reserved.
//
import Foundation
import UIKit
let IOS8_SDK_ALLOWED = __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
let IOS9_SDK_ALLOWED = __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
let IOS10_SDK_ALLOWED = __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
let IOS11_SDK_ALLOWED = __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
let IOS_VERSION = Double(UIDevice.current.systemVersion)
let IS_LANDSCAPE = UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation)
let IS_DEVICE_LANDSCAPE = UIDeviceOrientationIsLandscape(UIDevice.current.orientation)
let SCREEN_WIDTH = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
let DEVICE_WIDTH = IS_LANDSCAPE ? SCREEN_HEIGHT : SCREEN_WIDTH
let DEVICE_HEIGHT = IS_LANDSCAPE ? SCREEN_WIDTH : SCREEN_HEIGHT
let SCREEN_SIZE_58INCH = CGSize(width: 375, height: 812)
let SCREEN_SIZE_55INCH = CGSize(width: 414, height: 736)
let SCREEN_SIZE_47INCH = CGSize(width: 375, height: 667)
let SCREEN_SIZE_40INCH = CGSize(width: 320, height: 568)
let SCREEN_SIZE_35INCH = CGSize(width: 320, height: 480)
let IS_58INCH_SCREEN = DEVICE_WIDTH == SCREEN_SIZE_58INCH.width && DEVICE_HEIGHT == SCREEN_SIZE_58INCH.height
let IS_55INCH_SCREEN = DEVICE_WIDTH == SCREEN_SIZE_55INCH.width && DEVICE_HEIGHT == SCREEN_SIZE_55INCH.height
let IS_47INCH_SCREEN = DEVICE_WIDTH == SCREEN_SIZE_47INCH.width && DEVICE_HEIGHT == SCREEN_SIZE_47INCH.height
let IS_40INCH_SCREEN = DEVICE_WIDTH == SCREEN_SIZE_40INCH.width && DEVICE_HEIGHT == SCREEN_SIZE_40INCH.height
let IS_35INCH_SCREEN = DEVICE_WIDTH == SCREEN_SIZE_35INCH.width && DEVICE_HEIGHT == SCREEN_SIZE_35INCH.height
let IS_320WIDTH_SCREEN = IS_35INCH_SCREEN || IS_40INCH_SCREEN
let IS_RETINASCREEN = UIScreen.main.scale >= 2.0
let IS_IPHONEX = IS_58INCH_SCREEN && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone
let ScreenBoundsSize = UIScreen.main.bounds.size
let ScreenNativeBoundsSize = UIScreen.main.nativeBounds.size
let ScreenScale = UIScreen.main.scale
let ScreenNativeScale = UIScreen.main.nativeScale
let StatusBarHeight = UIApplication.shared.isStatusBarHidden ? 0 : UIApplication.shared.statusBarFrame.size.height
let NavigationBarHeight: CGFloat = 44.0
let ToolBarHeight = IS_IPHONEX ? 83 : 44
let TabBarHeight = IS_IPHONEX ? 83 : 49
let NavigationContentStaticHeight = StatusBarHeight + NavigationBarHeight
|
//
// TableViewProtocolViewModel.swift
// Swift_Project
//
// Created by HongpengYu on 2018/8/2.
// Copyright © 2018年 HongpengYu. All rights reserved.
//
import UIKit
// MARK: - 协议
/// 标题协议
protocol TitlePresentable {
var titleLabel: UILabel! { get set }
func setTitle(title: String?)
}
extension TitlePresentable {
func setTitle(title: String?) {
titleLabel.text = title
}
}
/// 子标题协议
protocol SubTitlePresentable {
var subTitleLabel: UILabel! { get set }
func setSubTitle(title: String?)
}
extension SubTitlePresentable {
func setSubTitle(title: String?) {
subTitleLabel.text = title
}
}
/// 字节数协议
protocol BytesCountPresentable {
var bytesCountLabel: UILabel! { get set }
func setBytesCount(bytesCount: Int)
}
extension BytesCountPresentable {
func setBytesCount(bytesCount: Int) {
bytesCountLabel.text = bytesCountString(bytesCount)
}
private func bytesCountString(_ bytesCount: Int) -> String {
return "\(bytesCount)"
}
}
// MARK: -
// MARK: - 使用协议ViewModel
/// 带有switch 协议
protocol SwitchPresentable {
var title: String { get }
var switchIsOn: Bool { get }
func switchControlChange(isOn: Bool)
}
extension SwitchPresentable {
/// 设置开关默认颜色
func setSwitchColor() -> UIColor {
return .yellow
}
}
struct SwitchControlViewModel: SwitchPresentable {
var title: String = "开关cell"
var switchIsOn: Bool = true
func switchControlChange(isOn: Bool) {
if isOn {
print("打开的")
} else {
print("关闭的")
}
}
func setSwitchColor() -> UIColor {
return .orange
}
}
// MARK: -
// MARK: - 分离出cell 的数据源协议和委托协议
// MARK: - dataSource 协议
protocol SwitchControlCellDataSource {
var title: String { get }
var switchIsOn: Bool { get }
}
// MARK: - delegate 协议
protocol SwitchControlCellDelegate {
var textColor: UIColor { get }
var switchColor: UIColor { get }
var font: UIFont { get }
func switchControlChanged(isOn: Bool)
}
// 默认实现
extension SwitchControlCellDelegate {
var textColor: UIColor {
return .purple
}
var switchColor: UIColor {
return .orange
}
var font: UIFont {
return UIFont.boldSystemFont(ofSize: 14)
}
}
struct SwitchControlViewModel2: SwitchControlCellDataSource {
var title: String = "cell代理和数据源分离后cell"
var switchIsOn: Bool = false
}
extension SwitchControlViewModel2: SwitchControlCellDelegate {
var switchColor: UIColor {
return .blue
}
func switchControlChanged(isOn: Bool) {
if isOn {
print("cell2打开了开关")
} else {
print("cell2关闭了开关")
}
}
}
|
//
// XHBaseScrollViewViewController.swift
// ObjcTools
//
// Created by douhuo on 2021/3/1.
// Copyright © 2021 wangergang. All rights reserved.
//
import UIKit
class XHBaseScrollViewViewController: XHBaseViewController {
/// 当前页面
var page = 1
/// 当前的size
var pageSize = 10
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/// 刷新 tableview
func reloadTBView() {}
/// 停止架子啊动画
func stopAnimation() {}
// MARK: - 请求数据,供具体子类覆盖
/// 请求数据,供具体子类覆盖
override func requestList() {}
/// 加载更多
func loadMoreTableView() {}
// MARK: - 这个方法给子类设置 tableView 的 样式 ,frame pageSize 等
/// 这个方法给子类设置 tableView 的 样式 ,frame pageSize 等
func prepareTableView() {}
// MARK: - 初始化完成之后优化方法,比如设置cell class,tableview实际frame 等 需要在初始化 view 之后,如果没有特别的地方这个方法可以不用调用
/// 初始化完成之后优化方法,比如设置cell class,tableview实际frame 等 需要在初始化 view 之后,如果没有特别的地方这个方法可以不用调用
func optimizeMethod() {}
}
|
//
// DeviceOption.swift
// SaneScanner
//
// Created by Stanislas Chevallier on 30/01/19.
// Copyright (c) 2019 Syan. All rights reserved.
//
import Foundation
// MARK: Basic option
public class DeviceOption {
// MARK: Init
init(cOption: SANE_Option_Descriptor, index: Int, device: Device) {
self.index = index
self.device = device
self.identifier = cOption.name?.asString() ?? "option-\(index)"
self.localizedTitle = cOption.title?.asString()?.saneTranslation ?? ""
self.localizedDescr = cOption.desc?.asString()?.saneTranslation ?? ""
self.capabilities = SaneCapabilities(rawValue: cOption.cap)
self.type = cOption.type
self.unit = cOption.unit
self.size = Int(cOption.size)
}
// MARK: Properties
public let index: Int
public let device: Device
public let identifier: String
public var localizedTitle: String
public var localizedDescr: String
public var capabilities: SaneCapabilities
internal var type: SANE_Value_Type
internal var unit: SANE_Unit
internal var size: Int
// MARK: Computed properties
public var disabledOrReadOnly: Bool {
return capabilities.contains(.inactive) || !capabilities.contains(.softwareSettable)
}
public var hasSingleOption: Bool {
return true
}
// MARK: Value
public var localizedValue: String {
return ""
}
internal func refreshValue(_ block: SaneCompletion<()>?) {
block?(.success(()))
}
// MARK: Helpers
fileprivate static func assertType(cOption: SANE_Option_Descriptor, type: SANE_Value_Type, class: AnyClass) -> () {
guard cOption.type == type else {
let className = String(describing: `class`)
fatalError("\(className) should only be used with \(type.description) option type")
}
}
internal static func typedOption(cOption: SANE_Option_Descriptor, index: Int, device: Device) -> DeviceOption {
switch cOption.type {
case SANE_TYPE_BOOL: return DeviceOptionBool(cOption: cOption, index: index, device: device, initialValue: false)
case SANE_TYPE_INT: return DeviceOptionInt(cOption: cOption, index: index, device: device, initialValue: 0)
case SANE_TYPE_FIXED: return DeviceOptionFixed(cOption: cOption, index: index, device: device, initialValue: 0)
case SANE_TYPE_STRING: return DeviceOptionString(cOption: cOption, index: index, device: device, initialValue: "")
case SANE_TYPE_BUTTON: return DeviceOptionButton(cOption: cOption, index: index, device: device, initialValue: false)
case SANE_TYPE_GROUP: return DeviceOptionGroup(cOption: cOption, index: index, device: device)
default: fatalError("Unsupported type \(cOption.type) for option at index \(index) in device \(device.description)")
}
}
}
extension DeviceOption: CustomStringConvertible {
public var description: String {
return "\(Swift.type(of: self)): \(index), \(localizedTitle), \(type.description), \(unit.description)"
}
}
extension DeviceOption: Equatable {
public static func == (lhs: DeviceOption, rhs: DeviceOption) -> Bool {
return lhs.device == rhs.device && lhs.index == rhs.index
}
}
// MARK: Typed option
public class DeviceOptionTyped<T: Equatable & CustomStringConvertible>: DeviceOption {
// MARK: Init
init(cOption: SANE_Option_Descriptor, index: Int, device: Device, initialValue: T) {
self.value = initialValue
self.constraint = Swift.type(of: self).parseConstraint(cOption: cOption)
super.init(cOption: cOption, index: index, device: device)
}
// MARK: Value
public internal(set) var value: T
public func stringForValue(_ value: T, userFacing: Bool) -> String {
fatalError("Not implemented")
}
internal func bytesForValue(_ value: T) -> Data {
fatalError("Not implemented")
}
internal func valueForBytes(_ bytes: UnsafeRawPointer) -> T {
fatalError("Not implemented")
}
internal class func parseConstraint(cOption: SANE_Option_Descriptor) -> OptionConstraint<T> {
// it is very important to compute the constraint at init time, instead of keeping a ref to cOption
// because cOption.contraint.word_list might be freed if we're trying to access it on an option
// that has since been reloaded.
fatalError("Not implemented")
}
public private(set) var constraint: OptionConstraint<T>
public var bestPreviewValue: DeviceOptionNewValue<T> {
fatalError("Not implemented")
}
internal override func refreshValue(_ block: SaneCompletion<()>?) {
Sane.shared.valueForOption(self) { result in
if case .success(let value) = result {
self.value = value
}
block?(result.map { _ in () })
}
}
public override var hasSingleOption: Bool {
return constraint.hasSingleValue
}
}
// MARK: Value option protocol
public protocol DeviceOptionTypedProtocol: AnyObject {
associatedtype Value: Equatable & CustomStringConvertible
var value: Value { get }
}
extension DeviceOptionTyped : DeviceOptionTypedProtocol { }
// MARK: Typed option value
public enum DeviceOptionNewValue<T> {
case none, auto, value(T)
}
// MARK: Option constraints
public enum OptionConstraint<T: Equatable & CustomStringConvertible> {
case none, range(min: T, max: T), stepRange(min: T, max: T, step: T, values: [T]), list([T])
var hasSingleValue: Bool {
switch self {
case .none: return false
case .range(let min, let max): return min == max
case .stepRange(_, _, _, let values), .list(let values): return values.count == 1
}
}
}
extension OptionConstraint : CustomStringConvertible {
public var description: String {
switch self {
case .none:
return "OPTION CONSTRAINED NOT CONSTRAINED".saneTranslation
case .range(let min, let max):
return String(format: "OPTION CONSTRAINED RANGE FROM TO %@ %@".saneTranslation, min.description, max.description)
case .stepRange(let min, let max, let step, _):
return String(format: "OPTION CONSTRAINED RANGE FROM TO STEP %@ %@ %@".saneTranslation, min.description, max.description, step.description)
case .list(let values):
let strings = values.map { $0.description }
return String(format: "OPTION CONSTRAINED LIST %@".saneTranslation, strings.joined(separator: ", "))
}
}
}
// MARK: Bool
public class DeviceOptionBool: DeviceOptionTyped<Bool> {
override init(cOption: SANE_Option_Descriptor, index: Int, device: Device, initialValue: Bool) {
DeviceOption.assertType(cOption: cOption, type: SANE_TYPE_BOOL, class: DeviceOptionBool.self)
super.init(cOption: cOption, index: index, device: device, initialValue: initialValue)
}
public override var localizedValue: String {
return stringForValue(value, userFacing: true)
}
public override func stringForValue(_ value: Bool, userFacing: Bool) -> String {
if userFacing {
return value ? "OPTION BOOL ON".saneTranslation : "OPTION BOOL OFF".saneTranslation
}
return value ? "On" : "Off"
}
internal override func bytesForValue(_ value: Bool) -> Data {
var data = Data(repeating: 0, count: size)
data.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> () in
bytes.bindMemory(to: SANE_Bool.self).baseAddress?.pointee = value ? SANE_TRUE : SANE_FALSE
}
return data
}
internal override func valueForBytes(_ bytes: UnsafeRawPointer) -> Bool {
return bytes.bindMemory(to: SANE_Bool.self, capacity: size).pointee == SANE_TRUE
}
override class func parseConstraint(cOption: SANE_Option_Descriptor) -> OptionConstraint<Bool> {
return .none
}
public override var bestPreviewValue: DeviceOptionNewValue<Bool> {
guard let value = SaneStandardOption(saneIdentifier: identifier)?.bestPreviewValue else { return .none }
switch value {
case .auto: return capabilities.contains(.automatic) ? .auto : .value(self.value)
case .on: return .value(true)
case .off: return .value(false)
default:
fatalError("Unsupported preview value \(value) for option \(identifier)")
}
}
}
// MARK: Int
public class DeviceOptionInt: DeviceOptionTyped<Int> {
override init(cOption: SANE_Option_Descriptor, index: Int, device: Device, initialValue: Int) {
DeviceOption.assertType(cOption: cOption, type: SANE_TYPE_INT, class: DeviceOptionInt.self)
super.init(cOption: cOption, index: index, device: device, initialValue: initialValue)
}
public override var localizedValue: String {
return stringForValue(value, userFacing: true)
}
public override func stringForValue(_ value: Int, userFacing: Bool) -> String {
let unitString = userFacing && unit != SANE_UNIT_NONE ? " " + unit.description : ""
return String(value) + unitString
}
internal override func bytesForValue(_ value: Int) -> Data {
var data = Data(repeating: 0, count: size)
data.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> () in
bytes.bindMemory(to: SANE_Int.self).baseAddress?.pointee = SANE_Int(value)
}
return data
}
internal override func valueForBytes(_ bytes: UnsafeRawPointer) -> Int {
let saneValue = bytes.bindMemory(to: SANE_Int.self, capacity: size).pointee
return Int(saneValue)
}
internal override class func parseConstraint(cOption: SANE_Option_Descriptor) -> OptionConstraint<Int> {
switch cOption.constraint_type {
case SANE_CONSTRAINT_NONE:
return .none
case SANE_CONSTRAINT_RANGE:
let minValue = Int(cOption.constraint.range.pointee.min)
let maxValue = Int(cOption.constraint.range.pointee.max)
let stepValue = Int(cOption.constraint.range.pointee.quant)
if stepValue == 0 {
return OptionConstraint<Int>.range(min: minValue, max: maxValue)
}
let values = stride(from: minValue, through: maxValue, by: stepValue)
return OptionConstraint<Int>.stepRange(min: minValue, max: maxValue, step: stepValue, values: Array(values))
case SANE_CONSTRAINT_WORD_LIST:
let count = cOption.constraint.word_list.pointee
let values = (0..<Int(count))
.map { cOption.constraint.word_list.advanced(by: $0 + 1).pointee }
.map { Int($0) }
return OptionConstraint<Int>.list(values)
default:
fatalError("Unsupported constraint type for DeviceOptionInt")
}
}
public override var bestPreviewValue: DeviceOptionNewValue<Int> {
guard let value = SaneStandardOption(saneIdentifier: identifier)?.bestPreviewValue else { return .none }
switch value {
case .auto(let fallback):
return capabilities.contains(.automatic) ? .auto : .value(fallback?.one ?? self.value)
case .min, .max:
switch constraint {
case .range(let min, let max), .stepRange(let min, let max, _, _):
return value == .min ? .value(min) : .value(max)
case .list(let values):
guard !values.isEmpty else { return .none }
return value == .min ? .value(values.min()!) : .value(values.max()!)
case .none:
return .none
}
case .value(.one(let specificValue)):
switch constraint {
case .range(let min, let max):
return .value(specificValue.clamped(min: min, max: max))
case .list(let values), .stepRange(_, _, _, let values):
guard let closest = values.closest(to: specificValue) else { return .none }
return .value(closest)
case .none:
return .value(specificValue)
}
default:
fatalError("Unsupported preview value \(value) for option \(identifier)")
}
}
}
// MARK: Fixed float
public class DeviceOptionFixed: DeviceOptionTyped<Double> {
override init(cOption: SANE_Option_Descriptor, index: Int, device: Device, initialValue: Double) {
DeviceOption.assertType(cOption: cOption, type: SANE_TYPE_FIXED, class: DeviceOptionFixed.self)
super.init(cOption: cOption, index: index, device: device, initialValue: initialValue)
}
public override var localizedValue: String {
return stringForValue(value, userFacing: true)
}
public override func stringForValue(_ value: Double, userFacing: Bool) -> String {
let unitString = userFacing && unit != SANE_UNIT_NONE ? " " + unit.description : ""
return String(format: "%0.2lf", value) + unitString
}
internal override func bytesForValue(_ value: Double) -> Data {
var data = Data(repeating: 0, count: size)
data.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> () in
bytes.bindMemory(to: SANE_Word.self).baseAddress?.pointee = SaneFixedFromDouble(value)
}
return data
}
internal override func valueForBytes(_ bytes: UnsafeRawPointer) -> Double {
let saneValue = bytes.bindMemory(to: SANE_Fixed.self, capacity: size).pointee
return SaneDoubleFromFixed(saneValue)
}
internal override class func parseConstraint(cOption: SANE_Option_Descriptor) -> OptionConstraint<Double> {
switch cOption.constraint_type {
case SANE_CONSTRAINT_NONE:
return .none
case SANE_CONSTRAINT_RANGE:
let minValue = SaneDoubleFromFixed(cOption.constraint.range.pointee.min)
let maxValue = SaneDoubleFromFixed(cOption.constraint.range.pointee.max)
let stepValue = SaneDoubleFromFixed(cOption.constraint.range.pointee.quant)
if stepValue == 0 {
return OptionConstraint<Double>.range(min: minValue, max: maxValue)
}
let values = stride(from: minValue, through: maxValue, by: stepValue)
return OptionConstraint<Double>.stepRange(min: minValue, max: maxValue, step: stepValue, values: Array(values))
case SANE_CONSTRAINT_WORD_LIST:
let count = cOption.constraint.word_list.pointee
let values = (0..<Int(count))
.map { cOption.constraint.word_list.advanced(by: $0 + 1).pointee }
.map { SaneDoubleFromFixed($0)}
return OptionConstraint<Double>.list(values)
default:
fatalError("Unsupported constraint type for DeviceOptionFixed")
}
}
public override var bestPreviewValue: DeviceOptionNewValue<Double> {
guard let value = SaneStandardOption(saneIdentifier: identifier)?.bestPreviewValue else { return .none }
switch value {
case .auto(let fallback):
return capabilities.contains(.automatic) ? .auto : .value(fallback?.one.map(Double.init) ?? self.value)
case .min, .max:
switch constraint {
case .range(let min, let max), .stepRange(let min, let max, _, _):
return value == .min ? .value(min) : .value(max)
case .list(let values):
guard !values.isEmpty else { return .none }
return value == .min ? .value(values.min()!) : .value(values.max()!)
case .none:
return .none
}
case .value(.one(let specificValue)):
switch constraint {
case .range(let min, let max):
return .value(Double(specificValue).clamped(min: min, max: max))
case .list(let values), .stepRange(_, _, _, let values):
guard let closest = values.closest(to: Double(specificValue)) else { return .none }
return .value(closest)
case .none:
return .value(Double(specificValue))
}
default:
fatalError("Unsupported preview value \(value) for option \(identifier)")
}
}
}
// MARK: Numeric
internal protocol DeviceOptionNumeric {
var doubleValue: Double { get }
var bestPreviewDoubleValue: DeviceOptionNewValue<Double> { get }
}
extension DeviceOptionInt : DeviceOptionNumeric {
var doubleValue: Double {
return Double(value)
}
var bestPreviewDoubleValue: DeviceOptionNewValue<Double> {
switch self.bestPreviewValue {
case .value(let value): return .value(Double(value))
case .auto: return .auto
case .none: return .none
}
}
}
extension DeviceOptionFixed : DeviceOptionNumeric {
var doubleValue: Double {
return value
}
var bestPreviewDoubleValue: DeviceOptionNewValue<Double> {
return bestPreviewValue
}
}
// MARK: String
public class DeviceOptionString: DeviceOptionTyped<String> {
override init(cOption: SANE_Option_Descriptor, index: Int, device: Device, initialValue: String) {
DeviceOption.assertType(cOption: cOption, type: SANE_TYPE_STRING, class: DeviceOptionString.self)
super.init(cOption: cOption, index: index, device: device, initialValue: initialValue)
}
public override var localizedValue: String {
return stringForValue(value, userFacing: true)
}
public override func stringForValue(_ value: String, userFacing: Bool) -> String {
let unitString = userFacing && unit != SANE_UNIT_NONE ? " " + unit.description : ""
let stringValue = userFacing ? value.saneTranslation : value
return stringValue + unitString
}
internal override func bytesForValue(_ value: String) -> Data {
return value.data(using: .utf8)?.subarray(maxCount: size) ?? Data()
}
internal override func valueForBytes(_ bytes: UnsafeRawPointer) -> String {
let saneValue = bytes.bindMemory(to: SANE_Char.self, capacity: size)
return String(cString: saneValue)
}
internal override class func parseConstraint(cOption: SANE_Option_Descriptor) -> OptionConstraint<String> {
switch cOption.constraint_type {
case SANE_CONSTRAINT_NONE:
return .none
case SANE_CONSTRAINT_STRING_LIST:
var values = [String]()
while let value = cOption.constraint.string_list.advanced(by: values.count).pointee {
values.append(value.asString() ?? "")
}
return OptionConstraint<String>.list(values)
default:
fatalError("Unsupported constraint type for DeviceOptionString")
}
}
public override var bestPreviewValue: DeviceOptionNewValue<String> {
guard let value = SaneStandardOption(saneIdentifier: identifier)?.bestPreviewValue else { return .none }
switch value {
case .auto(let fallback):
return capabilities.contains(.automatic) ? .auto : .value(fallback?.other ?? self.value)
default:
fatalError("Unsupported preview value \(value) for option \(identifier)")
}
}
}
// MARK: Button
public class DeviceOptionButton: DeviceOptionTyped<Bool> {
override init(cOption: SANE_Option_Descriptor, index: Int, device: Device, initialValue: Bool) {
DeviceOption.assertType(cOption: cOption, type: SANE_TYPE_BUTTON, class: DeviceOptionButton.self)
super.init(cOption: cOption, index: index, device: device, initialValue: initialValue)
}
public func press(_ completion: SaneCompletion<SaneInfo>?) {
Sane.shared.updateOption(self, with: .value(true), completion: completion)
}
public override var value: Bool {
get { return false }
set { super.value = newValue }
}
public override var localizedValue: String {
return stringForValue(value, userFacing: true)
}
public override func stringForValue(_ value: Bool, userFacing: Bool) -> String {
return ""
}
internal override func bytesForValue(_ value: Bool) -> Data {
return Data(repeating: value ? 1 : 0, count: size)
}
internal override func valueForBytes(_ bytes: UnsafeRawPointer) -> Bool {
return false
}
override class func parseConstraint(cOption: SANE_Option_Descriptor) -> OptionConstraint<Bool> {
return .none
}
public override var bestPreviewValue: DeviceOptionNewValue<Bool> {
return .none
}
}
// MARK: Group
public class DeviceOptionGroup: DeviceOption {
override init(cOption: SANE_Option_Descriptor, index: Int, device: Device) {
DeviceOption.assertType(cOption: cOption, type: SANE_TYPE_GROUP, class: DeviceOptionGroup.self)
super.init(cOption: cOption, index: index, device: device)
}
public func options(includeAdvanced: Bool) -> [DeviceOption] {
let nextGroupIndex = device.options
.compactMap { ($0 as? DeviceOptionGroup)?.index }
.sorted()
.first(where: { $0 > index }) ?? device.options.count
let allOptions = device.options.filter { $0.index > index && $0.index < nextGroupIndex }
var filteredOptions = allOptions
.filter { $0.identifier != SaneStandardOption.preview.saneIdentifier }
if device.canCrop {
let cropOptionsIDs = SaneStandardOption.cropOptions.map { $0.saneIdentifier }
filteredOptions.removeAll(where: { cropOptionsIDs.contains($0.identifier) })
}
if !includeAdvanced {
filteredOptions.removeAll(where: { $0.capabilities.contains(.advanced) })
}
return filteredOptions
}
}
|
//
// MomentCell.swift
// HFang
//
// Created by CHUN MARTHA on 2017/4/4.
// Copyright © 2017年 CHUN MARTHA. All rights reserved.
//
import UIKit
class MomentCell: UITableViewCell {
@IBOutlet weak var avatarBtn: UIButton!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var sayingLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var sceneryImageContainerView: UIView!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var likeBtn: UIButton!
@IBOutlet weak var commentBtn: UIButton!
var sceneryImageViews: [UIImageView] = []
var currentIndex: Int?
var navi: UINavigationController?
var aut: Author?
override func awakeFromNib() {
super.awakeFromNib()
}
func populateCell(_ cell: MomentCell, withMoment moment: Moment) {
let photoCount = moment.photoUrl?.count
cell.createSceneryImageViews(photoCount!)
for (index, sceneryImageView) in cell.sceneryImageViews.enumerated() {
sceneryImageView.sd_setImage(with: URL(string: moment.photoUrl?[index] as! String), placeholderImage: #imageLiteral(resourceName: "pic2"))
}
if moment.user?.avatar != nil {
cell.avatarBtn.sd_setBackgroundImage(with: URL(string: (moment.user?.avatar)!), for: .normal)
}
else {
cell.avatarBtn.sd_setBackgroundImage(with: nil, for: .normal, placeholderImage: #imageLiteral(resourceName: "default_avatar"))
}
cell.aut = moment.user
cell.likeBtn.setTitle(" " + "\(moment.likeNumber!)", for: .normal)
cell.commentBtn.setTitle(" " + "\(moment.commentNumber!)", for: .normal)
cell.nameLabel.text = moment.user?.userName ?? "匿名用户"
cell.sayingLabel.text = moment.user?.saying ?? "这家伙很懒,什么也没有留下"
cell.descriptionLabel.text = moment.detail ?? nil
let (dateDescription, _) = try! moment.date!.colloquialSinceNow()
cell.timeLabel.text = dateDescription
}
override func prepareForReuse() {
super.prepareForReuse()
// This step is important for reusing a cell
// Remove all travel image view in the travel image container view
for sceneryImageView in sceneryImageContainerView.subviews {
sceneryImageView.removeFromSuperview()
}
// Also remove all references to travel image view
sceneryImageViews.removeAll()
}
@IBAction func moreBtnClick(_ sender: Any) {
let actionSheetController = ActionSheetController()
if aut?.id == BmobUser.current().objectId {
let alertAction1 = AlertAction(title: "删除", style: .default) {
print("delete")
}
actionSheetController.addAction(alertAction: alertAction1)
}
else {
let alertAction1 = AlertAction(title: "举报", style: .default) {
self.showText(hint: "举报成功")
}
actionSheetController.addAction(alertAction: alertAction1)
}
let alertActionCancel = AlertAction(title: "取消", style: .cancel, handler: nil)
actionSheetController.addAction(alertAction: alertActionCancel)
navi?.present(actionSheetController, animated: true, completion: nil)
}
@IBAction func jumpToProfile(_ sender: Any) {
let pc = ProfileViewController.storyBoardInstance()
pc?.author = aut
navi?.pushViewController(pc!, animated: true)
}
// MARK: - Public Methods
func createSceneryImageViews(_ count: Int) {
// Generate travel image views with a placeholder image named "pic2"
for index in 0..<count {
let sceneryImageView = UIImageView(image: #imageLiteral(resourceName: "pic2"))
sceneryImageView.contentMode = .scaleAspectFill
sceneryImageView.isUserInteractionEnabled = true
sceneryImageView.clipsToBounds = true
sceneryImageView.tag = index
sceneryImageContainerView.addSubview(sceneryImageView)
sceneryImageViews.append(sceneryImageView)
let tap = UITapGestureRecognizer(
target: self,
action: #selector(preview(_:))
)
sceneryImageView.addGestureRecognizer(tap)
}
// Layout the travel image views according to the number of travel image URLs
layoutSceneryImageViews()
}
// MARK: - Private Methods
@objc fileprivate func savePhotos(_ tap: UITapGestureRecognizer) {
if (tap.state == UIGestureRecognizerState.began) {
let alertController = UIAlertController(title: "保存照片", message: nil, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "确定", style: .default, handler: { (alert) in
let imageView = tap.view as! AnimatedPhotoBrowser
UIImageWriteToSavedPhotosAlbum(imageView.images[self.currentIndex!], nil, nil, nil)
}))
alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
navi?.present(alertController, animated: true, completion: nil)
}
}
@objc fileprivate func preview(_ tap: UITapGestureRecognizer) {
let sceneryImageView = tap.view as! UIImageView
let photoBrowser = AnimatedPhotoBrowser()
photoBrowser.currentPhotoIndex = sceneryImageView.tag
currentIndex = photoBrowser.currentPhotoIndex
photoBrowser.images = sceneryImageViews.map {
$0.image!
}
photoBrowser.sourceContentView = sceneryImageContainerView
photoBrowser.display()
let tap2 = UILongPressGestureRecognizer(
target: self,
action: #selector(savePhotos(_:))
)
photoBrowser.addGestureRecognizer(tap2)
}
fileprivate func layoutSceneryImageViews() {
let sceneryImageViewLayoutStyle = [layoutSceneryImageViewsStyleOne,
layoutSceneryImageViewsStyleTwo,
layoutSceneryImageViewsStyleThree,
layoutSceneryImageViewsStyleFour,
layoutSceneryImageViewsStyleFive,
layoutSceneryImageViewsStyleSix]
// Call the layout style function according to the number of scenery image URLs
sceneryImageViewLayoutStyle[sceneryImageViews.count - 1]()
}
fileprivate func layoutSceneryImageViewsStyleOne() {
// Layout only one travel image
sceneryImageViews.first!.frame = CGRect(
x: 10.0,
y: 10.0,
width: Dimensions.screenWidth - Dimensions.padding * 2.0 - 20,
height: Dimensions.screenWidth - Dimensions.padding * 2.0 - 20
)
}
fileprivate func layoutSceneryImageViewsStyleTwo() {
// Layout two travel images
let dimension = CGSize(
width: (Dimensions.screenWidth - Dimensions.padding * 3.0) / 2.0,
height: (Dimensions.screenWidth - Dimensions.padding * 3.0) / 2.0
)
for (index, sceneryImageView) in sceneryImageViews.enumerated() {
sceneryImageView.frame = CGRect(
x: (dimension.width + Dimensions.padding) * CGFloat(index),
y: 0.0,
width: dimension.width,
height: dimension.height
)
}
}
fileprivate func layoutSceneryImageViewsStyleThree() {
// Layout three travel images
let largeDimension = CGSize(
width: (Dimensions.screenWidth - Dimensions.padding * 3.0) * 0.67,
height: (Dimensions.screenWidth - Dimensions.padding * 3.0) * 0.67
)
let tinyDimension = CGSize(
width: (largeDimension.height - Dimensions.padding) / 2.0,
height: (largeDimension.height - Dimensions.padding) / 2.0
)
sceneryImageViews[0].frame = CGRect(
x: 0.0,
y: 0.0,
width: largeDimension.width,
height: largeDimension.height
)
sceneryImageViews[1].frame = CGRect(
x: largeDimension.width + Dimensions.padding,
y: 0.0,
width: tinyDimension.width,
height: tinyDimension.height
)
sceneryImageViews[2].frame = CGRect(
x: largeDimension.width + Dimensions.padding,
y: tinyDimension.height + Dimensions.padding,
width: tinyDimension.width,
height: tinyDimension.height
)
}
fileprivate func layoutSceneryImageViewsStyleFour() {
// Layout four travel images
let dimension = CGSize(
width: (Dimensions.screenWidth - Dimensions.padding * 3.0) / 2.0,
height: (Dimensions.screenWidth - Dimensions.padding * 3.0) / 2.0
)
for (index, sceneryImageView) in sceneryImageViews.enumerated() {
sceneryImageView.frame = CGRect(
x: (dimension.width + Dimensions.padding) * CGFloat(index % 2),
y: (dimension.height + Dimensions.padding) * CGFloat(index / 2),
width: dimension.width,
height: dimension.height
)
}
}
fileprivate func layoutSceneryImageViewsStyleFive() {
// Layout five travel images
let largeDimension = CGSize(
width: (Dimensions.screenWidth - Dimensions.padding * 4.0) / 2.0,
height: (Dimensions.screenWidth - Dimensions.padding * 4.0) / 2.0
)
let tinyDimension = CGSize(
width: (largeDimension.width - Dimensions.padding) / 2.0,
height: (largeDimension.width - Dimensions.padding) / 2.0
)
sceneryImageViews.first!.frame = CGRect(
x: 0.0,
y: 0.0,
width: largeDimension.width,
height: largeDimension.height
)
let offsetX = largeDimension.width + Dimensions.padding
// The algorithm of laying the rest of four travel images is the same as layout style four
for (index, sceneryImageView) in sceneryImageViews.enumerated() {
if index == 0 {
continue
}
sceneryImageView.frame = CGRect(
x: offsetX + (tinyDimension.width + Dimensions.padding) * CGFloat((index - 1) % 2),
y: (tinyDimension.height + Dimensions.padding) * CGFloat((index - 1) / 2),
width: tinyDimension.width,
height: tinyDimension.height
)
}
}
fileprivate func layoutSceneryImageViewsStyleSix() {
// Layout six travel images
let largeDimension = CGSize(
width: (Dimensions.screenWidth - Dimensions.padding * 3.0) * 0.67,
height: (Dimensions.screenWidth - Dimensions.padding * 3.0) * 0.67
)
let tinyDimension = CGSize(
width: (largeDimension.width - Dimensions.padding) / 2.0,
height: (largeDimension.height - Dimensions.padding) / 2.0
)
// The algorithm of laying the first three travel images is the same as layout style three
layoutSceneryImageViewsStyleThree()
let offsetY = largeDimension.height + Dimensions.padding
for index in 3..<sceneryImageViews.count {
sceneryImageViews[index].frame = CGRect(
x: (tinyDimension.width + Dimensions.padding) * CGFloat(index - 3),
y: offsetY,
width: tinyDimension.width,
height: tinyDimension.height
)
}
}
}
|
//
// CALayer+RoundingCorners.swift
// WavesWallet-iOS
//
// Created by mefilt on 07.08.2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import UIKit
fileprivate enum Constants {
static let maskName = "calayer.mask.clip.name"
}
public extension CALayer {
public func clip() {
self.mask = {
let mask = CAShapeLayer()
let path = UIBezierPath(rect: bounds)
mask.frame = bounds
mask.path = path.cgPath
return mask
}()
}
public func clip(roundedRect rect: CGRect? = nil,
byRoundingCorners corners: UIRectCorner = .allCorners,
cornerRadius: CGFloat,
inverse: Bool = false) {
self.mask = {
let roundedRect = rect ?? bounds
let mask = CAShapeLayer()
mask.name = Constants.maskName
let path = UIBezierPath(roundedRect: roundedRect,
byRoundingCorners: corners,
cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
if inverse {
path.append(UIBezierPath(rect: bounds))
mask.fillRule = CAShapeLayerFillRule.evenOdd
}
mask.frame = roundedRect
mask.path = path.cgPath
return mask
}()
}
public func removeClip() {
self.mask = nil
}
public func border(roundedRect rect: CGRect? = nil,
byRoundingCorners corners: UIRectCorner = .allCorners,
cornerRadius: CGFloat,
borderWidth: CGFloat,
borderColor: UIColor) {
self.removeBorder()
let rect = (rect ?? bounds)
self.mask = {
let mask = CAShapeLayer()
mask.path = UIBezierPath(roundedRect: rect,
byRoundingCorners: corners,
cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath
return mask
}()
let border: CAShapeLayer = {
let border = CAShapeLayer()
let inset = borderWidth / 2
let rect = rect.insetBy(dx: inset, dy: inset)
border.strokeColor = borderColor.cgColor
border.fillColor = UIColor.clear.cgColor
border.lineWidth = borderWidth
let cornerRadius = max(0, cornerRadius - inset)
border.path = UIBezierPath(roundedRect: rect,
byRoundingCorners: corners,
cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath
border.name = Constants.maskName
return border
}()
addSublayer(border)
}
public func removeBorder() {
self.sublayers?
.filter { $0.name == Constants.maskName }
.forEach { $0.removeFromSuperlayer() }
}
}
|
//
// DYThirdPlatformKey.swift
// Dayang
//
// Created by 田向阳 on 2017/8/28.
// Copyright © 2017年 田向阳. All rights reserved.
//
public let kBuglyAppId = "00cea04313"
public let kBuglyAppKey = "29bff0e8-020c-4aef-b044-9f85cb64a664"
|
//
// PresentedOrder.swift
// Driveo
//
// Created by Admin on 6/13/18.
// Copyright © 2018 ITI. All rights reserved.
//
import Foundation
import UIKit
struct PresentedOrder: Decodable {
var cost:Float?
var description:String?
var dest_latitude:Float?
var dest_longitude:Float?
var dropoff_location:String?
//var images:[OrderImages]?
var order_id:Int?
var payment_method:String?
var pickup_location:String?
var src_latitude:Float?
var src_longitude:Float?
var status:String?
var time:String?
var title:String?
var weight:Float?
}
class OrderImages: Decodable {
var url:String?
}
|
//
// ViewController.swift
// GithubIssueTrackerAlamo
//
// Created by Michael Le on 13/04/2017.
// Copyright © 2017 Michael Le. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class GithubIssueTrackerViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let disposeBag = DisposeBag()
var repositoryNetworkModel: RepositoryNetworkModel!
var searchBarText: Observable<String> {
return searchBar.rx.text
.orEmpty
.filter { $0.characters.count > 0 }
.debounce(0.3, scheduler: MainScheduler.instance)
.distinctUntilChanged()
}
override func viewDidLoad() {
super.viewDidLoad()
setupRx()
}
func setupRx() {
repositoryNetworkModel = RepositoryNetworkModel(withNameObservable: searchBarText)
repositoryNetworkModel.rx_repositories
.drive(tableView.rx.items(cellIdentifier: "IssueCell")) { (_, result, cell) in
cell.textLabel?.text = result.name
}
.addDisposableTo(disposeBag)
repositoryNetworkModel.rx_repositories
.filter { $0.count == 0 }
.drive(onNext: { repositories in
let alert = UIAlertController(title: ":(", message: "No repositories found for this user", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
if self.navigationController?.visibleViewController?.isMember(of: UIAlertController.self) != true {
self.present(alert, animated: true, completion: nil)
}
})
.addDisposableTo(disposeBag)
}
}
|
//
// CategoryTableViewController.swift
// To do list app
//
// Created by Arturs Vitins on 11/02/2018.
// Copyright © 2018 Arturs Vitins. All rights reserved.
//
import UIKit
import RealmSwift
import ChameleonFramework
class CategoryTableViewController: SwipeTableViewController {
let realm = try! Realm()
var categories: Results<Category>?
override func viewDidLoad() {
super.viewDidLoad()
loadCategory()
tableView.separatorStyle = .none
tableView.rowHeight = 90.0
}
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 categories?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let category = categories?[indexPath.row] {
// cell.textLabel?.text = categories?[indexPath.row].name ?? "No Categories added yet"
cell.textLabel?.text = category.name
guard let categoryColor = UIColor(hexString: category.cellColor) else {fatalError()}
// cell.backgroundColor = UIColor(hexString: (categories?[indexPath.row].cellColor) ?? "1D9BF6")
cell.backgroundColor = UIColor(hexString: category.cellColor)
cell.textLabel?.textColor = ContrastColorOf(categoryColor, returnFlat: true)
}
return cell
}
//MARK: - TableView Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToItems", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! ToDoListTableViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categories?[indexPath.row]
}
}
//MARK: - Data Manipulation Methods
@IBAction func addBtnPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Category", style: .default) { (action) in
let newCat = Category()
newCat.name = textField.text!
newCat.cellColor = UIColor.randomFlat.hexValue()
self.saveCategory(category: newCat)
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "create new category"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func saveCategory(category: Category) {
do{
try realm.write {
realm.add(category)
}
} catch {
print("Error saving context \(error)")
}
self.tableView.reloadData()
}
// func loadCategory(with request: NSFetchRequest<Category> = Category.fetchRequest()) {
func loadCategory() {
categories = realm.objects(Category.self)
}
override func updateModel(at indexPath: IndexPath) {
if let item = self.categories?[indexPath.row] {
do {
try self.realm.write {
self.realm.delete(item)
}
} catch{
print(error)
}
}
}
}
|
//
// Score.swift
// Helios
//
// Created by Lars Stegman on 08-08-17.
// Copyright © 2017 Stegman. All rights reserved.
//
import Foundation
public struct Score {
public var upvotes: Int
public var downvotes: Int
public var score: Int
public var likedRatio: Double?
public var scoreHidden: Bool
public let numberOfTimesGilded: Int
private enum UserCodingKeys: String, CodingKey {
case upvotes = "ups"
case downvotes = "downs"
case score
case likedRatio = "upvote_ratio"
case scoreHidden = "hide_score"
case numberOfTimesGilded = "gilded"
}
private enum LinkCodingKeys: String, CodingKey {
case upvotes = "ups"
case downvotes = "downs"
case score
case likedRatio = "upvote_ratio"
case scoreHidden = "score_hidden"
case numberOfTimesGilded = "gilded"
}
public init(userScoreFrom decoder: Decoder) throws {
let container = try decoder.container(keyedBy: UserCodingKeys.self)
upvotes = try container.decode(Int.self, forKey: .upvotes)
downvotes = try container.decode(Int.self, forKey: .downvotes)
score = try container.decode(Int.self, forKey: .score)
likedRatio = try container.decodeIfPresent(Double.self, forKey: .likedRatio)
scoreHidden = try container.decode(Bool.self, forKey: .scoreHidden)
numberOfTimesGilded = try container.decode(Int.self, forKey: .numberOfTimesGilded)
}
public init(linkScoreFrom decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LinkCodingKeys.self)
upvotes = try container.decode(Int.self, forKey: .upvotes)
downvotes = try container.decode(Int.self, forKey: .downvotes)
score = try container.decode(Int.self, forKey: .score)
likedRatio = try container.decodeIfPresent(Double.self, forKey: .likedRatio)
scoreHidden = try container.decode(Bool.self, forKey: .scoreHidden)
numberOfTimesGilded = try container.decode(Int.self, forKey: .numberOfTimesGilded)
}
}
|
import Foundation
import Crust
import JSONValueRX
enum HairColor: String, AnyMappable {
case Blue
case Brown
case Gold
case Unknown
init() {
self = .Unknown
}
}
struct Person: AnyMappable {
var bankAccounts: [Int] = [ 1234, 5678 ]
var attitude: String = "awesome"
var hairColor: HairColor = .Unknown
var ownsCat: Bool? = nil
}
class HairColorMapping: Transform {
typealias MappedObject = HairColor
func fromJSON(_ json: JSONValue) throws -> HairColor {
switch json {
case .string(let str):
switch str {
case "Gold":
return .Gold
case "Brown":
return .Brown
case "Blue":
return .Blue
default:
return .Unknown
}
default:
return .Unknown
}
}
func toJSON(_ obj: HairColor) -> JSONValue {
return .string(obj.rawValue)
}
}
class PersonMapping: AnyMapping {
typealias MappedObject = Person
func mapping(tomap: inout Person, context: MappingContext) {
tomap.bankAccounts <- "bank_accounts" >*<
tomap.attitude <- "traits.attitude" >*<
tomap.hairColor <- .mapping("traits.bodily.hair_color", HairColorMapping()) >*<
tomap.ownsCat <- "owns_cat" >*<
context
}
}
class PersonStub {
var bankAccounts: [Int] = [ 0987, 6543 ]
var attitude: String = "whoaaaa"
var hairColor: HairColor = .Blue
var ownsCat: Bool? = true
init() { }
func generateJsonObject() -> [AnyHashable : Any] {
var ownsCatVal: AnyObject
if let cat = self.ownsCat {
ownsCatVal = cat as AnyObject
} else {
ownsCatVal = NSNull()
}
return [
"owns_cat" : ownsCatVal,
"bank_accounts" : bankAccounts as AnyObject,
"traits" : [
"attitude" : attitude,
"bodily" : [
"hair_color" : hairColor.rawValue
]
],
]
}
func matches(_ object: Person) -> Bool {
var matches = true
matches &&= attitude == object.attitude
matches &&= hairColor == object.hairColor
matches &&= bankAccounts == object.bankAccounts
matches &&= ownsCat == object.ownsCat
return matches
}
}
|
//
// NotationTableViewCell.swift
// LetsPlayStoryboards
//
// Created by Christian Marino on 16/07/2019.
// Copyright © 2019 Christian Marino. All rights reserved.
//
import UIKit
class NotationTableViewCell: UITableViewCell {
var assocKey : String = "";
var i : Int = 0;
@IBOutlet var notationStringLabel: UILabel!
let ud = UserDefaults.standard;
let kk = "PreferredNotation";
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if i != 0{
print("Entro qui, selezione fatta");
let oldNot = ud.string(forKey: "PreferredNotation")!;
print(kk);
ud.set(assocKey, forKey: kk);
let itaEnMap = [
"Do": "C",
"Dom": "Cm",
"Re": "D",
"Rem": "Dm",
"Mi": "E",
"Mim": "Em",
"Fa": "F",
"Fam": "Fm",
"Sol": "G",
"Solm": "Gm",
"La": "A",
"Lam": "Am",
"Si": "B",
"Sim": "Bm",
]
let enItaMap = [
"C": "Do",
"Cm": "Dom",
"D": "Re",
"Dm": "Rem",
"E": "Mi",
"Em": "Mim",
"F": "Fa",
"Fm": "Fam",
"G": "Sol",
"Gm": "Solm",
"A": "La",
"Am": "Lam",
"B": "Si",
"Bm": "Sim",
]
if(oldNot != assocKey){
switch(assocKey){
case "IT":
print("TRADUZIONE EN TO IT")
let oldChords = ud.array(forKey: "chords_string") as! [String];
var newChords = [String]();
for old in oldChords{
newChords.append(enItaMap[old]!);
}
ud.set(newChords, forKey: "chords_string")
case "EN":
print("TRADUZIONE IT TO EN")
let oldChords = ud.array(forKey: "chords_string") as! [String];
var newChords = [String]();
for old in oldChords{
newChords.append(itaEnMap[old]!);
}
ud.set(newChords, forKey: "chords_string")
default:
break;
}
}
let tw = self.superview as! UITableView;
let twn = tw.next as! NotationTableViewController;
let i = twn.navigationController as! UINavigationController;
i.popViewController(animated: false);
// twn.updateChecked();
}
i+=1;
// (self.superview as! NotationTableViewController).updateChecked(assocKey);
// Configure the view for the selected state
}
}
|
//
// ActionViewCell.swift
// Fugu
//
// Created by Vishal on 05/02/19.
// Copyright © 2019 Socomo Technologies Private Limited. All rights reserved.
//
import UIKit
class ActionViewCell: UITableViewCell {
@IBOutlet weak var subView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clear
subView.backgroundColor = UIColor.clear
}
}
|
//
// URLConstructor.swift
// NewApp
//
// Created by Artsiom Habruseu on 5.03.21.
//
import Foundation
class URLConstructor {
private static let apiKey = "0363a0902c1d4ecb8d959d30a1452c46"
static func createURL(fromDate: String, toDate: String) -> URL? {
var components = URLComponents()
components.scheme = "https"
components.host = "newsapi.org"
components.path = "/v2/everything"
components.queryItems = [
URLQueryItem(name: "q", value: "us"),
URLQueryItem(name: "from", value: fromDate),
URLQueryItem(name: "to", value: toDate),
URLQueryItem(name: "apiKey", value: apiKey)
]
return components.url
}
}
|
//
// GameScene.swift
// FlappyBird
//
// Created by Cofyc on 9/14/14.
// Copyright (c) 2014 Cofyc. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var bird:SKSpriteNode = SKSpriteNode()
var pipeUpTexture:SKTexture = SKTexture()
var pipeDownTexture:SKTexture = SKTexture()
var pipeActions:SKAction = SKAction()
let birdCategory:UInt32 = 0x1 << 1 // 2
let pipeCategory:UInt32 = 0x1 << 2 // 4
let worldCategory:UInt32 = 0x1 << 3 // 8
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func didMoveToView(view: SKView) {
/* Setup your scene here */
// physics
self.physicsWorld.gravity = CGVectorMake(0, -5)
self.physicsWorld.contactDelegate = self
// bird
var birdTexture = SKTexture(imageNamed: "Bird")
birdTexture.filteringMode = SKTextureFilteringMode.Nearest
bird = SKSpriteNode(texture: birdTexture)
bird.setScale(0.5)
bird.position = CGPointMake(self.size.width * 0.1, self.size.height * 0.5)
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height/2)
bird.physicsBody?.dynamic = true
bird.physicsBody?.allowsRotation = false
bird.physicsBody?.categoryBitMask = birdCategory
bird.physicsBody?.contactTestBitMask = pipeCategory
self.addChild(bird)
// ground
var groundTexture = SKTexture(imageNamed: "ground")
groundTexture.filteringMode = SKTextureFilteringMode.Nearest
let end:Int = Int((2 + self.size.width / (groundTexture.size().width * 2)))
for i in 0...end {
var ground = SKSpriteNode(texture: groundTexture)
ground.setScale(2.0)
ground.position = CGPointMake(CGFloat(ground.size.width/2 + CGFloat(i) * ground.size.width), ground.size.height/2)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: ground.size)
ground.physicsBody?.dynamic = false
ground.physicsBody?.categoryBitMask = worldCategory
self.addChild(ground)
}
// pipes
pipeUpTexture = SKTexture(imageNamed:"PipeUp")
pipeDownTexture = SKTexture(imageNamed:"PipeDown")
// pipes/actions
let distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeUpTexture.size().width)
let movePipes = SKAction.moveByX(-distanceToMove, y: 0.0, duration: NSTimeInterval(0.01 * distanceToMove))
let removePipes = SKAction.removeFromParent()
pipeActions = SKAction.sequence([movePipes,removePipes])
// pipes/spawn
let spawn = SKAction.runBlock({
() in self.spawnPipes()
})
let delay = SKAction.waitForDuration(NSTimeInterval(2.0))
let spawnThenDelay = SKAction.sequence([spawn, delay])
self.runAction(SKAction.repeatActionForever(spawnThenDelay))
}
func spawnPipes() {
let pipePair = SKNode()
pipePair.position = CGPointMake(self.size.width + pipeUpTexture.size().width, 0)
pipePair.zPosition = -10
let height = UInt32(self.size.height / 5)
let y = arc4random() % height + height
let pipeDown = SKSpriteNode(texture: pipeDownTexture)
pipeDown.setScale(2.0)
let gap = arc4random() % 50 + 200
pipeDown.position = CGPointMake(0.0, CGFloat(y) + pipeDown.size.height + CGFloat(gap))
pipeDown.physicsBody = SKPhysicsBody(rectangleOfSize:pipeDown.size)
pipeDown.physicsBody?.dynamic = false
pipeDown.physicsBody?.categoryBitMask = pipeCategory
pipeDown.physicsBody?.contactTestBitMask = birdCategory
pipePair.addChild(pipeDown)
let pipeUp = SKSpriteNode(texture: pipeUpTexture)
pipeUp.setScale(2.0)
pipeUp.position = CGPointMake(0.0, CGFloat(y))
pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)
pipeUp.physicsBody?.dynamic = false
pipeUp.physicsBody?.categoryBitMask = pipeCategory
pipeUp.physicsBody?.contactTestBitMask = birdCategory
pipePair.addChild(pipeUp)
pipePair.runAction(pipeActions)
self.addChild(pipePair)
}
func didBeginContact(contact: SKPhysicsContact) {
var birdBody:SKPhysicsBody
var pipeBody:SKPhysicsBody
if (contact.bodyA.categoryBitMask == birdCategory && contact.bodyB.categoryBitMask == pipeCategory) {
birdBody = contact.bodyA
pipeBody = contact.bodyB
end()
} else if (contact.bodyB.categoryBitMask == birdCategory && contact.bodyA.categoryBitMask == pipeCategory) {
birdBody = contact.bodyB
pipeBody = contact.bodyA
end()
}
}
func end() {
// transit to game over scene
var transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5)
var scene:SKScene = GameOverScene(size:self.size, won: false)
self.view?.presentScene(scene, transition: transition)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
bird.physicsBody?.velocity = CGVectorMake(0, 0)
bird.physicsBody?.applyImpulse(CGVectorMake(0, 25))
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
|
//
// FileOpenPanelHelper.swift
// PushPush
//
import Cocoa
class FileOpenPanelHelper {
static func selectFile(withFormats formats: [String],
dialogTitle: String,
completion: (URL) -> Void) {
let dialog = NSOpenPanel()
dialog.title = dialogTitle
dialog.showsResizeIndicator = true
dialog.showsHiddenFiles = false
dialog.allowsMultipleSelection = false;
dialog.canChooseDirectories = false;
dialog.allowedFileTypes = formats;
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
completion(dialog.url!)
}
}
}
|
//
// GuestsViewController.swift
// SuCasa
//
// Created by Gabriela Resende on 12/11/19.
// Copyright © 2019 João Victor Batista. All rights reserved.
//
import UIKit
class GuestsViewController: UIViewController {
@IBOutlet weak var totalGuestsTextField: UITextField!
@IBOutlet weak var bedroomNumberTextField: UITextField!
@IBOutlet weak var bedNumberTextField: UITextField!
@IBOutlet weak var nextButton: UIButton!
var property: Property!
override func viewDidLoad() {
super.viewDidLoad()
setUpTextFields()
nextButton.isHidden = true
self.navigationController?.navigationBar.tintColor = Colors.buttonColor
//Tap gesture to hide keyboard
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
view.addGestureRecognizer(tap)
//keyboard notifications
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
//Scroll when keyboard activates
@objc func keyboardWillShow(notification:NSNotification){
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height/3
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
// if all text field is filled, 'next button' appear
if isTextFieldsFilled() {
nextButton.isHidden = false
}
}
/// This method will be called when the done button at the picker view has been pressed
@objc func donePicker() {
//End editing will hide the keyboard
self.view.endEditing(true)
}
@IBAction func proceedToNextView(_ sender: UIButton) {
self.performSegue(withIdentifier: "goToLocation", sender: self)
var number = Int(totalGuestsTextField.text!)
property.guestsTotal = number!
number = Int(bedroomNumberTextField.text!)
property.numberOfRooms = number!
number = Int(bedNumberTextField.text!)
property.numberOfBeds = number!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToLocation",
let locationVC = segue.destination as? LocationViewController {
locationVC.property = self.property
}
}
}
extension GuestsViewController: UITextFieldDelegate {
func setUpTextFields() {
totalGuestsTextField.delegate = self
bedroomNumberTextField.delegate = self
bedNumberTextField.delegate = self
totalGuestsTextField.keyboardType = .numberPad
bedroomNumberTextField.keyboardType = .numberPad
bedNumberTextField.keyboardType = .numberPad
let attributes = [NSAttributedString.Key.foregroundColor: Colors.placeholderColor]
totalGuestsTextField.attributedPlaceholder = NSAttributedString(string: "Selecione", attributes: attributes as [NSAttributedString.Key : Any])
bedroomNumberTextField.attributedPlaceholder = NSAttributedString(string: "Selecione", attributes: attributes as [NSAttributedString.Key : Any])
bedNumberTextField.attributedPlaceholder = NSAttributedString(string: "Selecione", attributes: attributes as [NSAttributedString.Key : Any])
totalGuestsTextField.textColor = Colors.textColor
bedroomNumberTextField.textColor = Colors.textColor
bedNumberTextField.textColor = Colors.textColor
//creating a toolbar
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.sizeToFit()
//creating a flexible space to put the done button on the toolbar's right side
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
//creating done button
let doneButton = UIBarButtonItem(title: "Concluido", style: UIBarButtonItem.Style.done, target: self, action: #selector(self.donePicker))
//putting the flexible space and the done button into the toolbar
toolBar.setItems([flexibleSpace, doneButton], animated: false)
//inputing toolbar into text fields
totalGuestsTextField.inputAccessoryView = toolBar
bedroomNumberTextField.inputAccessoryView = toolBar
bedNumberTextField.inputAccessoryView = toolBar
}
func isTextFieldsFilled() -> Bool{
if totalGuestsTextField.text!.isEmpty {
return false
}
else if bedroomNumberTextField.text!.isEmpty {
return false
}
else if bedNumberTextField.text!.isEmpty {
return false
}
//If all text field is filled, return true
return true
}
// func isTextFieldFilled(textField: UITextField) {
// return textField.text?.isEmpty ? false : true
// }
}
|
//
// UIImage+LGL.swift
// LGLExtension
//
// Created by Passer on 2021/2/17.
//
import UIKit
extension UIImage: LGLCompatible {}
public extension LGL where Base == UIImage {
/**
图片旋转90度
*/
func setImageRotate90() -> UIImage {
return Base(cgImage:base.cgImage!, scale:base.scale, orientation: .down)
}
/**
返回原始图片
*/
func setImageOriginal() -> UIImage {
return base.withRenderingMode(.alwaysOriginal)
}
/**
图片拉伸 指定
- parameter edgeInset: 指定不被拉伸的区域
- parameter resizeMode: 图片拉伸模式
resizeMode UIImageResizingModeTile -> 进行区域复制模式拉伸 【-】 -> 【-】【-】【-】
resizeMode UIImageResizingModeStretch -> 进行渐变复制模式拉伸 连续的 【-】 -> 【-----】
*/
func setStretchImage(_ edgeInset:UIEdgeInsets, _ resizeMode: UIImage.ResizingMode) -> UIImage {
return base.resizableImage(withCapInsets:edgeInset, resizingMode: resizeMode)
}
}
|
//
// Model.swift
// Cred.Com
//
// Created by IMAC-0025 on 12/01/20.
// Copyright © 2020 IMAC-0025. All rights reserved.
//
import Foundation
struct Card {
var cardImageName = ""
var isExpanded = false
}
|
//
// ViewController.swift
// DemoMapDirections
//
// Created by Brian Douglas Moakley on 4/29/16.
// Copyright © 2016 Razeware LLC. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController {
let locationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var directions: UITextView!
@IBAction func switchType(sender: AnyObject) {
let segmentedControl = sender as! UISegmentedControl
if segmentedControl.selectedSegmentIndex == 0 {
self.mapView.hidden = false
} else {
self.mapView.hidden = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
let sourceLocation = CLLocation(latitude: 37.4223652, longitude: -122.08418599999999)
let destinationLocation = CLLocation(latitude: 37.332112, longitude: -122.030776)
let sourcePlacemark = MKPlacemark(coordinate: sourceLocation.coordinate, addressDictionary: nil)
let destinationPlacemark = MKPlacemark(coordinate: destinationLocation.coordinate, addressDictionary: nil)
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: sourcePlacemark)
request.destination = MKMapItem(placemark: destinationPlacemark)
request.requestsAlternateRoutes = false
request.transportType = .Automobile
let region = MKCoordinateRegionMakeWithDistance(sourceLocation.coordinate, 15000, 15000)
mapView.setRegion(region, animated: true)
mapView.delegate = self
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler {
[weak self] (response, error) in
if error == nil {
for route in (response?.routes)! {
self?.mapView.addOverlay(route.polyline)
var text = ""
let formatter = MKDistanceFormatter()
formatter.unitStyle = .Full
for step in route.steps {
let distance = formatter.stringFromDistance(step.distance)
text += step.instructions + " (\(distance))\n"
}
self?.directions.text = text
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blueColor()
renderer.lineWidth = 5.0
return renderer
}
}
|
//
// AlertService.swift
// Pruebas
//
// Created by Julio Banda on 11/13/18.
// Copyright © 2018 Julio Banda. All rights reserved.
//
import Foundation
class AlertService {
private init(){}
static func actionSheet(in vc: UIViewController, title: String, completion: @escaping () -> Void){
let alert = UIAlertController(title: nil,
message: nil,
preferredStyle: .actionSheet)
let action = UIAlertAction(title: title,
style: .default) { (_) in
completion()
}
alert.addAction(action)
vc.present(alert, animated: true)
}
}
|
//
// ContentView.swift
// respuesta tarea 5b
//
// Created by Mauro Ciargo on 4/23/20.
// Copyright © 2020 Mauro Ciargo. All rights reserved.
//
import SwiftUI
struct ContentView: View {
struct ClickView: View {
@State private var redClicks = 0
@State private var yellowClicks = 0
@State private var blueClicks = 0
@State private var totalClicks = 0
var body: some View {
VStack {
CounterView(redClicks: $redClicks, yellowClicks: $yellowClicks, blueClicks: $blueClicks, textColor: .black)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// BlogSectionBackgroud.swift
// Plantza
//
// Created by Satya Prakash Sahu on 19/09/21.
//
import SwiftUI
struct BlogSectionBackgroud: View {
@Binding var rotateDegree : CGFloat
var body: some View {
GeometryReader { bounds in
ZStack{
LinearGradient(gradient: Gradient(colors: [Color("Background 1 Light"), Color("Primary")]), startPoint: .topTrailing, endPoint: .bottomLeading)
.edgesIgnoringSafeArea(.all)
Image("Inner Blob 1")
.blur(radius: 60)
.rotationEffect(Angle(degrees: Double(rotateDegree)))
.onAppear(perform: {
withAnimation(Animation.linear(duration: 8).repeatForever(autoreverses: false)) {
self.rotateDegree = 360
}
})
.offset(x: -170, y: -380)
.opacity(0.9)
Image("Inner Blob 1")
.blur(radius: 60)
.rotationEffect(Angle(degrees: Double(rotateDegree)))
.onAppear(perform: {
withAnimation(Animation.linear(duration: 6).repeatForever(autoreverses: false)) {
self.rotateDegree = 360
}
})
.offset(x: 280, y: -90)
.opacity(0.9)
Image("Inner Blob 3")
.blur(radius: 60)
.rotationEffect(Angle(degrees: Double(rotateDegree)))
.onAppear(perform: {
withAnimation(Animation.linear(duration: 5).repeatForever(autoreverses: false)) {
self.rotateDegree = 360
}
})
.offset(x: -250, y: 120)
.opacity(0.9)
Image("Inner Blob 2")
.blur(radius: 60)
.rotationEffect(Angle(degrees: Double(rotateDegree)))
.onAppear(perform: {
withAnimation(Animation.linear(duration: 5).repeatForever(autoreverses: false)) {
self.rotateDegree = 360
}
})
.offset(x: 250, y: 320)
.opacity(0.9)
BlurView(style:.systemThinMaterial)
.opacity(0.8)
.edgesIgnoringSafeArea(.all)
Image("Profile Outer Blob")
.offset(x: -30 ,y: -170)
}.frame(width : bounds.size.width)
}
}
}
struct BlogSectionBackgroud_Previews: PreviewProvider {
static var previews: some View {
BlogSectionBackgroud(rotateDegree: .constant(0))
}
}
|
//
// ViewController.swift
// SMTextView
//
// Created by mandrusiaks on 04/24/2017.
// Copyright (c) 2017 mandrusiaks. All rights reserved.
//
import UIKit
import SMTextView
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// textView.isCharacterCountEnabled = false
// textView.maxCharacterCount = 400
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
_ = textView.resignFirstResponder()
}
}
|
//
// Mark.swift
// ParseKindleClippings
//
// Created by huoshuguang on 2017/5/29.
// Copyright © 2017年 huoshuguang. All rights reserved.
//
import Cocoa
class Mark
{
//位置 ,时间,内容
var start = ""
var end = ""
var time = ""
var content = ""
init(start:String,end:String,time:String,content:String)
{
self.start = start
self.end = end
self.time = time
self.content = content
}
}
|
//
// CasesTableViewCell.swift
// Adcov8
//
// Created by Syafiq Mastor on 7/29/17.
// Copyright © 2017 syafiqmastor. All rights reserved.
//
import UIKit
class CasesTableViewCell: UITableViewCell {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var shortSummaryDetail: UILabel!
@IBOutlet weak var targetLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
containerView.layer.cornerRadius = 4
containerView.layer.shadowColor = UIColor.lightGray.cgColor
containerView.layer.shadowOpacity = 0.5
containerView.layer.shadowOffset = CGSize.zero //(width: -1, height: 1)
containerView.layer.shadowRadius = 4
// containerView.layer.shadowPath = UIBezierPath(rect: containerView.bounds).cgPath
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
static var identifier: String {
return String(describing: self)
}
}
|
//
// RequestPlayData.swift
// AllPeople
//
// Created by zzh_iPhone on 16/4/24.
// Copyright © 2016年 zzh_iPhone. All rights reserved.
//
import UIKit
class RequestPlayData: NSObject {
weak var delegate:RequestPlayDataDelegate?
func requestData() {
request.defaultInstance().GetRequest(PlayUrl).responseJSON { response in
switch response.result {
case.Success:
guard let JsonData = response.result.value else { return }
let column = JsonData["data"] as! NSArray
var modelArray = [PlayModel]()
for four in column {
let new = PlayModel()
new.mapping(four as! Dictionary<String,AnyObject>)
modelArray.append(new)
}
self.delegate?.request(modelArray)
case .Failure(let error):
print(error)
}
}
}
}
protocol RequestPlayDataDelegate: NSObjectProtocol {
func request(directAll:NSArray)
}
|
//
// NewsFeedWorker.swift
// VKNews
//
// Created by Eugene Kiselev on 20.02.2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
import UIKit
class NewsFeedService {
}
|
//
// NoteDetailViewController.swift
// TestProjectBSC
//
// Created by Adam Leitgeb on 14/02/2019.
// Copyright (c) 2019 Adam Leitgeb. All rights reserved.
//
import UIKit
protocol NoteDetailViewControllerInput: class {
func updateConfirmButton(title: String?)
func updateContent(_ text: String)
func updateTitle(_ title: String)
func loading(isActive: Bool)
}
final class NoteDetailViewController: UIViewController {
// MARK: - Outlets
@IBOutlet private weak var confirmBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var contentTextView: UITextView!
// MARK: - Properties
weak var coordinator: NoteDetailCoordinator?
var viewModel: NoteDetailViewModel!
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupTextView()
viewModel.viewDidLoad()
}
// MARK: - Setup
private func setupNavigationBar() {
title = NSLocalizedString("note-detail.title", comment: "Note Detail")
}
private func setupTextView() {
contentTextView.delegate = self
contentTextView.becomeFirstResponder()
}
// MARK: - Actions
@IBAction func confirmButtonTapped(_ sender: Any) {
viewModel.confirmButtonTapped()
}
}
extension NoteDetailViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
viewModel.textChanged(textView.text)
}
}
extension NoteDetailViewController: NoteDetailViewControllerInput {
func updateContent(_ text: String) {
contentTextView.text = text
}
func updateConfirmButton(title: String?) {
confirmBarButtonItem.title = title ?? " "
}
func updateTitle(_ title: String) {
self.title = title
}
func loading(isActive: Bool) {
contentTextView.isUserInteractionEnabled = !isActive
contentTextView.alpha = isActive ? 0.5 : 1.0
}
}
|
//
// CommitDO+P_DatabaseModel.swift
// SwipeTabBarController
//
// Created by Vadim Zhydenko on 30.05.2020.
// Copyright © 2020 Vadym Zhydenko. All rights reserved.
//
import Foundation
extension CommitDO: P_DatabaseModel {
}
|
//
// Place.swift
// CPlaces
//
// Created by Carlos Brito on 30/01/16.
// Copyright © 2016 Carlos Brito. All rights reserved.
//
import Foundation
class Place {
var name : String
var latitud : Double
var longitud : Double
init (name: String, latitud: Double, longitud: Double) {
self.name = name
self.latitud = latitud
self.longitud = longitud
}
}
class Places {
var details = [Place (name: "Auditorio Nacional", latitud: 19.424772, longitud: -99.194942), Place (name: "Feria de Chapultepec", latitud: 19.416564, longitud: -99.195734), Place (name: "Angel de la Independencia", latitud: 19.427099, longitud: -99.167653)]
} |
//
// ViewModelProtocol.swift
// PershinTestApp
//
// Created by Sergey Pershin on 08.04.2021.
//
import Foundation
protocol ViewControllerViewModelProtocol {
var showAlertEvent: Observable<AlertViewModel?> { get }
var showActionSheetEvent: Observable<AlertViewModel?> { get }
var showLoadingEvent: Observable<Bool> { get }
}
|
//
// MapViewController.swift
// blueunicorn
//
// Created by Thomas Blom on 4/17/15.
// Copyright (c) 2015 Thomas Blom. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let initialLocation = CLLocation(latitude: 30.248502, longitude: -97.752191)
// town lake, near lamar footbridge.
centerMapOnLocation( initialLocation );
mapView.delegate = self
HttpManager.getUnicornsWithSuccess( { (UnicornData) -> Void in
let json = JSON( data: UnicornData )
if let unicornArray = json["features"].array {
dispatch_async( dispatch_get_main_queue(), {
for unicorn in unicornArray {
let coordLon = unicorn["geometry"]["coordinates"][0].double
let coordLat = unicorn["geometry"]["coordinates"][1].double
let unicornMapInfo = UnicornMapInfo ( title: unicorn["properties"]["title"].string!,
date: unicorn["properties"]["date"].string!, coordinate: CLLocationCoordinate2D( latitude: coordLat!, longitude: coordLon! ) )
self.mapView.addAnnotation( unicornMapInfo );
print( "Added unicorn!" )
}
})
}
})
}
let regionRadius: CLLocationDistance = 4000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance( location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// AuthService.swift
// AustraliaStudy
//
// Created by user159725 on 10/20/19.
// Copyright © 2019 Australia Study. All rights reserved.
//
import Foundation
class AuthService{
static let instance = AuthService()
public private(set) var loggedIn: Bool
public private(set) var sessionId: String
private init(){
loggedIn = true
sessionId = "1568544929820"
}
}
|
//
// SurveyListModel.swift
// Nimble Survey App
//
// Created by PRAKASH on 7/25/19.
// Copyright © 2019 Prakash. All rights reserved.
//
import Foundation
// MARK: - Welcome
struct SurveyListModel: Codable {
let id, title, welcomeDescription: String
let accessCodePrompt, thankEmailAboveThreshold, thankEmailBelowThreshold, footerContent: String?
let isActive: Bool
let coverImageURL: String
let coverBackgroundColor: String?
let type, createdAt, activeAt: String
let inactiveAt: JSONNull?
let surveyVersion: Int
let shortURL: String?
let languageList: [DefaultLanguage]
let defaultLanguage: DefaultLanguage
let tagList: String
let isAccessCodeRequired, isAccessCodeValidRequired: Bool
let accessCodeValidation: String?
let theme: SurveyListThemeModel
let questions: [QuestionModel]
enum CodingKeys: String, CodingKey {
case id, title
case welcomeDescription = "description"
case accessCodePrompt = "access_code_prompt"
case thankEmailAboveThreshold = "thank_email_above_threshold"
case thankEmailBelowThreshold = "thank_email_below_threshold"
case footerContent = "footer_content"
case isActive = "is_active"
case coverImageURL = "cover_image_url"
case coverBackgroundColor = "cover_background_color"
case type
case createdAt = "created_at"
case activeAt = "active_at"
case inactiveAt = "inactive_at"
case surveyVersion = "survey_version"
case shortURL = "short_url"
case languageList = "language_list"
case defaultLanguage = "default_language"
case tagList = "tag_list"
case isAccessCodeRequired = "is_access_code_required"
case isAccessCodeValidRequired = "is_access_code_valid_required"
case accessCodeValidation = "access_code_validation"
case theme, questions
}
}
enum DefaultLanguage: String, Codable {
case en = "en"
case th = "th"
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public func hash(into hasher: inout Hasher) {
// No-op
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
class JSONCodingKey: CodingKey {
let key: String
required init?(intValue: Int) {
return nil
}
required init?(stringValue: String) {
key = stringValue
}
var intValue: Int? {
return nil
}
var stringValue: String {
return key
}
}
class JSONAny: Codable {
let value: Any
static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny")
return DecodingError.typeMismatch(JSONAny.self, context)
}
static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError {
let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny")
return EncodingError.invalidValue(value, context)
}
static func decode(from container: SingleValueDecodingContainer) throws -> Any {
if let value = try? container.decode(Bool.self) {
return value
}
if let value = try? container.decode(Int64.self) {
return value
}
if let value = try? container.decode(Double.self) {
return value
}
if let value = try? container.decode(String.self) {
return value
}
if container.decodeNil() {
return JSONNull()
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any {
if let value = try? container.decode(Bool.self) {
return value
}
if let value = try? container.decode(Int64.self) {
return value
}
if let value = try? container.decode(Double.self) {
return value
}
if let value = try? container.decode(String.self) {
return value
}
if let value = try? container.decodeNil() {
if value {
return JSONNull()
}
}
if var container = try? container.nestedUnkeyedContainer() {
return try decodeArray(from: &container)
}
if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) {
return try decodeDictionary(from: &container)
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any {
if let value = try? container.decode(Bool.self, forKey: key) {
return value
}
if let value = try? container.decode(Int64.self, forKey: key) {
return value
}
if let value = try? container.decode(Double.self, forKey: key) {
return value
}
if let value = try? container.decode(String.self, forKey: key) {
return value
}
if let value = try? container.decodeNil(forKey: key) {
if value {
return JSONNull()
}
}
if var container = try? container.nestedUnkeyedContainer(forKey: key) {
return try decodeArray(from: &container)
}
if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) {
return try decodeDictionary(from: &container)
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] {
var arr: [Any] = []
while !container.isAtEnd {
let value = try decode(from: &container)
arr.append(value)
}
return arr
}
static func decodeDictionary(from container: inout KeyedDecodingContainer<JSONCodingKey>) throws -> [String: Any] {
var dict = [String: Any]()
for key in container.allKeys {
let value = try decode(from: &container, forKey: key)
dict[key.stringValue] = value
}
return dict
}
static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws {
for value in array {
if let value = value as? Bool {
try container.encode(value)
} else if let value = value as? Int64 {
try container.encode(value)
} else if let value = value as? Double {
try container.encode(value)
} else if let value = value as? String {
try container.encode(value)
} else if value is JSONNull {
try container.encodeNil()
} else if let value = value as? [Any] {
var container = container.nestedUnkeyedContainer()
try encode(to: &container, array: value)
} else if let value = value as? [String: Any] {
var container = container.nestedContainer(keyedBy: JSONCodingKey.self)
try encode(to: &container, dictionary: value)
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
}
static func encode(to container: inout KeyedEncodingContainer<JSONCodingKey>, dictionary: [String: Any]) throws {
for (key, value) in dictionary {
let key = JSONCodingKey(stringValue: key)!
if let value = value as? Bool {
try container.encode(value, forKey: key)
} else if let value = value as? Int64 {
try container.encode(value, forKey: key)
} else if let value = value as? Double {
try container.encode(value, forKey: key)
} else if let value = value as? String {
try container.encode(value, forKey: key)
} else if value is JSONNull {
try container.encodeNil(forKey: key)
} else if let value = value as? [Any] {
var container = container.nestedUnkeyedContainer(forKey: key)
try encode(to: &container, array: value)
} else if let value = value as? [String: Any] {
var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key)
try encode(to: &container, dictionary: value)
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
}
static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws {
if let value = value as? Bool {
try container.encode(value)
} else if let value = value as? Int64 {
try container.encode(value)
} else if let value = value as? Double {
try container.encode(value)
} else if let value = value as? String {
try container.encode(value)
} else if value is JSONNull {
try container.encodeNil()
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
public required init(from decoder: Decoder) throws {
if var arrayContainer = try? decoder.unkeyedContainer() {
self.value = try JSONAny.decodeArray(from: &arrayContainer)
} else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) {
self.value = try JSONAny.decodeDictionary(from: &container)
} else {
let container = try decoder.singleValueContainer()
self.value = try JSONAny.decode(from: container)
}
}
public func encode(to encoder: Encoder) throws {
if let arr = self.value as? [Any] {
var container = encoder.unkeyedContainer()
try JSONAny.encode(to: &container, array: arr)
} else if let dict = self.value as? [String: Any] {
var container = encoder.container(keyedBy: JSONCodingKey.self)
try JSONAny.encode(to: &container, dictionary: dict)
} else {
var container = encoder.singleValueContainer()
try JSONAny.encode(to: &container, value: self.value)
}
}
}
//{
// "id": "ed1d4f0ff19a56073a14",
// "title": "ibis Bangkok Riverside",
// "description": "We'd love to hear from you!",
// "access_code_prompt": null,
// "thank_email_above_threshold": "Dear {name},<br /><br />Thank you for visiting Beach Republic and for taking the time to complete our brief survey. We are thrilled that you enjoyed your time with us! If you have a moment, we would be greatly appreciate it if you could leave a short review on <a href=\"http://www.tripadvisor.com/Hotel_Review-g1188000-d624070-Reviews-Beach_Republic_The_Residences-Lamai_Beach_Maret_Ko_Samui_Surat_Thani_Province.html\">TripAdvisor</a>. It helps to spread the word and let others know about the Beach Republic Revolution!<br /><br />Thank you again and we look forward to welcoming you back soon.<br /><br />Sincerely,<br /><br />Beach Republic Team",
// "thank_email_below_threshold": "Dear {name},<br /><br />Thank you for visiting Beach Republic and for taking the time to complete our brief survey. We are constantly striving to improve and your feedback allows us to help improve the experience for you on your next visit. Each survey is read individually by senior staff and discussed with the team in daily meetings. <br /><br />Thank you again and we look forward to welcoming you back soon.<br /><br />Sincerely,<br /><br />Beach Republic Team",
// "footer_content": "<div>Beach Republic (Samui) Co.,Ltd.</div><div>176/34 M.4, T.Maret, A.Koh Samui, </div><div>Suratthani, 84310<br />Thailand</div>",
// "is_active": true,
// "cover_image_url": "https://dhdbhh0jsld0o.cloudfront.net/m/287db81c5e4242412cc0_",
// "cover_background_color": null,
// "type": "Hotel",
// "created_at": "2017-01-23T10:32:24.585+07:00",
// "active_at": "2016-01-22T11:12:00.000+07:00",
// "inactive_at": null,
// "survey_version": 0,
// "short_url": "ibis",
// "language_list": [
// "en"
// ],
// "default_language": "en",
// "tag_list": "ibis",
// "is_access_code_required": false,
// "is_access_code_valid_required": false,
// "access_code_validation": "",
// "theme": {
// "color_active": "#EE100C",
// "color_inactive": "#3A3A3A",
// "color_question": "#ffffff",
// "color_answer_normal": "#000000",
// "color_answer_inactive": "#FFFFFF"
// },
// "questions": [
// {
// "id": "fa385b75617d98e069a3",
// "text": "Thank you for choosing ibis Bangkok Riverside!\nYour feedback is greatly appreciated and is read by management daily!",
// "help_text": null,
// "display_order": 0,
// "short_text": "Welcome",
// "pick": "none",
// "display_type": "intro",
// "is_mandatory": false,
// "correct_answer_id": null,
// "facebook_profile": null,
// "twitter_profile": null,
// "image_url": "https://dhdbhh0jsld0o.cloudfront.net/m/16ff8eb705e0de12b15e_",
// "cover_image_url": "https://dhdbhh0jsld0o.cloudfront.net/m/287db81c5e4242412cc0_",
// "cover_image_opacity": 0.63,
// "cover_background_color": null,
// "is_shareable_on_facebook": false,
// "is_shareable_on_twitter": false,
// "font_face": null,
// "font_size": null,
// "tag_list": "",
// "answers": [
// {
// "id": "7f82e73157e54a23d876",
// "question_id": "b8f06895134eb1da2d13",
// "text": null,
// "help_text": null,
// "input_mask_placeholder": null,
// "short_text": "answer_1",
// "is_mandatory": false,
// "is_customer_first_name": false,
// "is_customer_last_name": false,
// "is_customer_title": false,
// "is_customer_email": false,
// "prompt_custom_answer": false,
// "weight": null,
// "display_order": 0,
// "display_type": "default",
// "input_mask": null,
// "date_constraint": null,
// "default_value": null,
// "response_class": "text",
// "reference_identifier": null,
// "score": null,
// "alerts": []
// }
// ]
// },
|
//
// TableViewCell.swift
// TestAppForAvito
//
// Created by Mac on 03.09.2021.
//
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var skillsLabel: UILabel!
}
|
/// Update the string
public class MyLibray {
/// Change the string to caps.
/// - Parameter value: insert to string.
/// - Returns: captilaized string.
public static func changeToCaps(_ value: String) -> String {
return value.uppercased()
}
}
|
import Foundation
public class CSVEncoder: Encoder {
public var codingPath: [CodingKey] = []
public var userInfo: [CodingUserInfoKey : Any] = [:]
fileprivate let dateFormatter: DateFormatter
private var data = Data()
public static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.sss"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
public init(dateFormatter: DateFormatter = CSVEncoder.dateFormatter) {
self.dateFormatter = dateFormatter
}
@discardableResult public func encode(headers: [String]) throws -> Data {
write(headers.joined(separator: ","))
write("\n")
return data
}
public func encode<T: Encodable>(rows: T) throws -> Data {
try rows.encode(to: self)
return data
}
fileprivate func write(_ string: String) {
data.append(string.data(using: .utf8)!)
}
public func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
return KeyedEncodingContainer(CSVKeyedEncodingContainer<Key>(encoder: self))
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
return CSVUnkeyedEncodingContainer(encoder: self)
}
public func singleValueContainer() -> SingleValueEncodingContainer {
return self as! SingleValueEncodingContainer
}
private struct CSVKeyedEncodingContainer<K: CodingKey>: KeyedEncodingContainerProtocol {
typealias Key = K
var codingPath: [CodingKey] = []
private let encoder: CSVEncoder
public init(encoder: CSVEncoder) {
self.encoder = encoder
}
mutating func encodeNil(forKey key: K) throws {}
mutating func encode<T>(_ value: T, forKey key: K) throws where T : Encodable {
if let date = value as? Date {
encoder.write(encoder.dateFormatter.string(from: date))
} else if let string = value as? CustomStringConvertible {
encoder.write(String(describing: string))
}
encoder.write(",")
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
return encoder.container(keyedBy: keyType)
}
mutating func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer {
return encoder.unkeyedContainer()
}
mutating func superEncoder() -> Encoder {
return encoder
}
mutating func superEncoder(forKey key: K) -> Encoder {
return encoder
}
}
private struct CSVUnkeyedEncodingContainer: UnkeyedEncodingContainer {
var codingPath: [CodingKey] = []
var count: Int = 0
private let encoder: CSVEncoder
init(encoder: CSVEncoder) {
self.encoder = encoder
}
mutating func encode<T>(_ value: T) throws where T : Encodable {
try value.encode(to: encoder)
encoder.write("\n")
count += 1
}
mutating func encodeNil() throws {
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
return encoder.container(keyedBy: keyType)
}
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
return self
}
mutating func superEncoder() -> Encoder {
return encoder
}
}
}
|
//
// UserProfile.swift
// basiviti
//
// Created by BeeSightSoft on 12/25/19.
// Copyright © 2019 hnc. All rights reserved.
//
import UIKit
class UserProfile: NSObject {
var name: String?
var avatarUrl: String?
var address: String?
var phoneNumber: String?
var lat: Double?
var lng: Double?
func dictionaryData() -> Dictionary<String, Any> {
return [
"name": name ?? "",
"avatarUrl": avatarUrl ?? "",
"address": address ?? "",
"phoneNumber": phoneNumber ?? "",
"lat": lat ?? 0.0,
"lng": lng ?? 0.0
]
}
convenience init(dictionary: [String:AnyObject]) {
self.init()
self.name = dictionary["name"] as? String
self.avatarUrl = dictionary["avatarUrl"] as? String
self.address = dictionary["address"] as? String
self.phoneNumber = dictionary["phoneNumber"] as? String
self.lat = dictionary["lat"] as? Double
self.lng = dictionary["lng"] as? Double
}
}
|
//
// FigureCollectionCollectionViewCell.swift
// PaintApp
//
// Created by User on 16.02.2021.
// Copyright © 2021 User. All rights reserved.
//
import UIKit
class FigureCollectionCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageFigure: UIImageView!
}
|
//
// ViewController.swift
// XCode2
//
// Created by admin2 on 21.03.2021.
//
import UIKit
class ViewController: UIViewController {
private var point = 0
@IBOutlet var redLabel: UIView!
@IBOutlet var yellowLabel: UIView!
@IBOutlet var greenLabel: UIView!
@IBOutlet var startButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
redLabel.layer.cornerRadius = 50
redLabel.alpha = 0.3
greenLabel.layer.cornerRadius = 50
greenLabel.alpha = 0.3
yellowLabel.layer.cornerRadius = 50
yellowLabel.alpha = 0.3
}
@IBAction func startTouch() {
if point == 0 {
redLabel.alpha = 1
yellowLabel.alpha = 0.3
point += 1
} else if point == 1{
redLabel.alpha = 0.3
greenLabel.alpha = 1
point += 1
} else if point == 2 {
greenLabel.alpha = 0.3
yellowLabel.alpha = 1
point = 0
}
startButton.setTitle("NEXT", for: .normal)
}
}
|
//
// UEBubbleContainer.swift
// UEBubblePicker
//
// Created by Iuri Gil Claro Chiba on 28/05/19.
// Copyright © 2019 UOL edtech_. All rights reserved.
//
import UIKit
public enum UEBubbleContainerException: Error {
case duplicateBubble
}
public class UEBubbleContainer: UIView {
@IBOutlet public var delegate: UEBubbleContainerViewDelegate?
// MARK: - Configurable Controls
@IBInspectable public var debugEnabled: Bool = false {
didSet { self.animator.setValue(self.debugEnabled, forKey: "debugEnabled") }
}
@IBInspectable public var attractionAnchor: CGPoint = CGPoint(x: 0.5, y: 0.5) {
didSet { self.magneton.position = CGPoint(x: self.bounds.maxX, y: self.bounds.maxY) * self.attractionAnchor }
}
/** Selected item's density. Default value is **0.99.** */
@IBInspectable public var densitySelected: CGFloat = 0.99 {
didSet { self.selected.density = self.densitySelected }
}
/** Unselected item's density. Default value is **0.66.** */
@IBInspectable public var densityUnselected: CGFloat = 0.66 {
didSet { self.selected.density = self.densityUnselected }
}
/** Allows horizontal scrolling. Default value is **true** */
@IBInspectable public var horizontalScroll: Bool = true
/** Allows vertical scrolling. Default value is **true** */
@IBInspectable public var verticalScroll: Bool = true
/** Bubbles' resistance. Default value is **4.9.** */
@IBInspectable public var resistance: CGFloat = 4.9 {
didSet {
self.selected.resistance = self.resistance
self.unselected.resistance = self.resistance
}
}
// MARK: - Constants
private let kAllowRotation = false
private let kMagnetStrength: CGFloat = 9.8
// MARK: - Variables
// MARK: Screen Variables
private var lastBubbleSize = CGSize(width: 80, height: 80)
private var spawnPoints: [CGPoint] = []
private var lastSpawnPoint: CGPoint? // randomSpawnPoint repeat control
private var randomSpawnPoint: CGPoint {
var random: CGPoint? = self.lastSpawnPoint
while (random == self.lastSpawnPoint) {
random = self.spawnPoints.randomElement()
}; self.lastSpawnPoint = random
return random ?? self.magneton.position
}
// MARK: Animators
private lazy var animator = { return UIDynamicAnimator(referenceView: self) }()
private lazy var unselected = { return self.unselectedPropertiesSetup() }()
private lazy var selected = { return self.selectedPropertiesSetup() }()
private lazy var collider = { return self.collisionSetup() }()
private lazy var magneton = { return self.fieldSetup() }()
// MARK: Bubbles
public var bubbles = [UEBubbleView]()
public var selectedBubbles: [UEBubbleView] { return bubbles.filter({ $0.isSelected }) }
public var unselectedBubbles: [UEBubbleView] { return bubbles.filter({ !$0.isSelected }) }
// MARK: - Initialization
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
override public var bounds: CGRect {
didSet {
self.magneton.position = CGPoint(x: self.bounds.maxX, y: self.bounds.maxY) * self.attractionAnchor
self.reposition(bubbles: bubbles)
self.spawnPointsSetup()
self.setupBoundaries(for: self.collider)
}
}
private func commonInit() {
self.addPanGestureToContainer()
self.addBehaviors()
self.spawnPointsSetup()
self.isExclusiveTouch = true
}
// MARK: - Behaviors!
private func addBehaviors() {
self.animator.addBehavior(self.selected)
self.animator.addBehavior(self.unselected)
self.animator.addBehavior(self.collider)
self.animator.addBehavior(self.magneton)
}
private func unselectedPropertiesSetup() -> UIDynamicItemBehavior {
let props = UIDynamicItemBehavior(items: [])
props.allowsRotation = kAllowRotation
props.resistance = resistance
props.density = densitySelected
return props
}
private func selectedPropertiesSetup() -> UIDynamicItemBehavior {
let props = UIDynamicItemBehavior(items: [])
props.allowsRotation = kAllowRotation
props.resistance = resistance
props.density = densityUnselected
return props
}
private func collisionSetup() -> UICollisionBehavior {
let collider = UICollisionBehavior(items: [])
self.setupBoundaries(for: collider)
return collider
}
private func setupBoundaries(for collider: UICollisionBehavior) {
collider.removeAllBoundaries()
if !verticalScroll {
collider.addBoundary(withIdentifier: "bottom" as NSCopying, from: CGPoint(x: -8000, y: self.bounds.height), to: CGPoint(x: 8000, y: self.bounds.height))
collider.addBoundary(withIdentifier: "top" as NSCopying, from: CGPoint(x: -8000, y: 0), to: CGPoint(x: 8000, y: 0))
}
if !horizontalScroll {
collider.addBoundary(withIdentifier: "left" as NSCopying, from: CGPoint(x: 0, y: -8000), to: CGPoint(x: 0, y: 8000))
collider.addBoundary(withIdentifier: "right" as NSCopying, from: CGPoint(x: self.bounds.width, y: -8000), to: CGPoint(x: self.bounds.width, y: 8000))
}
}
private func fieldSetup() -> UIFieldBehavior {
let magneton = UIFieldBehavior.springField()
magneton.position = CGPoint(x: self.bounds.maxX, y: self.bounds.maxY) * self.attractionAnchor
magneton.strength = kMagnetStrength
return magneton
}
private func spawnPointsSetup() {
let right = self.bounds.maxX - lastBubbleSize.width
let bottom = self.bounds.maxY - lastBubbleSize.height
let topLeft = CGPoint(x: 0, y: 0)
let topRight = CGPoint(x: right, y: 0)
let bottomLeft = CGPoint(x: 0, y: bottom)
let bottomRight = CGPoint(x: right, y: bottom)
self.spawnPoints = [topLeft, topRight, bottomLeft, bottomRight]
}
// MARK: - Bubbles!
/**
Creates a new **UEDefaultBubbleView**, using any data from **UEBubbleData**.
- parameter withData: your data object. It customizes the view w/ images, colors, etc.
- parameter tag: any tag (must be Int) can be used to identify your bubbles.
- parameter forceSelection: force an initial state for your bubble, selected or not.
*/
public func createAndAddDefaultBubble(withData data: UEBubbleData!, tag: Int? = nil, forceSelection: Bool? = nil) {
let bubbleFrame = CGRect.init(origin: .zero, size: .zero)
let bubbleView = UEDefaultBubbleView.init(frame: bubbleFrame).setup(withData: data)
if forceSelection != nil { bubbleView.isSelected = forceSelection! }
if tag != nil { bubbleView.tag = tag! }
try? self.addBubble(bubbleView) // won't fail for duplication
}
/**
Adds a new bubble to the container. It can be a custom bubble, subclassing **UEBubbleView**.
- parameter bubbleView: your bubble view. It could be an **UEDefaultBubbleView** or any **UEBubbleView** subclass.
- throws: **UEBubbleContainerException.duplicateBubble**: if this bubble is already in the container.
*/
public func addBubble(_ bubbleView: UEBubbleView!, onCenter: Bool = false, animated: Bool = true) throws {
guard !self.bubbles.contains(bubbleView) else {
throw UEBubbleContainerException.duplicateBubble
}
// Bubble Setup
if bubbleView.frame.size == .zero { bubbleView.updateView() }
self.lastBubbleSize = bubbleView.frame.size
bubbleView.frame.origin = onCenter ? self.magneton.position : randomSpawnPoint
if animated { bubbleView.animateScale(appearing: true) }
self.addSubview(bubbleView)
// Enable Behaviors
self.enableBehaviors(for: bubbleView)
// Gestures Setup
self.addPanGesture(to: bubbleView) // Drag
self.addTapGesture(to: bubbleView) // Selection
// Save Bubble
self.bubbles.append(bubbleView)
}
// MARK: Bubble Behaviors
private func enableBehaviors(for bubbleView: UEBubbleView!) {
if bubbleView.isSelected { self.selected.addItem(bubbleView) }
else { self.unselected.addItem(bubbleView) }
self.collider.addItem(bubbleView)
self.magneton.addItem(bubbleView)
}
private func disableBehaviors(for bubbleView: UEBubbleView!) {
self.unselected.removeItem(bubbleView)
self.selected.removeItem(bubbleView)
self.collider.removeItem(bubbleView)
self.magneton.removeItem(bubbleView)
bubbleView.pushBehaviors.forEach { (behavior) in
behavior.removeItem(bubbleView)
behavior.active = false
self.animator.removeBehavior(behavior)
}
bubbleView.pushBehaviors.removeAll()
}
// MARK: Bubble Search
public func bubblesWithTag(_ tag: Int) -> UEBubbleViews? {
return self.bubblesWhere({ bubbleView -> Bool in
return bubbleView.tag == tag
})
}
public func bubblesWhere(_ filter: (UEBubbleView) throws -> Bool) -> UEBubbleViews? {
return try? self.bubbles.filter(filter)
}
// MARK: Bubble Removal
public func removeBubble(_ bubbleView: UEBubbleView!) {
self.bubbles.removeAll { item -> Bool in return item == bubbleView }
self.disableBehaviors(for: bubbleView)
bubbleView.animateScale(appearing: false) {
bubbleView.removeFromSuperview()
}
}
public func removeBubblesWithTag(_ tag: Int) {
self.removeBubblesWhere { bubbleView -> Bool in
return bubbleView.tag == tag
}
}
public func removeBubblesWhere(_ filter: (UEBubbleView) throws -> Bool) {
let filtered = try? self.bubbles.filter(filter)
filtered?.forEach { bubbleView in
self.removeBubble(bubbleView)
}
}
// MARK: Bubble Refresh
/**
Refreshes all bubbles, recalculating their collision bounds.
*/
public func refreshAllBubbles() {
self.bubbles.forEach { bubbleView in
self.refresh(bubbleView)
}
}
private func refresh(_ bubbleView: UEBubbleView, toggleSelection: Bool = false) {
self.disableBehaviors(for: bubbleView)
if toggleSelection {
if !bubbleView.isSelected {
for otherBubbleView in bubbles.filter({ $0 != bubbleView }) {
let pushBehavior = UIPushBehavior.init(items: [otherBubbleView], mode: .instantaneous)
pushBehavior.pushDirection = (otherBubbleView.center - bubbleView.center).convertToVector()
pushBehavior.magnitude = kMagnetStrength / 3
animator.addBehavior(pushBehavior)
otherBubbleView.pushBehaviors.append(pushBehavior)
}
}
bubbleView.isSelected = !bubbleView.isSelected
self.animator.updateItem(usingCurrentState: bubbleView)
self.enableBehaviors(for: bubbleView)
}
}
// MARK: Bubble Reposition
/**
Reposition all bubbles in array, distributing them based on last known position and proportionally positioning them on new bounds.
Also refreshes spawnpoints.
*/
private func reposition(bubbles: [UEBubbleView]) {
guard !bubbles.isEmpty, spawnPoints.count > 3 else { return }
let previousScreenSize = spawnPoints[3] + self.lastBubbleSize // bottomRight
for bubble in bubbles {
let bubbleAnchor = bubble.frame.origin / previousScreenSize
self.disableBehaviors(for: bubble)
bubble.frame.origin = bubbleAnchor * CGPoint(x: self.bounds.maxX, y: self.bounds.maxY)
self.enableBehaviors(for: bubble)
}
self.spawnPointsSetup()
}
// MARK: - Gestures
private func addPanGestureToContainer() {
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
self.addGestureRecognizer(pan)
}
// MARK: Selection Control
private func addTapGesture(to bubbleView: UEBubbleView!) {
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
bubbleView.addGestureRecognizer(tap)
}
@objc private func handleTap(recognizer: UITapGestureRecognizer) {
if let bubbleView = recognizer.view as? UEBubbleView {
self.refresh(bubbleView, toggleSelection: true)
if bubbleView.isSelected { self.delegate?.bubbleSelected?(bubbleView) }
else { self.delegate?.bubbleDeselected?(bubbleView) }
}
}
// MARK: Drag Control
private func addPanGesture(to bubbleView: UEBubbleView!) {
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
bubbleView.addGestureRecognizer(pan)
}
private var originalAttractionAnchor = CGPoint.zero
private var activeSnapper: UISnapBehavior?
@objc private func handlePan(recognizer: UIPanGestureRecognizer) {
if recognizer.view == self {
let viewSize = CGPoint(x: self.bounds.maxX, y: self.bounds.maxY)
switch recognizer.state {
case .began:
self.originalAttractionAnchor = self.attractionAnchor
case .changed:
let drag = self.originalAttractionAnchor + (recognizer.translation(in: self) / viewSize)
self.attractionAnchor = CGPoint(interpolate: self.attractionAnchor, with: drag, weight: 0.2)
case .ended, .cancelled, .failed:
self.attractionAnchor.constrain(by: CGRect(x: 0, y: 0, width: 1, height: 1))
case .possible: break
@unknown default: break
}
} else if let bubble = recognizer.view as? UEBubbleView {
switch recognizer.state {
case .began:
// Instantiate snapping location
self.createSnapperForBubble(bubble, forLocation: recognizer.location(in: self))
self.magneton.removeItem(bubble)
case .changed:
// Change snapping location
self.activeSnapper?.snapPoint = recognizer.location(in: self)
case .ended, .cancelled, .failed:
// Disable snapping location
self.disableActiveSnapper()
self.magneton.addItem(bubble)
case .possible: break
@unknown default: break
}
}
}
private func createSnapperForBubble(_ bubbleView: UEBubbleView, forLocation location: CGPoint) {
self.disableActiveSnapper() // Fix for multiple touches
self.activeSnapper = UISnapBehavior(item: bubbleView, snapTo: location)
self.activeSnapper?.damping = bubbleView.isSelected ? 1 : 0.66
if self.activeSnapper != nil {
self.animator.addBehavior(self.activeSnapper!)
}
}
private func disableActiveSnapper() {
if self.activeSnapper != nil {
self.animator.removeBehavior(self.activeSnapper!)
self.activeSnapper = nil
}
}
}
// MARK: -
// MARK: - Container Delegate!
@objc public protocol UEBubbleContainerViewDelegate: class {
@objc optional func bubbleSelected(_ bubbleView: UEBubbleView)
@objc optional func bubbleDeselected(_ bubbleView: UEBubbleView)
}
|
//
// UIView+Extension.swift
// AMImageEditor
//
// Created by Ali M Irshad on 08/10/20.
//
import UIKit
extension UIView {
func setBorderColorAndCornerWith(radius: CGFloat? = 0.0, color: UIColor? = .clear, width: CGFloat? = 0.0, masksToBounds: Bool = false) {
self.layer.borderColor = color!.cgColor
self.layer.borderWidth = width!
self.layer.cornerRadius = radius!
self.layer.masksToBounds = masksToBounds
}
func removeSubviews() {
for view in self.subviews {
view.removeFromSuperview()
}
}
var waitViewTag: Int {
return 500
}
func addWaitView(backgroundColor: UIColor = UIColor.lightGray.withAlphaComponent(0.2), indicatorColor: UIColor = UIColor.red) {
if viewWithTag(waitViewTag) != nil {
return
}
removeWaitView()
let containerView = UIView(frame: frame)
containerView.backgroundColor = backgroundColor
containerView.tag = waitViewTag
containerView.translatesAutoresizingMaskIntoConstraints = false
addSubViewWithConstraints(subview: containerView)
let activityIndicator = UIActivityIndicatorView(style: .gray)
activityIndicator.color = indicatorColor
containerView.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
activityIndicator.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
activityIndicator.startAnimating()
bringSubviewToFront(containerView)
}
func removeWaitView() {
viewWithTag(waitViewTag)?.removeFromSuperview()
}
func addSubViewWithConstraints(subview: UIView, padding: CGFloat = 0.0) {
subview.translatesAutoresizingMaskIntoConstraints = false
addSubview(subview)
subview.leftAnchor.constraint(equalTo: leftAnchor, constant: padding).isActive = true
subview.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding).isActive = true
subview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding).isActive = true
subview.topAnchor.constraint(equalTo: topAnchor, constant: padding).isActive = true
}
func asImage(captureRect: CGRect? = nil) -> UIImage {
if let captureRect = captureRect {
let renderer = UIGraphicsImageRenderer(bounds: captureRect)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
} else {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
}
|
//
// DetaiViewModel.swift
// HoroscopeApp
//
// Created by MCT on 29.10.2020.
//
import Foundation
import Alamofire
class DetailViewModel: DetailViewModelType {
// MARK: Properties
var result: AstroDetailModel? = nil {
didSet {
resultsDidChange?(result!)
}
}
var resultsDidChange: ((AstroDetailModel) -> Void)?
// MARK: Funcs
func returnRetult() -> AstroDetailModel {
return result!
}
func fetchData(param: [String:Any], completion: @escaping (AFResult<Codable>) -> Void) {
NetworkService.shared.service(.post, url: Constant.NetworkConstant.baseUrl, model: AstroDetailModel.self, parameters: param) { [weak self] (response) in
switch response {
case .success(let AstroDetail):
let astroDetailResult = AstroDetail as! AstroDetailModel
print(astroDetailResult)
self?.result = astroDetailResult
case .failure(let error):
print(error)
}
}
}
}
|
//
// Location.swift
// Favorites Food
//
// Created by Pavel Kurilov on 31.10.2018.
// Copyright © 2018 Pavel Kurilov. All rights reserved.
//
import Foundation
import MapKit
struct Location {
// typealias RealmType = RealmLocation
// MARK: - Properties
var name: String?
var coordinate: CLLocation?
}
|
//
// Reminder.swift
// ReminderApp
//
// Created by Mehmet Sahin on 4/23/19.
// Copyright © 2019 Mehmet Sahin. All rights reserved.
//
import Foundation
import RealmSwift
class Reminder: Object {
@objc dynamic var title: String = ""
@objc dynamic var isDone: Bool = false
@objc dynamic var dateCreated: Date?
// @objc dynamic var forPerson: Person?
var parentGroup = LinkingObjects(fromType: Group.self, property: "reminders")
}
|
//
// StatusConstants.swift
// App
//
// Created by developer on 16.05.16.
// Copyright © 2016 developer. All rights reserved.
//
import Foundation
struct StatusConstants {
struct Loading {
static let load = "Loading..."
}
struct Failed {
static let error = "Error"
static let noInternet = "No Internet"
}
}
|
//
// savedSongViewController.swift
// 新加坡中文电台
//
// Created by Jiang Nan Qing on 22/2/16.
// Copyright © 2016 CodeMarket.io. All rights reserved.
//
import UIKit
import MediaPlayer
import AVFoundation
class savedSongViewController: UIViewController {
@IBOutlet weak var savedSongTable: UITableView!
@IBOutlet weak var selectSegment: UISegmentedControl!
var savedSong:[String] = UserDefaults.standard.array(forKey: "SavedSongs") as? [String] ?? []
var recentSong:[String] = UserDefaults.standard.array(forKey: "RecentSongs") as? [String] ?? []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "收藏"
savedSongTable.dataSource = self
savedSongTable.delegate = self
// Do view setup here.
}
@IBAction func selectpage() {
savedSongTable.reloadData()
}
}
extension savedSongViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in savedSongTable: UITableView) -> Int {
return 1
}
func tableView(_ savedSongTable: UITableView, numberOfRowsInSection section: Int) -> Int {
selectSegment.selectedSegmentIndex == 0 ? savedSong.count:recentSong.count
}
func tableView(_ savedSongTable: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = savedSongTable.dequeueReusableCell(withIdentifier: "song", for: indexPath)
cell.textLabel?.backgroundColor = UIColor.clear
cell.textLabel?.text = selectSegment.selectedSegmentIndex == 0 ? savedSong[indexPath.row]:recentSong[indexPath.row]
return cell
}
}
|
//
// UIImage+encodedBase64.swift
// fakestagram
//
// Created by Andrès Leal Giorguli on 4/27/19.
// Copyright © 2019 3zcurdia. All rights reserved.
//
import Foundation
import UIKit
extension UIImage{
func encodedBase64() -> String?{
guard let data = self.jpegData(compressionQuality: 0.95) else{return nil}
return "data:image/jpeg;base64,\(data.base64EncodedString())"
}
}
|
//
// No1.swift
// study4
//
// Created by pxl on 2017/6/8.
// Copyright © 2017年 pxl. All rights reserved.
// 函数的返回值以及灵活多变的参数
import UIKit
class NO1: NSObject {
/*
func是定义函数的关键字,后面是函数名;
()中是可选的参数列表,既然是最简单的函数,自然我们可以让它留空;
()后面,是函数的返回值,同样,简单起见,我们也没有定义返回值;
{}中是函数要封装的逻辑,其实,在这里,我们调用的print,也是一个函数,只不过,它是一个定义在标准库中的函数,并且带有一个参数罢了;
**/
func printName() {
print("My name is Mars")
}
//向函数传递参数
func mul(m: Int, n: Int){
print(m * n)
}
//理解参数的两种名称
//个用于在定义函数的时候使用,叫做argument name,一个用于在调用函数时使用,叫做argument label。
// internal name / external name
func mul(multiplicand m: Int, of n: Int) {
print(m * n)
}
//使用_表示忽略
func mul(_ m: Int, off n: Int) {
print(m * n)
}
//为参数设置默认值
func mul(_ m: Int, of n: Int = 1) {
print(m * n)
}
//定义可变长参数
//No1().mul(2, 3, 5)
func mul(_ numbers: Int ...) {
let arrayMul = numbers.reduce(1, *)
print("mul : \(arrayMul)")
}
//定义inout参数
/*
在Swift里,函数的参数有一个性质:默认情况下,参数是只读的,这也就意味着:
你不能在函数内部修改参数值;
你也不能通过函数参数对外返回值;
*/
//其实,很简单,我们需要用inout关键字修饰一下参数的类型,明确告诉Swift编译器我们要修改这个参数的值:
func mul(result: inout Int, _ numbers: Int ...) {
result = numbers.reduce(1, *) // !!! Error here !!!
print("mul: \(result)")
}
//var result = 0
//mul(result: &result, 2, 3, 4, 5, 6, 7)
//result // 5040
}
|
//
// ViewHelperMethods.swift
// NasaImages
//
// Created by Jim Campagno on 3/19/17.
// Copyright © 2017 Jim Campagno. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func constrainEdges(to view: UIView) {
leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
topAnchor.constraint(equalTo: view.topAnchor).isActive = true
}
}
|
// Knapsack problem that returns the indexes of the elements
// that were added to the knapsack.
import Foundation
typealias Solution = (value: Int, isIncluded: Bool)
typealias Item = (weight: Int, value: Int)
func trackSolution(solutions: [[Solution]], items: [Item]) -> [Int] {
var limit = solutions[0].count - 1
var eIndex = solutions.count - 1
var solElements = [Int]()
while eIndex > 0 {
let sol = solutions[eIndex][limit]
if sol.isIncluded {
solElements.append(eIndex)
limit -= items[eIndex - 1].weight
}
eIndex -= 1
}
return solElements
}
func findValueSolutions(maxWeight: Int, items: [Item]) -> [[Solution]] {
let n = items.count
let defaultRow = [Solution](repeating: (0, false), count: maxWeight + 1)
var solutions = [[Solution]](repeating: defaultRow, count: n + 1)
for procIndex in 1...n {
let cElemIndex = procIndex - 1
for cWeightLimit in 1...maxWeight {
if items[cElemIndex].weight > cWeightLimit {
solutions[procIndex][cWeightLimit] = (solutions[procIndex - 1][cWeightLimit].value, false)
} else {
let pLimit = cWeightLimit - items[cElemIndex].weight
let withValue = items[cElemIndex].value + solutions[procIndex - 1][pLimit].value
let withoutValue = solutions[cElemIndex][cWeightLimit].value
if withValue >= withoutValue {
solutions[procIndex][cWeightLimit] = (withValue, true)
} else {
solutions[procIndex][cWeightLimit] = (withoutValue, false)
}
}
}
}
return solutions
}
func fillKnapsack(maxWeight: Int, items: [Item]) -> [Int] {
let solutions = findValueSolutions(maxWeight: maxWeight, items: items)
return trackSolution(solutions: solutions, items: items)
}
let maxWeight = 50
var items = [(weight: Int, value: Int)]()
items.append((10, 60))
items.append((20, 100))
items.append((30, 120))
let solution = fillKnapsack(maxWeight: maxWeight, items: items)
print("Solution indexes: \(solution)") |
//
// ViewController.swift
// ScheduleApp
//
// Created by Haroldo Leite on 21/12/18.
// Copyright © 2018 Haroldo Leite. All rights reserved.
//
import UIKit
class ContactListViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Navigation Bar
self.setNavigationTitle(StringConstants.ContactListTitle)
let addContact = UIBarButtonItem(image: ImageConstants.AddContactButton,
style: .plain,
target: self,
action: #selector(contactCreator))
self.navigationItem.rightBarButtonItem = addContact
}
// MARK: - Actions
@objc func contactCreator() {
let storyboard = UIStoryboard(name: StoryboardName.CreateContactStoryboard, bundle: nil)
if let vc = storyboard.instantiateViewController(withIdentifier: ViewControllerName.CreateContact) as? CreateContactViewController {
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
//
// THIndicatorLight.swift
// AudioLooper_Swift
//
// Created by nathan on 2020/12/25.
//
import UIKit
class THIndicatorLight: UIView {
var lightColor:UIColor?
}
|
//
// StickChartDataEntry.swift
// ChartsBugDemo
//
// Created by Лев Соколов on 10/01/2017.
// Copyright © 2017 TestName. All rights reserved.
//
import Foundation
open class StickChartDataEntry: ChartDataEntry
{
/// shadow-high value
open var high = Double(0.0)
/// shadow-low value
open var low = Double(0.0)
public required init()
{
super.init()
}
public init(x: Double, high: Double, low: Double)
{
super.init(x: x, y: (high + low) / 2.0)
self.high = high
self.low = low
}
public init(x: Double, high: Double, low: Double, data: AnyObject?)
{
super.init(x: x, y: (high + low) / 2.0, data: data)
self.high = high
self.low = low
}
/// - returns: The overall range (difference) between high and low.
open var bodyRange: Double
{
return abs(high - low)
}
/// the center value of the stick. (Middle value between high and low)
open override var y: Double
{
get
{
return super.y
}
set
{
super.y = (high + low) / 2.0
}
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! StickChartDataEntry
copy.high = high
copy.low = low
return copy
}
}
|
//
// Editportfolio.swift
// Tooli
//
// Created by Impero IT on 7/02/2017.
// Copyright © 2017 impero. All rights reserved.
//
import UIKit
import Toast_Swift
import NVActivityIndicatorView
import ObjectMapper
import Alamofire
import Kingfisher
import BSImagePicker
import Photos
class Editportfolio: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate,NVActivityIndicatorViewable , UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextViewDelegate
{
@IBOutlet weak var TxtDescription: UITextView!
@IBOutlet weak var TxtLocation: UITextField!
@IBOutlet weak var TxtProjectTitle: UITextField!
@IBOutlet weak var TxtCustomerName: UITextField!
@IBOutlet var collectionHeight : NSLayoutConstraint!
@IBOutlet weak var PortCollectionView: UICollectionView!
let sharedManager : Globals = Globals.sharedInstance
var portfolio : GetProtfolioM = GetProtfolioM()
var selectedImage : UIImage?
var imagePicker: UIImagePickerController!
var isImageSelected : Bool = false
var assets: [PHAsset]!
// Make this dynamic
var portfolioId = 0
override func viewWillAppear(_ animated: Bool)
{
self.startAnimating()
self.sideMenuController()?.sideMenu?.allowLeftSwipe = false
self.sideMenuController()?.sideMenu?.allowPanGesture = false
self.sideMenuController()?.sideMenu?.allowRightSwipe = false
var param = [:] as [String : Any]
param["PortfolioID"] = self.portfolioId
print(param)
AFWrapper.requestPOSTURL(Constants.URLS.PortfolioDetail, params :param as [String : AnyObject]? ,headers : nil , success: {
(JSONResponse) -> Void in
if JSONResponse["Status"].int == 1
{
self.portfolio = Mapper<GetProtfolioM>().map(JSONObject: JSONResponse.rawValue)!
self.stopAnimating()
self.TxtDescription.text = self.portfolio.Result.Description
self.TxtLocation.text = self.portfolio.Result.Location
self.TxtCustomerName.text = self.portfolio.Result.CustomerName
self.TxtProjectTitle.text = self.portfolio.Result.Title
self.PortCollectionView.reloadData()
}
else
{
self.stopAnimating()
self.view.makeToast(JSONResponse["Message"].rawString()!, duration: 3, position: .bottom)
}
})
{
(error) -> Void in
self.stopAnimating()
self.view.makeToast("Server error. Please try again later", duration: 3, position: .bottom)
}
guard let tracker = GAI.sharedInstance().defaultTracker else { return }
tracker.set(kGAIScreenName, value: "Edit portfolio Screen.")
guard let builder = GAIDictionaryBuilder.createScreenView() else { return }
tracker.send(builder.build() as [NSObject : AnyObject])
}
@IBAction func actionBack(sender : UIButton) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func BtnBackMainScreen(_ sender: UIButton)
{
AppDelegate.sharedInstance().moveToDashboard()
}
@IBAction func actionPost(sender : UIButton)
{
var isValid : Bool = true
if TxtProjectTitle.text == ""
{
isValid = false;
self.view.makeToast("Please enter valid Project Title", duration: 3, position: .center)
}
else if TxtLocation.text == ""
{
isValid = false
self.view.makeToast("Please enter valid Location", duration: 3, position: .center)
}
else if TxtCustomerName.text == ""
{
isValid = false
self.view.makeToast("Please enter valid Customer Name", duration: 3, position: .center)
}
else if TxtDescription.text == "Enter Description"
{
isValid = false;
self.view.makeToast("Please enter valid Description", duration: 3, position: .center)
}
else if(self.portfolio.Result.PortfolioImageList.count == 0)
{
isValid = false;
self.view.makeToast("Please select at least one image", duration: 3, position: .center)
}
if isValid
{
uploadPortfolioWithImage()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
self.PortCollectionView.delegate = self
self.PortCollectionView.dataSource = self
let flow = PortCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
flow.sectionInset = UIEdgeInsetsMake(0, 3, 0, 3)
flow.minimumInteritemSpacing = 1
flow.minimumLineSpacing = 1
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
if textView.text == "Enter Description" {
textView.text = ""
}
return true
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
if textView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "" {
textView.text = "Enter Description"
}
return true
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0
{
var totalItems = ceil(Double(portfolio.Result.PortfolioImageList.count + 1) / 3)
if totalItems == 0
{
totalItems = 1
}
self.collectionHeight.constant = CGFloat( CGFloat(totalItems) * ((Constants.ScreenSize.SCREEN_WIDTH / 3)))
return portfolio.Result.PortfolioImageList.count + 1
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row == portfolio.Result.PortfolioImageList.count
{
let Addcell = collectionView.dequeueReusableCell(withReuseIdentifier: "Addcell", for: indexPath) as! Addcell
return Addcell
}
else
{
let Collectcell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PortfolioCell
if portfolio.Result.PortfolioImageList[indexPath.row].addedByMe == false
{
let imgURL = portfolio.Result.PortfolioImageList[indexPath.row].ImageLink
let urlPro = URL(string: imgURL)
Collectcell.PortfolioImage.kf.indicatorType = .activity
let tmpResouce = ImageResource(downloadURL: urlPro!, cacheKey: portfolio.Result.PortfolioImageList[indexPath.row].ImageLink)
let optionInfo: KingfisherOptionsInfo = [
.downloadPriority(0.5),
.transition(ImageTransition.fade(1)),
.forceRefresh
]
Collectcell.PortfolioImage?.kf.setImage(with: tmpResouce, placeholder: nil, options: optionInfo, progressBlock: nil, completionHandler: nil)
}
else
{
Collectcell.PortfolioImage.image = portfolio.Result.PortfolioImageList[indexPath.row].image
}
Collectcell.btnRemove.addTarget(self, action: #selector(removePortfolio(sender:)), for: UIControlEvents.touchUpInside)
Collectcell.btnRemove.tag = indexPath.row + 1000
return Collectcell
}
}
func removePortfolio(sender : UIButton)
{
let index = sender.tag - 1000
if portfolio.Result.PortfolioImageList[index].addedByMe
{
portfolio.Result.PortfolioImageList.remove(at: index)
}
else
{
// Load webservice to delete
var param = [:] as [String : Any]
param["ImageID"] = portfolio.Result.PortfolioImageList[index].ImageID
print(param)
AFWrapper.requestPOSTURL(Constants.URLS.PortfolioDeleteImage, params :param as [String : AnyObject]? ,headers : nil , success: {
(JSONResponse) -> Void in
if JSONResponse["Status"].int == 1
{
self.stopAnimating()
self.portfolio.Result.PortfolioImageList.remove(at: index)
self.PortCollectionView.reloadData()
self.view.makeToast(JSONResponse["Message"].rawString()!, duration: 3, position: .bottom)
}
else
{
self.stopAnimating()
self.view.makeToast(JSONResponse["Message"].rawString()!, duration: 3, position: .bottom)
}
}) {
(error) -> Void in
self.stopAnimating()
self.view.makeToast("Server error. Please try again later", duration: 3, position: .bottom)
}
}
self.PortCollectionView.reloadData();
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let lastRowIndex = collectionView.numberOfItems(inSection: collectionView.numberOfSections-1)
if (indexPath.row == lastRowIndex - 1) {
let alert : UIAlertController = UIAlertController(title: "Upload Image", message: "Select image from", preferredStyle: UIAlertControllerStyle.actionSheet)
alert.addAction(UIAlertAction(title: "Take From Camera", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
self.takePhoto()
}))
alert.addAction(UIAlertAction(title: "Use Gallery", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
let vc = BSImagePickerViewController()
vc.maxNumberOfSelections = 50
self.bs_presentImagePickerController(vc, animated: true,
select: { (asset: PHAsset) -> Void in
print("Selected: \(asset)")
}, deselect: { (asset: PHAsset) -> Void in
print("Deselected: \(asset)")
}, cancel: { (assets: [PHAsset]) -> Void in
print("Cancel: \(assets)")
}, finish: { (assets: [PHAsset]) -> Void in
print("Finish: \(assets)")
DispatchQueue.main.async
{
if(assets.count != 0)
{
for assat in assets
{
var temp:PortfolioImageM = PortfolioImageM()
temp.addedByMe = true
temp.image = self.getAssetThumbnail(asset: assat)
self.portfolio.Result.PortfolioImageList.append(temp)
}
}
self.PortCollectionView.reloadData()
}
}, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (UIAlertAction) in
}))
self.startAnimating()
self.present(alert, animated: true) {
self.stopAnimating()
}
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow:CGFloat = 3
let hardCodedPadding:CGFloat = 10
let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
let itemHeight : CGFloat = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
return CGSize(width: itemWidth, height: itemHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func takePhoto() {
self.view.endEditing(true)
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func selectFromGallery() {
self.view.endEditing(true)
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
selectedImage = image
isImageSelected=true
} else{
print("Something went wrong")
}
picker.dismiss(animated: true, completion: nil);
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil);
}
func uploadPortfolioWithImage()
{
self.startAnimating()
var param = [:] as [String : Any]
param["Title"] = self.TxtProjectTitle.text
param["CustomerName"] = self.TxtCustomerName.text
param["Location"] = self.TxtLocation.text
param["Description"] = self.TxtDescription.text
param["PortfolioID"] = "\(self.portfolio.Result.PortfolioID)"
let header = ["Authorization": String.localizedStringWithFormat("%@",UserDefaults.standard.string(forKey: Constants.KEYS.TOKEN)! as String)]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for temp in self.portfolio.Result.PortfolioImageList
{
if(temp.addedByMe == true)
{
multipartFormData.append(UIImageJPEGRepresentation(temp.image, 0.5)!, withName: "PortfolioImageList", fileName: "toolicontractor.png", mimeType: "image/png")
}
}
for (key, value) in param
{
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to:Constants.URLS.PortfolioEdit,headers: header)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
})
upload.responseJSON { response in
self.stopAnimating()
print(response.result)
switch response.result
{
case .success(let JSON):
let response1 = JSON as! NSDictionary
if String(describing: response1.object(forKey: "Status")!) == "1"
{
self.TxtDescription.text = ""
self.TxtLocation.text = ""
self.TxtCustomerName.text = ""
self.TxtProjectTitle.text = ""
self.PortCollectionView.reloadData()
self.selectedImage = nil
self.view.makeToast("\(response1.object(forKey: "Message")!)", duration: 3, position: .center)
}
else
{
self.view.makeToast("\(response1.object(forKey: "Message")!)", duration: 3, position: .center)
}
case .failure(let error):
self.view.makeToast("Server error. Please try again later. \(error)", duration: 3, position: .center)
}
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
self.stopAnimating()
break
}
}
}
func getAssetThumbnail(asset: PHAsset) -> UIImage
{
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 800, height: 1100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
}
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A wrapper around a bitmap storage with room for at least `bitCount` bits.
public // @testable
struct _UnsafeBitMap {
public // @testable
let values: UnsafeMutablePointer<UInt>
public // @testable
let bitCount: Int
public // @testable
static func wordIndex(_ i: Int) -> Int {
// Note: We perform the operation on UInts to get faster unsigned math
// (shifts).
return Int(bitPattern: UInt(bitPattern: i) / UInt(UInt._sizeInBits))
}
public // @testable
static func bitIndex(_ i: Int) -> UInt {
// Note: We perform the operation on UInts to get faster unsigned math
// (shifts).
return UInt(bitPattern: i) % UInt(UInt._sizeInBits)
}
public // @testable
static func sizeInWords(forSizeInBits bitCount: Int) -> Int {
return (bitCount + Int._sizeInBits - 1) / Int._sizeInBits
}
public // @testable
init(storage: UnsafeMutablePointer<UInt>, bitCount: Int) {
self.bitCount = bitCount
self.values = storage
}
public // @testable
var numberOfWords: Int {
return _UnsafeBitMap.sizeInWords(forSizeInBits: bitCount)
}
public // @testable
func initializeToZero() {
values.initialize(with: 0, count: numberOfWords)
}
public // @testable
subscript(i: Int) -> Bool {
get {
_sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds")
let word = values[_UnsafeBitMap.wordIndex(i)]
let bit = word & (1 << _UnsafeBitMap.bitIndex(i))
return bit != 0
}
nonmutating set {
_sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds")
let wordIdx = _UnsafeBitMap.wordIndex(i)
let bitMask = 1 << _UnsafeBitMap.bitIndex(i)
if newValue {
values[wordIdx] = values[wordIdx] | bitMask
} else {
values[wordIdx] = values[wordIdx] & ~bitMask
}
}
}
}
|
//
// ModalPresentationContext.swift
// Coins
//
// Created by Kevin Mun on 09/05/18.
// Copyright © 2018 Global Commerce Technologies Pte. All rights reserved.
//
import Foundation
@objc protocol ModalPresentationContext {
func present(_ controller: UIViewController, animated: Bool, completion: (() -> Void)?)
func presentOverTop(_ controller: UIViewController, animated: Bool, completion: (() -> Void)?)
func dismiss(animated flag: Bool, completion: (() -> Swift.Void)?)
func view() -> UIView
func rootViewController() -> UIViewController?
}
|
import UIKit
protocol Presentable {
func present() -> UIViewController
}
protocol TabPresentable: Presentable {
var presentableTabBarItem: UITabBarItem { get }
}
extension UIViewController: TabPresentable {
func present() -> UIViewController {
self
}
var presentableTabBarItem: UITabBarItem {
tabBarItem
}
}
|
//
// ToDoTableViewController.swift
// ToDoList2
//
// Created by Jun Dang on 2018-12-18.
// Copyright © 2018 Jun Dang. All rights reserved.
//
import UIKit
import CoreData
class ToDoTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView: UITableView = UITableView(frame: CGRect.zero)
let cell = "cell"
var items = [Items]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var searchBar:UISearchBar?
var searchBarActive:Bool = false
var searchBarBoundsY:CGFloat?
var isObserverAdded = false
var toDOForSearchResult:[Items] = []
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupNavigationbar()
loadItems()
// Do any additional setup after loading the view.
}
func setupTableView() {
tableView.frame = self.view.frame
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cell)
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.tableFooterView = UIView()
//tableView.isEditing = true
prepareSearchBar()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.searchBarActive {
return toDOForSearchResult.count
}
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: self.cell, for: indexPath as IndexPath)
let item = (self.searchBarActive) ? toDOForSearchResult[indexPath.row] : items[indexPath.row]
cell.textLabel?.text = item.name
cell.accessoryType = item.completed ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("select row")
tableView.deselectRow(at: indexPath, animated: true)
items[indexPath.row].completed = !items[indexPath.row].completed
print("completed: \(items[indexPath.row].completed)")
saveItemsAndReloadTableView()
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
let item = items[indexPath.row]
items.remove(at: indexPath.row)
context.delete(item)
saveItems()
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
/*func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}*/
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedItem = self.items[sourceIndexPath.row]
items.remove(at: sourceIndexPath.row)
items.insert(movedItem, at: destinationIndexPath.row)
}
func saveItems() {
do {
try context.save()
} catch {
print("Error saving item with \(error)")
}
}
func loadItems() {
let request: NSFetchRequest<Items> = Items.fetchRequest()
do {
items = try context.fetch(request)
} catch {
print("Error saving item with \(error)")
}
tableView.reloadData()
}
}
extension ToDoTableViewController: UINavigationControllerDelegate, UINavigationBarDelegate {
func setupNavigationbar() {
navigationItem.title = "ToDoList"
let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action:#selector(addTapped))
navigationItem.rightBarButtonItem = addButton
}
@objc func addTapped(_sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Item", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
let newItem = Items(context: self.context)
newItem.name = textField.text!
self.items.append(newItem)
self.saveItemsAndReloadTableView()
}
alert.addAction(action)
alert.addTextField { (field) in
textField = field
textField.placeholder = "Add a New Item"
}
present(alert, animated: true, completion: nil)
}
func saveItemsAndReloadTableView() {
saveItems()
tableView.reloadData()
}
}
extension ToDoTableViewController: UISearchBarDelegate {
func prepareSearchBar(){
self.addSearchBar()
}
func addSearchBar(){
if self.searchBar == nil {
self.searchBarBoundsY = (self.navigationController?.navigationBar.frame.size.height)! + UIApplication.shared.statusBarFrame.size.height
self.searchBar = UISearchBar(frame: CGRect(x: 0,y: self.searchBarBoundsY!, width: UIScreen.main.bounds.size.width, height: 44))
self.searchBar!.searchBarStyle = UISearchBar.Style.minimal
self.searchBar!.tintColor = UIColor(red: (0/255.0), green: (153/255.0), blue: (0/255.0), alpha: 1.0)
self.searchBar!.barTintColor = UIColor.white
self.searchBar!.delegate = self
self.searchBar!.placeholder = "Search"
self.searchBar!.setShowsCancelButton(false, animated: true)
let textFieldInsideUISearchBar = searchBar!.value(forKey: "searchField") as? UITextField
textFieldInsideUISearchBar?.font = UIFont(name: "HelveticaNeue", size: 15)
tableView.tableHeaderView = searchBar
tableView.tableHeaderView?.backgroundColor = UIColor(red: (224/255.0), green: (224/255.0), blue: (224/255.0), alpha: 1.0)
}
if !self.searchBar!.isDescendant(of: self.view){
self.view.addSubview(self.searchBar!)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.cancelSearching()
self.tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.searchBarActive = true
self.view.endEditing(true)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar!.setShowsCancelButton(true, animated: true)
let uiButton = searchBar.value(forKey: "cancelButton") as! UIButton
uiButton.setTitle("cancel", for: UIControl.State())
uiButton.setTitleColor(UIColor(red: (0/255.0), green: (153/255.0), blue: (0/255.0), alpha: 1.0), for: UIControl.State())
uiButton.titleLabel!.font = UIFont(name: "HelveticaNeue", size: 15)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.searchBarActive = false
self.searchBar!.setShowsCancelButton(false, animated: false)
self.searchBar!.resignFirstResponder()
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
self.toDOForSearchResult = items.filter({( item : Items) -> Bool in
if let itemName = item.name {
print(itemName.lowercased().contains(searchText.lowercased()))
return itemName.lowercased().contains(searchText.lowercased())
} else {
return false
}
})
print("result: \(self.toDOForSearchResult[0].name)")
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.count > 0 {
self.searchBarActive = true
self.filterContentForSearchText(searchText)
tableView.reloadData()
} else {
self.searchBarActive = false
tableView.reloadData()
}
}
func cancelSearching(){
self.searchBarActive = false
self.searchBar!.resignFirstResponder()
self.searchBar!.text = ""
}
func addObservers(){
isObserverAdded = true
let context = UnsafeMutablePointer<UInt8>(bitPattern: 1)
self.tableView.addObserver(self, forKeyPath: "contentOffset", options: [.new,.old], context: context)
}
func removeObservers(){
if (isObserverAdded) {
self.tableView.removeObserver(self, forKeyPath: "contentOffset")
isObserverAdded = false
}
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?){
if keyPath! == "contentOffset" {
if let tableV:UITableView = object as? UITableView {
self.searchBar?.frame = CGRect(
x: self.searchBar!.frame.origin.x,
y: self.searchBarBoundsY! + ( (-1 * tableV.contentOffset.y) - self.searchBarBoundsY!),
width: self.searchBar!.frame.size.width,
height: self.searchBar!.frame.size.height
)
}
}
}
}
|
//
// TextField.swift
// testingArea
//
// Created by Quast, Malte on 09.11.17.
// Copyright © 2017 Quast, Malte. All rights reserved.
//
import UIKit
class TextField: UITextField {
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = #colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 0.249812714) // color literal auswählen und farbe eintragen
layer.cornerRadius = 5.0
textAlignment = .center
if placeholder == nil {
placeholder = " " // wichtig hier ein leerzeichen zu setzen
}
// alternative:
// if let p = placeholder{}
// if bedingung ist ein safety check, so dass placeholder nicht komplett leer ist, sondern "" --> da placerholder! implicit optional ist
let place = NSAttributedString(string: placeholder! , attributes: [.foregroundColor: #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1)])
attributedPlaceholder = place
// überschreiben des kompletten placeholders mit place um text an eigene bedürfnisse anzupassen
textColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
}
}
|
//
// ChartViewController.swift
// DailyHasslesApp1
//
// Created by 山本英明 on 2021/04/05.
//
import UIKit
import Charts
import FirebaseAuth
//LoadModel内で取得した最新指定月ユーザーデータはGetDataProtocolが持っている
class ChartViewController: UIViewController,ChartViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource,GetDataProtocol {
@IBOutlet weak var increDecre: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var chartView: LineChartView!
@IBOutlet weak var pickerView: UIPickerView!
var chartArray = [PersonalData]()
var sendModel = SendModel()
//getDataProtocolにて最新指定月ユーザー情報を取得したい
var loadModel = LoadModel()
//pickerView表記用 {$0}は全体を表す
let years = (2021...2031).map{ $0 }
let months = (1...12).map{ $0 }
override func viewDidLoad() {
super.viewDidLoad()
//pickerViewを使うときはデリゲートが必要
pickerView.delegate = self
pickerView.dataSource = self
//チャート(グラフ)の背景色
chartView.backgroundColor = .white
//ちょっと透けさせる
chartView.alpha = 0.9
//getDataProtocolにて最新指定月ユーザー情報を取得したい
loadModel.getDataProtocol = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//現在時刻→年月を確認→その月のデータを全て取得する
let date = GetDateModel.getTodayDate(slash: true)
let dateArray = date.components(separatedBy: "/")
//ピッカーを隠しておく
pickerView.isHidden = true
//LoadModelは何のため???
loadModel.loadMyRecordData(userID: Auth.auth().currentUser!.uid, yearMonth: dateArray[0] + dateArray[1], day: dateArray[2])
//タブで画面遷移するのでバックボタンは不必要
self.navigationController?.isNavigationBarHidden = true
}
//チャートに反映するための同ユーザーの全データをFSから取得したい
//今日の日付を取得する
//dateを取得する
//dateをパスにしてデータを引っ張ってくる
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//行だがコンポーネントによって違う
//0だったらyears = (2021...2031).map{ $0 }のカウントを返す
if component == 0{
return years.count
}else if component == 1{
return months.count
}else{
return 0
}
}
//ピッカービューにおいて年と月を別々に分割して選択できる
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
//ピッカーのタイトルをつける
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0{
return "\(years[row])年"
}else if component == 1{
return "\(months[row])月"
}else{
return nil
}
}
//ピッカーが選択された時に呼ばれる箇所
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//選択された値が変数に代入される
let year = years[pickerView.selectedRow(inComponent: 0)]
let month = months[pickerView.selectedRow(inComponent: 1)]
//1桁の値の場合は01,02月のように値を渡すための変数(ロード時にパスとして利用)
var month_1digit = String()
//1桁の値の場合
if month < 10 {
month_1digit = "0" + String(month)
dateLabel.text = "\(year)年\(month_1digit)月"
loadModel.loadMyRecordData(userID: Auth.auth().currentUser!.uid, yearMonth: String(year) + month_1digit, day: "")
//2桁の値の場合
}else{
dateLabel.text = "\(year)年\(month)月"
loadModel.loadMyRecordData(userID: Auth.auth().currentUser!.uid, yearMonth: String(year) + String(month), day: "")
}
//選択したタイミングでピッカービューを下げる
pickerView.isHidden = true
}
//読み込みが全て完了したら自動でここが呼ばれる(最新のデータ付)
func getData(dataArray: [PersonalData]) {
//これを使ってグラフに表していく
chartArray = dataArray
//最新データのチャートへの反映
setUpChart(values: chartArray)
//1回目→2回目のDHデータの差分(データが登録されていれば)
if chartArray.count > 0{
increDecre.text = String(Double(chartArray.last!.dailyHassle)! - Double(chartArray.first!.dailyHassle)!)
//追加(下にラベルをつける)
chartView.xAxis.labelPosition = .bottom
//X軸の縦の線の数
chartView.xAxis.labelCount = chartArray.count
// sendModel.sendDailyHassles(userName: GetUserDataModel.getUserData(key: "userModel"), dailyHassles: increDecre.text!)
//増減の結果をランキング用に送信する
sendModel.sendResultForRank(userName: GetUserDataModel.getUserData(key: "userName"), dailyHassles: increDecre.text!)
}
}
//Double型で返す
func setUpChart(values:[PersonalData]){
//値をチャートへ反映するメソッド
var entry = [ChartDataEntry]()
//(Xは日付、YはDHの数)をその数だけ繰り返す
for i in 0..<values.count{
let date = Date(timeIntervalSince1970: values[i].date)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "ja_JP")
dateFormatter.dateFormat = "dd"
//日付
let dateString = dateFormatter.string(from: date)
//(x:Double(dateString)は日付
//(x:Double(dateString)は日付
entry.append(ChartDataEntry(x:Double(dateString)!,y: Double(values[i].dailyHassle)!))
}
//繰り返しの値が入ったentryを格納する
let dataSet = LineChartDataSet(entries: entry, label: "My Daily Hassles")
chartView.data = LineChartData(dataSet: dataSet)
}
// //反映するために作成
// func setUpChart(values:PersonalData){
// //値をチャートへ反映するメソッド
// var entry = [ChartDataEntry]()
// //Xは日付YはDHの数
// for i in 0..<values.count{
//
// }
// }
//チャートのX軸、Y軸を規定
//出ない場合に疑う場所
func setUpLineChart(_ chart:LineChartView,data:LineChartData){
chart.delegate = self
//項目の表示を行うかどうか
chart.chartDescription?.enabled = true
//ドラッグの操作
chart.dragEnabled = true
//チャートの拡大表示
chart.setScaleEnabled(true)
//メモリの表示
chart.setViewPortOffsets(left: 15, top: 0, right: 0, bottom: 15)
//
chart.legend.enabled = true
//チャートの左の目盛
chart.leftAxis.enabled = true
chart.leftAxis.spaceTop = 0.8
chart.leftAxis.spaceBottom = 0.4
//チャートの右の目盛
chart.rightAxis.enabled = false
//目盛線の表示
chart.xAxis.enabled = true
//chartのデータの中に取得したdataを入れる
chart.data = data
//描画アニメーションを行うか(2秒かけて)
chart.animate(xAxisDuration: 2)
}
@IBAction func toRankVC(_ sender: Any) {
let rankVC = self.storyboard?.instantiateViewController(identifier: "rankVC") as! RankingViewController
//戻る必要があるのでバックボタンは必要
self.navigationController?.isNavigationBarHidden = false
self.navigationController?.pushViewController(rankVC, animated: true)
}
@IBAction func pickerShowAction(_ sender: Any) {
pickerView.isHidden = false
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// GroupManagementViewController.swift
// TaxiDriver
//
// Created by Syria.Apple on 5/10/20.
// Copyright © 2020 icanStudioz. All rights reserved.
//
import UIKit
import Alamofire
import Firebase
class GroupManagementViewController: UIViewController {
@IBOutlet var groupName: UILabel!
@IBOutlet var AdminAvatar: UIImageView!
@IBOutlet var tableView: UITableView!
// @IBOutlet var TextFieldDriverNumber: UITextField!
// @IBOutlet var TextFieldGroupName: UITextField!
@IBOutlet var AddGroupButton: UIButton!
@IBOutlet var AddDriverToGroupButton: UIButton!
@IBOutlet var DeleteDriverFromGroupButton: UIButton!
@IBOutlet var ChangeGroupNameButton: UIButton!
@IBOutlet var MyGroupsButton: UIButton!
var TextFieldGroup: UITextField!
var group_bool: Bool!
var group_indecator_number: Int!
var groups = [Group]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_Title", comment: "")
if LocalizationSystem.sharedInstance.getLanguage() == "ar" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// Here menuViewController is SideDrawer ViewCOntroller
let sidemenuViewController = storyboard.instantiateViewController(withIdentifier: "MenuViewController") as? MenuViewController
revealViewController().rightViewController = sidemenuViewController
self.revealViewController().rightViewRevealWidth = self.view.frame.width * 0.8
let menuButton = UIBarButtonItem(image: UIImage(named: "menu"),
style: .plain, target: SWRevealViewController(),
action: #selector(SWRevealViewController.rightRevealToggle(_:)))
self.navigationItem.leftBarButtonItem = menuButton
}
else{
if let revealController = self.revealViewController() {
revealController.panGestureRecognizer()
let menuButton = UIBarButtonItem(image: UIImage(named: "menu"),
style: .plain, target: revealController,
action: #selector(SWRevealViewController.revealToggle(_:)))
self.navigationItem.leftBarButtonItem = menuButton
}
}
// self.TextFieldDriverNumber.cornerRadius(radius: 20.0, andPlaceholderString: NSLocalizedString("+",comment: ""))
// self.TextFieldDriverNumber.paddedTextField(frame: CGRect(x: 0, y: 0, width: 25, height: self.TextFieldDriverNumber.frame.height))
self.AddDriverToGroupButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_AddDriver", comment: ""), for: .normal)
self.DeleteDriverFromGroupButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_DeleteDriver", comment: ""), for: .normal)
self.ChangeGroupNameButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_ChangeGroupName", comment: ""), for: .normal)
self.MyGroupsButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_MyGroups", comment: ""), for: .normal)
self.AddDriverToGroupButton.corner(radius: 20.0, color: UIColor.white, width: 1.0)
self.DeleteDriverFromGroupButton.corner(radius: 20.0, color: UIColor.white, width: 1.0)
self.ChangeGroupNameButton.corner(radius: 20.0, color: UIColor.white, width: 1.0)
self.MyGroupsButton.corner(radius: 20.0, color: UIColor.white, width: 1.0)
// self.TextFieldGroupName.cornerRadius(radius: 20.0, andPlaceholderString: NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_GroupName", comment: ""),comment: ""))
// self.TextFieldGroupName.paddedTextField(frame: CGRect(x: 0, y: 0, width: 25, height: self.TextFieldGroupName.frame.height))
self.AddGroupButton.setTitle(LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_AddGroup", comment: ""), for: .normal)
self.AddGroupButton.corner(radius: 20.0, color: UIColor.white, width: 1.0)
}
override func viewWillAppear(_ animated: Bool) {
self.loadAdminGroupInfo()
// self.loadGroupList()
loadMyGroupList()
getImgProfileAdmin()
}
func loadGroupList(){
let params = ["admin_id":Common.instance.getUserId()]
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
//HUD.show(to: view)
_ = Alamofire.request(APIRouters.getGroupList(params,headers)).responseObject { (response: DataResponse<Groups>) in
//HUD.hide(to: self.view)
if response.result.isSuccess{
if response.result.value?.status == true , ((response.result.value?.groups) != nil) {
self.groups = (response.result.value?.groups)!
DispatchQueue.main.async {
self.tableView.reloadData()
}
} else {
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: "No data found.", for: self)
}
}
if response.result.isFailure{
Common.showAlert(with: NSLocalizedString("Error!!", comment: ""), message: response.error?.localizedDescription, for: self)
}
}
}
func getImgProfileAdmin() {
Database
.database()
.reference()
.child("users")
.child("profile")
.child(Auth.auth().currentUser!.uid)
.queryOrderedByKey()
.observeSingleEvent(of: .value, with: { snapshot in
guard let dict = snapshot.value as? [String:Any] else {
print("Error")
return
}
let photoURL = (dict["photoURL"] as? String)!
if let urlString = URL(string: (photoURL)){
self.AdminAvatar.kf.setImage(with: urlString)
}
print("tttttttt",photoURL)
// let priceAd = dict["priceAd"] as? String
})
}
func loadMyGroupList(){
let params = ["user_id":Common.instance.getUserId()]
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
print("ibrahim123")
print(Common.instance.getUserId())
//HUD.show(to: view)
_ = Alamofire.request(APIRouters.getMyGroupList(params,headers)).responseObject { (response: DataResponse<Groups>) in
//HUD.hide(to: self.view)
print("ibrahim")
print(response)
if response.result.isSuccess{
if response.result.value?.status == true , ((response.result.value?.groups) != nil) {
print(response.result.value)
self.groups = (response.result.value?.groups)!
if self.groups.count > 0 {
self.groupName.text = self.groups[0].group_name
//if let urlString = URL(string: (self.groups[0].admin_avatar)){
//print(self.groups[0].admin_avatar)
// self.AdminAvatar.kf.setImage(with: urlString)
//}
}
} else {
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: "No data found.", for: self)
}
}
if response.result.isFailure{
Common.showAlert(with: NSLocalizedString("Error!!", comment: ""), message: response.error?.localizedDescription, for: self)
}
}
}
func loadAdminGroupInfo(){
let params = ["admin_id":Common.instance.getUserId()]
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
HUD.show(to: view)
_ = Alamofire.request(APIRouters.getAdminGroupInfo(params,headers)).responseObject { (response: DataResponse<Groups>) in
HUD.hide(to: self.view)
if response.result.value?.status == true{
// self.TextFieldGroupName.isHidden = true
self.AddGroupButton.isHidden = true
self.AddDriverToGroupButton.isHidden = false
self.DeleteDriverFromGroupButton.isHidden = false
self.ChangeGroupNameButton.isHidden = false
self.MyGroupsButton.isHidden = false
self.AdminAvatar.isHidden = false
self.groupName.isHidden = false
print("successfully")
print(response)
}
if response.result.value?.status == false{
// self.TextFieldDriverNumber.isHidden = false
self.AddGroupButton.isHidden = false
self.AddDriverToGroupButton.isHidden = true
self.DeleteDriverFromGroupButton.isHidden = true
self.ChangeGroupNameButton.isHidden = true
self.MyGroupsButton.isHidden = true
self.AdminAvatar.isHidden = true
self.groupName.isHidden = true
print(response)
}
}
}
@IBAction func AddGroupButtonClicked(_ sender: Any) {
group_bool = true
group_indecator_number = 1
openAlert()
// if openAlert() {
// AddGroupFunc()
// }
}
@IBAction func ChangeGroupNameButtonClicked(_ sender: Any) {
group_bool = true
group_indecator_number = 2
openAlert()
// if openAlert() {
// changeGroupNameFunc()
// }
}
@IBAction func AddDriverToGroupButtonClicked(_ sender: Any) {
group_bool = false
group_indecator_number = 3
openAlert()
// if openAlert(){
// AddDriverToGroupFunc()
// }
}
@IBAction func DeleteDriverFromGroupButtonClicked(_ sender: Any) {
false
group_indecator_number = 4
openAlert()
// if openAlert() {
// DeleteDriverFromGroupFunc()
// }
}
@IBAction func MyGroupsButtonClicked(_ sender: Any) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "MyGroupsViewController") as! MyGroupsViewController
self.navigationController?.pushViewController(vc, animated: true)
}
func AddGroupFunc() {
let refreshAlert = UIAlertController(title: "Add Group", message: "Please Confirm!", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
}))
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
var parameters = [String:Any]()
parameters["admin_id"] = Common.instance.getUserId()
parameters["group_name"] = self.TextFieldGroup.text//self.TextFieldGroupName.text
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
// -- show loading --
HUD.show(to: self.view)
// -- send request --
APIRequestManager.request(apiRequest: APIRouters.addGroup(parameters, headers), success: { (response) in
HUD.hide(to: self.view)
print("response from addgroup func")
print(response)
self.loadAdminGroupInfo()
self.loadMyGroupList()
if response is [String : Any] {
let alert = UIAlertController(title: NSLocalizedString("Success!!",comment: ""), message: "", preferredStyle: .alert)
let done = UIAlertAction(title: NSLocalizedString("Done", comment: ""), style: .default, handler: { (action) in
_ = self.navigationController?.popViewController(animated: true)
// self.TextFieldGroupName.isHidden = true
self.AddGroupButton.isHidden = true
self.loadAdminGroupInfo()
})
alert.addAction(done)
self.present(alert, animated: true, completion: nil)
}
}, failure: { (message) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: message, for: self)
}, error: { (err) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Error!!", comment: ""), message: err.localizedDescription, for: self)
})
}))
present(refreshAlert, animated: true, completion: nil)
}
func changeGroupNameFunc(){
print("ChangeGroupNameButtonClicked")
var parameters = [String:String]()
parameters["admin_id"] = Common.instance.getUserId()
parameters["group_name"] = self.TextFieldGroup.text//self.TextFieldGroupName.text
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
// -- show loading --
HUD.show(to: self.view)
// -- send request --
APIRequestManager.request(apiRequest: APIRouters.ChangeGruopName(parameters, headers), success: { (response) in
HUD.hide(to: self.view)
print("response")
print(response)
self.loadMyGroupList()
if response is [String : String] {
let alert = UIAlertController(title: NSLocalizedString("Success!!",comment: ""), message: "", preferredStyle: .alert)
let done = UIAlertAction(title: NSLocalizedString("Done", comment: ""), style: .default, handler: { (action) in
_ = self.navigationController?.popViewController(animated: true)
// self.TextFieldGroupName.isHidden = true
self.AddGroupButton.isHidden = true
})
alert.addAction(done)
self.present(alert, animated: true, completion: nil)
}
}, failure: { (message) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: message, for: self)
}, error: { (err) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Error!!", comment: ""), message: err.localizedDescription, for: self)
})
}
func AddDriverToGroupFunc() {
let refreshAlert = UIAlertController(title: "Add Driver", message: "Please Confirm!", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
var parameters = [String:Any]()
parameters["admin_id"] = Common.instance.getUserId()
parameters["mobile"] = self.TextFieldGroup.text//self.TextFieldDriverNumber.text
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
// -- show loading --
HUD.show(to: self.view)
// -- send request --
APIRequestManager.request(apiRequest: APIRouters.addUserToGroup(parameters, headers), success: { (response) in
HUD.hide(to: self.view)
if response is [String : Any] {
let alert = UIAlertController(title: NSLocalizedString("success",comment: ""), message: "Driver Added Successfully!"
, preferredStyle: .alert)
let done = UIAlertAction(title: NSLocalizedString("Done", comment: ""), style: .default, handler: { (action) in
_ = self.navigationController?.popViewController(animated: true)
})
alert.addAction(done)
self.present(alert, animated: true, completion: nil)
}
}, failure: { (message) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: message, for: self)
}, error: { (err) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Error!!", comment: ""), message: err.localizedDescription, for: self)
})
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
}))
present(refreshAlert, animated: true, completion: nil)
}
func DeleteDriverFromGroupFunc() {
let refreshAlert = UIAlertController(title: "Delete Driver", message: "Please Confirm!", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
var parameters = [String:Any]()
parameters["mobile"] = self.TextFieldGroup.text//self.TextFieldDriverNumber.text
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
// -- show loading --
HUD.show(to: self.view)
// -- send request --
APIRequestManager.request(apiRequest: APIRouters.delUserFromGroup(parameters, headers), success: { (response) in
HUD.hide(to: self.view)
if response is [String : Any] {
let alert = UIAlertController(title: NSLocalizedString("success",comment: "Driver Deleted Successfully"), message: "", preferredStyle: .alert)
let done = UIAlertAction(title: NSLocalizedString("Done", comment: ""), style: .default, handler: { (action) in
_ = self.navigationController?.popViewController(animated: true)
})
alert.addAction(done)
self.present(alert, animated: true, completion: nil)
}
}, failure: { (message) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: message, for: self)
}, error: { (err) in
HUD.hide(to: self.view)
Common.showAlert(with: NSLocalizedString("Error!!", comment: ""), message: err.localizedDescription, for: self)
})
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
}))
present(refreshAlert, animated: true, completion: nil)
}
func openAlert() -> Bool {
var alertController:UIAlertController?
alertController = UIAlertController(title:
NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "", comment: ""),comment: ""),message: NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "", comment: ""),comment: ""),preferredStyle: .alert)
// pickup point
alertController!.addTextField(
configurationHandler: {(textField: UITextField!) in
self.TextFieldGroup = textField
if self.group_bool == true{
textField.placeholder = NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_GroupName", comment: ""),comment: "")
textField.keyboardType = UIKeyboardType.default
}
else{
textField.placeholder = NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "hint: +9641231231231", comment: ""),comment: "")
textField.keyboardType = .phonePad
}
// textField.placeholder = NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "PickUpPoint", comment: ""),comment: "")
})
let action = UIAlertAction(title: NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "Submit", comment: ""),comment: ""),
style: UIAlertAction.Style.default,
handler: {[weak self]
(paramAction:UIAlertAction!) in
if let textFields = alertController?.textFields{
let theTextFields = textFields as [UITextField]
if theTextFields[0].text!.count == 0{
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: NSLocalizedString("Please fill all the fields.", comment: ""), for: self!)
return
}
else{
if self!.group_indecator_number == 1
{
self!.AddGroupFunc()
}else if self!.group_indecator_number == 2
{
self!.changeGroupNameFunc()
}else if self!.group_indecator_number == 3
{
if self!.validatePhoneNumber(value: theTextFields[0].text!){
print("Validate validatePhoneNumber")
self!.AddDriverToGroupFunc()
}else{
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: NSLocalizedString("invalid_phone_number", comment: ""), for: self!)
print("invalide validatePhoneNumber")
return
}
}else if self!.group_indecator_number == 4
{
if self!.validatePhoneNumber(value: theTextFields[0].text!){
print("Validate validatePhoneNumber")
self!.DeleteDriverFromGroupFunc()
}else{
Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: NSLocalizedString("invalid_phone_number", comment: ""), for: self!)
print("invalide validatePhoneNumber")
return
}
}
}
}
})
let action2 = UIAlertAction(title: NSLocalizedString(LocalizationSystem.sharedInstance.localizedStringForKey(key: "Cancel", comment: ""),comment: ""),
style: UIAlertAction.Style.default,
handler: {[weak self]
(paramAction:UIAlertAction!) in
})
alertController?.addAction(action)
alertController?.addAction(action2)
self.present(alertController!,
animated: true,
completion: nil)
return true
}
func validatePhoneNumber(value: String) -> Bool {
let PHONE_REGEX = "^(\\+)[0-9]{6,14}$";
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
}
extension GroupManagementViewController: UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groups.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "RequestsCell") as! RequestsCell
cell = tableView.dequeueReusableCell(withIdentifier: "RequestsCell") as! RequestsCell
cell.DriverNamelbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_DriverName", comment: "")
cell.DriveMobilelbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_DriverPh", comment: "")
cell.DriverMaillbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_DriverMail", comment: "")
cell.DriverStatuslbl.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "GroupManagementVC_DriverStatus", comment: "")
// -- get current Rides Object --
let currentObj = groups[indexPath.row]
cell.DriverNameVar.text = currentObj.driver_name
cell.DriveMobileVar.text = currentObj.driver_mobile
cell.DriverMailVar.text = currentObj.driver_email
cell.DriverStatusVar.text = currentObj.driver_is_online
if currentObj.driver_is_online == "1"{
cell.DriverStatusVar.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DriverInfoVC_Online", comment: "")
cell.DriverStatusVar.textColor = .green
}
else{
cell.DriverStatusVar.text = LocalizationSystem.sharedInstance.localizedStringForKey(key: "DriverInfoVC_Offline", comment: "")
cell.DriverStatusVar.textColor = .red
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// -- push to detail view with required data --
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DriverInfoViewController") as! DriverInfoViewController
vc.DriverData = ["driver_id": groups[indexPath.row].driverID]
self.navigationController?.pushViewController(vc, animated: true)
}
}
|
import Foundation
@objcMembers public class USAutocompleteLookup: NSObject, Codable {
// In addition to holding all of the input data for this lookup, this class also will contain the result
// of the lookup after it comes back from the API.
//
// See "https://smartystreets.com/docs/cloud/us-autocomplete-api#http-request-input-fields"
//
// prefix: The beginning of an address (required)
// suggestions: Maximum number of suggestions
// cityFilter: List of cities from which to include suggestions
// stateFilter: List of states from which to include suggestions
// prefer: List of cities/states. Suggestions from the members of this list will appear first
// preferRatio: Percentage of suggestions that will be from preferred cities/states.
// (Decimal value between 0 and 1)
// geolocateType: This field corresponds to the geolocate and geolocate precision fields in the
// US Autocomplete API. Use the constants in GeolocateType to set this field
let SSMaxSuggestions = 10
let SSPreferRatio = 1.0 / 3.0
public var result:USAutocompleteResult?
public var prefix:String?
public var maxSuggestions:Int?
public var cityFilter:[String]?
public var stateFilter:[String]?
public var prefer:[String]?
public var geolocateType:GeolocateType?
public var preferRatio:Double?
enum CodingKeys: String, CodingKey {
case maxSuggestions = "max_suggestions"
case cityFilter = "city_filter"
case stateFilter = "state_filter"
case geolocateType = "geolocate_type"
case preferRatio = "prefer_ratio"
}
override public init() {
self.maxSuggestions = SSMaxSuggestions
self.cityFilter = [String]()
self.stateFilter = [String]()
self.prefer = [String]()
self.geolocateType = GeolocateType(name:"city")
self.preferRatio = SSPreferRatio
}
public func withPrefix(prefix:String) -> USAutocompleteLookup {
self.prefix = prefix
return self
}
func getResultAtIndex(index:Int) -> USAutocompleteSuggestion{
if let result = self.result {
return result.suggestions![index]
} else {
return USAutocompleteSuggestion(dictionary: NSDictionary())
}
}
func getMaxSuggestionsStringIfSet() -> String {
if self.maxSuggestions == SSMaxSuggestions {
return String()
} else {
return "\(self.maxSuggestions ?? 0)"
}
}
func getPreferRatioStringIfSet() -> String {
if self.preferRatio == SSPreferRatio {
return String()
} else {
return "\(self.preferRatio ?? 0)"
}
}
public func setMaxSuggestions(maxSuggestions: Int, error: inout NSError?) {
if maxSuggestions > 0 && maxSuggestions <= 10 {
self.maxSuggestions = maxSuggestions
} else {
let details = [NSLocalizedDescriptionKey:"Max suggestions must be a postive integer no larger than 10."]
error = NSError(domain: SmartyErrors().SSErrorDomain, code: SmartyErrors.SSErrors.NotPositiveIntergerError.rawValue, userInfo: details)
}
}
public func addCityFilter(city:String) {
self.cityFilter?.append(city)
}
public func addStateFilter(state:String) {
self.stateFilter?.append(state)
}
public func addPrefer(cityORstate:String) {
self.prefer?.append(cityORstate)
}
}
|
//
// AlbumDetailViewController.swift
// TopAlbums
//
// Created by Shreenath on 05/07/20.
//
import UIKit
class AlbumDetailViewController: UIViewController {
let customBlueColor = UIColor(red: 56/255, green: 125/255, blue: 204/255, alpha: 1)
lazy var largeAlbumArtwork: AsyncDownloadingImageView = {
let img = AsyncDownloadingImageView()
img.image = nil
img.clipsToBounds = true
img.contentMode = .scaleAspectFit
img.addShadow()
img.translatesAutoresizingMaskIntoConstraints = false
return img
}()
lazy var albumTitleLabel: UILabel = {
let lbl = UILabel()
lbl.text = nil
lbl.textColor = .black
lbl.numberOfLines = 0
lbl.textAlignment = .left
lbl.font = UIFont.boldSystemFont(ofSize: 18)
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
lazy var artistNameLabel: UILabel = {
let lbl = UILabel()
lbl.text = nil
lbl.textColor = customBlueColor
lbl.numberOfLines = 0
lbl.textAlignment = .left
lbl.font = UIFont.systemFont(ofSize: 16, weight: .medium)
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
lazy var genereDetailTitleLabel: UILabel = {
let lbl = UILabel()
lbl.text = nil
lbl.textColor = .lightGray
lbl.numberOfLines = 0
lbl.textAlignment = .left
lbl.font = UIFont.systemFont(ofSize: 14, weight: .regular)
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
lazy var copyRightDetailTitleLabel: UILabel = {
let lbl = UILabel()
lbl.text = nil
lbl.textColor = .lightGray
lbl.numberOfLines = 0
lbl.textAlignment = .left
lbl.font = UIFont.systemFont(ofSize: 12, weight: .light)
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
lazy var releaseDateTitle: UILabel = {
let lbl = UILabel()
lbl.text = nil
lbl.textColor = .lightGray
lbl.numberOfLines = 0
lbl.textAlignment = .left
lbl.font = UIFont.systemFont(ofSize: 12, weight: .light)
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
lazy var viewAlbumButton: UIButton = {
let btn = UIButton(type: .custom)
btn.backgroundColor = customBlueColor
btn.setTitle("View Album", for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.layer.cornerRadius = 9
btn.clipsToBounds = true
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
let largeArtworkSize:CGFloat = 200
var albumData:Results?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
dispayData()
}
}
private extension AlbumDetailViewController {
func dispayData() {
guard
let data = albumData,
let strURL = data.artworkUrl100,
let albumTitle = data.name,
let artistName = data.artistName,
let generes = data.genres,
let releaseDate = data.releaseDate,
let copyright = data.copyright
else {return}
largeAlbumArtwork.loadImage(withImageURL: strURL)
albumTitleLabel.text = albumTitle
artistNameLabel.text = artistName
genereDetailTitleLabel.text = generes.map({ (genere) -> String in
guard let name = genere.name else {return ""}
return name
}).joined(separator: ", ")
releaseDateTitle.text = "RELEASED " + releaseDate
copyRightDetailTitleLabel.text = copyright
}
func setupUI() {
view.backgroundColor = .white
view.addSubview(largeAlbumArtwork)
view.addSubview(albumTitleLabel)
view.addSubview(artistNameLabel)
view.addSubview(genereDetailTitleLabel)
view.addSubview(copyRightDetailTitleLabel)
view.addSubview(releaseDateTitle)
view.addSubview(viewAlbumButton)
NSLayoutConstraint.activate([
largeAlbumArtwork.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15),
largeAlbumArtwork.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0),
albumTitleLabel.topAnchor.constraint(equalTo: largeAlbumArtwork.bottomAnchor, constant: 15),
albumTitleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 15),
albumTitleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15),
artistNameLabel.topAnchor.constraint(equalTo: albumTitleLabel.bottomAnchor, constant: 5),
artistNameLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 15),
artistNameLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15),
genereDetailTitleLabel.topAnchor.constraint(equalTo: artistNameLabel.bottomAnchor, constant: 1),
genereDetailTitleLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 15),
genereDetailTitleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15),
releaseDateTitle.topAnchor.constraint(equalTo: genereDetailTitleLabel.bottomAnchor, constant: 8),
releaseDateTitle.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 15),
copyRightDetailTitleLabel.topAnchor.constraint(equalTo: releaseDateTitle.bottomAnchor, constant: 2),
copyRightDetailTitleLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 15),
copyRightDetailTitleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15),
viewAlbumButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
viewAlbumButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor, constant: 0),
viewAlbumButton.heightAnchor.constraint(equalToConstant: 44),
viewAlbumButton.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, constant: -40)
])
viewAlbumButton.addTarget(self, action: #selector(openItunesApp), for: .touchUpInside)
}
@objc func openItunesApp() {
guard let urlStr = albumData?.url, let url = URL(string: urlStr) else {return}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
Alert.showNormalAlertWith(message: "Can not open the url. Please try again")
}
}
}
|
//
// UserProfile.swift
// Aeris
//
// Created by Camilo Rossi on 2018-10-13.
// Copyright © 2018 Camilo Rossi. All rights reserved.
//
import UIKit
import AVFoundation
import Firebase
import FirebaseCoreDiagnostics
class UserProfile: UIViewController, UIImagePickerControllerDelegate
{
@IBOutlet weak var pfp: UIImageView!
@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var followersLabel: UILabel!
@IBOutlet weak var rankLabel: UILabel!
@IBOutlet weak var countryLabel: UILabel!
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
var player: AVPlayer?
let imagePicker = UIImagePickerController()
override var preferredStatusBarStyle: UIStatusBarStyle
{
return .lightContent
}
override func viewDidLoad()
{
super.viewDidLoad()
imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
/*
let videoURL: NSURL = Bundle.main.url(forResource: "BackgroundVid", withExtension: "mp4")! as NSURL
player = AVPlayer(url: videoURL as URL)
player?.actionAtItemEnd = .none
player?.isMuted = true
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer.zPosition = -1
playerLayer.frame = view.frame
view.layer.addSublayer(playerLayer)
//player?.play()
*/
}
override func viewDidAppear(_ animated: Bool)
{
getDocument()
NotificationCenter.default.addObserver(self, selector: #selector(UserProfile.finishBackgroundVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
@IBAction func backToMenu(_ sender: Any)
{
performSegue(withIdentifier: "backToHome", sender: self)
}
func RankPlayers(followers: Int)
{
}
private func getDocument()
{
//Get specific document from current user
let docRef = Firestore.firestore().collection("users").whereField("uid", isEqualTo: Auth.auth().currentUser?.uid ?? "")
// Get data
docRef.getDocuments
{
(querySnapshot, err) in
if let err = err
{
print(err.localizedDescription)
return
}
else
if querySnapshot!.documents.count != 1
{
print("More than one documents or none")
}
else
{
for document in querySnapshot!.documents
{
let username = document.get("username") as! String
let firstAndLastName = document.get("firstandlastname") as! String
let email = document.get("email") as! String
let followers = document.get("currentFollowers") as! Int
let country = document.get("country") as! String
self.usernameLabel.text = "@\(username)"
self.nameLabel.text = "\(firstAndLastName)"
self.emailLabel.text = "\(email)"
let kFollowers: Double = Double(followers)
let roundedKFollower = kFollowers.kmFormatted
let mFollowers: Double = Double(followers)
let roundedMFollower = mFollowers.kmFormatted
self.RankPlayers(followers: followers)
if followers > 1
{
self.followersLabel.text = "\(followers) FOLLOWERS"
}
else
{
self.followersLabel.text = "\(followers) FOLLOWER"
}
if followers > 9999
{
self.followersLabel.text = "\(roundedKFollower) FOLLOWERS"
}
if followers >= 999999
{
self.followersLabel.text = "\(roundedMFollower) FOLLOWERS"
}
self.countryLabel.text = "\(country)"
}
}
}
}
@IBAction func searchForUserTapped(_ sender: Any)
{
performSegue(withIdentifier: "fromUserToSearchUser", sender: self)
}
@objc func finishBackgroundVideo(notification: NSNotification)
{
if let playerItem = notification.object as? AVPlayerItem
{
playerItem.seek(to: CMTime.zero, completionHandler: nil)
}
}
}
extension Double
{
var kmFormatted: String
{
if self >= 10000, self <= 999999
{
return String(format: "%.1fK", locale: Locale.current,self/1000).replacingOccurrences(of: ".0", with: "")
}
if self >= 999999
{
return String(format: "%.1fM", locale: Locale.current,self/1000000).replacingOccurrences(of: ".0", with: "")
}
return String(format: "%.0f", locale: Locale.current,self)
}
}
|
/*:
[Previous](@previous) | [Next](@next)
****
Copyright (c) 2016 Juan Antonio Karmy.
Licensed under MIT License
Official Apple documentation available at [Swift Language Reference](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/)
See Juan Antonio Karmy - [karmy.co](http://karmy.co) | [@jkarmy](http://twitter.com/jkarmy)
****
*/
/*:
# Collection Types
*/
import UIKit
/*:
Arrays and dictionaries in swift use generics and can be mutable or immutable
depending on whether they are assigned to a var or let
Structs are VALUE types, which means that when working with mutating functions, you'll need to store them in "var".
Everytime the struct is "mutated", a new struct will be created and stored in that var.
*/
//: ## Arrays
var shoppingList: [String] = ["Eggs", "Pigs"]
var anotherShoppingList = ["Eggs", "Pigs"] //Both are the same
if shoppingList.isEmpty { //Checks if count == 0
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
shoppingList.append("Cow") //At the end of the array
shoppingList += ["Bird", "Shark"]
shoppingList[1...3] = ["Bananas", "Apples", "Strawberries"] //Replace several items at once
shoppingList.insert("Maple Syrup", at: 0) //Inserts element at index
let mapleSyrup = shoppingList.remove(at: 0) // Returns removed item
var emptyArray = [Int]() //Initialize empty array, type of elements must be provided
var anotherEmptyArray: [Int] = [] // Also valid
var someArray = ["Hello", "World"]
someArray = [] // This is valid when the context already provides type information
var array = [Int](repeating: 0, count: 3) //Initalizes an array of length 3 with zeros
var compoundArray = array + emptyArray
var reversedShoppingList: [String] = shoppingList.reversed()
reversedShoppingList.removeLast() // Removes last item. Remove the first with removeFirst(). No returned value.
reversedShoppingList.popLast() // Pops the last item, removing it from the array and also returning it. Note that if the array is empty, the returned value is nil.
//: ## Sets
//: The items in Set must comform to Hashable and Equatable protocol
struct MyStruct {
let i: Int
}
extension MyStruct: Hashable { // Hashable
public var hashValue: Int { get {return i} }
}
extension MyStruct: Equatable { // Equatable
public static func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
return lhs.i == rhs.i
}
}
var set: Set<MyStruct> = [ MyStruct(i: 1), MyStruct(i: 2) ]
set.insert(MyStruct(i: 3))
set.insert(MyStruct(i: 3))
print("----")
for item in set {
print(item)
}
print("---sorted---")
for item in set.sorted(by: { $0.i < $1.i }) {
print(item)
}
//: ### intersection & subtracting & union
let s0 = Set(0...10)
let s1 = Set(2..<3)
let ss0 = s0.intersection(s1) // 交集
let ss1 = s0.subtracting(s1) // s0中的元素不在s1中出现
let s2 = Set(12..<13)
let ss2 = s0.union(s2) // 并集
//: ## Dictionaries
var airports: [String: String] = ["Key1": "Value1", "Key2": "Value2"]
airports["Key3"] = "Value3"
//: updateValue return the old value. If old doesn't exist, return nil
if let oldValue = airports.updateValue("Key4", forKey:"Value4") {
print("Old value is \(oldValue)")
}
print(airports)
//: Set value to nil, will remove this (key, value)
airports["Key1"] = nil // (key1, value1) was removed!
print("====\(airports)")
airports.removeValue(forKey: "Key2") // Also
print("====\(airports)")
//: Iterating a dictionary
//Iterating over the whole dictionary
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
//Iterating on Keys
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
//Iterating on Values
for airportName in airports.values {
print("Airport name: \(airportName)")
}
//: ### NOTE
/*:
You can use your own custom types as dictionary key types by making
them conform to the Hashable protocol from Swift’s standard library.
Types that conform to the Hashable protocol must provide a
gettable Int property called hashValue, and must also provide an
implementation of the “is equal” operator (==). The value returned by a
type’s hashValue property is not required to be the same across different
executions of the same program, or in different programs.
All of Swift’s basic types (such as **String**, **Int**, **Double**, and **Bool**) are hashable by default
*/
|
//
// CourseCollectionViewCell.swift
// VirtualCourses
//
// Created by Emanuel Flores Martínez on 11/04/21.
//
import UIKit
class CourseCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var courseImageView: UIImageView!
@IBOutlet weak var backgroundColorView: UIView!
@IBOutlet weak var courseNameLabel: UILabel!
@IBOutlet weak var scheduleLabel: UILabel!
var course: Course! {
didSet {
self.updateUI()
}
}
func updateUI() {
if let course = course {
courseImageView.image = course.imageCourse
courseNameLabel.text = course.courseName
scheduleLabel.text = course.schedule
backgroundColorView.backgroundColor = UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8)
} else {
courseImageView = nil
courseNameLabel.text = nil
scheduleLabel.text = nil
backgroundColorView.backgroundColor = nil
}
backgroundColorView.layer.cornerRadius = 10.0
backgroundColorView.layer.masksToBounds = true
courseImageView.layer.cornerRadius = 10.0
courseImageView.layer.masksToBounds = true
}
}
|
//
// PersonViewController.swift
// SDS-iOS-APP
//
// Created by 石川諒 on 2018/01/31.
// Copyright © 2018年 石川諒. All rights reserved.
//
import UIKit
import AVFoundation
import ProjectOxfordFace
import SVProgressHUD
class PersonViewController: UITableViewController, SDSViewControllerType, FaceManagerViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var alertView = SDSAlertView()
var personGroupId: String!
var person: MPOPerson!
var persistedFaceIds: [String] = []
var isChangePersonFace = false
override func viewDidLoad() {
super.viewDidLoad()
setPersistedFaceIds(ids: person.persistedFaceIds)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
guard isChangePersonFace else {
return
}
faceAPIClient.trainPersonGroup(withPersonGroupId: personGroupId) { error in
if let error = error {
self.showErrorAlert(title: "エラー", message: error.localizedDescription, handler: nil)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "ShowFaceManageView",
let childViewController = segue.destination as? FaceManageViewController else {
return
}
childViewController.delegate = self
childViewController.userData = person.userData
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mangePersistedFaceId() {
tableView.setEditing(!tableView.isEditing, animated: true)
}
func startUIImagePicker() {
let cameraPicker = UIImagePickerController()
cameraPicker.sourceType = UIImagePickerControllerSourceType.camera
cameraPicker.cameraDevice = UIImagePickerControllerCameraDevice.front
cameraPicker.delegate = self
self.present(cameraPicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var userData: String? = nil
if let pickedImage = info[UIImagePickerControllerOriginalImage]
as? UIImage {
let jpeg = UIImageJPEGRepresentation(pickedImage, 0.5)
guard let data = jpeg else {
showErrorAlert(title: "エラー", message: "撮影に失敗しました。", handler: nil)
return
}
let alert = alertView.oneTextFieldAlert(
title: "userDataの入力",
message: "userDataを入力してください。(任意)") {
(_, text) in
userData = text
self.addPersonFace(data: data, userData: userData)
SVProgressHUD.show(withStatus: "追加中")
}
picker.dismiss(animated: true, completion: nil)
self.present(alert, animated: true, completion: nil)
}
}
func addButtonTapped() {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
var errorMessage:String? = nil
switch status {
case .authorized:
// アクセス許可あり
startUIImagePicker()
case .notDetermined:
// まだアクセス許可を聞いていない
// カメラが利用可能かチェック
if !UIImagePickerController.isSourceTypeAvailable(
UIImagePickerControllerSourceType.camera) {
errorMessage = "カメラが起動できませんでした。"
} else {
startUIImagePicker()
}
case .restricted:
// ユーザー自身にカメラへのアクセスが許可されていない
errorMessage = "カメラを使用する許可がありません。"
case .denied:
// アクセス許可されていない
errorMessage = "許可がありません。カメラ使うには、設定よりカメラへのアクセスを許可してください。"
}
if let message = errorMessage {
showErrorAlert(title: "エラー", message: message, handler: nil)
}
}
func addPersonFace(data: Data, userData: String?) {
faceAPIClient.addPersonFace(
withPersonGroupId: personGroupId,
personId: person.personId,
data: data,
userData: userData,
faceRectangle: nil) { (result, error) in
if let error = error {
SVProgressHUD.dismiss()
self.showErrorAlert(
title: "エラー",
message: error.localizedDescription,
handler: nil
)
return
}
guard let id = result?.persistedFaceId else {
SVProgressHUD.dismiss()
self.showErrorAlert(title: "エラー", message: "顔を検出できませんでした。", handler: nil)
return
}
self.isChangePersonFace = true
self.persistedFaceIds.append(id)
self.tableView.reloadData()
SVProgressHUD.dismiss()
}
}
func setPersistedFaceIds(ids: [Any]) {
persistedFaceIds = ids.map({ any -> String? in
guard let id = any as? String else {
return nil
}
return id
}).flatMap({ (id) -> String? in
id
})
}
func deletePerson() {
SVProgressHUD.show(withStatus: "削除中")
faceAPIClient.deletePerson(
withPersonGroupId: personGroupId,
personId: person.personId) { error in
if let error = error {
SVProgressHUD.dismiss()
self.showErrorAlert(
title: "エラー",
message: error.localizedDescription,
handler: nil
)
return
}
SVProgressHUD.dismiss()
self.navigationController?.popViewController(animated: true)
}
}
func deletePersistedFaceid(id: String) {
SVProgressHUD.show(withStatus: "削除中")
faceAPIClient.deletePersonFace(
withPersonGroupId: personGroupId,
personId: person.personId,
persistedFaceId: id) { error in
SVProgressHUD.dismiss()
if let error = error {
self.showErrorAlert(
title: "エラー",
message: error.localizedDescription,
handler: nil
)
return
}
SVProgressHUD.dismiss()
}
}
@IBAction func deleteButtonTapped(_ sender: Any) {
let deleteAlert = alertView.deleteAlert(
title: "ユーザーの削除",
message: "\(person.name)を削除しますか?\n登録済みの顔情報も失われます。") { _ in
self.deletePerson()
}
present(deleteAlert, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return persistedFaceIds.count == 0 ? 1 : persistedFaceIds.count
} else {
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell?
switch indexPath.section {
case 0:
cell = tableView.dequeueReusableCell(withIdentifier: "PersistedFaceIdCell")
guard persistedFaceIds.count != 0 else {
cell?.textLabel?.text = "なし"
break
}
cell?.textLabel?.text = persistedFaceIds[indexPath.row]
case 1:
cell = tableView.dequeueReusableCell(withIdentifier: "DeleteCell")
default:
cell = nil
}
if let reuseCell = cell {
return reuseCell
} else {
return UITableViewCell()
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "persistedFaceId"
case 1:
return "削除"
default:
return nil
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 0, persistedFaceIds.count > 0 {
return true
} else {
return false
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == UITableViewCellEditingStyle.delete else {
return
}
let id = persistedFaceIds[indexPath.row]
let deleteAlert = alertView.deleteAlert(
title: "顔情報の削除",
message: "登録した顔情報、\(id)は、削除されます。") { _ in
self.deletePersistedFaceid(id: id)
self.persistedFaceIds.remove(at: indexPath.row)
self.tableView.reloadData()
if self.persistedFaceIds.count == 0 {
self.tableView.setEditing(false, animated: true)
}
}
present(deleteAlert, animated: true, completion: nil)
}
}
|
func calcularIMC(peso: Double, altura: Double)-> Double{
let icm=peso/(altura*altura)
return icm
}
var a=calcularIMC(peso:20.2,altura:1.2)
var b=calcularIMC(peso:50.2,altura:1.6)
print(a)
print(b) |
//
// TeleCartViewDelegate.swift
// TeleChart
//
// Created by Alex Sklyarenko on 3/11/19.
// Copyright © 2019 Alex Sklyarenko. All rights reserved.
//
import Foundation
public protocol TeleChartViewDelegate: class {
}
|
//
// LibraryPageViewController.swift
// Anghami-Playlists-Reimagined
//
// Created by Omar Khodr on 7/27/20.
// Copyright © 2020 Omar Khodr. All rights reserved.
//
import UIKit
class LibraryPageViewController: UIPageViewController {
var lists = [
"https://bus.anghami.com/public/user/playlists",
"https://bus.anghami.com/public/user/albums",
"https://bus.anghami.com/public/user/artists"
]
var savedVCs = [MusicViewController?](repeating: nil, count: 3)
var currentIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
currentIndex = 0
if let viewController = viewMusicController(currentIndex) {
let viewControllers = [viewController]
// 2
setViewControllers(viewControllers,
direction: .forward,
animated: false,
completion: nil)
dataSource = self
}
}
func viewMusicController(_ index: Int) -> MusicViewController? {
if let saved = savedVCs[index] {
return saved
} else {
guard
let storyboard = storyboard,
let page = storyboard
.instantiateViewController(withIdentifier: "MusicViewController")
as? MusicViewController
else {
return nil
}
page.requestURL = lists[index]
page.listIndex = index
savedVCs[index] = page
return page
}
}
}
extension LibraryPageViewController: UIPageViewControllerDataSource {
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController)
-> UIViewController? {
if let viewController = viewController as? MusicViewController,
let index = viewController.listIndex,
index > 0 {
currentIndex = index-1
return viewMusicController(index - 1)
}
return nil
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController)
-> UIViewController? {
if let viewController = viewController as? MusicViewController,
let index = viewController.listIndex,
(index + 1) < lists.count {
currentIndex = index+1
return viewMusicController(index + 1)
}
return nil
}
}
|
//
// CircleView.swift
// Tourney
//
// Created by German Espitia on 12/12/19.
// Copyright © 2019 Will Cohen. All rights reserved.
//
import UIKit
/**
Class to draw a circle view.
*/
class CircleView: UIView {
override func awakeFromNib() {
layer.cornerRadius = frame.width / 2
}
}
|
//
// Status.swift
// TrocoSimples
//
// Created by gustavo r meyer on 7/9/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import UIKit
/**
Message Status
*/
public class Status {
// MARK: - Constants
internal struct Keys {
static let id = "id"
static let groupId = "groupId"
static let groupName = "groupName"
static let name = "name"
}
// MARK: - Intance Properties
public var id: Int
public var groupId: Int
public var groupName: String
public var name: String
// MARK: - Object Lifecycle
public convenience init?(jsonData data: Data) {
guard let jsonObject = try? JSONSerialization.jsonObject(with: data),
let dictionary = jsonObject as? [AnyHashable: Any] else {
return nil
}
self.init(dictionary: dictionary)
}
public required init?(dictionary: [AnyHashable: Any]) {
guard let id = dictionary[Keys.id] as? Int,
let groupId = dictionary[Keys.groupId] as? Int,
let groupName = dictionary[Keys.groupName] as? String,
let name = dictionary[Keys.name] as? String
else {
return nil
}
self.id = id
self.groupId = groupId
self.groupName = groupName
self.name = name
}
}
|
//
// FriendsTableViewController.swift
// TheDocument
//
import UIKit
import Firebase
class FriendsTableViewController: BaseTableViewController {
fileprivate var filteredFriends = [TDUser]()
fileprivate var sections = [String]()
var selectedIndexpath: IndexPath? = nil
var friends: Array<TDUser> = []
var friendsRef: DatabaseReference!
let kSectionSearchResults = 0
let kSectionInvites = 1
let kSectionCurrent = 2
@IBOutlet weak var searchBarContainer: UIView!
lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = true
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.delegate = self
return searchController
}()
override func viewDidLoad() {
super.viewDidLoad()
// Set the Firebase reference
friendsRef = Database.database().reference().child("friends").child(currentUser.uid)
self.navigationController?.navigationBar.shadowImage = Constants.Theme.mainColor.as1ptImage()
self.navigationController?.navigationBar.setBackgroundImage(Constants.Theme.mainColor.as1ptImage(), for: .default)
let searchBar = searchController.searchBar
searchBar.autocapitalizationType = .none
searchBar.autocorrectionType = .no
searchBar.spellCheckingType = .no
searchBar.autoresizingMask = [.flexibleWidth, .flexibleHeight]
searchBarContainer.addSubview(searchBar)
searchBar.sizeToFit()
definesPresentationContext = true
searchController.searchBar.barTintColor = Constants.Theme.mainColor
searchController.searchBar.tintColor = Constants.Theme.mainColor
for subView in searchController.searchBar.subviews {
for searchBarSubView in subView.subviews {
if let textField = searchBarSubView as? UITextField {
textField.font = UIFont(name: "OpenSans", size: 15.0)
}
}
}
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(FriendsTableViewController.refreshFriends), for: .valueChanged)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "\(UserEvents.showToolbar)"), object: nil)
friends.removeAll()
friendsRef.observe(.childAdded, with: { (snapshot) -> Void in
if let friendData = snapshot.value as? [String: Any] {
var friendDataUpdated = friendData
friendDataUpdated["uid"] = snapshot.key as AnyObject
if let friend: TDUser = API().friendFromJSON(friendDataUpdated) {
self.friends.append(friend)
self.friends.alphaSort()
self.refresh()
}
}
})
friendsRef.observe(.childRemoved, with: { (snapshot) -> Void in
if let index = self.indexOfMessage(snapshot) {
self.friends.remove(at: index)
self.refresh()
}
})
friendsRef.observe(.childChanged, with: { (snapshot) -> Void in
if let index = self.indexOfMessage(snapshot), let friendData = snapshot.value as? [String: Any] {
var friendDataUpdated = friendData
friendDataUpdated["uid"] = snapshot.key as AnyObject
if let friend: TDUser = API().friendFromJSON(friendDataUpdated) {
self.friends[index] = friend
self.refresh()
}
}
})
currentUser.getFriends() {
self.refresh()
}
}
override func viewWillDisappear(_ animated: Bool) {
friendsRef.removeAllObservers()
}
func indexOfMessage(_ snapshot: DataSnapshot) -> Int? {
var index = 0
for friend in self.friends {
if snapshot.key == friend.uid {
return index
}
index += 1
}
return nil
}
func loadDiscoverFriends() {
DispatchQueue.main.async {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "discover_friends_nvc") as? UINavigationController {
self.present(viewController, animated: true, completion: nil)
}
}
}
@IBAction func discoverFriendsIconPressed(_ sender: Any) {
self.loadDiscoverFriends()
}
//MARK: BaseTableVC
override func rowsCount() -> Int { return currentUser.friends.count }
override func emptyViewAction() { self.loadDiscoverFriends() }
}
//MARK: IBActions
extension FriendsTableViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? FriendDetailsViewController, let indexPath = selectedIndexpath {
let friend = friends.filter{ $0.accepted == 0 }[indexPath.row]
dest.friend = friend
} else if segue.identifier == "show_friend_user_profile", let profileVC = segue.destination as? HeadToHeadViewController, let friend = sender as? TDUser {
profileVC.playerTwo = friend
}
}
}
//MARK: UITableView delegate & datasource
extension FriendsTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case kSectionSearchResults where searchController.isActive:
return filteredFriends.count
case kSectionCurrent where !searchController.isActive:
return friends.filter{ $0.accepted == 1 }.count
case kSectionInvites where !searchController.isActive:
return friends.filter{ $0.accepted == 0 }.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemTableViewCell") as! ItemTableViewCell
var item: TDUser
switch indexPath.section {
case kSectionSearchResults:
item = filteredFriends[indexPath.row]
case kSectionCurrent:
item = friends.filter{ $0.accepted == 1 }[indexPath.row]
case kSectionInvites:
item = friends.filter{ $0.accepted == 0 }[indexPath.row]
default:
item = TDUser.empty()
}
var friend = item
if let friendIndex = friends.index(where: { $0.uid == item.uid }) {
friend = friends[friendIndex]
}
cell.setup(friend)
setImage(id: friend.uid, forCell: cell)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedIndexpath = indexPath
switch indexPath.section {
case kSectionSearchResults:
let friend = filteredFriends[indexPath.row]
performSegue(withIdentifier: "show_friend_user_profile", sender: friend)
case kSectionCurrent:
let friend = friends.filter{ $0.accepted == 1 }[indexPath.row]
performSegue(withIdentifier: "show_friend_user_profile", sender: friend)
case kSectionInvites:
let friend = friends.filter{ $0.accepted == 0 }[indexPath.row]
performSegue(withIdentifier: "show_friend_details", sender: friend)
default:
return
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (section > 0 && searchController.isActive) { return nil }
switch section {
case kSectionSearchResults where searchController.isActive,
kSectionCurrent where !friends.isEmpty:
return "FRIENDS"
case kSectionInvites where !friends.filter{ $0.accepted == 0 }.isEmpty:
return "INVITES"
default:
return nil
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
var item: TDUser
switch indexPath.section {
case kSectionSearchResults:
item = filteredFriends[indexPath.row]
case kSectionCurrent:
item = friends.filter{ $0.accepted == 1 }[indexPath.row]
case kSectionInvites:
item = friends.filter{ $0.accepted == 0 }[indexPath.row]
default:
item = TDUser.empty()
}
if !item.isEmpty {
API().endFriendship(with: item.uid){[weak self] in
_ = self?.perform(#selector(FriendsTableViewController.refreshFriends))
}
}
}
}
func startChallenge(withFriend friend: TDUser) {
if let newChallengeNavVC = self.storyboard?.instantiateViewController(withIdentifier: "NewChallengeNavVC") as? UINavigationController, let newChallengeVC = newChallengeNavVC.viewControllers.first as? NewChallengeViewController {
newChallengeVC.toId = friend.uid
self.present(newChallengeNavVC, animated: true, completion: nil)
}
}
}
//MARK: IO
extension FriendsTableViewController {
@objc func refreshFriends() {
self.refreshControl?.endRefreshing()
currentUser.getFriends() {
self.refresh()
}
}
}
//MARK: Searching
extension FriendsTableViewController: UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {
func updateSearchResults(for searchController: UISearchController) {
guard let searchTerm = searchController.searchBar.text else { return }
self.filterData(searchTerm)
}
func filterData( _ searchTerm: String) -> Void {
guard searchTerm.count > 1 else { filteredFriends = friends; refresh(); return }
filteredFriends = friends.filter { friend -> Bool in
return friend.name.lowercased().contains(searchTerm.lowercased())
}
refresh()
}
func didDismissSearchController (_ searchController: UISearchController) {
refresh()
}
}
|
//
// UILabel+Extensions.swift
// Jenin Residences
//
// Created by Ahmed Khalaf on 8/5/17.
// Copyright © 2017 pxlshpr. All rights reserved.
//
import UIKit
extension UILabel {
override class func layoutable() -> UILabel {
let view = UILabel()
// view.backgroundColor = UIColor.getRandomColor()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
}
|
//
// AsteroidsModels.swift
// TestApp
//
// Created by Михаил Красильник on 12.05.2021.
//
import Foundation
enum Asteroids: Hashable {
enum FetchData: Hashable {
struct Request {
}
struct Response {
let asteroids: [NearEarthObject]
}
struct ViewModel: Hashable {
struct Object: Hashable {
let asteroidName: String
let date: String
let relativeVelocity: String
let diameter: String
let url: String
}
var objects: [Object]
}
}
enum SendURL: Hashable {
struct Request {
let url: String
}
struct Response {
}
struct ViewModel: Hashable {
}
}
}
|
//
// HomeVM.swift
// MyLoqta
//
// Created by Ashish Chauhan on 09/07/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import Foundation
import UIKit
import ObjectMapper
typealias HomeFeedType = (cellType: Int , height: CGFloat)
protocol HomeVModeling: class {
func getHomeFeedDetails(page: Int, isShowLoader: Bool, completion: @escaping (HomeFeed) ->Void)
func getDatasourceForHomeFeed(homeFeedData: HomeFeed, page: Int, previousDataSource: [[HomeFeedType]]) -> [[HomeFeedType]]
func requestLikeProduct(param: [String: AnyObject], completion: @escaping (_ success: Bool, _ isDelete: Bool, _ message: String) ->Void)
func requestReportProduct(param: [String: AnyObject], completion: @escaping (Bool) ->Void)
}
class HomeVM: BaseModeling, HomeVModeling {
func getDatasourceForHomeFeed(homeFeedData: HomeFeed, page: Int, previousDataSource: [[HomeFeedType]]) -> [[HomeFeedType]] {
var arrayDataSource = previousDataSource
let feedFirstCell = HomeFeedType(HomeFeedsCell.firstFeedCell.rawValue, 491.0)
let forYouCell = HomeFeedType(HomeFeedsCell.forYouCell.rawValue, 351.0)
let secondFeedCell = HomeFeedType(HomeFeedsCell.secondFeedCell.rawValue, 491.0)
let categoryCell = HomeFeedType(HomeFeedsCell.categoryCell.rawValue, 335)
let lastFeedCell = HomeFeedType(HomeFeedsCell.lastFeedCell.rawValue, 491.0)
//FirstFeed
if let arrFirstFeed = homeFeedData.feedFirst, arrFirstFeed.count > 0, page == 1 {
var firstFeedDataSource = [HomeFeedType]()
for _ in arrFirstFeed {
firstFeedDataSource.append(contentsOf: [feedFirstCell])
}
arrayDataSource.append(firstFeedDataSource)
}
//ForYou
if let forYouData = homeFeedData.forYou, forYouData.count > 0, page == 1 {
var forYouDataSource = [HomeFeedType]()
forYouDataSource.append(contentsOf: [forYouCell])
arrayDataSource.append(forYouDataSource)
}
//SecondFeed
if let arrSecondFeed = homeFeedData.feedSecond, arrSecondFeed.count > 0, page == 1 {
var secondFeedDataSource = [HomeFeedType]()
for _ in arrSecondFeed {
secondFeedDataSource.append(contentsOf: [secondFeedCell])
}
arrayDataSource.append(secondFeedDataSource)
}
//Category
if let category = homeFeedData.category, let _ = category.name, page == 1 {
var categoryDataSource = [HomeFeedType]()
categoryDataSource.append(contentsOf: [categoryCell])
arrayDataSource.append(categoryDataSource)
}
//LastFeed
if let arrLastFeed = homeFeedData.feedLast, arrLastFeed.count > 0 {
var lastFeedDataSource = [HomeFeedType]()
for _ in arrLastFeed {
lastFeedDataSource.append(contentsOf: [lastFeedCell])
}
if page > 2 {
let lastIndex = arrayDataSource.count - 1
arrayDataSource[lastIndex] = arrayDataSource[lastIndex] + lastFeedDataSource
} else {
arrayDataSource.append(lastFeedDataSource)
}
}
return arrayDataSource
}
func getHomeFeedDetails(page: Int, isShowLoader: Bool, completion: @escaping (HomeFeed) ->Void) {
let param: [String: AnyObject] = ["page": page as AnyObject]
self.apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .homeFeed(param: param, isShowLoader: isShowLoader)), completionHandler: { (response, success) in
print(response)
if success, let result = response as? [String: Any] {
if let homeFeedData = Mapper<HomeFeed>().map(JSON:result) {
completion(homeFeedData)
}
}
})
}
func requestLikeProduct(param: [String: AnyObject], completion: @escaping (_ success: Bool, _ isDelete: Bool, _ message: String) ->Void) {
self.apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .likeProduct(param: param)), completionHandler: { (response, success) in
print(response)
if success {
//print(result)
completion(success, false, "")
} else if let dataObject = response as? [String: AnyObject] , let errorCode = dataObject["Status"] as? Int, errorCode == 302, let message = dataObject["Message"] as? String {
completion(false, true, message)
}
})
}
func requestReportProduct(param: [String: AnyObject], completion: @escaping (Bool) ->Void) {
self.apiManagerInstance()?.request(apiRouter: APIRouter.init(endpoint: .reportProduct(param: param)), completionHandler: { (response, success) in
print(response)
if success, let result = response as? [String: Any] {
print(result)
completion(success)
}
})
}
}
|
//
// PolylineRenderer.swift
// MapboxSceneKit
//
// Created by Jim Martin on 9/12/18.
// Copyright © 2018 MapBox. All rights reserved.
//
import Foundation
import SceneKit
import Metal
/// Implement this protocol to define new line rendering behavior
internal protocol PolylineRenderer {
func render(_ polyline: PolylineNode, withSampleCount sampleCount: Int)
}
/// Responsible for selecting the correct renderer based on iOS version or GPU context.
internal class PolylineRendererVersion {
/// Change linerenderer class based on the ios version / metal availability
///
/// - Returns: The best linerenderer for the current platform
public static func getValidRenderer() -> PolylineRenderer {
//first, check if a metal rendering context is available
let device = MTLCreateSystemDefaultDevice()
if device == nil {
// No metal rendering context available, fallback to cylinder polylines
return PolylineCylinder()
}
//then, check if the ios version can support framework shaders
if #available(iOS 10.0, *) {
return PolylineShader()
} else {
return PolylineCylinder()
}
}
}
|
//
// CameraHelper.swift
// Contech
//
// Created by Lauren Shultz on 8/16/18.
// Copyright © 2018 Lauren Shultz. All rights reserved.
//
import Foundation
import UIKit
class CameraHelper {
var currentImage = UIImage()
var currentImageSize = 0
var currentImageData: Data!
var imageDisplayer: UIImageView = UIImageView()
var vc: ViewController!
init (vc: ViewController) {
self.vc = vc
}
/*
* FUNCTION: addImage
* PURPOSE: Appends an image from either the camera or gallery to the current new issue
*/
func addImage()
{
CameraHandler.shared.showActionSheet(vc: vc)
CameraHandler.shared.imagePickedBlock = { (image) in
self.currentImage = image
// self.issueImage.isHidden = false
self.openEditor()
}
}
/*
* FUNCTION: openEditor
* PURPOSE: Opens a screen with the current image displayed and access to editing tools
*/
func openEditor()
{
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "imageEditor") as! ImageEditorViewController
popOverVC.currentImage = currentImage
vc.addChildViewController(popOverVC)
vc.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: vc)
popOverVC.onEditorClosed = onEditorClosed
}
func callOpenEditor(imageDisplayer: UIImageView)
{
self.imageDisplayer = imageDisplayer
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "imageEditor") as! ImageEditorViewController
popOverVC.currentImage = self.currentImage
vc.addChildViewController(popOverVC)
vc.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: vc)
popOverVC.onEditorClosed = onEditorClosed
}
/*
* FUNCTION: onEditorClosed
* PURPOSE: Callback function called when image editor closed that updates the current image to the edited image
*/
func onEditorClosed(_ image: UIImage)
{
currentImage = image
currentImageSize = (UIImagePNGRepresentation(currentImage)?.count)!
// size.text = String(describing: currentImageSize)
imageDisplayer.image = image
}
}
|
import XCTest
import SwiftCheck
import BowLaws
import Bow
extension TrampolinePartial: EquatableK {
public static func eq<A>(_ lhs: TrampolineOf<A>, _ rhs: TrampolineOf<A>) -> Bool where A : Equatable {
lhs^.run() == rhs^.run()
}
}
class TrampolineTest: XCTestCase {
func testFunctorLaws() {
FunctorLaws<TrampolinePartial>.check()
}
func testApplicativeLaws() {
ApplicativeLaws<TrampolinePartial>.check()
}
func testSelectiveLaws() {
SelectiveLaws<TrampolinePartial>.check()
}
func testMonadLaws() {
MonadLaws<TrampolinePartial>.check()
}
func testDoesNotCrashStack() {
XCTAssert(isEven(200000))
}
func isEven(_ n: Int) -> Bool {
_isEven(n).run()
}
func _isEven(_ n: Int) -> Trampoline<Bool> {
if n == 0 {
return .done(true)
} else if n == 1 {
return .done(false)
} else {
return .defer { self._isOdd(n - 1) }
}
}
func _isOdd(_ n: Int) -> Trampoline<Bool> {
if n == 0 {
return .done(false)
} else if n == 1 {
return .done(true)
} else {
return .defer { self._isEven(n - 1) }
}
}
}
|
//
// NewsAPI.swift
// Top News
//
// Created by Egor on 06.08.17.
// Copyright © 2017 Egor. All rights reserved.
//
import Foundation
import SwiftyJSON
import Alamofire
class NewsAPI{
//static let sharedInstance = NewsAPI()
class func getNews(stringUrl: String, newsArray: @escaping ([Article]?) -> Void){
Alamofire.request(stringUrl).responseJSON { (fetchedJson) in
if let jsonData = fetchedJson.data{
let json = JSON(data: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers , error: nil)
if let articlesJsonArray = json["articles"].array{
for artJson in articlesJsonArray{
let newArticle = Article(json: artJson)
DispatchQueue.main.async {
newsArray([newArticle])
}
}
}
}
}
}
}
|
//
// ShadowView.swift
// HelloDrawRect
//
// Created by 默司 on 2016/8/16.
// Copyright © 2016年 默司. All rights reserved.
//
import UIKit
@IBDesignable
public class GUShadowView: UIView {
public var shadowColor: UIColor! = UIColor.blackColor()
public var shadowOffset: CGSize! = CGSizeMake(0.0, 1.0)
public var shadowOffsetY: NSNumber! = 1.0
public var shadowRadius: NSNumber! = 1.5
public var shadowOpacity: NSNumber! = 0.12
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override public func drawRect(rect: CGRect) {
// Drawing code
self.layer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: self.layer.cornerRadius).CGPath
self.layer.shadowOpacity = shadowOpacity.floatValue
self.layer.shadowRadius = CGFloat(shadowRadius.floatValue)
self.layer.shadowColor = shadowColor.CGColor
self.layer.shadowOffset = shadowOffset
}
}
|
//
// SearchForProductViewModel.swift
// PTC_IOS_TEST
//
// Created by gody on 9/17/21.
// Copyright © 2021 Jumia. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class SearchForProductViewModel {
public let searhBarText : PublishSubject<String> = PublishSubject()
var coordinator: SearchForProductCoordinator?
func navigateToProductsVC(withSearchKey key: String ){
coordinator?.navigateToProductsVC(withSearchKey:key)
}
}
|
//
// FunctionExtractor.swift
// Basic
//
// Created by Rob Saunders on 20/04/2019.
//
import SwiftSyntax
struct FunctionExtract {
var functionName: String?
}
class RouteExtractor : SyntaxVisitor {
var method: String? = nil
var operationId: String? = nil
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
self.operationId = "\(node.identifier)"
return .visitChildren
}
override func visit(_ node: MemberAccessExprSyntax) -> SyntaxVisitorContinueKind {
if "\(node.description)".contains("JsonHttpClient") {
method = "\(node.name)"
}
return .skipChildren
}
}
|
public struct Subtitles {
public let id: String
public let content: String
}
|
//
// Utils.swift
// coordinatorDemo
//
// Created by kkedziora on 08.01.2018.
// Copyright © 2018 home. All rights reserved.
//
import Foundation
import UIKit
protocol StoryboardInstantiable: class {
static var storyboardIdentifier: String { get }
static var viewControllerIdentifier: String { get }
static func instantiateFromStoryboard() -> Self
}
extension StoryboardInstantiable where Self: UIViewController {
static var viewControllerIdentifier: String {
// Get the name of current class
let classString = NSStringFromClass(self)
let components = classString.components(separatedBy: ".")
assert(components.count > 0, "Failed extract class name from \(classString)")
return components.last!
}
static func instantiateFromStoryboard() -> Self {
let storyboard = UIStoryboard(name: storyboardIdentifier, bundle: Bundle(for: self))
return instantiateFromStoryboard(storyboard, type: self)
}
static func instantiateFromStoryboard<T: UIViewController>(_ storyboard: UIStoryboard, type: T.Type) -> T {
return storyboard.instantiateViewController(withIdentifier: viewControllerIdentifier) as! T
}
}
internal extension UIView {
/// Adds constraints to this `UIView` instances `superview` object to make sure this always has the same size as the superview.
/// Please note that this has no effect if its `superview` is `nil` – add this `UIView` instance as a subview before calling this.
func bindFrameToSuperviewBounds() {
guard let superview = self.superview else {
print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.")
return
}
self.translatesAutoresizingMaskIntoConstraints = false
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
}
}
|
//
// ShareAlert.swift
// gjs_user
//
// Created by 大杉网络 on 2019/9/9.
// Copyright © 2019 大杉网络. All rights reserved.
//
@available(iOS 11.0, *)
class ShareDialog: UIView {
private let shareView = UIView()
private var viewHieght = 0
private var ratesurl : String?
private var taobaoPwd : String?
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(frame: CGRect, itemData: RecommendItem, goodsData: DetailData, qrUrl: String, checkIndex: Int) {
self.init(frame: frame)
let alertBox = self
alertBox.tag = 102
alertBox.backgroundColor = colorwithRGBA(0, 0, 0, 0.5)
alertBox.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW)
layout.height = YGValue(kScreenH)
layout.position = .relative
}
// 弹窗内容
let alertContent = UIScrollView()
alertContent.showsVerticalScrollIndicator = false
alertContent.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW)
layout.height = YGValue(kScreenH - 60)
layout.padding = 15
layout.paddingTop = YGValue(kStatuHeight + 10)
}
viewHieght += 30
alertBox.addSubview(alertContent)
// 分享图
shareView.clearAll2()
shareView.backgroundColor = .white
shareView.layer.cornerRadius = 5
shareView.layer.masksToBounds = true
shareView.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 30)
layout.padding = 15
}
alertContent.addSubview(shareView)
// 头像
let avatarBox = UIView()
avatarBox.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.alignItems = .center
layout.width = YGValue(kScreenW - 60)
}
shareView.addSubview(avatarBox)
let avatar = UIImageView(image: UIImage(named: "avatar-default"))
avatar.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 60
layout.height = 60
layout.marginRight = 10
}
viewHieght += 60
avatarBox.addSubview(avatar)
let info = UIView()
info.configureLayout { (layout) in
layout.isEnabled = true
layout.justifyContent = .center
layout.height = 60
layout.width = YGValue(kScreenW - 130)
}
avatarBox.addSubview(info)
let name = UILabel()
name.text = "赶紧省"
name.font = FontSize(16)
name.textColor = kMainTextColor
name.configureLayout { (layout) in
layout.isEnabled = true
layout.marginBottom = 10
}
info.addSubview(name)
let slogan = UILabel()
slogan.text = "自用省钱 分享赚钱"
slogan.font = FontSize(14)
slogan.configureLayout { (layout) in
layout.isEnabled = true
}
info.addSubview(slogan)
// 商品信息
let goodsInfo = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW - 60, height: 500))
goodsInfo.backgroundColor = .white
goodsInfo.layer.cornerRadius = 5
goodsInfo.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 60)
layout.marginTop = 10
}
viewHieght += 20
shareView.addSubview(goodsInfo)
// 宝贝图
let goodsImg = UIImageView()
goodsImg.layer.cornerRadius = 5
goodsImg.layer.masksToBounds = true
let url = URL(string: itemData.itempic![checkIndex])!
let placeholderImage = UIImage(named: "loading")
goodsImg.af_setImage(withURL: url, placeholderImage: placeholderImage)
let scale = Double((goodsImg.image!.size.width))/Double(kScreenW - 60)
let itemHeight = Double((goodsImg.image!.size.height))/scale
goodsImg.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 60)
layout.height = YGValue(CGFloat(itemHeight))
}
goodsInfo.addSubview(goodsImg)
viewHieght += Int(itemHeight)
// 宝贝信息
let goodsText = UIView()
goodsText.configureLayout { (layout) in
layout.isEnabled = true
layout.padding = 10
layout.paddingLeft = 20
layout.paddingRight = 20
layout.width = YGValue(kScreenW - 60)
}
goodsInfo.addSubview(goodsText)
viewHieght += 90
// 宝贝标题
let goodsName = IDLabel.init()
goodsName.font = FontSize(14)
goodsName.text = goodsData.itemtitle!
let titleH = getLabHeigh(labelStr: goodsData.itemtitle!, font: FontSize(14), width: kScreenW - 100) + 2
goodsName.numberOfLines = 0
goodsName.id_canCopy = true
goodsName.textColor = UIColor.black
if goodsData.shoptype == "C" {
goodsName.id_setupAttbutImage(img: UIImage(named: "taobao")!, index: 0)
} else {
goodsName.id_setupAttbutImage(img: UIImage(named: "tianmao")!, index: 0)
}
let style=NSMutableParagraphStyle.init()
style.lineSpacing = 10
goodsName.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 100)
layout.height = YGValue(titleH)
}
goodsText.addSubview(goodsName)
// ------价格box------
let priceBox = UIView()
priceBox.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.justifyContent = .spaceBetween
layout.alignItems = .center
layout.marginTop = 10
}
goodsText.addSubview(priceBox)
// 左
let priceLeft = UIView()
priceLeft.configureLayout { (layout) in
layout.isEnabled = true
}
priceBox.addSubview(priceLeft)
// 原价
var platform = "淘宝"
if goodsData.shoptype! == "B" {
platform = "天猫"
}
let oldPrice = UILabel()
oldPrice.text = "\(platform)价:\(itemData.itemprice!)元"
oldPrice.font = FontSize(12)
oldPrice.textColor = kGrayTextColor
oldPrice.configureLayout { (layout) in
layout.isEnabled = true
layout.marginBottom = 5
}
priceLeft.addSubview(oldPrice)
// 优惠券
let coupon = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
coupon.layer.contents = UIImage(named:"recommend-2")?.cgImage
coupon.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 100
layout.height = 27.8
layout.paddingLeft = 28.5
}
priceLeft.addSubview(coupon)
let couponMoney = UILabel()
couponMoney.text = "¥\(itemData.couponmoney!)"
couponMoney.textColor = .white
couponMoney.textAlignment = .center
couponMoney.font = FontSize(14)
couponMoney.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 71.5
layout.height = 27.8
}
coupon.addSubview(couponMoney)
// ------右------
let priceRight = UIView()
priceRight.configureLayout { (layout) in
layout.isEnabled = true
layout.alignItems = .flexEnd
layout.width = 200
}
priceBox.addSubview(priceRight)
// 销量
let sales = UILabel()
sales.text = "\(goodsData.itemsale!)人已买"
sales.font = FontSize(12)
sales.textColor = kGrayTextColor
sales.configureLayout { (layout) in
layout.isEnabled = true
layout.marginBottom = 5
}
priceRight.addSubview(sales)
// 券后价
let newPrice = UIView()
newPrice.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.alignItems = .center
layout.height = 27.8
}
priceRight.addSubview(newPrice)
let newLabel1 = UILabel()
newLabel1.text = "[券后价]"
newLabel1.font = FontSize(12)
newLabel1.textColor = kLowOrangeColor
newLabel1.configureLayout { (layout) in
layout.isEnabled = true
layout.marginRight = 5
}
newPrice.addSubview(newLabel1)
let newLabel2 = UILabel()
newLabel2.text = "¥\(itemData.itemendprice!)"
newLabel2.font = FontSize(20)
newLabel2.textColor = kLowOrangeColor
newLabel2.configureLayout { (layout) in
layout.isEnabled = true
}
newPrice.addSubview(newLabel2)
// ---------二维码----------
let aQrcodeBox = UIView()
aQrcodeBox.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.alignItems = .center
layout.width = YGValue(kScreenW - 60)
}
shareView.addSubview(aQrcodeBox)
viewHieght += 115
let aQrcode = UIView()
aQrcode.backgroundColor = .white
aQrcode.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 100
layout.height = 100
layout.padding = 10
layout.marginRight = 10
}
aQrcodeBox.addSubview(aQrcode)
// 生成二维码
let aQrcodeImg = UIImageView()
QRGenerator.setQRCodeToImageView(aQrcodeImg, qrUrl)
aQrcodeImg.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 80
layout.height = 80
}
aQrcode.addSubview(aQrcodeImg)
// 长按二维码提示
let aQrcodeRight = UIView()
aQrcodeRight.configureLayout { (layout) in
layout.isEnabled = true
layout.justifyContent = .center
layout.height = 100
}
aQrcodeBox.addSubview(aQrcodeRight)
// 邀请码
let inviteCode = UILabel()
inviteCode.backgroundColor = colorwithRGBA(247, 51, 47, 1)
inviteCode.textAlignment = .center
inviteCode.layer.cornerRadius = 3
inviteCode.layer.masksToBounds = true
inviteCode.text = "邀请码:\(UserDefaults.getInfo()["inviteCode"]!)"
inviteCode.textColor = .white
inviteCode.font = FontSize(12)
inviteCode.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 130
layout.height = 20
layout.marginBottom = 5
}
aQrcodeRight.addSubview(inviteCode)
let cue = UIView()
cue.configureLayout { (layout) in
layout.isEnabled = true
}
aQrcodeRight.addSubview(cue)
let cueLabel1 = UILabel()
cueLabel1.text = "长按识别二维码"
cueLabel1.font = FontSize(12)
cueLabel1.textColor = kGrayTextColor
cueLabel1.configureLayout { (layout) in
layout.isEnabled = true
}
cue.addSubview(cueLabel1)
let cueLabel2 = UILabel()
cueLabel2.text = "查看商品详情"
cueLabel2.font = FontSize(12)
cueLabel2.textColor = kGrayTextColor
cueLabel2.configureLayout { (layout) in
layout.isEnabled = true
layout.marginTop = 5
}
cue.addSubview(cueLabel2)
// 识别不了提醒
let noIdentify = UIImageView(image: UIImage(named: "recommend-3"))
noIdentify.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 30)
layout.height = YGValue((kScreenW - 30) * 0.11)
layout.marginLeft = -15
layout.marginBottom = -15
}
shareView.addSubview(noIdentify)
// 下载及分享按钮
let alertBtns = UIView()
alertBtns.configureLayout { (layout) in
layout.isEnabled = true
layout.height = 60
layout.flexDirection = .row
layout.justifyContent = .center
layout.alignItems = .center
}
alertBox.addSubview(alertBtns)
// 下载按钮
let downloadBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
downloadBtn.addTarget(self, action: #selector(downloadImg), for: .touchUpInside)
downloadBtn.setTitle("下载图片", for: .normal)
downloadBtn.titleLabel?.font = FontSize(14)
downloadBtn.setTitleColor(.white, for: .normal)
downloadBtn.layer.cornerRadius = 15
downloadBtn.gradientColor(CGPoint(x: 0, y: 0.5), CGPoint(x: 1, y: 0.5), kCGGradientColors)
downloadBtn.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 100
layout.height = 30
layout.marginRight = 10
}
alertBtns.addSubview(downloadBtn)
// 分享按钮
let shareBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
shareBtn.addTarget(self, action: #selector(shareBox), for: .touchUpInside)
shareBtn.setTitle("分享图片", for: .normal)
shareBtn.titleLabel?.font = FontSize(14)
shareBtn.setTitleColor(.white, for: .normal)
shareBtn.layer.cornerRadius = 15
shareBtn.gradientColor(CGPoint(x: 0, y: 0.5), CGPoint(x: 1, y: 0.5), kCGGradientColors)
shareBtn.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 100
layout.height = 30
}
alertBtns.addSubview(shareBtn)
// 关闭按钮
let closeBtn = UIButton()
closeBtn.setImage(UIImage(named: "close-danger"), for: .normal)
closeBtn.isUserInteractionEnabled = true
closeBtn.addTarget(self, action: #selector(closedAction), for: .touchUpInside)
closeBtn.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(30)
layout.height = YGValue(30)
layout.position = .absolute
layout.top = YGValue(kStatuHeight + 15)
layout.right = 15
}
alertBox.addSubview(closeBtn)
alertContent.contentInset = UIEdgeInsets(top: CGFloat(0), left: CGFloat(0), bottom: CGFloat(viewHieght + 100), right: CGFloat(0))
alertBox.yoga.applyLayout(preservingOrigin: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 关闭弹窗
@objc func closedAction(btn: UIButton) {
let delegate = UIApplication.shared.delegate as! AppDelegate
delegate.window?.viewWithTag(102)?.removeFromSuperview()
}
// 下载图片到本地
@objc func downloadImg (_ btn: UIButton) {
let shareUIImage = getImageFromView(view: shareView)
loadImage(image: shareUIImage)
}
func loadImage(image:UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
}
@objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
if error != nil{
IDToast.id_show(msg: "保存失败", success: .fail)
}else{
IDToast.id_show(msg: "保存成功", success: .success)
}
}
// 生成二维码
@objc func qrcode (_ btn: UIButton) {
_ = btn.tag
_ = UIImageView(image: UIImage(named: "logo"))
}
// 分享弹窗模块
@objc func shareBox(){
let shareUIImage = getImageFromView(view: shareView)
var data = ShareSdkModel()
data.title = "赶紧省"
data.content = "既能省钱又能赚钱的APP"
data.url = "https://www.ganjinsheng.com"
data.image = shareUIImage
data.type = .image
let ShareBox = ShareSdkView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: UIScreen.main.bounds.size.height), data: data)
let delegate = UIApplication.shared.delegate as! AppDelegate
delegate.window?.addSubview(ShareBox)
}
}
|
// MIT License
//
// Copyright (c) 2018 Veldspar Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import VeldsparCore
// this class is a background thread which constantly monitors the time, and creates new blocks when required, checks quorum, and queries other nodes to make sure we posess all of the transactions and none are missed.
class BlockMaker {
var lock: Mutex = Mutex()
var currentBlockData: Data?
var inProgress = false
func currentNetworkBlockHeight() -> Int {
let currentTime = consensusTime()
return Int((currentTime - Config.BlockchainStartDate) / (Config.BlockTime * 1000))
}
func Loop() {
// sleep for 5 minutes, waiting for nodes to transmit the missing transactions to the server before producing a block
if settings.isSeedNode {
logger.log(level: .Info, log: "Waiting for other nodes to send outstanding transactions before continuing to produce blocks.")
Thread.sleep(forTimeInterval: 30)
logger.log(level: .Info, log: "Updates recieved, starting the production of blocks.")
}
while true {
queueBlockProductionIfRequired()
Thread.sleep(forTimeInterval: 0.2)
}
}
func validateNewBlockWithNetwork(_ newBlock: Block) {
logger.log(level: .Info, log: "Generated block @ height \(newBlock.height!) with hash \(newBlock.hash!.toHexString().lowercased())")
if !settings.isSeedNode {
var agreement: Float = 0.0
var responses: Float = 0.0
var attempts = 0
// now contact the seed node(s) to get their hashes
var nodes = Config.SeedNodes
if isTestNet {
nodes = Config.TestNetNodes
}
while true {
for n in nodes {
let blockHash = comms.hashForBlock(address: n, height: newBlock.height!)
if blockHash != nil {
if blockHash!.ready! {
responses += 1.0
if blockHash?.hash == newBlock.hash {
agreement += 1.0
} else {
}
} else {
// seed block is not ready yet, do nothing, because we will re-try after a delay
}
} else {
// timeout, or error. Do nothing, because it will be covered in a retry
}
}
if responses == 1.0 {
break
}
if attempts == 480 {
logger.log(level: .Error, log: "Unable to communicate with network for 240 mins, exiting as impossible to verify block image.")
exit(1)
}
attempts += 1
logger.log(level: .Warning, log: "Failed to seek agreement for block hash with the network, will retry in 30 seconds.")
Thread.sleep(forTimeInterval: 30)
}
// check the level of quorum
let quorum = agreement / responses
if quorum < 1.0 {
logger.log(level: .Warning, log: "Block signature verification failed, attempting to re-sync block data with network")
// something we have is either missing or extra :(. Ask the authoritive node for all of the transactions for a certain height
var authoritiveBlockData = comms.blockDataAtHeight(height: newBlock.height!)
if authoritiveBlockData == nil {
// unable to get the block data from the seed node, wait and try again
logger.log(level: .Warning, log: "Network failed to return block data, waiting 30 seconds and trying again.")
Thread.sleep(forTimeInterval: 30.0)
authoritiveBlockData = comms.blockDataAtHeight(height: newBlock.height!)
}
if authoritiveBlockData == nil {
logger.log(level: .Warning, log: "Network failed to return block data for verification. Aborting production of this block.")
lock.mutex {
self.currentBlockData = nil;
self.inProgress = false
}
} else {
// we have the authoritive block data, so poop-can the current block data and re-write it with the new.
_ = blockchain.removeBlockAtHeight(newBlock.height!)
lock.mutex {
self.currentBlockData = authoritiveBlockData
}
// inflate the block data back into an object
let o = try? JSONDecoder().decode(Block.self, from: authoritiveBlockData!)
if o != nil {
logger.log(level: .Info, log: "Block signature verification passed, committing block \(o!.height!) into blockchain with signature \(o!.hash!.toHexString().lowercased())")
_ = blockchain.addBlock(o!)
// dispatch the finalise closure
Execute.background {
self.finalise(newBlock.height!)
}
} else {
lock.mutex {
self.currentBlockData = nil;
self.inProgress = false
}
}
}
} else {
logger.log(level: .Info, log: "Block signature verification passed, committing block \(newBlock.height!) into blockchain with signature \(newBlock.hash!.toHexString().lowercased())")
_ = !blockchain.addBlock(newBlock)
// dispatch the finalise closure
Execute.background {
if settings.blockchain_export_data {
logger.log(level: .Info, log: "Encoding block data for storage within cache.")
let b = blockchain.blockAtHeight(newBlock.height!, includeTransactions: true)
let d = try? JSONEncoder().encode(b)
if d != nil {
self.lock.mutex {
self.currentBlockData = d
}
}
Execute.background {
self.finalise(newBlock.height!)
}
} else {
Execute.background {
self.finalise(newBlock.height!)
}
}
}
}
} else {
// this is a/the seed node, so just write this (until we go for quorum model in v0.2.0)
logger.log(level: .Info, log: "Block signature verification passed, committing block \(newBlock.height!) into blockchain with signature \(newBlock.hash!.toHexString().lowercased())")
_ = blockchain.addBlock(newBlock)
// dispatch the finalise closure
Execute.background {
if settings.blockchain_export_data {
logger.log(level: .Info, log: "Encoding block data for storage within cache.")
let b = blockchain.blockAtHeight(newBlock.height!, includeTransactions: true)
let d = try? JSONEncoder().encode(b)
if d != nil {
self.lock.mutex {
self.currentBlockData = d
}
}
Execute.background {
self.finalise(newBlock.height!)
}
} else {
Execute.background {
self.finalise(newBlock.height!)
}
}
}
}
}
func generateHashForBlock(_ height: Int) {
// produce the block, hash it, seek quorum, then write it
let previousBlock = blockchain.blockAtHeight(height-1, includeTransactions: false)
var newBlock = Block()
newBlock.height = height
var newHash = Data()
newHash.append(previousBlock?.hash ?? Data())
newHash.append(contentsOf: height.toHex().bytes)
newHash.append(blockchain.HashForBlock(height))
newBlock.hash = newHash.sha224()
newBlock.transactions = []
Execute.background {
self.validateNewBlockWithNetwork(newBlock)
}
}
func makeNextBlock() {
let height = Int(blockchain.height()+1)
Execute.background {
self.generateHashForBlock(height)
}
}
func queueBlockProductionIfRequired() {
let currentTime = consensusTime()
if currentTime > Config.BlockchainStartDate {
lock.mutex {
if inProgress == false {
let currentTime = consensusTime()
if currentTime > Config.BlockchainStartDate {
// get the current height, and work out which block should be created and when
let blockHeightForTime = currentNetworkBlockHeight()
if blockchain.height() < blockHeightForTime {
inProgress = true
// blocks are required, now dispatch the activity
Execute.background {
self.makeNextBlock()
}
}
}
}
}
}
}
func finalise(_ height: Int) {
if settings.blockchain_export_data {
try? FileManager.default.createDirectory(atPath: "./cache/blocks", withIntermediateDirectories: true, attributes: [:])
let filePath = "./cache/blocks/\(height).block"
lock.mutex {
if self.currentBlockData != nil {
do {
try self.currentBlockData!.write(to: URL(fileURLWithPath: filePath))
} catch {
logger.log(level: .Error, log: "Failed to export block \(height), error = '\(error)'")
}
}
self.currentBlockData = nil
// if we are in here, then this is the end point and we need to unlock the block production
}
}
lock.mutex {
self.inProgress = false
}
}
}
|
//
// ViewController.swift
// Example 9 - AsyncSequence
//
// Created by Aleksander Lorenc on 12/06/2021.
//
import UIKit
struct ViewModel {
let weatherSupplier = WeatherSupplier()
}
class ViewController: UIViewController {
@IBOutlet var temperatureLabel: UILabel!
var fetchWeatherTask: Task.Handle<Void, Never>?
let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
startFetchingWeather()
}
private func startFetchingWeather() {
guard fetchWeatherTask == nil else { return }
fetchWeatherTask = async {
for await weather in viewModel.weatherSupplier {
updateWeather(weather)
}
}
}
@IBAction func startFetchingWeatherTouched(_ sender: Any) {
startFetchingWeather()
}
@IBAction func stopFetchingWeatherTouched(_ sender: Any) {
stopFetchingWeather()
}
private func stopFetchingWeather() {
fetchWeatherTask?.cancel()
fetchWeatherTask = nil
}
@MainActor
func updateWeather(_ weather: Weather) {
temperatureLabel.text = String(format: "%@ %.0f℃", weather.city, weather.temp)
}
}
|
//
// MTLContextWrapper.swift
// Lutty
//
// Created by Andrey Volodin on 29.10.2019.
// Copyright © 2019 Andrey Volodin. All rights reserved.
//
import Alloy
public class MTLContextWrapper: ObservableObject {
let context: MTLContext
public init(context: MTLContext) {
self.context = context
}
}
|
//
// PizzaModel.swift
// PizzaStore
//
// Created by Macbook pro on 03/02/16.
// Copyright © 2016 Stricz Labs. All rights reserved.
//
import Foundation
class Pizza{
var tipoMasa:String?
var tipoQueso:String?
var tamanio:String?
var tipoIngrediente:Set<String> = Set<String>()
func isComplete()->Bool {
print(tipoMasa)
print(tipoQueso)
print(tamanio)
print(tipoIngrediente.isEmpty)
if( tipoIngrediente.isEmpty || tipoMasa == nil || tamanio == nil || tipoQueso == nil){
return false
}
else{
return true
}
}
}
enum TipoMasa:String{
case Delgada = "delgada",
Crujiente = "crujiente",
Gruesa = "gruesa"
func getName()->String{
return self.rawValue
}
static var toArray:[String] = [TipoMasa.Delgada.getName(),TipoMasa.Crujiente.getName(),TipoMasa.Gruesa.getName(),]
}
enum TipoQueso:String{
case Mozarela = "mozarela",
Cheddar = "cheddar",
Parmesano = "parmesano",
Sin_queso = "sin queso"
func getName()->String{
return self.rawValue
}
static var toArray:[String] = [TipoQueso.Mozarela.getName(),TipoQueso.Cheddar.getName(),TipoQueso.Parmesano.getName(),TipoQueso.Sin_queso.getName()]
}
enum TamanoPizza: String{
case Chica = "chica",
Mediana = "mediana",
Grande = "grande"
func getName()->String{
return self.rawValue
}
static var toArray:[String] = [TamanoPizza.Chica.getName(),TamanoPizza.Mediana.getName(),TamanoPizza.Grande.getName(),]
}
enum TipoIngrediente:String{
case Jamon = "Jamón",
Pepperoni = "pepperoni",
Pavo = "Pavo",
Salchicha = "salchicha",
Aceituna = "aceituna",
Cebolla = "cebolla",
Pimiento = "pimiento",
Pina = "piña",
Anchoa = "anchoa"
func getName()->String{
return self.rawValue
}
static var toArray:[String] = [TipoMasa.Delgada.getName(),TipoMasa.Crujiente.getName(),TipoMasa.Gruesa.getName(),]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.