text stringlengths 8 1.32M |
|---|
//
// ViewController.swift
// SubmitFormOnKeyboard
//
// Created by rMac on 2019/02/10.
// Copyright © 2019 naipaka. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var submitForm: UIView!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var submitFormBottomConstraints: NSLayoutConstraint!
var submitFormY:CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textLabel.layer.borderColor = UIColor.blue.cgColor
textLabel.layer.borderWidth = 1
// 通知センターの取得
let notification = NotificationCenter.default
// keyboardのframe変化時
notification.addObserver(self,
selector: #selector(self.keyboardChangeFrame(_:)),
name: UIResponder.keyboardDidChangeFrameNotification,
object: nil)
// keyboard登場時
notification.addObserver(self,
selector: #selector(self.keyboardWillShow(_:)),
name: UIResponder.keyboardWillShowNotification,
object: nil)
// keyboard退場時
notification.addObserver(self,
selector: #selector(self.keyboardDidHide(_:)),
name: UIResponder.keyboardDidHideNotification,
object: nil)
}
// 「送信フォームを表示」ボタン押下時の処理
@IBAction func showKeyboard(_ sender: Any) {
// キーボードを表示
textField.becomeFirstResponder()
}
// 画面タップ時の処理
@IBAction func closeKeyboard(_ sender: Any) {
// キーボードをしまう
view.endEditing(true)
}
@IBAction func submitText(_ sender: Any) {
textLabel.text = textField.text
}
// キーボードのフレーム変化時の処理
@objc func keyboardChangeFrame(_ notification: NSNotification) {
// keyboardのframeを取得
let userInfo = (notification as NSNotification).userInfo!
let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
// submitFormの最大Y座標と、keybordの最小Y座標の差分を計算
let diff = self.submitForm.frame.maxY - keyboardFrame.minY
if (diff > 0) {
//submitFormのbottomの制約に差分をプラス
self.submitFormBottomConstraints.constant += diff
self.view.layoutIfNeeded()
}
}
// キーボード登場時の処理
@objc func keyboardWillShow(_ notification: NSNotification) {
// 現在のsubmitFormの最大Y座標を保存
submitFormY = self.submitForm.frame.maxY
textField.text = textLabel.text
}
//キーボードが退場時の処理
@objc func keyboardDidHide(_ notification: NSNotification) {
//submitFormのbottomの制約を元に戻す
self.submitFormBottomConstraints.constant = -submitFormY
self.view.layoutIfNeeded()
}
}
|
//
// Model.swift
//
//
// Created by Jamison Bunge on 11/28/18.
//
import Foundation
import UIKit
class ModelGame {
//how do i want to store the shapes?
//array of shape struct?
//var imagesArray : [UIImageView]
var setOfShapes : [shapeInfo] = []
//var music = true
var sound : Bool
let dock : shapeInfo
let size : Int
var isReady : Bool
var numberOfShapesLeft : Int {
didSet {
if numberOfShapesLeft == 0 {
print("newGame")
numberOfShapesLeft = size
//this new game isnt even used really, come back and evaluate this
}
}
}
var score : Int
// var squareInShapeInfo: shapeInfo
// var starInShapeInfo: shapeInfo
// var triangleInShapeInfo: shapeInfo
func touch() {
//do nothing
}
func newShapes() {
for i in 0..<setOfShapes.count {
setOfShapes[i].newName()
}
}
func grabShape(liveShape: UIImageView) -> shapeInfo {
if let i = setOfShapes.index(where: { $0.shapeImage == liveShape }) {
// print("hidden name: \(setOfShapes[i].name),tag: \(setOfShapes[i].shapeImage.tag) ")
// print("the tag is \(setOfShapes[i].shapeImage.tag) and i is \(i)")
// print(setOfShapes[i].name)
return setOfShapes[i]
}
//temp defualt return
return dock
}
// func grabShapeInfoFromName(name: string ) -> shapeInfo {
// }
func grabShapeInfo(name: String ) -> shapeInfo {
let info : shapeInfo = dock
if let i = setOfShapes.index(where: { $0.name == name }) {
// print("hidden name: \(setOfShapes[i].name),tag: \(setOfShapes[i].shapeImage.tag) ")
// print("the tag is \(setOfShapes[i].shapeImage.tag) and i is \(i)")
print(setOfShapes[i].name)
return setOfShapes[i]
}
return info
}
//this guy is supposed to be what the new init will turn into when the old way is refactored to support the shape struct
func startGame(numberOfShapes: Int) {
//in this function i want to randomly select 3 shapes from the string array
//that array needs to get smaller when an option is popped
//not worrying about the PEG stuff right now, just pass the shape for both
//based on the shape that i need to select an image and such
// let setOfShapes : [shapeInfo]
//create 3 shapes
//create 3 pegs
//
}
func updatePeggedCordsFromMovedImage(peg: UIImageView) {
if let i = setOfShapes.index(where: { $0.pegImage == peg }) {
setOfShapes[i].peggedCenterX = peg.center.x
setOfShapes[i].peggedCenterY = peg.center.y
setOfShapes[i].peggedMinX = peg.frame.minX
setOfShapes[i].peggedMaxX = peg.frame.maxX
setOfShapes[i].peggedMinY = peg.frame.minY
setOfShapes[i].peggedMaxY = peg.frame.maxY
}
}
func addShape(shape: UIImageView, peg: UIImageView) {
setOfShapes.append(shapeInfo.init(shape: shape, peg: peg))
}
init(size: Int, dockPassed: UIImageView) {
dock = shapeInfo.init(shape: dockPassed, peg: dockPassed)
self.size = size
numberOfShapesLeft = size
score = 0
isReady = false
sound = true
}
func newGame() {
}
func newGame(size: Int) {
}
func inRange(object: shapeInfo, target: shapeInfo) -> Bool {
if (((object.shapeImage.center.x > target.peggedMinX) && (object.shapeImage.center.x < target.peggedMaxX))
&& ((object.shapeImage.center.y > target.peggedMinY) && (object.shapeImage.center.y < target.peggedMaxY))) {
return true
} else {
return false
}
}
}
|
//
// FirstViewController.swift
// UITabber-demo
//
// Created by Sho Emoto on 2018/09/11.
// Copyright © 2018年 Sho Emoto. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
// MARK: - IBOutlet
@IBOutlet weak var testTableView: UITableView!
// MARK: - Properties
private let dataSource = TableViewProvider()
override func viewDidLoad() {
super.viewDidLoad()
testTableView.dataSource = dataSource
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indexPathForSelectedRow = testTableView.indexPathForSelectedRow {
testTableView.deselectRow(at: indexPathForSelectedRow, animated: true)
}
}
}
// MARK: - UITableViewDelegate
extension FirstViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
toDetail()
}
}
// MARK: - File Extension
extension FirstViewController {
// MARK: - 画面遷移用メソッド
private func toDetail() {
let storyboard = UIStoryboard(name: "DetailViewController", bundle: nil)
let detailVC = storyboard.instantiateInitialViewController()
self.navigationController?.pushViewController(detailVC!, animated: true)
}
}
|
//
// NameCell.swift
// Exercicio4
//
// Created by Yuri Cavalcanti on 05/10/20.
//
import UIKit
class NameCell: UICollectionViewCell {
@IBOutlet weak var labelNome: UILabel?
func setup(name: String) {
labelNome?.text = name
}
}
|
//
// ViewController.swift
// GeniusPlazaCodeChallegnge
//
// Created by Kadeem Palacios on 4/11/19.
// Copyright © 2019 Kadeem Palacios. All rights reserved.
//
import UIKit
import AlamofireImage
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var mainTableView:UITableView!
var tableviewData:[appleData] = []
var index = 0
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
rightBarButtonSetup()
NetworkingService.requestData(index: index) { (data) in
self.tableviewData = data
self.mainTableView.reloadData()
self.setTitle()
self.index += 1
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
UIView.animate(withDuration: 1) {
self.mainTableView.frame.size = CGSize(width: size.width , height: size.height)
self.mainTableView.reloadData()
self.view.setNeedsLayout()
}
} else {
UIView.animate(withDuration: 1) {
self.mainTableView.frame = CGRect(x: 20, y: 0, width: size.width - 40, height: size.height)
self.mainTableView.reloadData()
self.view.setNeedsLayout()
}
}
}
func rightBarButtonSetup() {
let button = UIButton(type: .system)
button.tintColor = UIColor.black
button.setImage(UIImage(imageLiteralResourceName: "Arrow"), for: .normal)
button.addTarget(self, action: #selector(incrementMediaType), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}
func setupTableView() {
mainTableView = UITableView()
mainTableView.autoresizesSubviews = true
mainTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width - 40, height: self.view.frame.height)
mainTableView.center = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY)
mainTableView.delegate = self
mainTableView.dataSource = self
mainTableView.register(itunesTableViewCell.self, forCellReuseIdentifier: "Cell")
self.view.addSubview(mainTableView)
}
func setTitle() {
switch self.index {
case 0:
self.title = "Apple Music"
case 1:
self.title = "Itunes Music"
case 2:
self.title = "iOS Apps"
case 3:
self.title = "Mac Apps"
case 4:
self.title = "Audiobooks"
case 5:
self.title = "Books"
case 6:
self.title = "TV Shows"
default:
self.title = ""
}
}
@objc func incrementMediaType() {
if index == 7 {
index = 0
}
UIView.animateKeyframes(withDuration: 2, delay: 0, options: [.calculationModeCubic], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.1, animations: {
self.mainTableView.frame.origin = CGPoint(x: -self.mainTableView.frame.width - 50, y: 0)
self.mainTableView.layer.opacity = 0
})
UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 0.1, animations: {
self.mainTableView.frame.origin = CGPoint(x: self.mainTableView.frame.width + 50, y: 0)
NetworkingService.requestData(index: self.index) { (data) in
self.tableviewData = data
self.mainTableView.reloadData()
self.setTitle()
self.index += 1
}
})
UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.2, animations: {
self.mainTableView.layer.opacity = 1
self.mainTableView.center = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY)
})
self.mainTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableviewData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = mainTableView.dequeueReusableCell(withIdentifier: "Cell") as! itunesTableViewCell
let data = tableviewData[indexPath.row]
cell.titleLabel.text = data.title
cell.descriptionLabel.text = data.artist
DispatchQueue.main.async {
UIView.animate(withDuration: 2, animations: {
cell.imageCover.af_setImage(withURL: URL(string: data.image)!)
})
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let newCell = cell as? itunesTableViewCell {
if UIApplication.shared.statusBarOrientation.isLandscape {
UIView.animate(withDuration:1) {
newCell.imageCover.frame.size = CGSize(width: 100, height: 100)
newCell.containerView.frame.size = CGSize(width: self.mainTableView.frame.width, height: newCell.frame.height - 5)
newCell.titleLabel.frame.origin = CGPoint(x: newCell.imageCover.frame.maxX + 10, y: newCell.imageCover.frame.minY + 5)
newCell.titleLabel.frame.size = CGSize(width: newCell.containerView.frame.width - newCell.imageCover.frame.width - 20, height: 20)
newCell.descriptionLabel.frame.size = CGSize(width: newCell.containerView.frame.width - newCell.imageCover.frame.width - 20, height: 20)
newCell.descriptionLabel.frame.origin = CGPoint(x: newCell.imageCover.frame.maxX + 10, y: newCell.imageCover.frame.maxY - newCell.descriptionLabel.frame.height - 5)
}
} else {
UIView.animate(withDuration: 1) {
newCell.imageCover.frame.size = CGSize(width: 85, height: 85)
newCell.containerView.frame.size = CGSize(width: self.mainTableView.frame.width - 20, height: newCell.frame.height - 5)
newCell.titleLabel.frame.origin = CGPoint(x: newCell.imageCover.frame.maxX + 10, y: newCell.imageCover.frame.minY + 5)
newCell.titleLabel.frame.size = CGSize(width: newCell.containerView.frame.width - newCell.imageCover.frame.width - 20, height: 20)
newCell.descriptionLabel.frame.size = CGSize(width: newCell.containerView.frame.width - newCell.imageCover.frame.width - 20, height: 20)
newCell.descriptionLabel.frame.origin = CGPoint(x: newCell.imageCover.frame.maxX + 10, y: newCell.imageCover.frame.maxY - newCell.descriptionLabel.frame.height - 5)
}
}
}
}
}
|
//
// Typecasting.swift
// Just Maps
//
// Created by Robert Blundell on 11/12/2017.
// Copyright © 2017 Robert Blundell. All rights reserved.
//
import Foundation
let defaults = UserDefaults.standard
var directionsToPlaceArray: [directionToPlace]!
|
//
// pickerVIewController.swift
// SSASideMenuStoryboardExample
//
// Created by RAYW2 on 20/3/2017.
// Copyright © 2017年 SebastianAndersen. All rights reserved.
//
import UIKit
class PickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerWeek.count
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let formatter = DateFormatter()
formatter.dateFormat = "E dd MMM"
let date = formatter.string(from: pickerWeek[row]!)
return NSAttributedString(string: date, attributes: [NSForegroundColorAttributeName:hexColor(hex: "#66CCFF")])
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return (self.view.frame.size.width*60)/100*0.8;
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
whatDayIndex = row
}
}
|
//
// WalletHeaderView.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 4/26/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
private enum Constants {
static let height: CGFloat = 48
}
final class WalletHeaderView: UITableViewHeaderFooterView, NibReusable {
@IBOutlet private var buttonTap: UIButton!
@IBOutlet private var labelTitle: UILabel!
@IBOutlet private var iconArrow: UIImageView!
var arrowDidTap: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
buttonTap.addTarget(self, action: #selector(tapHandler), for: .touchUpInside)
}
func setupArrow(isExpanded: Bool, animation: Bool) {
let transform = isExpanded ? CGAffineTransform(rotationAngle: CGFloat.pi) : CGAffineTransform.identity
if animation {
UIView.animate(withDuration: 0.3) {
self.iconArrow.transform = transform
}
} else {
iconArrow.transform = transform
}
}
@objc private func tapHandler() {
arrowDidTap?()
}
class func viewHeight() -> CGFloat {
return Constants.height
}
}
// MARK: ViewConfiguration
extension WalletHeaderView: ViewConfiguration {
func update(with model: String) {
labelTitle.text = model
}
}
|
//
// IntegrationTests.swift
// Sealion
//
// Copyright (c) 2016 Dima Bart
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
//
import XCTest
import Sealion
class IntegrationTests: XCTestCase {
typealias Block = () -> Void
var api: API!
// ----------------------------------
// MARK: - Setup -
//
override func setUp() {
super.setUp()
if let token = ProcessInfo.processInfo.environment["AUTH_TOKEN"], !token.isEmpty {
self.api = API(version: .v2, token: token)
} else {
fatalError("Failed run integration tests. Missing `AUTH_TOKEN` in current environment. Provide your Digital Ocean OAuth token to run integration tests.")
}
}
// ----------------------------------
// MARK: - Everything -
//
func testEverything() {
/* ---------------------------------
** Create resources that we'll need
** to conduct the tests.
*/
let droplet = self.createDroplet()
let tags = self.createTags()
/* ---------------------------------
** Wait for all the resources to
** finish initializing before
** running tests.
*/
_ = self.pollDropletUntilActive(dropletToPoll: droplet)
/* ---------------------------------
** Test fetching resources after they
** have been successfully created.
*/
self.fetchDropletsLookingFor(dropletToFind: droplet)
self.fetchDroplet(droplet: droplet)
/* ---------------------------------
** Clean up all the resources that
** were used in the tests.
*/
self.deleteDroplet(droplet: droplet)
}
// ----------------------------------
// MARK: - Creating Resources -
//
private func createDroplet() -> Droplet {
let e = self.expectation(description: "Create droplet")
var droplet: Droplet?
let request = Droplet.CreateRequest(name: "test-droplet", region: "nyc3", size: "512mb", image: "ubuntu-14-04-x64")
let handle = self.api.create(droplet: request) { result in
switch result {
case .success(let d):
droplet = d!
case .failure(let error, _):
XCTFail(error?.description ?? "Failed to create droplet")
}
e.fulfill()
}
handle.resume()
self.waitForExpectations(timeout: 10.0, handler: nil)
return droplet!
}
private func createTags() -> [Tag] {
let e = self.expectation(description: "Create tags")
let count = 2
var tags = [Tag]()
let group = DispatchGroup()
for i in 0..<count {
group.enter()
let request = Tag.CreateRequest(name: "test-tag-\(i)")
let handle = self.api.create(tag: request) { result in
DispatchQueue.main.async {
switch result {
case .success(let tag):
XCTAssertNotNil(tag)
tags.append(tag!)
case .failure(let error, _):
XCTFail(error?.description ?? "Failed to create tag: \(request.name)")
}
group.leave()
}
}
handle.resume()
}
group.notify(queue: DispatchQueue.main) {
e.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
return tags
}
// ----------------------------------
// MARK: - Polling Resources -
//
private func pollDropletUntilActive(dropletToPoll: Droplet) -> Droplet {
let e = self.expectation(description: "Poll droplet")
var droplet: Droplet?
let handle = self.api.poll(droplet: dropletToPoll.id, status: .active) { result in
switch result {
case .success(let d):
droplet = d!
case .failure(let error, _):
XCTFail(error?.description ?? "Failed to poll droplet")
}
e.fulfill()
}
handle.resume()
self.waitForExpectations(timeout: 300.0, handler: nil)
return droplet!
}
// ----------------------------------
// MARK: - Fetching Resources -
//
// private func fetchImages() {
// let e = self.expectation(description: "Fetch Images")
//
// let handle = self.api.images(type: .distribution, page: Page(index: 0, count: 200)) { result in
// e.fulfill()
// }
// handle.resume()
//
// self.waitForExpectations(timeout: 10.0, handler: nil)
// }
private func fetchDropletsLookingFor(dropletToFind: Droplet) {
let e = self.expectation(description: "Fetch droplets")
let handle = self.api.droplets { result in
switch result {
case .success(let droplets):
XCTAssertNotNil(droplets)
let foundDroplet = droplets!.filter { $0.id == dropletToFind.id }.first
XCTAssertNotNil(foundDroplet)
case .failure(let error, _):
XCTFail(error?.description ?? "Failed to fetch droplets")
}
e.fulfill()
}
handle.resume()
self.waitForExpectations(timeout: 10.0, handler: nil)
}
private func fetchDroplet(droplet: Droplet) {
let e = self.expectation(description: "Fetch droplet")
let handle = self.api.dropletWith(id: droplet.id) { result in
switch result {
case .success(let fetchedDroplet):
XCTAssertNotNil(fetchedDroplet)
XCTAssertEqual(fetchedDroplet!.id, droplet.id)
case .failure(let error, _):
XCTFail(error?.description ?? "Failed to fetch droplet")
}
e.fulfill()
}
handle.resume()
self.waitForExpectations(timeout: 10.0, handler: nil)
}
// ----------------------------------
// MARK: - Cleaning Up Resources -
//
private func deleteDroplet(droplet: Droplet) {
let e = self.expectation(description: "Delete droplet")
let handle = self.api.delete(droplet: droplet.id) { result in
switch result {
case .success:
break
case .failure(let error, _):
XCTFail(error?.description ?? "Failed to delete droplet")
}
e.fulfill()
}
handle.resume()
self.waitForExpectations(timeout: 10.0, handler: nil)
}
}
|
//
// TreeNode.swift
// AVLTree
//
// Created by Alex Nichol on 6/10/14.
// Copyright (c) 2014 Alex Nichol. All rights reserved.
//
import Cocoa
class TreeNode : NSView {
var left: TreeNode?
var right: TreeNode?
var depth: Int = 0
var value: Int!
var label: NSTextField!
class func nodeDepth(aNode: TreeNode?) -> Int {
if aNode {
return aNode!.depth + 1
} else {
return 0
}
}
init(frame: CGRect) {
super.init(frame: frame)
}
init(value aValue: Int) {
super.init()
self.autoresizesSubviews = false
value = aValue
label = NSTextField(frame: CGRectMake(0, 0, 1, 1))
label.stringValue = "\(value)"
label.alignment = .CenterTextAlignment
label.editable = false
label.selectable = false
label.backgroundColor = NSColor.clearColor()
label.bordered = false
self.addSubview(label)
}
func insertNode(node: TreeNode) {
if node.value < value {
if !left {
left = node
} else {
left!.insertNode(node)
}
} else {
if !right {
right = node
} else {
right!.insertNode(node)
}
}
recalculateDepth()
left = left ? left!.rebalance() : nil
right = right ? right!.rebalance() : nil
}
func recalculateDepth() -> Int {
let leftDepth = (left ? left!.recalculateDepth() + 1 : 0)
let rightDepth = (right ? right!.recalculateDepth() + 1 : 0)
depth = max(leftDepth, rightDepth)
return depth
}
func isRightHeavy() -> Bool {
if !right {
return false
} else if !left {
return true
} else {
return right!.depth > left!.depth
}
}
func rebalance() -> TreeNode {
let leftDepth = (left ? left!.recalculateDepth() + 1 : 0)
let rightDepth = (right ? right!.recalculateDepth() + 1 : 0)
if leftDepth + 1 < rightDepth {
// right is too dominant, do a floopty
if right!.isRightHeavy() {
var oldRight = right!
right = right!.left
oldRight.left = self
return oldRight
} else {
var newTop = right!.left
var oldRight = right!
right = newTop!.left
oldRight.left = newTop!.right
newTop!.right = oldRight
newTop!.left = self
return newTop!
}
} else if rightDepth + 1 < leftDepth {
if !left!.isRightHeavy() {
var oldLeft = left!
left = left!.right
oldLeft.right = self
return oldLeft
} else {
var newTop = left!.right
var oldLeft = left!
left = newTop!.right
oldLeft.right = newTop!.left
newTop!.left = oldLeft
newTop!.right = self
return newTop!
}
} else {
return self
}
}
func padding(size: CGSize) -> CGFloat {
let nodeCount : CGFloat = CGFloat((1 << (depth + 1)) - 1)
return (size.width / nodeCount) / 20.0
}
func calculateNodeSize(size: CGSize) -> CGFloat {
let heightBound = (size.height - (CGFloat(depth) * padding(size))) / CGFloat(depth + 1)
let nodeCount : CGFloat = CGFloat((1 << (depth + 1)) - 1)
let widthBound = (size.width - (nodeCount - 1) * padding(size)) / nodeCount
return min(heightBound, widthBound)
}
func performLayout(rect: CGRect, size: CGSize, padding: CGFloat, animated: Bool) {
if animated {
self.animator().frame = CGRectMake(rect.origin.x + (rect.size.width - size.width) / 2, rect.origin.y, size.width, size.height)
self.label.frame = CGRectMake(0, (size.height - 22) / 2, size.width, 22)
} else {
self.frame = CGRectMake(rect.origin.x + (rect.size.width - size.width) / 2, rect.origin.y, size.width, size.height)
self.label.frame = CGRectMake(0, (size.height - 22) / 2, size.width, 22)
}
var leftFrame = CGRectMake(rect.origin.x,
rect.origin.y + size.height + padding,
(rect.size.width - size.width) / 2.0 - padding,
rect.size.height - size.height - padding)
var rightFrame = CGRectMake(rect.origin.x + (rect.size.width + size.width) / 2 + padding,
leftFrame.origin.y,
leftFrame.size.width,
leftFrame.size.height)
left?.performLayout(leftFrame, size: size, padding: padding, animated: animated)
right?.performLayout(rightFrame, size: size, padding: padding, animated: animated)
}
func addTo(view: NSView) {
if self.superview != view {
if self.superview {
self.removeFromSuperview()
}
view.addSubview(self)
}
right?.addTo(view)
left?.addTo(view)
}
func removeFrom(view: NSView) {
if self.superview == view {
self.removeFromSuperview()
}
right?.removeFrom(view)
left?.removeFrom(view)
}
override func drawRect(dirtyRect: NSRect) {
NSColor.clearColor().set()
NSRectFillUsingOperation(self.bounds, .CompositeSourceOver)
NSColor.yellowColor().set()
NSBezierPath(ovalInRect: self.bounds).fill()
}
}
|
//
// ReviewTimeWSTests.swift
// ReviewTime
//
// Created by Nathan Hegedus on 31/08/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
import XCTest
import OHHTTPStubs
class ReviewTimeWSTests: XCTestCase {
func testShouldBeAbleToFetchDataAndConvertCorrectly() {
let stub: OHHTTPStubsDescriptor = OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
let containsReviewTimeURL = request.URL?.absoluteString.hasSuffix("reviewTime.json")
XCTAssertTrue(containsReviewTimeURL!, "doens't have URL")
XCTAssertEqual("GET", request.HTTPMethod!, "Methods aren't equals")
XCTAssertNil(request.HTTPBody, "body's nil")
return containsReviewTimeURL!
}, withStubResponse: { (request) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(fileAtPath: OHPathForFile("reviewTime.json", self.classForCoder)!, statusCode: 200, headers: ["Content-Type": "application/json"])
})
let expectation: XCTestExpectation = self.expectationWithDescription("Expectation for ReviewTime request")
let request = ReviewTimeWS.fetchReviewTimeData { (reviewTime, error) -> Void in
XCTAssertNil(error, "error's not nil")
XCTAssertNotNil(reviewTime, "doesn't have reviewTime")
}
expectation.fulfill()
self.waitForExpectationsWithTimeout(request.task.originalRequest!.timeoutInterval, handler: { (error) -> Void in
OHHTTPStubs.removeStub(stub)
})
}
}
|
import Foundation
import RxSwift
class BenchmarkViewModel {
var timers:[TimerItem]? = nil
var isAutoUpdateChart = true
var updatedRow = 0
private var timer:Timer?
private let repository: TimerItemsRepository
private let disposeBag = DisposeBag()
private var binder:((ViewModelState) -> ())? = nil
init(repository: TimerItemsRepository) {
self.repository = repository
}
func bind(_ binder: @escaping (ViewModelState) -> ()) {
self.binder = binder
self.loadTimerItems()
self.initializeTickingTimer()
}
func unBind() {
self.binder = nil
}
func didSelectTimer(row: Int){
let timerItem = repository.timers[row]
print("launched \(String(describing: repository.launchedTimers[row]))")
print("paused \(String(describing: repository.pausedTimers[row]))")
if repository.launchedTimers[row] != nil {
timerItem.showPlayButton()
repository.pausedTimers[row] = repository.timers[row]
repository.launchedTimers.removeValue(forKey: row)
} else {
timerItem.showPauseButton()
repository.launchedTimers[row] = repository.timers[row]
repository.pausedTimers.removeValue(forKey: row)
}
updateCell(row: row)
}
private func loadTimerItems() {
repository.getRemoteAlgorithmItems()
.subscribe { event in
switch event {
case .success(let items):
self.timers = items
self.binder?(.result)
case .error(let error):
print(error)
}
}
.disposed(by: self.disposeBag)
}
private func updateCell(row:Int) {
self.updatedRow = row
self.binder?(.result)
}
private func initializeTickingTimer(){
let interval = 0.1
timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { timer in
for(index, timer) in self.repository.launchedTimers {
timer.incrementDuration(interval)
self.updateCell(row: index)
}
for(index, timer) in self.repository.pausedTimers {
timer.incrementPausedTime(interval)
self.updateCell(row: index)
}
}
}
}
|
//
// Pokemons+mock.swift
// pokemonSerch
//
// Created by 葛 智紀 on 2021/05/17.
//
import Foundation
extension Pokemons {
static let mock1 = Pokemons(
count: 1,
next: "",
previous: "",
results: [.mock1])
}
|
//
// LaunchCounter.swift
// Start
//
// Created by Igor Matyushkin on 31.08.2018.
// Copyright © 2018 Igor Matyushkin. All rights reserved.
//
import Foundation
public final class LaunchCounter {
// MARK: Class variables & properties
internal static let shared = {
return LaunchCounter()
}()
// MARK: Public class methods
// MARK: Private class methods
// MARK: Initializers
fileprivate init() {
}
// MARK: Deinitializer
deinit {
}
// MARK: Object variables & properties
public var count: Int {
get {
return DefaultsManager.shared.launchCount
}
}
// MARK: Public object methods
public func increment() {
let defaultsManager = DefaultsManager.shared
let currentLaunchCount = defaultsManager.launchCount
let newLaunchCount = currentLaunchCount + 1
defaultsManager.launchCount = newLaunchCount
}
public func reset() {
DefaultsManager.shared.launchCount = 0
}
// MARK: Private object methods
}
public extension LaunchCounter {
public var isFirst: Bool {
get {
return DefaultsManager.shared.launchCount == 1
}
}
}
|
//
// ServerCheck.swift
// CheckTLS
//
// Copyright © 2016 vivami. All rights reserved.
//
import Foundation
enum CheckStatus: Int {
case TLS_ENCRYTPED = 1, UNCERTAIN, UNENCRYPTED, ERROR
}
class ServerCheck {
let sslToolsAddr = "https://ssl-tools.net/mailservers/"
let jsonFormat = "?format=json"
static let instance = ServerCheck.init()
init() {}
func check(server: String) -> CheckStatus {
if let jsonData = getJSON(server) {
let result = checkStatus(jsonData)
NSLog("[CheckTLS] \(server) is \(result)")
return result
}
NSLog("[CheckTLS] Could not get TLS info for \(server) from ssl-tools.net.")
return CheckStatus.ERROR
}
func getJSON(s: String) -> NSData? {
let addr = sslToolsAddr + s + jsonFormat
guard let url = NSURL(string: addr) else {
NSLog("[CheckTLS] Error: cannot create URL")
return nil
}
if let data = try? NSData(contentsOfURL: url, options: []) {
return data
}
return nil
}
func checkStatus(data: NSData) -> CheckStatus {
let json = JSON(data: data)
if json["state"].description == "done" {
if let hosts = json["hosts"].array {
var returnStatus = CheckStatus.UNCERTAIN
for host in hosts {
if host["error"] == "Bad return code for STARTTLS" ||
host["certificate"] == nil
{
/* Don't directly return, as there may be another mailserver having proper TLS. */
returnStatus = CheckStatus.UNENCRYPTED
} else if host["error"] == nil &&
host["certificate"] != nil &&
host["pfs"] == true {
return CheckStatus.TLS_ENCRYTPED
} else {
returnStatus = CheckStatus.UNCERTAIN
}
}
return returnStatus
} else {
NSLog("[CheckTLS] Incomplete JSON.")
return CheckStatus.ERROR
}
} else {
NSLog("[CheckTLS] Could not load JSON. Please check if ssl-tools.net is up an running.")
return CheckStatus.ERROR
}
}
} |
//
// Project+CoreDataProperties.swift
//
//
// Created by Gi Pyo Kim on 2/6/20.
//
//
import Foundation
import CoreData
extension Project {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Project> {
return NSFetchRequest<Project>(entityName: "Project")
}
@NSManaged public var name: String?
@NSManaged public var jobs: NSSet?
}
// MARK: Generated accessors for jobs
extension Project {
@objc(addJobsObject:)
@NSManaged public func addToJobs(_ value: Job)
@objc(removeJobsObject:)
@NSManaged public func removeFromJobs(_ value: Job)
@objc(addJobs:)
@NSManaged public func addToJobs(_ values: NSSet)
@objc(removeJobs:)
@NSManaged public func removeFromJobs(_ values: NSSet)
}
|
//
// PoemsViewModel.swift
// Poetry
//
// Created by Alexander Ostrovsky on 03.05.16.
// Copyright © 2016 Alexander Ostrovsky. All rights reserved.
//
import Foundation
import GoogleAPIClientForREST_Blogger
struct Post {
var title: String
var text: String
var date: Date?
var tags: [String]
}
extension Post {
var markdownContent: String {
var content = ""
for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
var line = line
if !line.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
line = line + " "
}
content += line + "\n"
}
content = content.replacingOccurrences(of: " \n\n", with: "\n\n")
content = content.replacingOccurrences(of: "*", with: "\\*")
return content
}
var jekyllMarkdown: String {
"""
---
title: "\(title.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))"
date: \(date?.formatted(.iso8601) ?? "")
tags: \(tags)
---
\(markdownContent)
"""
}
var jekyllFilenameBase: String { "\(date?.formatted(.iso8601.year().month().day()) ?? "")-\(title)" }
init(_ post: GTLRBlogger_Post) {
title = post.title ?? ""
text = post.content?.attributedHtmlString?.string ?? ""
date = post.published.flatMap { ISO8601DateFormatter().date(from: $0) }
tags = post.labels ?? []
}
}
class PoemsViewModel: ObservableObject {
@Published var poems = [Post]()
init() {
fetchPoems()
}
private func fetchPoems() {
Blogger.shared.posts { [weak self] (posts, error) in
if let error = error {
print("Error fetching posts\(error)")
} else {
self?.poems = posts.map(Post.init)
#if DEBUG
self?.savePostsInDocuments(bloggerPosts: posts)
#endif
}
}
}
private func savePostsInDocuments(bloggerPosts: [GTLRBlogger_Post]) {
let postsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("Posts-\(Date.now.formatted(.iso8601))")
print("Posts dir URL is \(postsURL)")
do {
try FileManager.default.createDirectory(at: postsURL, withIntermediateDirectories: true)
} catch {
print(error.localizedDescription)
}
for bloggerPost in bloggerPosts {
let post = Post(bloggerPost)
print("================================================")
print("Title: \(post.title)")
print("Published: \(bloggerPost.published ?? "")")
print("Tags: \(post.tags)")
print("Post ID: \(bloggerPost.identifier ?? "")")
print("Post URL: \(bloggerPost.url ?? "")")
do {
try post.jekyllMarkdown.write(to: postsURL.appendingPathComponent(post.jekyllFilenameBase + ".md"), atomically: true, encoding: .utf8)
} catch {
print(error.localizedDescription)
}
if bloggerPost.images?.isEmpty == false {
let postImagesFolder = postsURL.appendingPathComponent(post.jekyllFilenameBase)
do {
try FileManager.default.createDirectory(at: postImagesFolder, withIntermediateDirectories: true)
} catch {
print(error.localizedDescription)
}
Task {
for imageUrlItem in bloggerPost.images ?? [] {
guard let url = URL(string: imageUrlItem.url ?? "") else { continue }
do {
let (imageData, _) = try await URLSession.shared.data(from: url)
try imageData.write(to: postImagesFolder.appendingPathComponent(url.lastPathComponent))
} catch {
print(error.localizedDescription)
}
}
}
}
}
}
}
extension String {
var utfData: Data {
return Data(utf8)
}
var attributedHtmlString: NSAttributedString? {
do {
return try NSAttributedString(data: utfData, options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
],
documentAttributes: nil)
} catch {
print("Error:", error)
return nil
}
}
}
|
import UIKit
//UITableViewCellクラスを継承
//cell作成時、Also creat XIB fileにチェックを入れる
class CustomCell: UITableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
//
// NewsVM.swift
// CryptocurrencyNews
//
// Created by Kristijan Delivuk on 23/10/2017.
// Copyright © 2017 Kristijan Delivuk. All rights reserved.
//
import Defines
import RxSwift
final class NewsVM: NewsVMProtocol {
// MARK: - Coordinator Actions
var onDidTapItem: ((Cryptocurrency) -> ()) = { _ in }
// MARK: - Public Properties
lazy var stateObservable: Observable<NewsVMState> = self._state.asObservable().throttle(0.5, scheduler: MainScheduler.instance)
let disposeBag: DisposeBag
var numberOfRows: Int {
return filteredCriptocurrencies.count
}
var priceInFiat: String
lazy var titleObservable: Observable<String> = self._title.asObservable().throttle(0.5, scheduler: MainScheduler.instance)
private var _title: Variable<String>
// MARK: - Private Properties
private var criptocurrencies: [Cryptocurrency]
private var filteredCriptocurrencies: [Cryptocurrency]
private let _state: Variable<NewsVMState>
private let cryptocurrencyManager: CryptocurrencyManagerProtocol
// MARK: - Class Lifecycle
init(cryptocurrencyManager: CryptocurrencyManagerProtocol) {
self.cryptocurrencyManager = cryptocurrencyManager
disposeBag = DisposeBag()
_state = Variable(NewsVMState.top([]))
criptocurrencies = []
filteredCriptocurrencies = []
_title = Variable(NSLocalizedString("Top \(cryptocurrencyManager.limit)", comment: ""))
priceInFiat = "Price in \(cryptocurrencyManager.fiatCurrency.title())"
cryptocurrencyManager
.limitObservable
.subscribe(onNext: { [weak self] limit in
guard let weakself = self else { return }
switch weakself._state.value {
case .top:
weakself._title.value = NSLocalizedString("Top \(limit)", comment: "")
case .search(let state):
switch state {
case .searching:
weakself._title.value = NSLocalizedString("Searching...", comment: "")
default:
weakself._title.value = ""
}
}
weakself.top()
}).disposed(by: disposeBag)
cryptocurrencyManager
.fiatCurrencyObservable
.subscribe(onNext: { [weak self] currency in
guard let weakself = self else { return }
weakself.priceInFiat = NSLocalizedString("Prince in \(currency.title())", comment: "")
weakself.top()
}).disposed(by: disposeBag)
}
func search(word: String) {
// set state to searching which enables spinner
// while quering for result
_state.value = .search(.searching)
// if there are more than 0 characters currently
// present in the searchbar
if word.count > 0 {
clear()
// query through all the items and find ones that contain search word
filteredCriptocurrencies = self.criptocurrencies.filter({$0.name.contains(word)})
// if there are no items that satisfy our search result
// set the empty state for search table view
if filteredCriptocurrencies.count == 0 {
self._state.value = NewsVMState.search(SearchResultState.empty)
} else {
// else return those items and show them to user
self._state.value = NewsVMState.search(SearchResultState.results(self.filteredCriptocurrencies))
}
self._title.value = NSLocalizedString("\(word)", comment: "")
} else {
// if the search bar is empty
// show the top results to the user
top()
}
}
func top() {
cryptocurrencyManager
.top()
.subscribe(onNext: { [weak self] currencies in
guard let weakself = self else { return }
weakself.criptocurrencies = currencies
weakself.filteredCriptocurrencies = weakself.criptocurrencies
weakself._title.value = NSLocalizedString("Top \(weakself.cryptocurrencyManager.limit)", comment: "")
weakself._state.value = NewsVMState.top(weakself.filteredCriptocurrencies)
}).disposed(by: disposeBag)
}
func clear() {
filteredCriptocurrencies = []
}
// MARK: - Public Methods
func item(for indexPath: IndexPath) -> Cryptocurrency {
return filteredCriptocurrencies[indexPath.row]
}
func didSelectItem(at indexPath: IndexPath) {
onDidTapItem(filteredCriptocurrencies[indexPath.row])
}
}
|
//
// SignInViewController.swift
// PasswordStorage
//
// Created by João Paulo dos Anjos on 31/01/18.
// Copyright © 2018 Joao Paulo Cavalcante dos Anjos. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import LocalAuthentication
class SignInViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var registerButton: UIButton!
private var viewModel = SignInViewModel()
private let disposeBag = DisposeBag()
private var finishedAnimation = false;
var context = LAContext()
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
bindElement()
animateTextFiels()
animateLogo()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
moveElements()
checkTouchID()
}
// MARK: - IBActions
@IBAction func loginButtonTouchUpInside(_ sender: UIButton) {
dismissKeyboard()
viewModel.postLogin()
}
@IBAction func registerButtonTouchUpInside(_ sender: UIButton) {
self.present(SignUpViewController.instantiate(), animated: true, completion: nil)
}
// MARK: - MISC
func setupUI() {
fillColor()
}
func fillColor() {
registerButton.backgroundColor = ThemeColor.shared.primaryColor;
loginButton.setTitleColor(ThemeColor.shared.primaryColor, for: .normal)
}
func dismissKeyboard() {
view.endEditing(true)
}
// MARK: - Bind
func bindElement() {
emailTextField.rx.text
.map { $0 ?? "" }
.bind(to: viewModel.email)
.disposed(by: disposeBag)
passwordTextField.rx.text
.map { $0 ?? "" }
.bind(to: viewModel.password)
.disposed(by: disposeBag)
viewModel.isDataValid
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [unowned self] isValid in
self.loginButton.isEnabled = isValid
}).disposed(by: disposeBag)
viewModel.serviceResponse
.asObservable()
.subscribe(onNext: { [unowned self] response in
if let _ = response {
DispatchQueue.main.async {
self.emailTextField.text = ""
self.passwordTextField.text = ""
self.present(AccountNavigationController.instantiate(), animated: true, completion: nil)
}
}
}).disposed(by: disposeBag)
viewModel.errorResponse
.asObservable()
.subscribe(onNext: { [unowned self] response in
if let response = response {
self.showAlert(title: "Error", message: response.message!, buttonTitle: "OK", dissmisBlock: { })
}
}).disposed(by: disposeBag)
viewModel.isLoading.asObservable()
.subscribe(onNext: { [unowned self] isLoading in
self.view.enableLoading(isLoading)
}).disposed(by: disposeBag)
}
}
extension SignInViewController {
// MARK: TouchID
func checkTouchID() {
if !AutoLoginConvience().autoLoginEnable { return }
let policy: LAPolicy = .deviceOwnerAuthenticationWithBiometrics
var err: NSError?
guard context.canEvaluatePolicy(policy, error: &err) else {
return
}
loginProcess(policy: policy)
}
private func loginProcess(policy: LAPolicy) {
context.evaluatePolicy(policy, localizedReason: "Touch to Sign In", reply: { (success, error) in
DispatchQueue.main.async {
guard success else {
guard let error = error else { return }
switch(error) {
case LAError.authenticationFailed:
self.fillEmailTextField()
break
default:
break
}
return
}
self.autoLogin()
}
})
}
func fillEmailTextField() {
let autoLogin = AutoLoginConvience()
emailTextField.text = autoLogin.username
}
func autoLogin() {
let autoLogin = AutoLoginConvience()
if !autoLogin.autoLoginEnable { return }
viewModel.email.value = autoLogin.username
viewModel.password.value = autoLogin.password
viewModel.postLogin()
}
}
extension SignInViewController {
// MARK: - Animations
func moveElements() {
if (finishedAnimation) { return }
emailTextField.center.x += self.view.bounds.width
passwordTextField.center.x -= self.view.bounds.width
loginButton.alpha = 0
registerButton.alpha = 0
}
func animateTextFiels() {
UIView.animate(withDuration: 0.5, delay: 1.5, options: [], animations: {
self.emailTextField.center.x -= self.view.bounds.width
self.passwordTextField.center.x += self.view.bounds.width
}) { (sucess) in
self.animateButtons()
}
}
func animateButtons() {
UIView.animate(withDuration: 0.5, delay: 0, options: [], animations: {
self.loginButton.alpha = 1
self.registerButton.alpha = 1
}) { (sucess) in
self.finishedAnimation = true
}
}
func animateLogo() {
UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
self.logoImageView.center.y = 0
}) { (sucess) in
}
}
}
extension SignInViewController {
// MARK: - Instantiation
static func instantiate() -> SignInViewController {
let storyboard = UIStoryboard(name: "SignIn", bundle: nil)
return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! SignInViewController
}
}
|
//
// String+Ex.swift
// ChatterBox
//
// Created by Jitendra Kumar on 23/05/20.
// Copyright © 2020 Jitendra Kumar. All rights reserved.
//
import UIKit
struct Validator{
enum Validate {
case predicate(SPredicate)
func formatter(in string: String)->Bool{
switch self {
case .predicate(let field):
return field.evaluate(with: string)
}
}
}
enum SPredicate {
case validateUrl
var regularExp:String{
switch self {
case .validateUrl: return "(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
}
}
var predicate:NSPredicate{
return NSPredicate(format: "SELF MATCHES %@", self.regularExp)
}
func evaluate(with object: Any?) -> Bool{
return predicate.evaluate(with: object)
}
}
}
extension String{
//MARK:- String Validation
//MARK:- validFormatter
func validFormatter(_ formate:Validator.Validate)->Bool{
guard !self.isEmpty else {return false}
return formate.formatter(in: self)
}
//MARK:- isValidateUrl
var isValidateUrl : Bool {
return validFormatter(.predicate(.validateUrl))
}
//MARK:- urlQueryEncoding
/// Returns a new string made from the `String` by replacing all characters not in the unreserved
/// character set (As defined by RFC3986) with percent encoded characters.
var urlQueryEncoding: String? {
let allowedCharacters = CharacterSet.urlQueryAllowed
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}
//MARK:- isEqualTo
func isEqualTo(other:String)->Bool{
return self.caseInsensitiveCompare(other) == .orderedSame ? true : false
}
}
|
//
// FarApiClient.swift
// FAR
//
// Created by VISHAL-SETH on 12/30/17.
// Copyright © 2017 Infoicon. All rights reserved.
//
import UIKit
import Alamofire
class SparkyApiHelper: NSObject {
//MARK:- APi call with parameter only
class func apiCall(serviceName: String,param: Any?,showLoader: Bool? = nil,
completionClosure: @escaping(NSDictionary?,Error?) ->())
{
if CommonFunction.isInternetAvailable()
{
var isShowLoader=true
if let show = showLoader
{
if show == false
{
isShowLoader=false
}
else
{
isShowLoader=true
}
}
if isShowLoader
{
CommonFunction.startLoader(title: "Loading...")
}
var paramValues:Parameters?
paramValues = param as? Parameters
print("REQUEST URL :: \(serviceName)")
print("REQUEST PARAMETERS :: \(String(describing: paramValues))")
//Header Implementation
// let valueArrayNotToCheckAuth = [API_CONSTANT.kLogin,API_CONSTANT.kRegister,API_CONSTANT.kForgotPassword,API_CONSTANT.kCountry]
let headers: HTTPHeaders = [
"Content-Type":"application/json"
]
// if valueArrayNotToCheckAuth.contains(serviceName){
// headers = [
// "Content-Type": "application/json"
// ]
// }else{
//
// headers = [
// "Content-Type": "application/json",
// "USER": CommonFunction.getUserIdFromUserDefault()
// ]
// }
// Remove above code if you dont want to Header
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 60
manager.request(serviceName,method:.post,parameters:paramValues,encoding: JSONEncoding.default,headers:headers).responseJSON { response in
CommonFunction.stopLoader()
switch response.result
{
case .success:
if let JSON = response.result.value{
debugPrint("Repsonse::\(JSON)");
DispatchQueue.main.async
{
let responseJson=JSON as? NSDictionary
completionClosure(responseJson, nil)
}
}
case .failure(let error):
print(error)
CommonFunction.showAlert(message: error.localizedDescription)
//completionClosure(JSON as? NSDictionary, nil)
}
}
}
}
class func apiCallDownloadPdf(serviceName: String,param: Any?,showLoader: Bool? = nil,
completionClosure: @escaping(URL?,Error?) ->())
{
if CommonFunction.isInternetAvailable()
{
var isShowLoader=true
if let show = showLoader
{
if show == false
{
isShowLoader=false
}
else
{
isShowLoader=true
}
}
if isShowLoader
{
CommonFunction.startLoader(title: "Loading...")
}
var paramValues:Parameters?
paramValues = param as? Parameters
print("REQUEST URL :: \(serviceName)")
print("REQUEST PARAMETERS :: \(String(describing: paramValues))")
//Header Implementation
// let valueArrayNotToCheckAuth = [API_CONSTANT.kLogin,API_CONSTANT.kRegister,API_CONSTANT.kForgotPassword,API_CONSTANT.kCountry]
let headers: HTTPHeaders = [
"Content-Type":"application/json"
]
// if valueArrayNotToCheckAuth.contains(serviceName){
// headers = [
// "Content-Type": "application/json"
// ]
// }else{
//
// headers = [
// "Content-Type": "application/json",
// "USER": CommonFunction.getUserIdFromUserDefault()
// ]
// }
// Remove above code if you dont want to Header
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 60
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL:NSURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
let PDF_name : String = "All_User_List.pdf"
let fileURL = documentsURL.appendingPathComponent(PDF_name)
return (fileURL!,[.removePreviousFile, .createIntermediateDirectories])
}
manager.download(serviceName, to: destination).downloadProgress(closure: { (prog) in
}).response { response in
CommonFunction.stopLoader()
if response.error == nil, let filePath = response.destinationURL?.path
{
//Open this filepath in Webview Object
let fileURL = URL(fileURLWithPath: filePath)
completionClosure(fileURL, nil)
}
}
}
}
//MARK:- Upload Image and video with parameter
class func apiCallWithImageAndVideos(serviceName: String,image:NSArray,video : NSArray,param: Any?,showLoader: Bool? = nil,
completionClosure: @escaping(NSDictionary?,Error?) ->())
{
if CommonFunction.isInternetAvailable(){
var isShowLoader=true
if let show = showLoader{
if show == false{
isShowLoader=false
}else{
isShowLoader=true
}
}
if isShowLoader{
CommonFunction.startLoader(title: "Loading...")
}
print("REQUEST URL :: \(serviceName)")
print("REQUEST PARAMETERS :: \(String(describing: param))")
var paramString:String?
if let theJSONData = try? JSONSerialization.data(
withJSONObject: param!,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .utf8)!
paramString = theJSONText as String
print("JSON string = \(theJSONText)")
}
var headers: HTTPHeaders = [:]
headers = [
"Content-Type": "application/json"
]
let manager = Alamofire.SessionManager.default
manager.upload(multipartFormData: { multipartFormData in
// import image to request
for i in 0..<image.count
{
// NSURLQueryItem(name: "front_prd_img", value:front_prd_img),
// NSURLQueryItem(name: "side_prd_img", value:side_prd_img),
// NSURLQueryItem(name: "back_prd_img", value:back_prd_img)]
if i==0
{
let imageData = UIImageJPEGRepresentation(image[i] as! UIImage, 0.6)
multipartFormData.append(imageData!, withName:"front_prd_img", fileName: "\(Date().timeIntervalSince1970).png", mimeType: "image/jpeg")
}
else if i==1
{
let imageData = UIImageJPEGRepresentation(image[i] as! UIImage, 0.6)
multipartFormData.append(imageData!, withName:"side_prd_img", fileName: "\(Date().timeIntervalSince1970).png", mimeType: "image/jpeg")
}
else if i==2
{
let imageData = UIImageJPEGRepresentation(image[i] as! UIImage, 0.6)
multipartFormData.append(imageData!, withName:"back_prd_img", fileName: "\(Date().timeIntervalSince1970).png", mimeType: "image/jpeg")
}
}
multipartFormData.append((paramString?.data(using: String.Encoding.utf8)!)!, withName: "data")
},to: serviceName,headers: headers, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
print("Image upload:\(response)")
if let JSON = response.result.value
{
//debugPrint("Repsonse::\(JSON)");
DispatchQueue.main.async {
let responseJson=JSON as? NSDictionary
CommonFunction.stopLoader()
completionClosure(responseJson, nil)
}
}
}
case .failure(let encodingError):
CommonFunction.stopLoader()
CommonFunction.showAlert(message: encodingError.localizedDescription)
print("encodingError:\(encodingError)")
}
})
}
}
//MARK:- Upload Image with parameter
class func apiCallWithImage(serviceName: String,image:UIImage,imageName:String,param: Any?,showLoader: Bool? = nil,
completionClosure: @escaping(NSDictionary?,Error?) ->())
{
if CommonFunction.isInternetAvailable(){
var isShowLoader=true
if let show = showLoader{
if show == false{
isShowLoader=false
}else{
isShowLoader=true
}
}
if isShowLoader{
CommonFunction.startLoader(title: "Loading...")
}
print("REQUEST URL :: \(serviceName)")
print("REQUEST PARAMETERS :: \(String(describing: param))")
var paramString:String?
if let theJSONData = try? JSONSerialization.data(
withJSONObject: param!,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .utf8)!
paramString = theJSONText as String
print("JSON string = \(theJSONText)")
}
var headers: HTTPHeaders = [:]
headers = [
"Content-Type": "multipart/form-data",
//"USER": CommonFunction.getUserIdFromUserDefault(),
//"LANG" : UserDefaults.standard.value(forKey: "language") as! String
]
let manager = Alamofire.SessionManager.default
let imageData = UIImageJPEGRepresentation(image, 0.6)
manager.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: imageName,fileName: "file.jpg", mimeType: "image/jpg")
multipartFormData.append((paramString?.data(using: String.Encoding.utf8)!)!, withName: "data")
}, to: serviceName,headers: headers, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
print("Image upload:\(response)")
if let JSON = response.result.value{
//debugPrint("Repsonse::\(JSON)");
DispatchQueue.main.async {
let responseJson=JSON as? NSDictionary
CommonFunction.stopLoader()
completionClosure(responseJson, nil)
}
}
}
case .failure(let encodingError):
CommonFunction.stopLoader()
CommonFunction.showAlert(message: encodingError.localizedDescription)
print("encodingError:\(encodingError)")
}
})
}
}
}
|
//
// BlypImage.swift
// blyp
//
// Created by Hayden Hong on 4/23/20.
// Copyright © 2020 Team Sonar. All rights reserved.
//
import SDWebImageSwiftUI
import SwiftUI
/// A VERY unsafe view for BlypImage. ONLY use this if you're sure everything required isn't null.
struct BlypImage: View {
var blyp: Blyp
var contentMode: ContentMode?
var body: some View {
GeometryReader { geometry in
WebImage(url: URL(string: self.blyp.imageUrl!))
.onSuccess { _, _ in
}
.resizable()
.placeholder(Image(uiImage: UIImage(blurHash: self.blyp.imageBlurHash!, size: CGSize(width: self.blyp.imageBlurHashWidth!, height: self.blyp.imageBlurHashHeight!))!))
.scaledToFit()
.aspectRatio(contentMode: self.contentMode != nil ? self.contentMode! : .fill)
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
}
}
}
struct BlypImage_Previews: PreviewProvider {
static var previews: some View {
BlypImage(blyp: Blyp(id: UUID(), name: "TestBlyp", description: "Uhhh", imageUrl: "", imageBlurHash: "", imageBlurHashWidth: 32.0, imageBlurHashHeight: 32.0))
}
}
|
//
// GameCell.swift
// WrigleyWinds
//
// Created by Vik Denic on 4/17/16.
// Copyright © 2016 vikzilla. All rights reserved.
//
import UIKit
import TextAttributes
class CurrentlyCell: UICollectionViewCell {
@IBOutlet var conditionsLabel: UILabel!
@IBOutlet var windLabel: UILabel!
var hour : Hourly! {
didSet {
setUpCell()
}
}
func setUpCell() {
conditionsLabel.text = "\(hour.time!.toAbbrevTimeString()): \(Int(round(hour.temperature!)))° & \(hour.summary!)"
let attrs = TextAttributes()
.font(name: kFontGaramondProRegular, size: 30)
.lineHeightMultiple(1.3)
.alignment(.center)
let displayString = "Wind blowing\n \(hour.windBearing!.windDirection().ballparkString)\n at \(hour.windSpeed!) MPH"
windLabel.attributedText = NSAttributedString(string: displayString, attributes: attrs)
}
}
|
//
// CustomUnderline.swift
// GuessTheFlag
//
// Created by Tino on 17/4/21.
//
import SwiftUI
struct CustomUnderline: ViewModifier {
let underlineHeight = CGFloat(3)
func body(content: Content) -> some View {
ZStack(alignment: .bottom) {
Rectangle()
.fill(Color.white)
.frame(height: underlineHeight)
content
.offset(y: underlineHeight)
}
}
}
extension View {
func customUnderline() -> some View {
modifier(CustomUnderline())
}
}
|
//
// NoteDetailsViewController.swift
// Notes
//
// Created by mw on 27.12.2019.
// Copyright © 2019 mw. All rights reserved.
//
import UIKit
import LocalAuthentication
class NoteDetailsViewController: UIViewController {
var db = DBHelper.get()
var note: NoteModel?
@IBOutlet weak var noteTitleLabel: UILabel!
@IBOutlet weak var noteBodyLabel: UILabel!
@IBOutlet weak var noteDateLabel: UILabel!
@IBOutlet weak var noteTitle: UILabel!
@IBOutlet weak var noteBody: UITextView!
@IBOutlet weak var noteDate: UILabel!
@IBOutlet weak var googleSection: UIStackView!
@IBOutlet weak var securitySection: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
noteTitleLabel.isHidden = true
noteBodyLabel.isHidden = true
noteDateLabel.isHidden = true
noteTitle.isHidden = true
noteBody.isHidden = true
noteDate.isHidden = true
googleSection.isHidden = true
securitySection.isHidden = true
if (note != nil) {
if (note!.secured) {
authenticationWithTouchID()
} else {
bindNote()
}
}
}
@IBAction func cancel(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
func bindNote() {
DispatchQueue.main.async {
if (self.note != nil) {
self.noteTitleLabel.isHidden = false
self.noteBodyLabel.isHidden = false
self.noteDateLabel.isHidden = false
self.noteTitle.isHidden = false
self.noteBody.isHidden = false
self.noteDate.isHidden = false
self.noteTitle.text = self.note!.title
self.noteBody.text = self.note!.body
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm"
self.noteDate.text = df.string(from: self.note!.date)
let user = self.db.getGoogleUser()
self.googleSection.isHidden = self.note!.calendarEventId.isEmpty || user == nil
self.securitySection.isHidden = !(self.note!.secured)
}
}
}
func authError(msg: String) {
let alert = UIAlertController(title: "Błąd autoryzacji", message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true)
}
}
extension NoteDetailsViewController {
func authenticationWithTouchID() {
let localAuthenticationContext = LAContext()
localAuthenticationContext.localizedFallbackTitle = "Użyj kodu dostępu"
var authError: NSError?
let reasonString = "Autoryzuj w celu wyświetlenia zawartości notatki"
if localAuthenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
localAuthenticationContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString) { success, evaluateError in
if success {
self.bindNote()
} else {
guard let error = evaluateError else {
return
}
let _msg = self.evaluateAuthenticationPolicyMessageForLA(errorCode: error._code)
self.authError(msg: _msg)
}
}
} else {
guard let error = authError else {
return
}
let _msg = self.evaluateAuthenticationPolicyMessageForLA(errorCode: error._code)
self.authError(msg: _msg)
}
}
func evaluatePolicyFailErrorMessageForLA(errorCode: Int) -> String {
var message = ""
if #available(iOS 11.0, macOS 10.13, *) {
switch errorCode {
case LAError.biometryNotAvailable.rawValue:
message = "Nie można przeprowadzić autoryzacji, ponieważ urządzenie nie obsługuje biometrii."
case LAError.biometryLockout.rawValue:
message = "Nie można przeprowadzić autoryzacji, ponieważ autoryzacja nie powiodła się zbyt wiele razy."
case LAError.biometryNotEnrolled.rawValue:
message = "Nie można przeprowadzić autoryzacji, ponieważ biometria nie została skonfigurowana."
default:
message = "Nieznany błąd autoryzacji."
}
} else {
switch errorCode {
case LAError.touchIDLockout.rawValue:
message = "Zbyt wiele nieudanych prób."
case LAError.touchIDNotAvailable.rawValue:
message = "TouchID jest niedostępne na tym urządzeniu."
case LAError.touchIDNotEnrolled.rawValue:
message = "TouchID nie zostało skonfigurowane na tym urządzeniu."
default:
message = "Nieznany błąd TouchID."
}
}
return message;
}
func evaluateAuthenticationPolicyMessageForLA(errorCode: Int) -> String {
var message = ""
switch errorCode {
case LAError.authenticationFailed.rawValue:
message = "Autoryzacja nie powiodła się."
case LAError.appCancel.rawValue:
message = "Autoryzacja została anulowana przez aplikację."
case LAError.invalidContext.rawValue:
message = "Nieprawidłowy kontekst."
case LAError.notInteractive.rawValue:
message = "Not interactive"
case LAError.passcodeNotSet.rawValue:
message = "Passcode nie został skonfigurowany na urządzeniu."
case LAError.systemCancel.rawValue:
message = "Autoryzacja została anulowana przez system."
case LAError.userCancel.rawValue:
message = "Autoryzacja została anulowana przez użytkownika."
case LAError.userFallback.rawValue:
message = "Użytkownik anulował autoryzację."
default:
message = evaluatePolicyFailErrorMessageForLA(errorCode: errorCode)
}
return message
}
}
|
//
// DetailPostVC.swift
// communityApplication
//
// Created by Aravind on 23/03/2021.
//
import UIKit
import Kingfisher
import FirebaseAuth
import FirebaseFirestore
class DetailPostVC: UIViewController {
@IBOutlet weak var solutionTableView: UITableView!
@IBOutlet weak var heightOfSolutionTableView: NSLayoutConstraint!
@IBOutlet weak var postUsrNameLbl: UILabel!
@IBOutlet weak var postTimeLabel: UILabel!
@IBOutlet weak var postTiteLabel: UILabel!
@IBOutlet weak var postQstnLabel: UILabel!
@IBOutlet weak var postImageView: UIImageView!
lazy var presenter = DetailPostPresenter(with: self)
var postData: PostModel?
var userInfo: UserModel?
let db = Firestore.firestore()
var index = 0
override func viewDidLoad() {
super.viewDidLoad()
presenter.getAnswers(postId: postData?.id ?? "")
solutionTableView.delegate = self
solutionTableView.dataSource = self
AppUtil.shared.getUserInfo(uid: postData?.uid ?? "") { user in
self.postUsrNameLbl.text = "By \(user.name ?? "")"
self.navigationController?.title = "Answer By \(user.name ?? "")"
}
postTiteLabel.text = postData?.title
postTimeLabel.text = postData?.createdAt?.numberOfDaysBetween()
postQstnLabel.text = postData?.descriptionTitle
postImageView.isHidden = (postData?.imageUrl ?? "" == "")
postImageView.kf.setImage(with: URL(string: postData?.imageUrl ?? ""))
// Do any additional setup after loading the view.
}
@IBAction func onAddAnswerClick(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let Answervc = storyboard.instantiateViewController(withIdentifier: "AnswerVC") as? AnswerVC else {return}
Answervc.modalPresentationStyle = .popover
Answervc.postId = postData?.id ?? ""
self.present(Answervc, animated: true, completion: nil)
}
}
extension DetailPostVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
index = indexPath.row
self.performSegue(withIdentifier: "goToDetailAnswer", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.destination is DetailAnswerVC {
let vc = segue.destination as? DetailAnswerVC
vc?.answerData = presenter.answerData[index]
vc?.postId = postData?.id
}
}
}
extension DetailPostVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return presenter.answerData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SolutionTableViewCell", for: indexPath) as! SolutionTableViewCell
cell.setData(model: presenter.answerData[indexPath.row])
DispatchQueue.main.async {
self.heightOfSolutionTableView.constant = tableView.contentSize.height
}
return cell
}
}
extension DetailPostVC: DetailPostViewPresenter {
func getAnswerDataSuccessfully() {
solutionTableView.reloadData()
}
}
|
//
// MusicTableViewCell.swift
// SoTube
//
// Created by yoni celen on 29/05/2017.
// Copyright © 2017 NV Met Talent. All rights reserved.
//
import UIKit
class MusicTableViewCell: UITableViewCell {
@IBOutlet weak var itemImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
}
|
import Metal
open class BasicFilter: NSObject, ImageFilter {
public let targets = TargetContainer()
let renderTarget: RenderTargetState
let operationName: String
let textureInputSemaphore = DispatchSemaphore(value: 1)
var previousTexture: Texture?
/// Initialization using shaders in library
public init(context: MIContext = .default, vertexFunctionName: String = MetallicImageLitetals.defaultVertex.rawValue, fragmentFunctionName: String, operationName: String = #file) {
self.operationName = operationName
renderTarget = RenderTargetState(vertexFunctionName: vertexFunctionName, fragmentFunctionName: fragmentFunctionName, context: context)
}
public func newTexture(_ texture: Texture) {
_ = textureInputSemaphore.wait(timeout: DispatchTime.distantFuture)
defer {
textureInputSemaphore.signal()
}
let outputTexture = Texture(orientation: texture.orientation,
width: texture.width,
height: texture.height,
timingType: texture.timingType,
pixelFormat: texture.pixelFormat,
colorSpace: texture.colorSpace)
guard let commandBuffer = renderTarget.context.commandQueue.makeCommandBuffer() else {
print("Warning: \(operationName) Failed to create command buffer")
return
}
commandBuffer.label = operationName
commandBuffer.render(from: texture, to: outputTexture, targetState: renderTarget)
commandBuffer.commit()
textureInputSemaphore.signal()
commandBuffer.waitUntilCompleted()
previousTexture = outputTexture
updateTargets(with: outputTexture)
_ = textureInputSemaphore.wait(timeout: DispatchTime.distantFuture)
}
public func transmitPreviousImage(to target: ImageConsumer, completion: ((Bool) -> Void)? = nil) {
if let texture = previousTexture {
target.newTexture(texture)
completion?(true)
} else {
completion?(false)
}
}
}
|
//
// QuestDescImageAndTextCell.swift
// Carousel
//
// Created by Andrey on 27.04.17.
// Copyright © 2017 Quest. All rights reserved.
//
import UIKit
class QuestDescImageAndTextCell: UITableViewCell {
static var height = 105
@IBOutlet weak var csLeadingLabel: NSLayoutConstraint!
@IBOutlet weak var avaIV: UIImageView!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var containerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
}
func setData(text: String, image: UIImage? = nil) {
if let img = image {
avaIV.isHidden = false
containerView.backgroundColor = AppColors.darkblueAlpha()
infoLabel.textColor = AppColors.whiteAlpha()
infoLabel.font = UIFont(name: AppFonts.RobotoItalic, size: 12)
avaIV.image = img
csLeadingLabel.constant = avaIV.frame.width + 8
containerView.layer.cornerRadius = 5
containerView.clipsToBounds = true
} else {
avaIV.isHidden = true
csLeadingLabel.constant = 8
containerView.backgroundColor = UIColor.clear
infoLabel.font = UIFont(name: AppFonts.RobotoLight, size: 12)
infoLabel.textColor = AppColors.darkblueAlpha()
}
self.layoutIfNeeded()
infoLabel.text = text
}
}
|
//
// KKOutletElement.swift
// KKView
//
// Created by zhanghailong on 2016/11/26.
// Copyright © 2016年 kkserver.cn. All rights reserved.
//
import UIKit
import KKObserver
public extension KKElement {
public func set(outlet:KKOutletElement, prop:KKProperty, name:String, value:Any?) ->Void {
if prop == KKProperty.Data {
var data = get(KKProperty.Data) as? NSMutableDictionary
if data == nil {
data = NSMutableDictionary.init()
}
let key = name.substring(from: name.index(name.startIndex, offsetBy: 5))
if value == nil {
data!.removeObject(forKey: key)
} else {
data![key] = value
}
set(KKProperty.Data,data)
} else {
set(prop, value);
}
}
}
open class KKOutletElement: KKScriptElement {
public static let Done:NSObject = NSObject.init()
private var _fn:KKScriptElementFunction?
public required init(element:KKElement) {
super.init(element:element)
if element is KKOutletElement {
_fn = (element as! KKOutletElement)._fn
}
}
public required init(style: KKStyle) {
super.init(style: style)
}
public required init() {
super.init()
}
override internal func onRunScript(_ runnable:KKScriptElementRunnable) ->Void {
let text = get(KKProperty.Text, defaultValue: "")
if(text != "") {
_fn = runnable.compile(code: text as NSString);
}
}
override internal func onPropertyChanged(_ property:KKProperty,_ value:Any?,_ newValue:Any?) {
if(property == KKProperty.WithObserver) {
let obs = newValue as! KKWithObserver?
if(obs != nil) {
let name = get(KKProperty.Name,defaultValue: "")
let prop = name.hasPrefix("data-") ? KKProperty.Data : KKStyle.get(name)
if prop != nil {
onValueChanged(observer: obs!, changedKeys: [], prop: prop!, name:name, value: obs!.get([]));
obs!.on([], { (obs:KKObserver, changedKeys:[String], weakObject:AnyObject?) in
if(weakObject != nil) {
(weakObject as! KKOutletElement?)!.onValueChanged(observer: obs, changedKeys: changedKeys,prop: prop!, name:name, value: obs.get([]));
}
}, self);
}
}
}
super.onPropertyChanged(property, value, newValue);
}
internal func onValueChanged(observer:KKObserver, changedKeys:[String], prop:KKProperty, name: String, value: Any?) ->Void {
var v = value;
if(_fn != nil) {
let object = NSMutableDictionary.init(capacity: 4)
object["value"] = value
object["element"] = self
object["observer"] = observer
object["changedKeys"] = changedKeys
v = _fn!.invoke(object: object)
}
if(v != nil && v is NSObject && (v as! NSObject) == KKOutletElement.Done) {
} else {
let target = self.value(forKeyPath: get(KKProperty.Target, defaultValue: "parent")) as! KKElement?
if(target != nil) {
target!.set(outlet: self, prop: prop, name: name, value: v);
}
}
}
}
|
//
// define.swift
// tcc
//
// Created by Cayke Prudente on 06/12/16.
// Copyright © 2016 Cayke Prudente. All rights reserved.
//
import Foundation
struct Define {
// plataform description
static let plataform = "swift";
static let timeout = 30;
/*
REQUEST (client sends to server)
READ - {type: "read", request_code: int}
READ TIMESTAMP - {type: "read_timestamp", request_code: int}
WRITE - {type: "write", request_code: int, client_id: int, variable: dict, timestamp: int, data_signature: string}
CLOSE SOCKET - {type: "bye"}
*/
static let type = "type";
static let read = "read";
static let read_timestamp = "read_timestamp";
static let write = "write";
static let variable = "variable";
static let timestamp = "timestamp";
static let data_signature = "data_signature";
static let client_id = "client_id";
static let bye = "bye";
static let request_code = "request_code";
/*
RESPONSE (server sends to client)
BASIC STRUCTURE - {server_id: int, plataform: string, request_code: int, status: string, msg = string, data = dictionary or array}
*/
static let server_id = "server_id";
static let server_plataform = "plataform";
static let status = "status";
static let success = "success";
static let error = "error";
static let msg = "msg";
static let data = "data";
static let variable_updated = "variable_updated";
//errors
static let undefined_type = "undefined_type";
static let unknown_error = "unknown_error";
static let outdated_timestamp = "outdated_timestamp";
static let invalid_signature = "invalid_signature";
/*
DIGITAL SIGN
OBS: The signature is in BASE64 format (to reduce the size)
It is signed: Variable+str(timestamp) -> data_signature
*/
}
|
//
// PlanetList.swift
// StarWarsApp
//
// Created by Gianmarco Cotellessa on 10/08/2019.
// Copyright © 2019 Gianmarco Cotellessa. All rights reserved.
//
import Foundation
struct PlanetList: Decodable {
var count: Int?
var next: String?
var previous: String?
var results: [Planet]?
}
|
//
// Canvas.swift
// spriteMaker
//
// Created by 박찬울 on 2021/03/04.
//
import UIKit
import QuartzCore
import RxSwift
import RxCocoa
class Canvas: UIView {
var drawingVC: DrawingViewController!
var grid: Grid!
var selectedArea: SelectedArea!
var numsOfPixels: Int!
var lengthOfOneSide: CGFloat!
var onePixelLength: CGFloat!
var isTouchesBegan: Bool!
var isTouchesMoved: Bool!
var isTouchesEnded: Bool!
var initTouchPosition: CGPoint!
var moveTouchPosition: CGPoint!
var targetLayerIndex: Int = 0
var activatedDrawing: Bool!
var selectedDrawingMode: String!
var selectedDrawingTool: String!
var isGridHidden: Bool = false
private let canvasColor = BehaviorRelay<UIColor>(value: UIColor.white)
public var canvasColorObservable: Observable<UIColor>
var selectedColor: UIColor {
set {
canvasColor.accept(newValue)
setNeedsDisplay()
}
get { return (canvasColor.value) }
}
let disposeBag = DisposeBag()
// tools
var lineTool: LineTool!
var squareTool: SquareTool!
var eraserTool: EraserTool!
var pencilTool: PencilTool!
var pickerTool: PickerTool!
var selectSquareTool: SelectSquareTool!
var magicTool: MagicTool!
var paintTool: PaintTool!
var photoTool: PhotoTool!
var undoTool: UndoTool!
var handTool: HandTool!
var touchDrawingMode: TouchDrawingMode!
var timeMachineVM: TimeMachineViewModel!
var timerTouchesEnded: Timer?
var canvasRenderer: UIGraphicsImageRenderer!
init(_ lengthOfOneSide: CGFloat, _ numsOfPixels: Int, _ drawingVC: DrawingViewController?) {
self.grid = Grid()
self.selectedDrawingMode = "pen"
self.selectedDrawingTool = CoreData.shared.selectedMainTool
self.activatedDrawing = false
self.lengthOfOneSide = lengthOfOneSide
self.numsOfPixels = numsOfPixels
self.onePixelLength = lengthOfOneSide / CGFloat(numsOfPixels)
self.canvasRenderer = UIGraphicsImageRenderer(
size: CGSize(width: lengthOfOneSide, height: lengthOfOneSide)
)
self.isTouchesBegan = false
self.isTouchesMoved = false
self.isTouchesEnded = false
self.moveTouchPosition = CGPoint()
self.initTouchPosition = CGPoint()
self.drawingVC = drawingVC
self.canvasColorObservable = canvasColor.asObservable()
super.init(
frame: CGRect(x: 0, y: 0, width: self.lengthOfOneSide, height: self.lengthOfOneSide)
)
self.selectedArea = SelectedArea(self)
self.lineTool = LineTool(self)
self.squareTool = SquareTool(self)
self.eraserTool = EraserTool(self)
self.pencilTool = PencilTool(self)
self.pickerTool = PickerTool(self)
self.selectSquareTool = SelectSquareTool(self)
self.magicTool = MagicTool(self)
self.paintTool = PaintTool(self)
self.photoTool = PhotoTool(self)
self.undoTool = UndoTool(self)
self.handTool = HandTool(self)
self.touchDrawingMode = TouchDrawingMode(self)
}
override func layoutSubviews() {
CoreData.shared.paletteIndexObservable
.subscribe { [weak self] _ in
if let color = CoreData.shared.selectedColor?.uicolor {
self?.selectedColor = color
}
self?.setNeedsDisplay()
}.disposed(by: disposeBag)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reload() {
self.setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else { return }
drawLayers(context)
if isTouchesEnded {
switchToolsTouchesEnded(context)
isTouchesEnded = false
isTouchesMoved = false
isTouchesBegan = true
draw(rect)
updateLayerImage(targetLayerIndex)
updateAnimatedPreview()
return
}
switchToolsAlwaysUnderGirdLine(context)
if (!isGridHidden) { drawGridLine(context) }
if (selectedArea.isDrawing) {
selectedArea.drawSelectedAreaOutline(context)
}
if isTouchesMoved {
switchToolsTouchesMoved(context)
isTouchesBegan = false
return
}
if isTouchesBegan {
switchToolsTouchesBeganOnDraw(context)
return
}
switchToolsNoneTouches(context)
}
// layer의 순서대로 image와 grid데이터를 그린다.
func drawLayers(_ context: CGContext) {
let layerImages = drawingVC.layerVM.getVisibleLayerImages()
let selectedLayerIndex = drawingVC.layerVM.selectedLayerIndex
for idx in 0..<layerImages.count {
if (idx != selectedLayerIndex) {
guard let image = layerImages[idx] else { continue }
if (image.size.height == 0 && image.size.width == 0) { continue }
guard let flipedCgImage = flipImageVertically(originalImage: image).cgImage else { continue }
let imageRect = CGRect(x: 0, y: 0, width: self.lengthOfOneSide, height: self.lengthOfOneSide)
context.draw(flipedCgImage, in: imageRect)
} else {
drawGridPixelsInt32(context, grid.data, onePixelLength)
if (selectedArea.isDrawing) {
selectedArea.drawSelectedAreaPixels(context)
}
}
}
}
// 캔버스의 그리드 선을 그린다
func drawGridLine(_ context: CGContext) {
context.setLineWidth(0.5)
context.setStrokeColor(UIColor.init(named: "Color_gridLine")!.cgColor)
for i in 1...Int(numsOfPixels - 1) {
let gridWidth = onePixelLength * CGFloat(i)
context.move(to: CGPoint(x: gridWidth, y: 0))
context.addLine(to: CGPoint(x: gridWidth, y: lengthOfOneSide))
context.move(to: CGPoint(x: 0, y: gridWidth))
context.addLine(to: CGPoint(x: lengthOfOneSide, y: gridWidth))
}
context.strokePath()
}
// 숨겨진 레이어
func alertIsHiddenLayer() {
let alert = UIAlertController(title: "", message: "현재 선택된 레이어가 숨겨진 상태입니다\n해제하시겠습니까?", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: hiddenAlertHandler))
alert.addAction(UIAlertAction(title: "No", style: .destructive, handler: nil))
drawingVC.present(alert, animated: true)
}
func hiddenAlertHandler(_ alert: UIAlertAction) -> Void {
drawingVC.layerVM.toggleVisibilitySelectedLayer()
}
// 터치 시작
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if (drawingVC.layerVM.isHiddenSelectedLayer) {
alertIsHiddenLayer()
} else {
let position = findTouchPosition(touches: touches)
if (activatedDrawing) {
moveTouchPosition = position
} else {
initTouchPosition = position
moveTouchPosition = position
}
switchToolsTouchesBegan(initTouchPosition)
isTouchesBegan = true
timerTouchesEnded?.invalidate()
setNeedsDisplay()
}
}
// 터치 움직임
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let movePosition = findTouchPosition(touches: touches)
if (selectedDrawingMode == "touch") {
moveTouchPosition = CGPoint(
x: movePosition.x - touchDrawingMode.cursorTerm.x,
y: movePosition.y - touchDrawingMode.cursorTerm.y
)
} else {
moveTouchPosition = CGPoint(x: movePosition.x, y: movePosition.y)
}
isTouchesMoved = true
setNeedsDisplay()
}
// 터치 마침
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if isTouchesMoved {
isTouchesEnded = true
}
if (isTouchesBegan && selectedDrawingTool == "Pencil") {
timerTouchesEnded = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false)
{ (Timer) in
self.isTouchesBegan = false
self.setNeedsDisplay()
}
}
updateLayerImage(targetLayerIndex)
updateAnimatedPreview()
self.setNeedsDisplay()
}
// 터치 좌표 초기화
func setCenterTouchPosition() {
let centerOfSide: CGFloat!
centerOfSide = (onePixelLength * 7) + (onePixelLength / 2)
initTouchPosition = CGPoint(x: centerOfSide, y: centerOfSide)
moveTouchPosition = CGPoint(x: centerOfSide, y: centerOfSide)
}
// 보정된 터치 좌표 반환
func findTouchPosition(touches: Set<UITouch>) -> CGPoint {
guard var point = touches.first?.location(in: self) else { return CGPoint() }
point.y = point.y - 5
return point
}
// 터치 좌표를 Grid 좌표로 변환
func transPosition(_ point: CGPoint) -> CGPoint {
let x = Int(point.x / onePixelLength)
let y = Int(point.y / onePixelLength)
return CGPoint(x: x == 16 ? 15 : x, y: y == 16 ? 15 : y)
}
// Grid에서 픽셀 추가
func addPixel(_ pos: CGPoint, _ color: String? = nil) {
guard var hex = selectedColor.hexa else { return }
if (color != nil) { hex = color! }
if (selectedArea.isDrawing) {
if (selectedArea.selectedPixelArrContains(pos)) {
selectedArea.addLocation(hex, pos)
grid.addLocation(hex, pos)
}
} else {
grid.addLocation(hex, pos)
}
}
// Grid에서 픽셀 제거
func removePixel(_ pos: CGPoint) {
if (selectedArea.isDrawing) {
if (selectedArea.selectedPixelArrContains(pos)) {
selectedArea.removeLocation(pos)
grid.removeLocation(pos)
}
} else {
grid.removeLocation(pos)
}
}
// PencilTool의 함수로 픽셀이 선택되는 범위를 확인
func transPositionWithAllowRange(_ point: CGPoint, range: Int) -> CGPoint? {
let pixelSize = Int(onePixelLength)
let x = Int(point.x) % pixelSize
let y = Int(point.y) % pixelSize
if range > pixelSize || range < 0 { return nil }
if checkPixelRange(x, range, pixelSize) && checkPixelRange(y, range, pixelSize) {
return transPosition(point)
}
return nil
}
func checkPixelRange(_ point: Int, _ range: Int, _ pixelSize: Int) -> Bool {
return (range / 2 < point) && (pixelSize - range / 2 > point)
}
}
// LayerVM Methods
extension Canvas {
// canvas를 UIImage로 렌더링
func renderCanvasImage() -> UIImage {
return canvasRenderer.image { context in
drawLayers(context.cgContext)
}
}
func renderLayerImageIntData() -> UIImage {
return canvasRenderer.image { context in
drawGridPixelsInt32(context.cgContext, grid.data, onePixelLength)
if (selectedArea.isDrawing) {
selectedArea.drawSelectedAreaPixels(context.cgContext)
}
}
}
func initViewModelImageIntData() {
guard let viewModel = drawingVC.layerVM else { return }
guard let data = CoreData.shared.selectedAsset.gridData else { return }
if (data.count == 0) {
viewModel.frames = []
viewModel.selectedFrameIndex = 0
viewModel.selectedLayerIndex = 0
viewModel.addEmptyFrame(index: 0)
changeGrid(index: 0, gridData: generateInitGrid())
timeMachineVM.addTime()
} else {
timeMachineVM.timeData = [data]
timeMachineVM.selectedData = [[]]
timeMachineVM.endIndex = 0
timeMachineVM.startIndex = 0
timeMachineVM.setTimeToLayerVMIntData()
}
drawingVC.previewImageToolBar.animatedPreviewVM.initAnimatedPreview()
}
func updateLayerImage(_ layerIndex: Int) {
guard let viewModel = self.drawingVC.layerVM else { return }
let frameIndex = viewModel.selectedFrameIndex
let layerImage = renderLayerImageIntData()
let previewImage = renderCanvasImage()
if (viewModel.isExistedFrameAndLayer(frameIndex, layerIndex)) {
viewModel.updateSelectedLayerAndFrame(previewImage, layerImage, data: grid.data)
}
}
func updateAnimatedPreview() {
if(drawingVC.previewImageToolBar.changeStatusToggle.selectedSegmentIndex == 0) {
self.drawingVC.previewImageToolBar.animatedPreviewVM.changeAnimatedPreview()
} else {
self.drawingVC.previewImageToolBar.animatedPreviewVM.setSelectedFramePreview()
}
}
func changeGrid(index: Int, gridData: [Int]) {
targetLayerIndex = index
grid.data = gridData
updateLayerImage(index)
updateAnimatedPreview()
setNeedsDisplay()
}
}
|
//
// ScreenForm.swift
// TabBarUIActionDemo
//
// Created by Fabrizio Duroni on 25/03/21.
//
import SwiftUI
struct ScreenForm: View {
let title: String
@Binding var text: String
var body: some View {
Form {
Label("Field", systemImage: "pencil")
TextField("field", text: $text)
.multilineTextAlignment(.center)
.accessibility(identifier: self.title.getAccessibilityIdentifier(suffix: "Field"))
}
.padding(0)
.background(Color.clear)
.navigationTitle(title)
}
}
|
//
// VModel.swift
// TG
//
// Created by Andrii Narinian on 9/23/17.
// Copyright © 2017 ROLIQUE. All rights reserved.
//
import Foundation
import SwiftyJSON
enum Link {
case `selff`(link: String), next(link: String)
}
extension FirebaseHelper {
static func save(model: Model) {
guard let currentUserName = AppConfig.currentUserName else { return }
let values = model.encoded
existsForCurrentUser(model: model) { exists in
if !exists {
updateValues(
on: historyReference
.child(currentUserName)
.child(model.type ?? "no_type")
.child(model.id ?? "no_id"),
values: values
)
}
}
}
static func existsForCurrentUser(model: Model, completion: @escaping ( Bool ) -> Void) {
guard let currentUserName = AppConfig.currentUserName else {
completion(false)
return }
historyReference
.child(currentUserName)
.child(model.type ?? "no_type")
.child(model.id ?? "no_id")
.observeSingleEvent(of: .value, with: { snap in
completion(snap.exists())
}, withCancel: { _ in
completion(false)
})
}
}
class VModel {
var id: String?
var type: String?
var attributes: Any?
var relationships: Relationships?
var rels: [VModel] {
var rels = [VModel]()
relationships?.categories?.forEach { rels.append(contentsOf: $0.data ?? [VModel]()) }
return rels
}
init (id: String?,
type: String?,
attributes: Any?,
relationships: Relationships?) {
self.id = id
self.type = type
self.attributes = attributes
self.relationships = relationships
}
required init (json: JSON, included: [VModel]? = nil) {
var jsonModel = [String: JSON]()
if let data = json["data"].dictionary {
jsonModel = data
} else {
jsonModel = json.dictionaryValue
}
self.id = jsonModel["id"]?.string
self.type = jsonModel["type"]?.string
self.attributes = jsonModel["attributes"]
self.relationships = Relationships(json: jsonModel["relationships"] ?? JSON.null, included: included)
}
var encoded: [String: Any?] {
return [:]
}
}
extension VModel {
func update(with model: VModel) {
self.id = model.id
self.type = model.type
self.attributes = model.attributes
self.relationships = model.relationships
}
func parseAttributes() -> [String: Any]? {
guard let json = attributes as? JSON else { return nil }
var output = [String: Any]()
for (key, value) in json.dictionaryValue {
if value.dictionary != nil {
output = parseLayer(json: value, transferData: output)
} else {
output[key] = value.object
}
}
return output
}
private func parseLayer(json: JSON, transferData: [String: Any]) -> [String: Any] {
var output = transferData
for (key, value) in json.dictionaryValue {
if value.dictionary != nil {
output = parseLayer(json: value, transferData: output)
} else {
output[key] = value.object
}
}
return output
}
// static func mapDict(_ dict: [String: Any?], _ sequence: @escaping (String, Any?) -> (String, Any?)) -> [String: Any] {
// var newDict = [String: Any]()
// dict.keys.forEach { key in
// let value: Any? = dict[key] as Any
// let map = sequence(key, value)
// newDict[map.0] = map.1
// }
// return newDict
// }
}
class Category {
var name: String?
var data: [VModel]?
var included: [VModel]?
var links: Links?
init (name: String? = nil, json: JSON, included: [VModel]? = nil) {
self.name = name
self.included = json["included"].arrayValue.map({ VModel(json: $0, included: included) })
if let arrayValue = json["data"].array {
self.data = arrayValue.map({ VModel(json: $0, included: included) })
} else {
self.data = [VModel(json: json["data"], included: included)]
}
if let injectedIncluded = included {
updateData(with: injectedIncluded)
}
if json["links"].dictionary != nil {
self.links = Links(json: json["links"])
}
}
func updateData(with included: [VModel]) {
data?.forEach { storedModel in
if let includedModel = included.filter({ ($0.id == storedModel.id) && ($0.type == storedModel.type) }).first {
storedModel.update(with: includedModel)
}
if storedModel.relationships?.categories?.count ?? 0 > 0 {
storedModel.relationships?.update(with: included)
}
}
}
}
class Links {
var next: String?
var selff: String?
init (json: JSON) {
next = json["next"].string
selff = json["self"].string
}
}
class Relationships {
var categories: [Category]?
init (json: JSON, included: [VModel]? = nil) {
var categories = [Category]()
for (categoryName, dataJSON) in json.dictionaryValue {
categories.append(Category(name: categoryName, json: dataJSON, included: included))
}
self.categories = categories
}
func update(with includes: [VModel]) {
categories?.forEach({ category in
category.updateData(with: includes)
})
}
}
|
//
// PinAnnotation.swift
// TrabalhoFinaliOSAvancado
//
// Created by iossenac on 12/11/16.
// Copyright © 2016 Kassiane Mentz. All rights reserved.
//
import UIKit
import MapKit
class PinAnnotation: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
let station:WeatherStation?
init(station: WeatherStation) {
self.station = station
title = station.station!
coordinate = station.coordinate()!
super.init()
}
}
|
//
// Proctocols.swift
// SDKDemo1
//
// Created by Vishal on 18/06/18.
// Copyright © 2018 CL-macmini-88. All rights reserved.
//
import Foundation
import UIKit
#if canImport(HippoCallClient)
import HippoCallClient
#endif
/*
For counting the number of cases on enum
*/
protocol CaseCountable { }
extension CaseCountable where Self : RawRepresentable, Self.RawValue == Int {
static var count: Int {
var count = 0
while Self(rawValue: count) != nil { count+=1 }
return count
}
static var allValues: [Self] {
return (0..<count).compactMap({ Self(rawValue: $0) })
}
}
public protocol HippoDelegate: class {
func hippoUnreadCount(_ totalCount: Int)
func hippoUserUnreadCount(_ usersCount: [String: Int])
func hippoDeinit()
func hippoDidLoad()
func hippoMessageRecievedWith(response: [String: Any], viewController: UIViewController)
func promotionMessageRecievedWith(response: [String: Any], viewController: UIViewController)
func deepLinkClicked(response : [String : Any])
func hippoUserLogOut()
func startLoading(message: String?)
func stopLoading()
func hippoAgentTotalUnreadCount(_ totalCount: Int)
func hippoAgentTotalChannelsUnreadCount(_ totalCount: Int)
func sendDataIfChatIsAssignedToSelfAgent(_ dic : [String : Any])
func sendp2pUnreadCount(unreadCount : Int, channelId : Int)
func chatListButtonAction()
func passSecurityCheckError(error : String)
#if canImport(HippoCallClient)
func loadCallPresenterView(request: CallPresenterRequest) -> CallPresenter?
#endif
}
extension HippoDelegate {
func sendp2pUnreadCount(unreadCount : Int, channelId : Int){
}
func hippoUnreadCount(_ totalCount: Int) {
}
func hippoUserUnreadCount(_ usersCount: [String: Int]) {
}
func hippoDeinit() {
}
func hippoDidLoad() {
}
func hippoMessageRecievedWith(response: [String: Any], viewController: UIViewController) {
}
func promotionMessageRecievedWith(response: [String: Any], viewController: UIViewController) {
}
}
protocol RetryMessageUploadingDelegate: class {
func retryUploadFor(message: HippoMessage)
func cancelImageUploadFor(message: HippoMessage)
}
protocol DocumentTableViewCellDelegate: class {
func performActionAccordingToStatusOf(message: HippoMessage, inCell cell: DocumentTableViewCell)
}
protocol VideoTableViewCellDelegate: class {
func downloadFileIn(message: HippoMessage)
func openFileIn(message: HippoMessage)
}
|
//
// HomeVC.swift
// Blinked
//
// Created by Fikret Şengül on 16.02.2019.
// Copyright © 2019 zer0-day. All rights reserved.
//
import UIKit
import Firebase
import FAPanels
import ActiveLabel
private let reuseIdentifier = "PostCell"
class HomeVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
// will be removed
func handleCommentTapped(for cell: PostCell) {
print("")
}
// MARK: - Properties
var like: Int?
var posts = [PostModel]()
var post: PostModel?
var viewSinglePost = false
var userProfileController: UserProfileVC?
let refreshControl = UIRefreshControl()
fileprivate var isLoadingPost = false
var messageNotificationView: MessageNotificationView = {
let view = MessageNotificationView()
return view
}()
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
// Configure collection view
collectionView.backgroundColor = UIColor(red: 13, green: 14, blue: 21)
collectionView.contentInset = UIEdgeInsets(top: 7, left: 0, bottom: 0, right: 0)
// Register cell classes
self.collectionView!.register(PostCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Configure refresh control
refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
collectionView?.refreshControl = refreshControl
// Configure nav bar
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Feed", style: .plain, target: self, action: nil)
navigationItem.leftBarButtonItem?.isEnabled = false
self.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "SourceSansPro-Bold", size: 32)!, NSAttributedString.Key.foregroundColor: UIColor.white], for: .disabled)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "navChat"), style: .plain, target: self, action: #selector(handleShowMessages))
// Fetch posts
if !viewSinglePost {
fetchPosts()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set unread messages count
setUnreadMessageCount()
}
// MARK: - UICollectionViewFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 18, left: 0, bottom: 14, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = view.frame.width - 20
let height = API.Helper.calculateTextHeight(width: view.frame.width - 36, font: UIFont(name: "OpenSans", size: 14)!, text: posts[indexPath.item].caption)
return CGSize(width: width, height: height + 112)
}
// MARK - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// Pagination show more posts
if posts.count > 10 {
if indexPath.item == posts.count - 1 {
guard !isLoadingPost else {
return
}
isLoadingPost = true
guard let lastPostTimestamp = self.posts.last?.timestamp else {
isLoadingPost = false
return
}
API.Feed.observeOldFeed(uid: API.User.CURRENT_USER!.uid, timestamp: lastPostTimestamp, limit: 10) { (results) in
if results.count == 0 {
return
}
for result in results {
self.posts.append(result)
}
self.collectionView.reloadData()
self.isLoadingPost = false
}
}
}
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if viewSinglePost {
return 1
} else {
return posts.count
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PostCell
cell.delegate = self
if viewSinglePost {
if let post = self.post {
cell.post = post
}
} else {
cell.post = posts[indexPath.item]
}
//handleHashtagTapped(forCell: cell)
handleUsernameLabelTapped(forCell: cell)
handleMentionTapped(forCell: cell)
return cell
}
// MARK: - FeedCellDelegate
func handleUsernameTapped(for cell: PostCell) {
guard let post = cell.post else { return }
let userProfileVC = UserProfileVC(collectionViewLayout: UICollectionViewFlowLayout())
userProfileVC.user = post.user
navigationController?.pushViewController(userProfileVC, animated: true)
}
func handleOptionsTapped(for cell: PostCell) {
guard let post = cell.post else { return }
if post.ownerUid == Auth.auth().currentUser?.uid {
let alertController = UIAlertController(title: "Options", message: nil, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Delete Post", style: .destructive, handler: { (_) in
post.deletePost()
if !self.viewSinglePost {
self.handleRefresh()
} else {
if let userProfileController = self.userProfileController {
_ = self.navigationController?.popViewController(animated: true)
userProfileController.handleRefresh()
}
}
}))
alertController.addAction(UIAlertAction(title: "Edit Post", style: .default, handler: { (_) in
let uploadPostController = SharePostVC()
let navigationController = UINavigationController(rootViewController: uploadPostController)
uploadPostController.postToEdit = post
uploadPostController.uploadAction = SharePostVC.UploadAction(index: 1)
self.present(navigationController, animated: true, completion: nil)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
func handleLikeTapped(for cell: PostCell, isDoubleTap: Bool) {
guard let post = cell.post else { return }
if(!post.didLike) {
cell.likesLabel.text = String(Int(cell.likesLabel.text!)!+1)
post.didLike = true
post.adjustLikes(addLike: true, completion: { (likes) in
//cell.likesLabel.text = "\(likes)"
})
} else {
cell.likesLabel.text = String(Int(cell.likesLabel.text!)!-1)
post.didLike = false
post.adjustLikes(addLike: false, completion: { (likes) in
//cell.likesLabel.text = "\(likes)"
})
}
}
func handleShowLikes(for cell: PostCell) {
guard let post = cell.post else { return }
guard let postId = post.postId else { return }
let followLikeVC = FollowLikeVC()
followLikeVC.viewingMode = FollowLikeVC.ViewingMode(index: 2)
followLikeVC.postId = postId
navigationController?.pushViewController(followLikeVC, animated: true)
}
func handleConfigureLikeButton(for cell: PostCell) {
guard let post = cell.post else { return }
guard let postId = post.postId else { return }
guard let currentUid = Auth.auth().currentUser?.uid else { return }
USER_LIKES_REF.child(currentUid).observeSingleEvent(of: .value) { (snapshot) in
// check if post id exists in user-like structure
if snapshot.hasChild(postId) {
post.didLike = true
cell.likeButton.isSelected = true
} else {
post.didLike = false
cell.likeButton.isSelected = false
}
}
}
func configureCommentIndicatorView(for cell: PostCell) {
guard let post = cell.post else { return }
guard let postId = post.postId else { return }
COMMENT_REF.child(postId).observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
cell.addCommentIndicatorView(toStackView: cell.stackView)
} else {
cell.commentIndicatorView.isHidden = true
}
}
}
/*func handleCommentTapped(for cell: PostCell) {
guard let post = cell.post else { return }
let commentVC = CommentVC(collectionViewLayout: UICollectionViewFlowLayout())
commentVC.post = post
navigationController?.pushViewController(commentVC, animated: true)
}*/
// MARK: - Handlers
@objc func handleRefresh() {
fetchPosts()
}
func handleMentionTapped(forCell cell: PostCell) {
cell.captionLabel.handleMentionTap { (nickname) in
self.getMentionedUser(withUsername: nickname)
}
}
func handleUsernameLabelTapped(forCell cell: PostCell) {
guard let user = cell.post?.user else { return }
guard let username = user.nickname else { return }
let customType = ActiveType.custom(pattern: "^\(username)\\b")
if API.User.CURRENT_USER!.uid != cell.post?.user?.uid {
cell.captionLabel.handleCustomTap(for: customType) { (_) in
let userProfileController = UserProfileVC(collectionViewLayout: UICollectionViewFlowLayout())
userProfileController.user = user
self.navigationController?.pushViewController(userProfileController, animated: true)
}
}
}
func setUnreadMessageCount() {
if !viewSinglePost {
getUnreadMessageCount { (unreadMessageCount) in
guard unreadMessageCount != 0 else { return }
self.navigationController?.navigationBar.addSubview(self.messageNotificationView)
self.messageNotificationView.anchor(top: self.navigationController?.navigationBar.topAnchor, left: nil, bottom: nil, right: self.navigationController?.navigationBar.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 20, height: 20)
self.messageNotificationView.layer.cornerRadius = 20 / 2
self.messageNotificationView.notificationLabel.text = "\(unreadMessageCount)"
}
}
}
func configureLogoutButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "navChat"), style: .plain, target: self, action: #selector(handleLogout))
}
@objc func handleLogout() {
do {
// Attempt Sign Out
try Auth.auth().signOut()
// Present Welcome controller
let welcomeVC = WelcomeVC()
let navController = UINavigationController(rootViewController: welcomeVC)
self.present(navController, animated: true, completion: nil)
} catch {
// Handle error
print("ERROR")
}
}
// MARK: - API
func setUserFCMToken() {
// Check and update user token
guard let fcmToken = Messaging.messaging().fcmToken else { return }
let values = ["fcmToken": fcmToken]
USER_REF.child(API.User.CURRENT_USER!.uid).updateChildValues(values)
}
func fetchPosts() {
// Fetch posts
var posts = [PostModel]()
isLoadingPost = true
API.Feed.observeRecentFeed(uid: API.User.CURRENT_USER!.uid, timestamp: posts.first?.timestamp, limit: 10) { (results) in
if results.count > 0 {
results.forEach({ (result) in
posts.append(result)
})
}
if self.refreshControl.isRefreshing {
self.refreshControl.endRefreshing()
}
self.isLoadingPost = false
self.collectionView.refreshControl?.endRefreshing()
self.posts = posts
posts.removeAll()
self.collectionView.reloadData()
}
}
func getUnreadMessageCount(withCompletion completion: @escaping(Int) -> ()) {
guard let currentUid = Auth.auth().currentUser?.uid else { return }
var unreadCount = 0
USER_MESSAGES_REF.child(currentUid).observe(.childAdded) { (snapshot) in
let uid = snapshot.key
USER_MESSAGES_REF.child(currentUid).child(uid).observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
MESSAGES_REF.child(messageId).observeSingleEvent(of: .value) { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String, AnyObject> else { return }
let message = MessageModel(dictionary: dictionary)
if message.fromId != currentUid {
if !message.read {
unreadCount += 1
}
}
completion(unreadCount)
}
})
}
}
@objc func handleShowMessages() {
let messagesController = MessagesVC()
self.messageNotificationView.isHidden = true
navigationController?.pushViewController(messagesController, animated: true)
}
}
|
import UIKit
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class AsyncOperation: Operation {
enum State: String {
case ready, executing, finished
fileprivate var keyPath: String {
return "is" + rawValue.capitalized
}
}
var state = State.ready {
willSet {
willChangeValue(forKey: newValue.keyPath)
willChangeValue(forKey: state.keyPath)
}
didSet {
didChangeValue(forKey: oldValue.keyPath)
didChangeValue(forKey: state.keyPath)
}
}
}
extension AsyncOperation {
override var isReady: Bool {
return super.isReady && state == .ready
}
override var isExecuting: Bool {
return state == .executing
}
override var isFinished: Bool {
return state == .finished
}
override var isAsynchronous: Bool {
return true
}
override func start() {
if isCancelled {
state = .finished
return
}
main()
state = .executing
}
override func cancel() {
state = .finished
}
}
public func asyncAdd(lhs: Int, rhs: Int, callback: @escaping (Int) -> ()) {
let addQueue = OperationQueue()
addQueue.addOperation { sleep(1); callback(lhs + rhs) }
}
class SumOperation: AsyncOperation {
let lhs: Int
let rhs: Int
var result: Int?
init(lhs: Int, rhs: Int) {
self.lhs = lhs
self.rhs = rhs
super.init()
}
override func main() {
asyncAdd(lhs: lhs, rhs: rhs) { (result) in
self.result = result
self.state = .finished
}
}
}
let addingTwoIntQueue = OperationQueue()
let input = [(1,2), (1,3), (4,2), (5,2), (5,5), (10,3)]
input.forEach { lhs, rhs in
let operation = SumOperation(lhs: lhs, rhs: rhs)
operation.completionBlock = {
guard let result = operation.result else { return }
print("\(lhs) + \(rhs) = \(result)")
}
addingTwoIntQueue.addOperation(operation)
}
// ----------- ----------- ----------- Load View ----------- ----------- -----------
//------------------------------------------------------------------------------
var view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
var eiffelImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
eiffelImage.backgroundColor = .yellow
eiffelImage.contentMode = .scaleAspectFit
view.addSubview(eiffelImage)
//------------------------------------------------------------------------------
let imageURL = URL(string:"http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg")
let imageString = "http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg"
class ImageLoaderOperation: AsyncOperation {
var url: URL?
var outImage: UIImage?
init(url: URL) {
self.url = url
super.init()
}
override func main() {
if let imageString = url {
asyncImageLoad(urlString: imageString.absoluteString) { [unowned self] (image) in
self.outImage = image
self.state = .finished
}
}
}
}
let operationLoad = ImageLoaderOperation(url: imageURL ?? URL(string:"https://google.com")!)
operationLoad.completionBlock = {
OperationQueue.main.addOperation {
eiffelImage.image = operationLoad.outImage
}
}
let loadQueue = OperationQueue()
loadQueue.addOperation(operationLoad)
loadQueue.waitUntilAllOperationsAreFinished()
sleep(3)
operationLoad.outImage
//PlaygroundPage.current.finishExecution()
|
//
// ContactGroup.swift
// FindMyFriends
//
// Created by Susan Kohler on 2/14/15.
// Copyright (c) 2015 Susan Kohler. All rights reserved.
//
import Foundation
class ContactGroup: NSObject, NSCoding {
var groupName: String
var memberArray:[String]
init(groupName:String){
self.groupName = groupName
self.memberArray = []
super.init()
}
required init(coder decoder: NSCoder) {
self.groupName = decoder.decodeObject(forKey: "groupName")! as! String
self.memberArray = decoder.decodeObject(forKey: "memberArray")!as! Array <String>
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(self.groupName, forKey: "groupName")
coder.encode(self.memberArray, forKey:"memberArray")
}
}
|
/*:
* при присваивании копируется
* живут в стеке
* изменение части = перезапись всей переменной целиком
* не поддерживают наследование
*/
struct Foo {
var property: Int
}
let one = Foo(property: 1)
var two = one
two.property = 2
print(one.property)
print(two.property)
//________________
func changeToFive(foo: inout Foo) {
foo.property = 5
}
var zero = Foo(property: 0)
changeToFive(foo: &zero)
print(zero.property)
|
//
// Client.swift
// Yelnur
//
// Created by Дастан Сабет on 04.04.2018.
// Copyright © 2018 Дастан Сабет. All rights reserved.
//
import Foundation
protocol ClientSettings: Codable {
var phone: String { get set }
var name: String { get set }
var city: Point { get set }
var type: String { get set }
var courier_type: Int? { get set }
var avatar: String? { get set }
var experience: Int? { get set }
var rating: Double? { get set }
var about: String? { get set }
}
class User: ClientSettings {
var phone: String
var name: String
var city: Point
var type: String
var courier_type: Int?
var avatar: String?
var experience: Int?
var rating: Double?
var about: String?
let id: Int
var token: String?
init(phone: String, name: String, city: Point, type: String, about: String?) {
self.phone = phone
self.name = name
self.city = city
self.type = type
self.id = 0
self.token = nil
self.experience = nil
self.rating = nil
self.about = about
self.courier_type = nil
self.avatar = nil
}
init(sender: Data) {
let client = try! JSONDecoder().decode(User.self, from: sender)
print("CLIENT: ", client)
self.id = client.id
self.token = client.token
self.phone = client.phone
self.name = client.name
self.city = client.city
self.type = client.type
self.avatar = client.avatar
self.experience = client.experience
self.rating = client.rating
self.about = client.about
self.courier_type = client.courier_type
UserSettings.shared.saveUser(user: client)
}
init(withoutToken: Data) {
let client = try! JSONDecoder().decode(User.self, from: withoutToken)
print("CLIENT: ", client)
self.id = client.id
self.token = client.token
self.phone = client.phone
self.name = client.name
self.city = client.city
self.type = client.type
self.avatar = client.avatar
self.experience = client.experience
self.rating = client.rating
self.about = client.about
self.courier_type = client.courier_type
UserSettings.shared.saveUserWithoutToken(user: client)
}
}
|
//
// NDBarButtonItem.swift
// NDYingKe_swift4
//
// Created by 李家奇_南湖国旅 on 2017/8/12.
// Copyright © 2017年 NorthDogLi. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
class func creatBarItem(image:String, highImage:String, title:String, tagget:Any, action:Selector) -> UIBarButtonItem {
let button = UIButton.init(type: UIButtonType.custom)
button.setTitle(title, for: UIControlState.normal)
button.setImage(UIImage.init(named: image), for: UIControlState.normal)
button.setImage(UIImage.init(named: highImage), for: UIControlState.highlighted)
button.addTarget(tagget, action: action, for: UIControlEvents.touchUpInside)
button.sizeToFit()
return UIBarButtonItem.init(customView: button)
}
}
|
//
// Created by Jim van Zummeren on 05/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
class ImageAttributedStringBlockBuilder : LayoutBlockBuilder<NSMutableAttributedString> {
//MARK: LayoutBuilder
override func relatedMarkDownItemType() -> MarkDownItem.Type {
return ImageMarkDownItem.self
}
override func build(markDownItem:MarkDownItem, asPartOfConverter converter : MarkDownConverter<NSMutableAttributedString>, styling : ItemStyling) -> NSMutableAttributedString {
let imageMarkDownItem = markDownItem as! ImageMarkDownItem
let attachment = NSTextAttachment()
if let image = UIImage(named: imageMarkDownItem.file) {
attachment.image = image
}
let mutableAttributedString = NSAttributedString(attachment: attachment)
return mutableAttributedString as! NSMutableAttributedString
}
} |
//
// CheckBoxButton.swift
// SwiftCheckBox
//
// Created by Ian-Andoni Magarzo Fernandez on 25/03/2020.
//
import UIKit
public class CheckBoxButton: UIButton {
public var selectedBlock: ((Bool)->())?
public override init(frame: CGRect) {
super.init(frame: frame)
self.frame = frame
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard buttonType == .custom else {
fatalError("Requires to set [Type: Custom] from the storyBoard")
}
commonInit()
}
private func commonInit() {
let appBundle = Bundle(for: Self.self)
let assetsBundleURL = appBundle.bundleURL.appendingPathComponent("SwiftCheckBoxImgs.bundle")
guard let assetsBundle = Bundle(url: assetsBundleURL) else {
fatalError("nil bundle")
}
let unckeckedImg = UIImage(named: "unchecked_checkbox", in: assetsBundle, compatibleWith: nil)
setImage(unckeckedImg, for: .normal)
setTitle("", for: .normal)
let checkedImg = UIImage(podAssetName: "checked_checkbox")
setImage(checkedImg, for: .selected)
setTitle("", for: .selected)
addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
}
@objc private func touchUpInside() {
self.isSelected = !self.isSelected
selectedBlock?(self.isSelected)
}
}
//https://github.com/CocoaPods/CocoaPods/issues/1892
extension UIImage {
convenience init?(podAssetName: String) {
let podBundle = Bundle(for: CheckBoxButton.self)
/// A given class within your Pod framework
guard let url = podBundle.url(forResource: "SwiftCheckBoxImgs",
withExtension: "bundle") else {
return nil
}
self.init(named: podAssetName,
in: Bundle(url: url),
compatibleWith: nil)
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var lotteryWinnings : Int?
// lotteryWinnings = 500
//lotteryWinnings! is the way of unwrapping the value stored in optional named lotteryWinnings
// Strongly not recommended to unwrap the optionals like this in the application
if(lotteryWinnings != nil){
print(lotteryWinnings!)
}
//IF LET SYNTAX
//so if the lotteryWinnings exist, then create a variable with value in lotteryWinnings and execute the code in the condition parantheses
if let winning = lotteryWinnings {
print(winning)
}
//THIS IS THE ONLY WAY THE OPTIONALS SHOULD BE USED
class Car{
var modal: String?
}
var vehicle : Car?
vehicle = Car()
vehicle?.modal = "Chevrolet"
if let v=vehicle{
if let m = v.modal{
print(m)
}
}
// OR
vehicle?.modal = "fiat"
//here it means, if vehicle exists and v.modal exists, then execute this
if let v=vehicle,let m=v.modal{
print(m)
}
var cars : [Car]?
cars = [Car]()
if let carArr = cars, carArr.count>0{
//only execute this code when cars is not nill and carArr.count>0
} else {
cars?.append(Car())
print(cars?.count)
}
class Person{
var age:Int!
func setAge(newAge:Int){
self.age = newAge
}
}
//here ! is similar to declaring optionals....but here we are garanteeing that the variable will definately hold a value at a point of time
//not a good practice...could lead to program crash
class Person2{
private var _age:Int!
var age :Int {
//getter method...method to fetch value internally...could be used for data hiding
if _age==nil{
_age = 15
}
return _age
}
}
class Dog{
var species : String
init(someSpecies:String){
//constructor
species = someSpecies
}
}
var lab = Dog(someSpecies:"black lab");
lab.species
|
// Input.swift
class Input {
let opponentCard: Card
let dealerCards: [Card]
init(opponentCard: Card, dealerCards: [Card]) {
self.opponentCard = opponentCard
self.dealerCards = dealerCards
}
} |
//
// CardsViewController.swift
// Task Sorter
//
// Created by Beau Young on 17/12/2015.
// Copyright © 2015 Beau Young. All rights reserved.
//
import UIKit
class CardsViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var collectionView: UICollectionView!
var transition = QZCircleSegue()
var fibonacciNumbers: [String] = {
return ["?", "0", "1/2", "1", "2", "3", "5", "8", "13", "20", "40", "100", "∞"]
}()
var tshirtSizes: [String] = {
return ["XS", "S", "M", "L", "XL"]
}()
override func viewDidLoad() {
super.viewDidLoad()
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: "segmentChanged:", forControlEvents: .ValueChanged)
// Do any additional setup after loading the view.
}
// MARK: Actions
@IBAction func closeButtonTapped(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
}
func segmentChanged(sender: UISegmentedControl) {
collectionView.reloadData()
}
@IBAction func unwindToMainViewController (sender: UIStoryboardSegue) {
// self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let selection = sender as? UICollectionViewCell {
transition.animationChild = selection
transition.animationColor = UIColor(red: 40.0/255.0, green: 200.0/255.0, blue: 150.0/255.0, alpha: 1.0)
if let label = sender?.viewWithTag(11) as? UILabel {
transition.labelText = label.text
}
let toViewController = segue.destinationViewController as! FullCardViewController
toViewController.title = (selection.viewWithTag(11) as! UILabel).text
self.transition.fromViewController = self
self.transition.toViewController = toViewController
toViewController.transitioningDelegate = transition
}
}
}
extension CardsViewController: UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if segmentedControl.selectedSegmentIndex == 0 {
return tshirtSizes.count
} else {
return fibonacciNumbers.count
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath)
if let label = cell.viewWithTag(11) as? UILabel {
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.font = UIFont.systemFontOfSize(50)
if segmentedControl.selectedSegmentIndex == 0 {
label.text = tshirtSizes[indexPath.row]
} else {
label.text = fibonacciNumbers[indexPath.row]
}
label.adjustsFontSizeToFitWidth = true
}
return cell
}
}
//extension CardsViewController: UICollectionViewDelegate {
// func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// let selection = collectionView.cellForItemAtIndexPath(indexPath)
// performSegueWithIdentifier("fullCardSegue", sender: selection)
// }
//}
|
//
// CXCConstants.swift
// Copycat of xCurrency
//
// Created by AnLuoRidge on 2/27/17.
// Copyright © 2017 里脊. All rights reserved.
//
import UIKit
enum Currency: String {
case AUD = "AUD"
// case BTC = "BTC"
case CAD = "CAD"
case CNH = "CNH"
case CNY = "CNY"
case DKK = "DKK"
case EUR = "EUR"
case FJD = "FJD"
case GBP = "GBP"
case HKD = "HKD"
case INR = "INR"
case JPY = "JPY"
case KES = "KES"
case KPW = "KPW"
case LYD = "LYD"
case MOP = "MOP"
case MWK = "MWK"
case OMR = "OMR"
case PAB = "PAB"
case QAR = "QAR"
case SGD = "SGD"
case TWD = "TWD"
case USD = "USD"
case VND = "VND"
case XAU = "XAU"
case XAG = "XAG"
case YER = "YER"
case ZMW = "ZMW"
}
/*
# Currency display name translations
AED=United Arab Emirates Dirham
AFN=Afghan Afghani
ALL=Albanian Lek
AMD=Armenian Dram
ARS=Argentine Peso
AUD=Australian Dollar
AZN=Azerbaijani Manat
BAM=Bosnia-Herzegovina Convertible Mark
BDT=Bangladeshi Taka
BGN=Bulgarian Lev
BHD=Bahraini Dinar
BOB=Bolivian Boliviano
BRL=Brazilian Real
BYR=Belarusian Ruble
CAD=Canadian Dollar
CHF=Swiss Franc
CLP=Chilean Peso
CNY=Chinese Yuan
COP=Colombian Peso
CZK=Czech Republic Koruna
DJF=Djiboutian Franc
DKK=Danish Krone
DZD=Algerian Dinar
EGP=Egyptian Pound
ETB=Ethiopian Birr
EUR=Euro
GBP=British Pound Sterling
GEL=Georgian Lari
GNF=Guinean Franc
HKD=Hong Kong Dollar
HRK=Croatian Kuna
HUF=Hungarian Forint
IDR=Indonesian Rupiah
ILS=Israeli New Sheqel
INR=Indian Rupee
IQD=Iraqi Dinar
IRR=Iranian Rial
ISK=Icelandic Króna
JOD=Jordanian Dinar
JPY=Japanese Yen
KES=Kenyan Shilling
KGS=Kyrgystani Som
KRW=South Korean Won
KWD=Kuwaiti Dinar
KZT=Kazakhstani Tenge
LBP=Lebanese Pound
LKR=Sri Lankan Rupee
MAD=Moroccan Dirham
MDL=Moldovan Leu
MGA=Malagasy Ariary
MKD=Macedonian Denar
MNT=Mongolian Tugrik
MXN=Mexican Peso
MYR=Malaysian Ringgit
MZN=Mozambican Metical
NOK=Norwegian Krone
NZD=New Zealand Dollar
PAB=Panamanian Balboa
PEN=Peruvian Nuevo Sol
PHP=Philippine Peso
PKR=Pakistani Rupee
PLN=Polish Zloty
QAR=Qatari Rial
RON=Romanian Leu
RSD=Serbian Dinar
RUB=Russian Ruble
SAR=Saudi Riyal
SEK=Swedish Krona
SGD=Singapore Dollar
SYP=Syrian Pound
THB=Thai Baht
TJS=Tajikistani Somoni
TMT=Turkmenistani Manat
TND=Tunisian Dinar
TRY=Turkish Lira
TWD=New Taiwan Dollar
TZS=Tanzanian Shilling
UAH=Ukrainian Hryvnia
USD=US Dollar
UYU=Uruguayan Peso
UZS=Uzbekistan Som
VEF=Venezuelan Bolívar
VND=Vietnamese Dong
XAF=CFA Franc BEAC
XDR=Special Drawing Rights
XOF=CFA Franc BCEAO
YER=Yemeni Rial
ZAR=South African Rand
*/
let fullNameDict = ["AUD":"Australian Dollar",
// "BTC":"Bitcoin",
"CAD":"Canadian Dollar",
"CNH":"RMB Offshore",
"CNY":"Chinese Yuan",
"DKK":"Danish Krone",
"EUR":"Euro",
"FJD":"Fiji Dollar",
"GBP":"British Pound",
"HKD":"Hong Kong Dollar",
"INR":"Indian Rupee",
"JPY":"Japanese Yen",
"KES":"Kenyan Shilling",
"LYD":"Libyan Dinar",
"MOP":"Macau Pataca",
"MWK":"Malawi Kwacha",
"KPW":"North Korean Won",
"OMR":"Omani Rial",
"PAB":"Panama Balboa",
"QAR":"Qatar Rial 暂无数据",
"SGD":"Singapore Dollar",
"TWD":"Taiwan Dollar",
"USD":"United States Dollar",
"VND":"Vietnam Dong",
"XAU":"Gold 暂无数据",
"XAG":"Silver 暂无数据",
"YER":"Yemen Riyal",
"ZMW":"Zambian Kwacha"]
let symbolDict = ["AUD":"$",
// "BTC":"฿",
"CAD":"$",
"CNH":"¥",
"CNY":"¥",
"DKK":"Kr",
"EUR":"€",
"FJD":"$",
"GBP":"£",
"HKD":"$",
"INR":"Rs",
"JPY":"¥",
"KES":"Ksh",
"LYD":"LD",
"MOP":"MOP$",
"MWK":"MK",
"KPW":"W",
"OMR":"OR",// to replace by a strange symbol
"PAB":"B/.",
"QAR":"AR",// to replace by a strange symbol
"SGD":"$",
"TWD":"$",
"USD": "$",
"VND":"VD",// to replace by a strange symbol
"XAG":"Ounce",
"XAU":"Ounce",
"YER":"YR",// replace
"ZMW":"ZK"
]
var currentCurrencyDict:[String:Float] = ["CNY/HKD":1.4,
"CNY/EUR":1/10,
"CNY/USD":1/6,
"CNY/AUD":1/4,
"CNY/JPY":14,
"USD/CNY":6.8665,
"USD/AUD":1.2968,
"USD/USD":1.0,
"USD/EUR":0.8,
"USD/HKD":7.5,
"USD/JPY":113.393]
var commonCurrencies = [CXCCurrencyModel.init(currency: .CNY),
CXCCurrencyModel.init(currency: .USD),
CXCCurrencyModel.init(currency: .JPY),
CXCCurrencyModel.init(currency: .AUD),
]
let preciousCurrencies = [CXCCurrencyModel(currencyEntity: .XAU), CXCCurrencyModel(currencyEntity: .XAG)]
let aCurrencies = [CXCCurrencyModel(currencyEntity: .AUD)]
let bCurrencies = [CXCCurrencyModel(currencyEntity: .GBP)]
let cCurrencies = [CXCCurrencyModel(currencyEntity: .CNY)]
let dCurrencies = [CXCCurrencyModel(currencyEntity: .DKK)]
let eCurrencies = [CXCCurrencyModel(currencyEntity: .EUR)]
let fCurrencies = [CXCCurrencyModel(currencyEntity: .FJD)]
let gCurrencies = [CXCCurrencyModel(currencyEntity: .XAU)]
let hCurrencies = [CXCCurrencyModel(currencyEntity: .HKD)]
let iCurrencies = [CXCCurrencyModel(currencyEntity: .INR)]
let jCurrencies = [CXCCurrencyModel(currencyEntity: .JPY)]
let kCurrencies = [CXCCurrencyModel(currencyEntity: .KES)]
let lCurrencies = [CXCCurrencyModel(currencyEntity: .LYD)]
let mCurrencies = [CXCCurrencyModel(currencyEntity: .MOP), CXCCurrencyModel(currencyEntity: .MWK)]
let nCurrencies = [CXCCurrencyModel(currencyEntity: .KPW)]
let oCurrencies = [CXCCurrencyModel(currencyEntity: .OMR)]
let pCurrencies = [CXCCurrencyModel(currencyEntity: .PAB)]
let qCurrencies = [CXCCurrencyModel(currencyEntity: .QAR)]
let rCurrencies = [CXCCurrencyModel(currencyEntity: .CNH)]
let sCurrencies = [CXCCurrencyModel(currencyEntity: .XAG)]
let tCurrencies = [CXCCurrencyModel(currencyEntity: .TWD)]
let uCurrencies = [CXCCurrencyModel(currencyEntity: .USD)]
let vCurrencies = [CXCCurrencyModel(currencyEntity: .VND)]
let yCurrencies = [CXCCurrencyModel(currencyEntity: .YER)]
let zCurrencies = [CXCCurrencyModel(currencyEntity: .ZMW)]
let allCurrencies = [commonCurrencies,
preciousCurrencies,
aCurrencies,
bCurrencies,
cCurrencies,
dCurrencies,
eCurrencies,
fCurrencies,
gCurrencies,
hCurrencies,
iCurrencies,
jCurrencies,
kCurrencies,
lCurrencies,
mCurrencies,
nCurrencies,
oCurrencies,
pCurrencies,
qCurrencies,
rCurrencies,
sCurrencies,
tCurrencies,
uCurrencies,
vCurrencies,
yCurrencies,
zCurrencies]
var fourVisibleCurrencis = [Currency.CNY, Currency.USD, Currency.EUR, Currency.HKD]
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let xppi = screenWidth / 375.0
let yppi = screenHeight / 667.0
let keyboardHeight: CGFloat = CGFloat(280.0.yppi)
let dateButtonSelectedColor = UIColor(hex: "#29B774")
let dateButtonNormalColor = UIColor(hex: "#99A4BF")
let mainCellRowHeight = (screenHeight - 58.yppi - 280.yppi) / 4
class CXCConstants: NSObject {
}
|
//
// BaseViewController.swift
// Suitmedia
//
// Created by irwan on 10/05/20.
// Copyright © 2020 irwan. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func keyboardshow() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
func hideKeyboardWhenTappedAround() {
let tapGesture = UITapGestureRecognizer(target: self,
action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
}
@objc func hideKeyboard() {
view.endEditing(true)
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
func setDefaultToolbar(dismissTabBar: Selector?){
let image = UIImage(named: "ic_back_white")?.withRenderingMode(.alwaysOriginal)
let leftBarItem = UIBarButtonItem(image: image, style: .plain, target: self, action: dismissTabBar)
self.navigationItem.leftBarButtonItem = leftBarItem
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
self.navigationController?.navigationBar.backgroundColor = UIColor.orange
self.navigationController?.navigationBar.tintColor = UIColor.gray
self.navigationController?.navigationBar.barTintColor = UIColor.orange
self.navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.white
]
}
func showleftMenu(menu1: String, menu2: String) {
let menuBarButtonItem = UIBarButtonItem(image: UIImage(named: menu2), style: .plain, target: self, action: #selector(openMenuController))
let menuBarButtonItem2 = UIBarButtonItem(image: UIImage(named: menu1), style: .plain, target: self, action: #selector(openMenuController))
menuBarButtonItem.tintColor = UIColor.white
menuBarButtonItem2.tintColor = UIColor.white
navigationItem.rightBarButtonItems = [menuBarButtonItem, menuBarButtonItem2]
}
func showAlertAction(title: String, message: String){
hideKeyboard()
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
}))
self.present(alert, animated: true, completion: nil)
}
@objc func openMenuController(){}
}
|
//
// User.swift
// github
//
// Created by Bowyer on 2016/06/18.
// Copyright © 2016年 Bowyer. All rights reserved.
//
struct User {
let name:String
let url:NSURL?
let avatarUrl:NSURL?
}
|
//: Playground - noun: a place where people can play
import Cocoa
/**
* 高级运算符
*/
//位运算符,"~"按位取反,"&"按位与,"|"按位或,"^"按位异或,"<<"按位左移,">>"按位右移
let initiaBits : UInt8 = 0b00001111
let other : UInt8 = 0b11110000
let invertedBits : UInt8 = ~initiaBits
print(invertedBits)
//溢出运算符,swift默认是不允许溢出的,当计算后的数值超过类型所表示的数值范围,会编译报错。当然也可以利用溢出运算符来进行溢出计算,溢出运算都是以"&"开头的。"&+""&-""&*"
/**
* 运算符重载,运算符分为前缀、中缀、后缀运算符。添加关键字"prefix"、"infix"和"postfix"关键字来声明是前缀、中缀或者后缀
*/
struct Verctor2D {
var x = 0.0, y = 0.0
}
func +(left :Verctor2D, right:Verctor2D) -> Verctor2D{
let x = left.x + right.x
let y = left.y + right.y
return Verctor2D(x: x, y: y)
}
prefix func -(verctor:Verctor2D) -> Verctor2D{
return Verctor2D(x: -verctor.x, y: -verctor.y)
}
|
//
// Practice.swift
// PythiaSwift
//
// Created by Louis Ye on 8/17/20.
// Copyright © 2020 Louis Ye. All rights reserved.
//
import SwiftUI
struct Practice: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct Practice_Previews: PreviewProvider {
static var previews: some View {
Practice()
}
}
|
import MarketKit
class MarketTopPlatformsViewModel {
let service: MarketTopPlatformsService
init(service: MarketTopPlatformsService) {
self.service = service
}
func topPlatform(uid: String) -> TopPlatform? {
service.topPlatforms?.first { $0.blockchain.uid == uid }
}
}
|
//
// UILabel+Extension.swift
// 3Dlook
//
// Created by Тимур Кошевой on 27.08.2020.
// Copyright © 2020 homeAssignment. All rights reserved.
//
import UIKit
extension UILabel {
func setTextFromSeconds(_ seconds: Int) {
let minutes = seconds / 60 % 60
let seconds = seconds % 60
self.text = String(format:"%02i:%02i", minutes, seconds)
}
}
|
//
// StepTableViewCell.swift
// Recipe Me
//
// Created by Jora on 10/19/18.
// Copyright © 2018 Jora. All rights reserved.
//
import UIKit
class StepTableViewCell: UITableViewCell {
@IBOutlet weak var stepNumber: UILabel!
@IBOutlet weak var stepImageView: UIImageView!
@IBOutlet weak var stepLabel: UILabel!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
heightConstraint.constant = 0
stepNumber.text = nil
stepImageView.image = nil
stepLabel.text = nil
}
func setImage(image: UIImage?) {
guard image != nil else { return }
heightConstraint.constant = image!.size.height
stepImageView.image = image
}
}
|
//
// ViewController.swift
// 系统设置包
//
// Created by bingoogol on 14/10/6.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nameTf: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
/*
1.观察者:NSNotificationCenter
2.通知对象:self
3.执行方法:valueChanged
4.观察对象:NSUserDefaults(系统偏好)数值变化
*/
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("valueChanged"), name: NSUserDefaultsDidChangeNotification, object: nil)
}
// 在多视图控制器之间来回切换,出现屏幕上时才会执行,通常很少重写此方法
// 如果应用程序已经运行,用户点击图标进入系统,此方法不会执行
override func viewDidAppear(animated: Bool) {
println("viewDidAppear")
}
func valueChanged() {
println("valueChanged")
// 显示用户在设置中输入的文本
// 1>读取【系统偏好】设置中的内容,方法和系统偏好一致
var defaults = NSUserDefaults.standardUserDefaults()
// 2>键值对应的字符串就是Root.plist中的identifier
var str = defaults.stringForKey("name_preference")
nameTf.text = str
}
} |
//
// StockModel.swift
// MasterBeeTestVersion
//
// Created by Shayin Feng on 3/11/17.
// Copyright © 2017 Shayin Feng. All rights reserved.
//
/**
{
"name": "Cabbage braised in stock",
"product_id": 201,
"left_quantity": 20,
"price": 4.99,
"menus": [
{
"id": 30,
"name": "Top",
"locale": "en"
}
],
"images": [
{
"locale": "en",
"image_type": "Menu",
"updated_at": "2017-03-06T15:13:14.796-05:00",
"image_url_original": "http://s3.amazonaws.com/mb-op-prod-r1/production/images/333/image/original/1488831194.jpg?1488831194",
"image_url_xxl": "http://s3.amazonaws.com/mb-op-prod-r1/production/images/333/image/xxl/1488831194.jpg?1488831194",
"image_url_xl": "http://s3.amazonaws.com/mb-op-prod-r1/production/images/333/image/xl/1488831194.jpg?1488831194",
"image_url_l": "http://s3.amazonaws.com/mb-op-prod-r1/production/images/333/image/l/1488831194.jpg?1488831194",
"image_url_m": "http://s3.amazonaws.com/mb-op-prod-r1/production/images/333/image/m/1488831194.jpg?1488831194",
"image_url_s": "http://s3.amazonaws.com/mb-op-prod-r1/production/images/333/image/s/1488831194.jpg?1488831194"
}
],
"temperature": "hot"
}
*/
import UIKit
class StockModel: NSObject {
var dictionary: NSDictionary!
var name: String!
var product_id: Int!
var left_quantity: Int!
var price: Float?
var menus: [MenuModel]?
var images: [StockImageModel]?
var temperature: String?
/** extra vars from UI: table row index */
var rowAt: IndexPath? /* IndexPath for MenuTable */
var indexPathAt: IndexPath? /* IndexPath for ContentTable, it should be an array of IndexPath if a single product has multiple menus */
var countInCart: Int = 0 /* count of orders put in cart */
init(dictionary: NSDictionary) {
self.dictionary = dictionary
if let name = dictionary["name"] as? String {
self.name = name
} else {
self.name = "NO NAME"
print("[StockModel] Error: nil name")
}
if let product_id = dictionary["product_id"] as? Int {
self.product_id = product_id
} else {
self.product_id = -1
print("[StockModel] Error: nil product_id")
}
if let left_quantity = dictionary["left_quantity"] as? Int {
self.left_quantity = left_quantity
} else {
self.left_quantity = 0
print("[StockModel] Error: nil left_quantity")
}
if let price = dictionary["price"] as? Float {
self.price = price
} else {
print("[StockModel] Error: nil price")
}
if let menus = dictionary["menus"] as? NSArray {
var menuArray: [MenuModel] = []
for menu in menus {
menuArray.append(MenuModel(dictionary: menu as! NSDictionary))
}
self.menus = menuArray
} else {
print("[StockModel] Error: nil menus")
}
if let images = dictionary["images"] as? NSArray {
var imageArray: [StockImageModel] = []
for image in images {
imageArray.append(StockImageModel(dictionary: image as! NSDictionary))
}
self.images = imageArray
} else {
print("[StockModel] Error: nil images")
}
if let temperature = dictionary["temperature"] as? String {
self.temperature = temperature
} else {
print("[StockModel] Error: nil temperature")
}
self.countInCart = 0
}
}
|
// Copyright © 2019 Pablo Mateos García. All rights reserved.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var spainBt: UIButton!
override func viewDidAppear(_ animated: Bool) {
let data = UserDefaults.init()
if (data.string(forKey: "name") != nil){
self.performSegue(withIdentifier: "main", sender: self)
}
else{
for e in super.view.subviews{
e.isHidden = false
}
}
}
@IBAction func chooseLanguage(_ sender: UIButton) {
let data = UserDefaults.init()
var esp = false
if(sender.isEqual(spainBt)){
esp = true
}
data.set(esp, forKey: "esp")
}
}
|
//
// PageViewController.swift
// MyQDaily
//
// Created by 石冬冬 on 17/1/21.
// Copyright © 2017年 sdd. All rights reserved.
//
import UIKit
class PageViewController: UIPageViewController {
fileprivate var pageView:CustomPageView?
fileprivate var suspensionView:SuspensionView?
fileprivate var menuView:MenuView?
fileprivate lazy var subViewControllers:NSMutableArray = {
var array = NSMutableArray()
let VC1 = HomeViewController()
let VC2 = HomeLABSViewController()
array.add(VC1)
array.add(VC2)
return array
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let array:[String] = ["NEWS","LABS"]
pageView = CustomPageView()
pageView!.titleArray = array
pageView?.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREENH_HEIGHT)
pageView?.VCArray = subViewControllers
pageView?.fatherVC = self
view.addSubview(pageView!)
setupUI()
}
fileprivate func setupUI() {
suspensionView = SuspensionView()
suspensionView?.frame = CGRect(x: 10, y: SCREENH_HEIGHT - 70, width: 54, height: 54)
suspensionView?.delegate = self
suspensionView?.style = .qDaily
menuView = MenuView()
menuView?.cellBlock = {(methodName:String) -> Void
in
self.suspensionView?.style = .close
let method = NSSelectorFromString(methodName)
self.perform(method)
self.menuView?.removeFromSuperview()
}
menuView?.popupNewsClassificationViewBlock = {()->Void in
self.suspensionView?.style = .homeBack
self.changgeSuspensionViewOffsetX(-SCREEN_WIDTH - 100)
}
menuView?.hideNewsClassificationViewBlock = {()-> Void in
self.menuView?.hideNewsClassificationViewAnimation()
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.changgeSuspensionViewOffsetX(15)
}, completion: { (_) -> Void in
UIView.animate(withDuration: 0.15, animations: { () -> Void in
self.changgeSuspensionViewOffsetX(5)
}, completion: { (_) -> Void in
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.changgeSuspensionViewOffsetX(10)
})
})
})
}
menuView?.frame = view.bounds
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
automaticallyAdjustsScrollViewInsets = false
let window = UIApplication.shared.keyWindow
window!.addSubview(suspensionView!)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
suspensionView?.removeFromSuperview()
}
// 改变悬浮按钮的x值
fileprivate func changgeSuspensionViewOffsetX(_ offsetX: CGFloat) {
var tempFrame = self.suspensionView?.frame
tempFrame?.origin.x = offsetX
self.suspensionView?.frame = tempFrame!
}
func aboutUs() {
print("\(#function)")
}
func newsClassification() {
print("\(#function)")
}
func paogramaCenter() {
print("\(#function)")
}
func curiosityResearch() {
print("\(#function)")
}
func myMessage() {
print("\(#function)")
}
func userCenter() {
let vc = UserCenterViewController()
present(vc, animated: true, completion: nil)
menuView?.hideMenuViewAnimation()
print("\(#function)")
}
func homePage() {
print("\(#function)")
}
}
extension PageViewController:SuspensionViewDelegate
{
// MARK: SuspensionViewDelegate
func popUpMenu() {
let window = UIApplication.shared.keyWindow
window!.insertSubview(menuView!, belowSubview:suspensionView!)
menuView?.popupMunuViewAnimation()
}
func closeMenu() {
menuView?.hideMenuViewAnimation()
}
func backToMenuView() {
suspensionView?.style = .qDaily
menuView?.hideMenuViewAnimation()
}
}
|
//
// ContainerView.swift
// GWDrawEngine
//
// Created by 陈琪 on 2020/6/26.
// Copyright © 2020 Chen. All rights reserved.
//
import UIKit
/** 添加事件通知*/
let GlobalAddEventNotifyKey = "GlobalAddEventNotifyKey"
/** 添加代理通知*/
let GlobalAddDelegateNotifyKey = "GlobalAddDelegateNotifyKey"
/** 添加圆角通知*/
let GlobalAddRadiusLoctionNotifyKey = "GlobalAddRadiusLoctionNotifyKey"
/** 渐变背景通知*/
let GloablGradientcolorsNotifyKey = "GloablGradientcolorsNotifyKey"
protocol ContainerViewDelegate: NSObjectProtocol {
func containerViewClickedByAction(view: UIView, action: ActionEntry)
// Textfield结束编辑
func containerViewTextFieldEndEdit(textfield: GWTextField)
/** 刷新*/
func containerViewHeaderRefreshAction(view: UIView)
func containerViewFooterRefreshAction(view: UIView)
/***********************/
}
class ContainerView: View {
deinit {
// print("******当前节点View被销毁:\(self)*****")
}
weak var delegate: ContainerViewDelegate?
/****************** 包含代理的组件(tableView, collectionView, pickerView)********************/
var tableView: GWTableView?
var pickerView: GWPickerView?
var collectionView: GWCollectionView?
var pageView: GWPageView?
/******************* Others*************************/
// 保存需要添加圆角的View对象
lazy var radiusLoctionViewList: [UIView] = [UIView]()
// 渐变背景对象
lazy var gradientcolorList: [UIView] = [UIView]()
/********************************************/
var rootNode: BaseLayoutElement
var state: [String: Any]? // 当前节点状态
/// 需要设置变量的节点
var variableNodes: [BaseLayoutElement]?
var dynamicVariableNodes: [BaseLayoutElement]?
var lastData: Data?
/******************* init *************************/
// 通过模板初始化容器view, 可设置对应的节点ID
class func viewContainer(templateType: String, nodeIdentify: String?) -> ContainerView? {
// 获取模板节点
guard let node = TemplateManager.shared.createTemplateNodeTreeForType(type: templateType) else {
print("***创建模板类型:\(templateType) 节点为空!***")
return nil
}
if let identify = nodeIdentify {
node.id = identify
}
return ContainerView.init(rootNode: node)
}
init(rootNode: BaseLayoutElement) {
self.rootNode = rootNode
super.init(frame: CGRect())
self.state = rootNode.state
/**** 监听通知***/
// 添加事件
NotificationCenter.default.addObserver(self, selector: #selector(addEventNotify(notify:)), name: NSNotification.Name(rawValue: GlobalAddEventNotifyKey), object: nil)
// 添加代理
NotificationCenter.default.addObserver(self, selector: #selector(addDelegateNotify(notify:)), name: NSNotification.Name(rawValue: GlobalAddDelegateNotifyKey), object: nil)
// 添加多方位圆角
NotificationCenter.default.addObserver(self, selector: #selector(addRadiusLoctionNotify(notify:)), name: NSNotification.Name(rawValue: GlobalAddRadiusLoctionNotifyKey), object: nil)
// 渐变
NotificationCenter.default.addObserver(self, selector: #selector(addGradientcolorsNotify(notify:)), name: NSNotification.Name(rawValue: GloablGradientcolorsNotifyKey), object: nil)
/**************/
// 获取变量属性
self.variableNodes = rootNode.getVariableNodes()
self.dynamicVariableNodes = rootNode.getDynamicVariableNodes()
// 绘制节点
let _ = DrawEngineHelper.drawViewFromDataSource(rootNode, parent: self)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/********************************************/
override func draw(_ rect: CGRect) {
super.draw(rect)
// for view in radiusLoctionViewList {
// DrawComponentsUtils.drawRadiusLoction(view: view)
// }
// radiusLoctionViewList.removeAll()
// for view in gradientcolorList {
// // 渐变背景
// if let gradientcolors = view.node?.backgroudGradientColors {
// if let type = view.node?.gradientType {
// view.setGradientColor(colors: gradientcolors, gradientType: type)
// }
// }
// }
// gradientcolorList.removeAll()
}
/// 更新数据及显示布局
/// - Parameter data: 需要更新的参数
func update(data: Data?) {
updateData(data: data)
// 更新TableView关联表达数据
if self.tableView != nil {
self.tableView?.updateTableViewDataSource(originData: data)
self.tableView?.updateDynamicTableViewDataSource(orginData: data)
}
// 更新CollectionView关联变量数据
if self.collectionView != nil {
self.collectionView?.updateDynamicCollectionViewDataSource(orginData: data)
}
if self.pageView != nil {
self.pageView?.updateDynamicPageViewDataSource(orginData: data)
}
// 更新布局
updateLayOut()
}
/// 更新数据
/// - Parameter data: 需要更新的参数
func updateData(data: Data?) {
if let data = data, self.lastData != data {
self.lastData = data
var newVariableNodes = [BaseLayoutElement]()
for index in 0..<(variableNodes ?? []).count {
if let node = variableNodes?[index] {
// 通过可设置变量节点,获取设置属性key 从Data取值刷新
for (property, path) in node.expressionSetters {
if let value = OYUtils.getValueFromJsonData(data: data, path: path) {
// 设置节点属性动态值
node.updateNodePropertyValue(propertyName: property, value: value)
}
}
newVariableNodes.append(node)
}
}
self.variableNodes = newVariableNodes
for index in 0..<(dynamicVariableNodes ?? []).count {
if let node = dynamicVariableNodes?[index] {
if let viewState = (try? JSON.init(data: data))?.dictionaryObject {
// 更新动态节点
NotificationCenter.default.post(name: NSNotification.Name(rawValue: SignNodeStateChangeNotifyKey), object: (node,viewState))
}
}
}
}
}
/// 更新布局
func updateLayOut() {
DrawDataEnginHelper.updateContainerView(rootView: self, variableNodes: self.variableNodes ?? [])
}
}
extension ContainerView {
@objc func actionHandler(_ tap: UITapGestureRecognizer) {
if let reponseView = tap.view, let action = reponseView.actionEntry {
print("***** \(reponseView.actionEntry?.actionType ?? "方法名不存在") params: \(String(describing: reponseView.actionEntry?.params))****")
self.delegate?.containerViewClickedByAction(view: reponseView, action: action)
}
}
}
// MARK: 添加响应事件
extension ContainerView {
@objc func addEventNotify(notify: Notification) {
if let view = notify.object as? UIView {
let tap = UITapGestureRecognizer.init(target: self, action: #selector(actionHandler(_:)))
view.tapGesture = tap
view.addGestureRecognizer(tap)
}
}
@objc func addDelegateNotify(notify: Notification) {
if let tableV = notify.object as? GWTableView {
self.tableView = tableV
self.tableView?.gwDelegate = self
} else if let textF = notify.object as? GWTextField {
textF.gwDelegate = self
} else if let pickV = notify.object as? GWPickerView {
self.pickerView = pickV
} else if let collectionV = notify.object as? GWCollectionView {
self.collectionView = collectionV
self.collectionView?.gwDelegate = self
} else if let pageV = notify.object as? GWPageView {
self.pageView = pageV
pageV.gwDelegate = self
}
}
// 圆角
@objc func addRadiusLoctionNotify(notify: Notification) {
if let view = notify.object as? UIView {
// 添加到需要绘制圆角的数组, 在界面渲染时候调用绘制圆角
radiusLoctionViewList.append(view)
}
}
// 渐变背景
@objc func addGradientcolorsNotify(notify: Notification) {
if let view = notify.object as? UIView {
// 添加到需要绘制圆角的数组, 在界面渲染时候调用绘制圆角
gradientcolorList.append(view)
}
}
}
|
//
// SearchView.swift
// Anime
//
// Created by Usha Natarajan on 8/1/21.
//
import SwiftUI
/**
Search view
*/
struct SearchView: View {
@Binding var searchText: String
@State var size: CGSize
@State var text = ""
@Binding var isEditing: Bool
struct Constants {
static let radius: CGFloat = 10
static let lineWidth: CGFloat = 0.25
static let height: CGFloat = 4.0
}
var body: some View {
TextField("Search ⏎", text: $text, onCommit: { // The search field
self.isEditing = false
self.searchText = text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
})
.onAppear { // to detect when keyboard is shown to add a blur to search results
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { _ in
self.isEditing = true
}
}
.padding(.vertical)
.frame(width: size.width / 2, height: Constants.height)
.padding()
.cornerRadius(Constants.radius)
.disableAutocorrection(true)
.overlay( // Frame for search bar
RoundedRectangle(cornerRadius: Constants.radius)
.stroke(Color.gray, lineWidth: Constants.lineWidth)
)
}
}
|
//
// SettingsBuilder.swift
// MyLeaderboard
//
// Created by Joseph Roque on 2019-08-22.
// Copyright © 2019 Joseph Roque. All rights reserved.
//
import UIKit
import FunctionalTableData
protocol SettingsActionable: AnyObject {
func changePreferredPlayer()
func changePreferredOpponents()
func changeBoard()
func viewSource()
func viewLicenses()
func viewContributors()
func nextInterfaceStyle()
}
enum SettingsBuilder {
static func sections(
currentBoard: BoardDetailsFragment?,
preferredPlayer: PlayerListItem?,
preferredOpponents: [PlayerListItem],
interfaceStyle: UIUserInterfaceStyle,
actionable: SettingsActionable
) -> [TableSection] {
return [
boardSection(currentBoard: currentBoard, actionable: actionable),
playerSection(preferredPlayer: preferredPlayer, actionable: actionable),
opponentsSection(preferredOpponents: preferredOpponents, actionable: actionable),
settingsSection(interfaceStyle: interfaceStyle, actionable: actionable),
aboutSection(actionable: actionable),
]
}
private static func boardSection(
currentBoard: BoardDetailsFragment?,
actionable: SettingsActionable
) -> TableSection {
var rows: [CellConfigType] = []
if let currentBoard = currentBoard {
let labelState = LabelState(
text: .plain("Current board:"),
textColor: .textSecondary,
size: Metrics.Text.body
)
let boardState = LabelState(
text: .plain(currentBoard.boardName),
textColor: .text,
size: Metrics.Text.body
)
rows.append(contentsOf: [
Cells.header(key: "Header", title: "Board"),
CombinedCell<UILabel, LabelState, UILabel, LabelState, LayoutMarginsTableItemLayout>(
key: "current-board",
style: CellStyle(highlight: true, accessoryType: .disclosureIndicator),
actions: CellActions(selectionAction: { [weak actionable] _ in
actionable?.changeBoard()
return .deselected
}),
state: CombinedState(state1: labelState, state2: boardState),
cellUpdater: { view, state in
if state == nil {
view.view1.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.stackView.spacing = 0
} else {
view.view1.setContentHuggingPriority(.required, for: .horizontal)
view.stackView.spacing = Metrics.Spacing.small
}
CombinedState<LabelState, LabelState>.updateView(view, state: state)
}
),
])
}
return TableSection(key: "CurrentBoard", rows: rows)
}
private static func playerSection(
preferredPlayer: PlayerListItem?,
actionable: SettingsActionable
) -> TableSection {
let rows: [CellConfigType] = [
Cells.header(key: "Header", title: "Preferred Player"),
PlayerListItemCell(
key: "Player",
style: CellStyle(highlight: true, accessoryType: .disclosureIndicator),
actions: CellActions(selectionAction: { [weak actionable] _ in
actionable?.changePreferredPlayer()
return .deselected
}),
state: PlayerListItemState(
displayName: preferredPlayer?.displayName ?? "No player selected",
username: preferredPlayer?.username ?? "Tap to choose...",
avatar: preferredPlayer.qualifiedAvatar
),
cellUpdater: PlayerListItemState.updateView
),
]
return TableSection(key: "PreferredPlayer", rows: rows)
}
private static func opponentsSection(
preferredOpponents: [PlayerListItem],
actionable: SettingsActionable
) -> TableSection {
var rows: [CellConfigType] = [
Cells.header(key: "Header", title: "Opponents in Widget"),
]
rows.append(contentsOf: preferredOpponents.map {
return PlayerListItemCell(
key: "Opponent-\($0.id)",
state: PlayerListItemState(
displayName: $0.displayName,
username: $0.username,
avatar: $0.qualifiedAvatar
),
cellUpdater: PlayerListItemState.updateView
)
})
rows.append(Cells.label(
key: "ChangeOpponents",
text: preferredOpponents.count == 0 ? "Add opponents" : "Change opponents",
onAction: { [weak actionable] in
actionable?.changePreferredOpponents()
}
))
return TableSection(key: "PreferredOpponents", rows: rows)
}
private static func settingsSection(
interfaceStyle: UIUserInterfaceStyle,
actionable: SettingsActionable
) -> TableSection {
let rows: [CellConfigType] = [
Cells.header(key: "Header", title: "Settings"),
Cells.toggle(
key: "InterfaceStyle",
text: "Override interface style",
option: interfaceStyle.stringValue
) { [weak actionable] in
actionable?.nextInterfaceStyle()
},
]
return TableSection(key: "Settings", rows: rows)
}
private static func aboutSection(actionable: SettingsActionable) -> TableSection {
let rows: [CellConfigType] = [
Cells.header(key: "Header", title: "About"),
Cells.label(key: "Source", text: "View source") { [weak actionable] in
actionable?.viewSource()
},
Cells.label(key: "Licenses", text: "Licenses") { [weak actionable] in
actionable?.viewLicenses()
},
Cells.label(key: "Contributors", text: "Contributors") { [weak actionable] in
actionable?.viewContributors()
},
LabelCell(
key: "AppInfo-Name",
state: LabelState(
text: .attributed(NSAttributedString(string: "MyLeaderboard", textColor: .textSecondary)),
alignment: .right,
size: Metrics.Text.caption
),
cellUpdater: LabelState.updateView
),
LabelCell(
key: "AppInfo-Version",
state: LabelState(
text: .attributed(NSAttributedString(string: "iOS v\(appVersion())", textColor: .textSecondary)),
alignment: .right,
size: Metrics.Text.caption
),
cellUpdater: LabelState.updateView
),
]
return TableSection(key: "About", rows: rows)
}
private static func appVersion() -> String {
let dictionary = Bundle.main.infoDictionary!
let version = dictionary["CFBundleShortVersionString"] as? String
return version ?? ""
}
private enum Cells {
static func header(key: String, title: String) -> CellConfigType {
return LabelCell(
key: key,
style: CellStyle(backgroundColor: .primaryLight),
state: LabelState(
text: .attributed(NSAttributedString(string: title, textColor: .text)),
size: Metrics.Text.title
),
cellUpdater: LabelState.updateView
)
}
static func label(key: String, text: String, onAction: @escaping () -> Void) -> CellConfigType {
return LabelCell(
key: key,
style: CellStyle(highlight: true, accessoryType: .disclosureIndicator),
actions: CellActions(selectionAction: { _ in
onAction()
return .deselected
}),
state: LabelState(
text: .attributed(NSAttributedString(string: text, textColor: .text)),
size: Metrics.Text.body
),
cellUpdater: LabelState.updateView
)
}
static func toggle(
key: String,
text: String,
option: String,
onAction: @escaping () -> Void
) -> CellConfigType {
return CombinedCell<UILabel, LabelState, UILabel, LabelState, LayoutMarginsTableItemLayout>(
key: key,
style: CellStyle(highlight: true),
actions: CellActions(selectionAction: { _ in
onAction()
return .deselected
}),
state: CombinedState(
state1: LabelState(
text: .attributed(NSAttributedString(string: text, textColor: .text)),
size: Metrics.Text.body
),
state2: LabelState(
text: .attributed(NSAttributedString(string: option, textColor: .text)),
size: Metrics.Text.body
)
),
cellUpdater: CombinedState<LabelState, LabelState>.updateView
)
}
}
}
|
//
// PlacemarkTableViewCell.swift
// WunderTest
//
// Created by Danijel Kecman on 11/12/18.
// Copyright © 2018 Danijel Kecman. All rights reserved.
//
import UIKit
import Reusable
class PlacemarkTableViewCell: UITableViewCell, NibReusable {
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var coordinatesLabel: UILabel!
@IBOutlet weak var engineTypeLabel: UILabel!
@IBOutlet weak var exteriorLabel: UILabel!
@IBOutlet weak var fuelLabel: UILabel!
@IBOutlet weak var interiorLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var vinLabel: UILabel!
func configure(with item: PlacemarkCellItem) {
addressLabel.text = "Address: \(item.address)"
coordinatesLabel.text = "Coordinates: \(item.coordinates.map({"\($0)"}).joined(separator: ","))"
engineTypeLabel.text = "Engine type: \(item.engineType)"
exteriorLabel.text = "Exterior: \(item.exterior)"
fuelLabel.text = "Fuel: \(item.fuel)"
interiorLabel.text = "Interior: \(item.interior)"
nameLabel.text = "Name: \(item.name)"
vinLabel.text = "VIN: \(item.vin)"
}
}
|
//
// AppViewController.swift
// Book Phui
//
// Created by Thanh Tran on 3/11/17.
// Copyright © 2017 Half Bird. All rights reserved.
//
import UIKit
import SideMenu
class AppViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
self.configSideMenu()
}
func configSideMenu() {
// Enable gestures. The left and/or right menus must be set up above for these to work.
// Note that these continue to work on the Navigation Controller independent of the view controller it displays!
SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar)
SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view)
}
}
|
import Flutter
import UIKit
public class SwiftGreetingsPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "greetings", binaryMessenger: registrar.messenger())
let instance = SwiftGreetingsPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getPlatformVersion":
result("iOS " + UIDevice.current.systemVersion)
case "getDefaultGreeting":
result("Welcome iOS user")
case "getDefaultGreetingForUser":
guard let args = call.arguments as? [String: Any], let name = args["name"] as? String else {
//If no arguments then retuen the default
result("Welcome iOS user")
return
}
result("Welcome iOS user \(name)")
default:
result(FlutterMethodNotImplemented)
}
}
}
|
//
// PrimaryKeyColumnProtocol.swift
// RepoDB
//
// Created by Groot on 11.09.2020.
// Copyright © 2020 K. All rights reserved.
//
import GRDB
public protocol PrimaryKeyColumnProtocol: TableColumnProtocol {
var autoincremented: Bool { get set }
func save(to container: inout PersistenceContainer, wiht key: String)
}
|
//
// Playing.swift
// EscapeGame
//
// Created by MrChen on 2019/4/6.
// Copyright © 2019 MrChen. All rights reserved.
//
import UIKit
import GameplayKit
class Playing: GKState {
unowned let scene: GameScene
init(scene: SKScene) {
self.scene = scene as! GameScene
super.init()
}
// 游戏开始
override func didEnter(from previousState: GKState?) {
if previousState is WaitingForTap {
// 给小球添加一个随机方向的力
let ball: SKSpriteNode = scene.childNode(withName: BallCategoryName) as! SKSpriteNode
// ball.physicsBody!.applyImpulse(CGVector(dx: randomDirection() * BallImpulse, dy: randomDirection()))
ball.physicsBody?.velocity = CGVector(dx: 117.0, dy: -117.0)
}
}
// playing状态下 每一帧调用一个
override func update(deltaTime seconds: TimeInterval) {
// 获取小球节点
let ball = scene.childNode(withName: BallCategoryName) as! SKSpriteNode
// 设置一个最大速度
let maxSpeed: CGFloat = 400.0
// 计算速度
let xSpeed = sqrt(ball.physicsBody!.velocity.dx * ball.physicsBody!.velocity.dx)
let ySpeed = sqrt(ball.physicsBody!.velocity.dy * ball.physicsBody!.velocity.dy)
let speed = sqrt(ball.physicsBody!.velocity.dx * ball.physicsBody!.velocity.dx + ball.physicsBody!.velocity.dy * ball.physicsBody!.velocity.dy)
if xSpeed <= 10.0 {
ball.physicsBody!.applyImpulse(CGVector(dx: randomDirection(), dy: 0.0))
}
if ySpeed <= 10.0 {
ball.physicsBody!.applyImpulse(CGVector(dx: 0.0, dy: randomDirection()))
}
// 如果小球速度过大 给一个阻尼 降低速度
if speed > maxSpeed {
ball.physicsBody!.linearDamping = 0.4
}
else {
ball.physicsBody!.linearDamping = 0.0
}
}
// 游戏开始 给小球一个随机方向
func randomDirection() -> CGFloat {
let speedFactor: CGFloat = 1.0
if randomFloat(from: 0.0, to: 100.0) >= 50 {
return -speedFactor
} else {
return speedFactor
}
}
// 产生一个随机数让开始的时候小球有一个随机方向
func randomFloat(from: CGFloat, to: CGFloat) -> CGFloat {
let rand: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF)
return (rand) * (to - from) + from
}
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is GameOver.Type || stateClass is Pause.Type
}
}
|
import Inputs
import XCTest
final class CLITests: XCTestCase {
func testYearInitialiserValidYear() {
let cliYears = ["21"].map(CLI.Year.init(rawValue:))
XCTAssertEqual(cliYears, [.y21])
}
func testYearInitialiserInvalid() {
XCTAssertNil(CLI.Year(rawValue: "10"))
}
func testProblemInitialiserValidDay() {
let cliProblems = (1..<26).compactMap(CLI.Problem.init(rawValue:))
XCTAssertEqual(cliProblems, CLI.Problem.allCases)
}
func testProblemInitialiserInvalid() {
XCTAssertNil(CLI.Problem.init(rawValue:0))
}
}
|
//
// SwiftLoopView.swift
// SwiftLoopView
//
// Created by Lanvige Jiang on 4/22/15.
// Copyright (c) 2015 Lanvige Jiang. All rights reserved.
//
import UIKit
public class SwiftLoopModelBase {
public init() { }
}
public class SwiftBaseCollectionCell: UICollectionViewCell {
public var model: SwiftLoopModelBase
public init(frame: CGRect, model: SwiftLoopModelBase) {
self.model = model
super.init(frame: frame)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public class SwiftLoopView: UIView {
// MARK: Properties
private var placeholder: UIImage?
private let kCellIdentifier = "ReuseCellIdentifier"
public var models: [SwiftLoopModelBase]?
public let greetingPrinter: () -> () = {}
// public override init(frame: CGRect) {
// super.init(frame: frame)
// }
public init(frame: CGRect, models: [SwiftLoopModelBase]) {
super.init(frame: frame)
self.models = models
// self.collectionView.reloadData()
self.addSubview(self.collectionView)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - LAZY
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: self.frame, collectionViewLayout: self.collectionLayout)
collectionView.backgroundColor = UIColor.lightTextColor()
collectionView.pagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: self.kCellIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.scrollEnabled = true
return collectionView
}()
private lazy var collectionLayout: UICollectionViewLayout = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.bounds.size
layout.minimumLineSpacing = 0
layout.scrollDirection = .Horizontal
return layout
}()
// private lazy var defaultCollectionCell: SwiftBaseCollectionCell = {
// let cell = SwiftBaseCollectionCell()
//
// return cell
// }()
// MARK: - UIView
public override func layoutSubviews() {
//
}
}
extension SwiftLoopView: UICollectionViewDataSource {
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let modelsValue = self.models {
return modelsValue.count * 50
}
return 0
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.kCellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
var count = 0
if let modelValue = self.models {
count = modelValue.count
}
var a = indexPath.row % count
switch (a) {
case 0:
cell.backgroundColor = UIColor.redColor()
case 1:
cell.backgroundColor = UIColor.blackColor()
case 2:
cell.backgroundColor = UIColor.greenColor()
default:
cell.backgroundColor = UIColor.blueColor()
}
return cell
}
}
extension SwiftLoopView: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//
}
}
extension SwiftLoopView: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
//
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
//
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//
}
} |
//
// BaseObject.swift
// WhatDidILike
//
// Created by Christopher G Prince on 9/30/17.
// Copyright © 2017 Spastic Muffin, LLC. All rights reserved.
//
//
import Foundation
import CoreData
import SMCoreLib
@objc(BaseObject)
public class BaseObject: NSManagedObject {
// Superclass *must* override
class func entityName() -> String {
assert(false)
return ""
}
class func newObject() -> NSManagedObject {
let newObj = CoreData.sessionNamed(CoreDataExtras.sessionName).newObject(withEntityName: entityName()) as! BaseObject
newObj.creationDate = NSDate()
newObj.userName = Parameters.userName.stringValue
return newObj
}
// See also https://stackoverflow.com/questions/5813309/get-modification-date-for-nsmanagedobject-in-core-data
override public func willSave() {
super.willSave()
if !isDeleted && changedValues()["modificationDate"] == nil {
modificationDate = NSDate()
}
}
}
extension BaseObject: Recommendations {
@objc var dates: [Date] {
return [creationDate as Date?, modificationDate as Date?].compactMap{$0}
}
}
|
public struct UIElementIdentifier {
public var id: String
public var type: ElementType
public init(id: String, type: ElementType) {
self.id = id
self.type = type
}
}
|
//
// DataDisplay.swift
// etdstats
//
// Created by Qiwei Li on 8/31/21.
//
import SwiftUI
struct DataDisplay: View {
let data: String;
let description: String;
let unit: String;
var body: some View {
HStack{
Text("\(data)")
.font(.title2)
Divider()
VStack{
Text("\(description)\n\(unit)")
.font(.title2)
}
}
.padding()
.frame(maxWidth: .infinity, maxHeight: 100)
.background(Color.gray.opacity(0.3))
.cornerRadius(10)
}
}
struct DataDisplay_Previews: PreviewProvider {
static var previews: some View {
DataDisplay(data: "7.83", description: "Block Time", unit: "s")
}
}
|
import Foundation
public final class RequestBuilderImpl: RequestBuilder {
private let commonHeadersProvider: CommonHeadersProvider
// MARK: - Init
public convenience init() {
self.init(commonHeadersProvider: CommonHeadersProviderImpl())
}
public init(commonHeadersProvider: CommonHeadersProvider) {
self.commonHeadersProvider = commonHeadersProvider
}
// MARK: - ApiRequest
public func buildUrlRequest<R: ApiRequest>(from request: R)
-> DataResult<URLRequest, RequestError<R.ErrorResponse>> {
switch buildRequestData(from: request) {
case .error(let error):
return .error(error)
case .data(let requestData):
return URLRequest(url: requestData.url)
.appendUrlRequestCommonProperties(
from: request,
headers: requestData.headers
)
.appendUrlRequestParameters(
from: request,
url: requestData.url
)
}
}
public func buildUploadRequest<R: UploadMultipartFormDataRequest>(from request: R)
-> DataResult<R, RequestError<R.ErrorResponse>> {
switch buildRequestData(from: request) {
case .error(let error):
return .error(error)
case .data(let result):
var request = request
request.url = result.url.absoluteString
request.headers = result.headers
return .data(request)
}
}
// MARK: - Private
private func buildRequestData<R: ApiRequest>(from request: R)
-> DataResult<RequestData, RequestError<R.ErrorResponse>> {
guard let url = buildUrl(from: request) else {
return .error(.apiClientError(.cantBuildUrl(.cantInitializeUrl)))
}
var headers = [HttpHeader]()
headers.append(contentsOf: commonHeadersProvider.headersForRequest(request: request))
headers.append(contentsOf: request.headers)
return .data(
RequestData(
url: url,
headers: headers
)
)
}
private func buildUrl<T: ApiRequest>(from request: T) -> URL? {
let baseURL = URL(string: request.basePath)
var pathComponents = [String]()
pathComponents.append(request.path)
let normalizedQueryPath = pathComponents.joined(separator: "/").normalizedQueryPath()
return URL(string: normalizedQueryPath, relativeTo: baseURL)
}
}
private struct RequestData {
let url: URL
let headers: [HttpHeader]
}
private extension URLRequest {
func appendUrlRequestCommonProperties<R: ApiRequest>(
from request: R,
headers: [HttpHeader])
-> URLRequest {
var urlRequest = self
urlRequest.appendHttpHeaders(headers)
urlRequest.httpMethod = request.method.value
urlRequest.cachePolicy = request.cachePolicy.toNSURLRequestCachePolicy
return urlRequest
}
func appendUrlRequestParameters<R: ApiRequest>(
from request: R,
url: URL)
-> DataResult<URLRequest, RequestError<R.ErrorResponse>> {
var urlRequest = self
var parameters = [String: Any]()
appendFlatternedParameters(¶meters, fromTreeParameters: request.params, keyPrefix: nil)
let shouldSendParametersInUrl = request.method == .get || request.method == .head
if shouldSendParametersInUrl {
let queryString = encodedSortedByKeyStringFrom(dictionary: request.params)
let postfix = queryString.isEmpty ? "" : "?\(queryString)"
urlRequest.url = URL(string: "\(url.absoluteString)\(postfix)")
} else {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch {
return .error(.apiClientError(.cantBuildUrl(.cantSerializeHttpBody)))
}
}
return .data(urlRequest)
}
// MARK: - Private
private func appendFlatternedParameters(
_ flatternedParameters: inout [String: Any],
fromTreeParameters treeParameters: [String: Any],
keyPrefix: String?) {
treeParameters.forEach { key, value in
let nextKeyPrefix: String
if let keyPrefix = keyPrefix {
nextKeyPrefix = "\(keyPrefix)[\(key)]"
} else {
nextKeyPrefix = key
}
if let array = value as? [Any] {
array.enumerated().forEach { index, item in
self.appendFlatternedParameters(
&flatternedParameters,
fromTreeParameters: [String(index): item],
keyPrefix: nextKeyPrefix
)
}
} else if let dictionary = value as? [String: Any] {
self.appendFlatternedParameters(
&flatternedParameters,
fromTreeParameters: dictionary,
keyPrefix: nextKeyPrefix
)
} else {
flatternedParameters[nextKeyPrefix] = value
}
}
}
private func encodedSortedByKeyStringFrom(dictionary: [String: Any]) -> String {
var result = ""
let sortedKeys = dictionary.keys.sorted(by: <)
sortedKeys.forEach { key in
if let value = dictionary[key] as? String {
if !result.isEmpty {
result+="&"
}
let encodedKey = key.byAddingCustomPercentEncodingForChecksumCalculation()
let encodedValue = value.byAddingCustomPercentEncodingForChecksumCalculation()
result += "\(encodedKey)=\(encodedValue)"
}
}
return result
}
}
|
//
// LibraryCell.swift
// MusicPlayer
//
// Created by Vlad Tkachuk on 27.05.2020.
// Copyright © 2020 Vlad Tkachuk. All rights reserved.
//
import SwiftUI
import URLImage
struct LibraryCell: View {
var cell: SearchViewModel.Cell
var body: some View {
HStack {
URLImage(URL(string: cell.iconUrlString ?? "")!) { proxy in
proxy.image.resizable()
}
.frame(width: 60, height: 60)
.cornerRadius(2)
VStack(alignment: .leading) {
Text(self.cell.trackName)
Text(self.cell.artistName)
}
}
}
}
struct LibraryCell_Previews: PreviewProvider {
static var previews: some View {
LibraryCell(cell: .init(iconUrlString: "https://static.guides.co/a/uploads/2672%2F10B.+Icon.png", trackName: "TrackName", collectionName: "CollectionName", artistName: "ArtistName", previewUrl: "Preview"))
}
}
|
import XCTest
import TextSearchTests
var tests = [XCTestCaseEntry]()
tests += TextSearchTests.allTests()
XCTMain(tests)
|
// Created by Sergii Mykhailov on 02/01/2018.
// Copyright © 2018 Sergii Mykhailov. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
import LocalAuthentication
class UIUtils {
//MARK: Methods
public static func blink(aboveView view:UIView) {
let blinkingView = UIView()
blinkingView.backgroundColor = UIColor.white
blinkingView.alpha = 0
view.addSubview(blinkingView)
blinkingView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
UIView.animate(withDuration:UIDefaults.DefaultAnimationDuration,
animations: {
blinkingView.alpha = 0.75
}) { (_) in
UIView.animate(withDuration:UIDefaults.DefaultAnimationDuration,
animations: {
blinkingView.alpha = 0
}, completion: { (_) in
blinkingView.removeFromSuperview()
})
}
}
public static func presentNotification(withMessage message:String,
onView containerView:UIView,
onCompletion:CompletionBlock) {
let label = UILabel()
label.text = message
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
let labelContainerView = UIView()
labelContainerView.backgroundColor = UIColor(white:0, alpha:0.1)
labelContainerView.alpha = 0
labelContainerView.layer.cornerRadius = UIDefaults.CornerRadius
containerView.addSubview(labelContainerView)
labelContainerView.addSubview(label)
labelContainerView.setContentHuggingPriority(.required, for:.vertical)
labelContainerView.setContentHuggingPriority(.required, for:.horizontal)
labelContainerView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.left.equalToSuperview().offset(UIDefaults.Spacing)
make.right.equalToSuperview().offset(-UIDefaults.Spacing)
}
label.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(UIDefaults.Spacing)
make.bottom.equalToSuperview().offset(-UIDefaults.Spacing)
make.left.equalToSuperview().offset(UIDefaults.Spacing)
make.right.equalToSuperview().offset(-UIDefaults.Spacing)
}
UIView.animateKeyframes(withDuration:NotificationAnimationDuration,
delay:0,
options:.calculationModeLinear,
animations: {
UIView.addKeyframe(withRelativeStartTime:0,
relativeDuration:1.0 / 8.0,
animations: {
labelContainerView.alpha = 1
label.alpha = 1
})
UIView.addKeyframe(withRelativeStartTime: 1.0 / 4.0 * NotificationAnimationDuration,
relativeDuration:1.0 / 4.0,
animations: {
labelContainerView.alpha = 0
label.alpha = 0
})
}) { (_) in
labelContainerView.removeFromSuperview()
}
}
typealias AuthenticationCompletionCallback = (Bool, Error?) -> Void
public static func authenticate(onCompletion:@escaping AuthenticationCompletionCallback) {
let localAuthenticationContext = LAContext()
localAuthenticationContext.localizedFallbackTitle = NSLocalizedString("Use Passcode", comment:"Fallback title")
let reasonString = NSLocalizedString("To access the application", comment: "Authentication reason string")
localAuthenticationContext.evaluatePolicy(.deviceOwnerAuthentication,
localizedReason:reasonString,
reply:onCompletion)
}
public static func formatAssetValue(amount:Double) -> String {
var floatingPointsCount = 0
if amount < MinValueFor2FloatingPoints {
floatingPointsCount = 2
}
if amount < MinValueFor5FloatingPoints {
floatingPointsCount = 5
}
let result = String(format:"%.\(floatingPointsCount)f", amount)
return result
}
// MARK: Properties
public static let PublicKeySettingsKey = "Public Key"
public static let PrivateKeySettingsKey = "Private Key"
public static let UserNameSettingsKey = "User Name"
public static let SecurityKeySettingsKey = "Security Key"
public static let UserIDSettingsKey = "User ID"
public static let UserPasswordSettingsKey = "User Password"
fileprivate static let NotificationAnimationDuration:TimeInterval = 2.0
fileprivate static let MinValueFor2FloatingPoints:Double = 10000
fileprivate static let MinValueFor5FloatingPoints:Double = 10
}
|
//
// RoratingViewsController.swift
// SimpleRotatingPolygons
//
// Created by Yurii Boiko on 5/19/19.
// Copyright © 2019 yurssoft. All rights reserved.
//
import UIKit
class RoratingViewsController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
private var flowLayout: UICollectionViewFlowLayout!
private let sectionInsets = UIEdgeInsets(top: 0,
left: 0,
bottom: 0,
right: 0)
override func viewDidLoad() {
super.viewDidLoad()
flowLayout = createBasicFlowLayout()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.collectionViewLayout = flowLayout
}
private func createBasicFlowLayout() -> UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
let viewWidth = collectionView.frame.width
let viewHeight = collectionView.frame.height
let itemsPerRow: CGFloat = 8
let widthPerItem = viewWidth/itemsPerRow
let itemHeight = viewHeight/itemsPerRow
let itemSize = CGSize(width: widthPerItem, height: itemHeight)
layout.itemSize = itemSize
layout.minimumInteritemSpacing = 0
layout.sectionInset = sectionInsets
layout.minimumLineSpacing = sectionInsets.left
return layout
}
}
extension RoratingViewsController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return flowLayout.itemSize
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: false)
}
}
extension RoratingViewsController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 8
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: String(describing: RotatingCell.self), for: indexPath) as? RotatingCell {
cell.setupPolygon()
cell.delegate = self
cell.cellIndexPath = indexPath
cell.setNeedsLayout()
cell.layoutIfNeeded()
return cell
}
return UICollectionViewCell()
}
private func applyRotation(layer: CALayer) {
let rotation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.byValue = Float.pi * 2
rotation.duration = 1
rotation.isCumulative = true
rotation.repeatCount = 1
rotation.timingFunction = CAMediaTimingFunction(name: .linear)
layer.add(rotation, forKey: "lineRotation")
}
private func applyRotation(for indexPath: IndexPath) {
let cells = collectionView.visibleCells.compactMap({ $0 as? RotatingCell })
if let cell = cells.first(where: { $0.cellIndexPath == indexPath}), let layerToRotate = cell.layerToRotate() {
applyRotation(layer: layerToRotate)
}
}
}
extension RoratingViewsController: RotatingCellDelegate {
func didTapRotateButton(layer: CALayer, indexPath: IndexPath) {
applyRotation(layer: layer)
let leftIndexPath = IndexPath(row: indexPath.row - 1, section: indexPath.section)
applyRotation(for: leftIndexPath)
let rightIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
applyRotation(for: rightIndexPath)
let topIndexPath = IndexPath(row: indexPath.row, section: indexPath.section + 1)
applyRotation(for: topIndexPath)
let bottomIndexPath = IndexPath(row: indexPath.row, section: indexPath.section - 1)
applyRotation(for: bottomIndexPath)
}
}
|
//
// CustomModal.swift
// instaclone
//
// Created by Rami Baraka on 17/12/16.
// Copyright © 2016 Rami Baraka. All rights reserved.
//
import UIKit
class CustomModal: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
//
// FinancialDetailsViewController.swift
// AdventistEduc
//
// Created by Andre Luiz Pimentel on 12/07/16.
// Copyright © 2016 Andre Pimentel. All rights reserved.
//
import UIKit
import Alamofire
class FinancialDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var data = [[String:AnyObject]]()
var codCarne = ""
override func viewDidLoad() {
super.viewDidLoad()
getData()
print(codCarne)
// Remove o separador de células
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellFinancialDetails", forIndexPath: indexPath) as! FinancialDetailsTableViewCell
// Configure the cell...
let plotDetails = data[indexPath.row]
cell.labelDescription?.text = plotDetails["descricao"] as? String
cell.labelValue?.text = plotDetails["valor"] as? String
var codSercico: String = plotDetails["cod_servico"] as! String
print(codSercico)
switch codSercico {
case "5":
cell.imageView?.image = UIImage(named: "educational.png")
case "597":
cell.imageView?.image = UIImage(named: "bolsadesc.png")
case "901":
cell.imageView?.image = UIImage(named: "pagamentoantecipado.png")
case "903":
cell.imageView?.image = UIImage(named: "ajustepagamento.png")
case "999":
cell.imageView?.image = UIImage(named: "pagamentos.png")
default:
cell.imageView?.image = UIImage(named: "default.png")
}
// Desabilita seleção de celula
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// 1. Setar o estado inicial
cell.alpha = 0
//let transform = CATransform3DTranslate(CATransform3DIdentity, -250, 20, 0)
//cell.layer.transform = transform
// 2. Mudar o metodo de animação
UIView.animateWithDuration(1.0){
cell.alpha = 1.0
//cell.layer.transform = CATransform3DIdentity
}
}
func getData() {
let params = [
"metodo": "parcelaDetalhes",
"cod_carne" : "1336034"
]
Alamofire.request(.GET, Constants.API.EndPoint, parameters: params)
.responseJSON { response in
if let JSON = response.result.value {
let jsonItems = JSON["parceladetalhes"] as! [[String: AnyObject]]
self.data = jsonItems
self.tableView.reloadData()
//refreshControl?.endRefreshing()
}
}
}
}
|
//
// MockArtObjectsService.swift
// RijksMuseumTests
//
// Created by Alexander Vorobjov on 1/3/21.
//
import Foundation
@testable import RijksMuseum
class MockArtObjectsService: ArtObjectsService {
var home: ArtObjectsResult?
var search: ArtObjectsResult?
var details: ArtObjectDetailsResult?
func loadHome(completion: @escaping ArtObjectsCompletion) {
if let home = home {
completion(home)
}
}
func search(query: String, completion: @escaping ArtObjectsCompletion) {
if let search = search {
completion(search)
}
}
func details(objectNumber: ArtObjectNumber, completion: @escaping ArtObjectDetailsCompletion) {
if let details = details {
completion(details)
}
}
}
|
//
// AddView.swift
// RememberMe
//
// Created by Tino on 7/4/21.
//
import SwiftUI
import MapKit
struct AddView: View {
@ObservedObject var peopleMet: PeopleMet
@Environment(\.presentationMode) var presentationMode
@State private var selectedImage: UIImage?
@State private var name = ""
@State private var description = ""
@State private var alertItem: AlertItem?
let locationFetcher = LocationFetcher()
var body: some View {
NavigationView {
VStack(spacing: 0) {
ImageSelect(selectedImage: $selectedImage)
Form {
Section {
TextField("Name", text: $name)
TextField("Description", text: $description)
}
}
}
.navigationBarTitle("Add person")
.navigationBarItems(trailing: Button("Add", action: addPerson))
}
.alert(item: $alertItem) { item in
Alert(
title: Text(item.title),
message: item.message != nil ? Text(item.message!) : nil,
dismissButton: item.primaryButton ?? .default(Text("OK"))
)
}
.onAppear(perform: locationFetcher.start)
}
}
// MARK: Functions
extension AddView {
func addPerson() {
if selectedImage == nil {
alertItem = AlertItem(
title: "Error",
message: "No image selected"
)
return
} else if name.isEmpty {
alertItem = AlertItem(
title: "Error",
message: "Enter a name"
)
return
}
// description isn't checked because it can be empty
var newPerson = Person(name: name, description: description)
if let location = locationFetcher.lastKnownLocation {
newPerson.locationWhenAdded.latitude = location.latitude
newPerson.locationWhenAdded.longitude = location.longitude
}
// since selected image is checked about its safe to force this
let image = self.selectedImage!
guard let imageData = image.jpegData(compressionQuality: 0.8) else {
fatalError("Failed to get image data")
}
let imageURL = FileManager.default.documentsURL().appendingPathComponent(newPerson.imagePath)
do {
try imageData.write(to: imageURL)
} catch {
print("Unresolved error \(error.localizedDescription)")
}
peopleMet.add(newPerson)
presentationMode.wrappedValue.dismiss()
}
}
struct AddView_Previews: PreviewProvider {
static var previews: some View {
AddView(peopleMet: PeopleMet())
}
}
|
//
// Date+Ext.swift
// Feedit
//
// Created by Tyler D Lawrence on 8/10/20.
//
import Foundation
extension Date {
func string(format: String = "MMM d, h:mm a") -> String {
let f = DateFormatter()
f.dateFormat = format
return f.string(from: self)
}
}
extension Date {
func dateToString() -> String{
let dateFormatter:DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let strdt = dateFormatter.string(from: self as Date)
if let dtDate = dateFormatter.date(from: strdt){
return dateFormatter.string(from: dtDate)
}
return "--"
}
}
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
Standard control accessibility examples
*/
import Foundation
import SwiftUI
public struct StandardControlExample: View {
@State public var toggleOn = false
public var body: some View {
VStack(alignment: .leading) {
Button(action: {}) {
Text("Button with hint & identifier")
}
.accessibilityHint(Text("Accessibility hint for first button"))
.accessibilityIdentifier("First Button")
LargeSpacer()
Toggle(isOn: $toggleOn) {
Text("Toggle with hint")
}
.accessibilityHint(Text("Accessibility hint for toggle"))
LargeSpacer()
Text("Element with Label and Value")
AccessibilityElementView(color: Color.purple, text: Text("Element"))
.accessibilityLabel(Text("Purple Color Label"))
.accessibilityValue(Text("Purple Color Value"))
}
}
public init() {}
}
|
//
// EasyPostCustomsItem.swift
// EasyPostApi
//
// Created by Sachin Vas on 19/04/18.
//
import Foundation
open class EasyPostCustomsItem {
open var id: String?
open var itemDescription: String?
open var quantity: NSNumber?
open var weight: NSNumber?
open var value: NSNumber?
open var hsTariffNumber: NSNumber?
open var originCountry: String?
open var createdAt: Date?
open var updatedAt: Date?
public init() {
}
public init(jsonDictionary: [String: Any]) {
//Load the JSON dictionary
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" //2013-04-22T05:40:57Z
if let stringValue = jsonDictionary["id"] as? String {
id = stringValue
}
if let stringValue = jsonDictionary["description"] as? String {
itemDescription = stringValue
}
if let intValue = jsonDictionary["quantity"] as? NSNumber {
quantity = intValue
}
if let intValue = jsonDictionary["weight"] as? NSNumber {
weight = intValue
}
if let intValue = jsonDictionary["value"] as? NSNumber {
value = intValue
}
if let intValue = jsonDictionary["hs_tariff_number"] as? NSNumber {
hsTariffNumber = intValue
}
if let stringValue = jsonDictionary["origin_country"] as? String {
originCountry = stringValue
}
if let stringValue = jsonDictionary["created_at"] as? String {
createdAt = dateFormatter.date(from: stringValue)
}
if let stringValue = jsonDictionary["updated_at"] as? String {
updatedAt = dateFormatter.date(from: stringValue)
}
}
open func jsonDict() -> [String: Any] {
var dict = [String: Any]()
if id != nil {
dict.updateValue(id! as AnyObject, forKey: "id")
}
if itemDescription != nil {
dict.updateValue(itemDescription! as AnyObject, forKey: "description")
}
if quantity != nil {
dict.updateValue(quantity! as AnyObject, forKey: "quantity")
}
if weight != nil {
dict.updateValue(weight! as AnyObject, forKey: "weight")
}
if value != nil {
dict.updateValue(value! as AnyObject, forKey: "value")
}
if hsTariffNumber != nil {
dict.updateValue(hsTariffNumber! as AnyObject, forKey: "hs_traiff_number")
}
if originCountry != nil {
dict.updateValue(originCountry! as AnyObject, forKey: "origin_country")
}
return dict
}
}
|
//
// DetailViewController.swift
// SweetHealth
//
// Created by Miguel Jaimes on 17/02/2020.
// Copyright © 2020 Miguel Jaimes. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var nameApp: UILabel!
@IBOutlet weak var logoApp: UIImageView!
let imageDownloader = ImagenCharged()
var app:AppElement?
var listApps:[AppElement] = [] {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
guard let name = (app?.name.map{$0.rawValue}) else{return}
let appSelection = appSelect(AppSelect: name)
self.callApi(JSONSelect: appSelection)
setUpView()
}
func appSelect(AppSelect appSelect:String) -> String {
var selectionApp:String = ""
switch appSelect {
case "Chrome":
selectionApp = "chromeJSON"
break
case "Facebook":
selectionApp = "facebookJSON"
break
case "Instagram":
selectionApp = "instagramJSON"
break
case "Gmail":
selectionApp = "gmailJSON"
break
case "Reloj":
selectionApp = "relojJSON"
break
case "Whatsapp":
selectionApp = "whatsappJSON"
break
default:
print("")
}
return selectionApp
}
func callApi(JSONSelect jsonSelected:String){
let apiManager = ApiManger()
apiManager.getAllData(File: jsonSelected, completion:{ appResult in
self.listApps = self.CreatListApp(ArrayApp:appResult)
})
}
func CreatListApp(ArrayApp arrayApp:App)->[AppElement]{
let arrayLocal = arrayApp.compactMap( {result in
AppElement(id: result.id, name: result.name, image: result.image, date: result.date, time: result.time, event: result.event, latitude: result.latitude, longitude: result.longitude) })
return arrayLocal
}
func setUpView(){
nameApp.text = app?.name.map{ $0.rawValue }
guard let image = app?.image else { return }
imageDownloader.downloader(URLString: image, completion: { (image:UIImage?) in
self.logoApp.image = image
self.logoApp.roundImage()
})
self.logoApp.alpha = 0.0
UIView.animate(withDuration: 0.5, delay: 0.5, options: .curveEaseOut, animations: {
self.logoApp.alpha = 1
}, completion: nil)
}
}
extension DetailViewController: UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = listApps.count
return section
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 100 //or whatever you need
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let imageUrl = listApps[indexPath.row].image else { fatalError("URL imagen no encontrada") }
let cellIdentifier = "cellDetail"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? DetailTableViewCell else {
fatalError("La celda no es una instancia de HomeCell")
}
imageDownloader.downloader(URLString: imageUrl, completion: { (image:UIImage?) in
cell.imageApp.image = image
})
cell.nameApp.text = listApps[indexPath.row].name.map { $0.rawValue }
cell.dateApp.text = listApps[indexPath.row].date
cell.timeApp.text = listApps[indexPath.row].time
return cell
}
}
|
//
// RecordListTableViewController.swift
// Record
//
// Created by xiyuexin on 15/11/20.
// Copyright © 2015年 xiyuexin. All rights reserved.
//
import UIKit
class RecordListTableViewController: UITableViewController {
var records: [Record]!
var recordListCellIdentifier = "recordInfoCell"
var prototypeCell: RecordInfoTableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
records = RecordManager().showRecords()
let nib = UINib(nibName: "RecordInfoCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: recordListCellIdentifier)
prototypeCell = tableView.dequeueReusableCellWithIdentifier(recordListCellIdentifier) as! RecordInfoTableViewCell
}
override func viewWillAppear(animated: Bool) {
records = RecordManager().showRecords()
tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(recordListCellIdentifier, forIndexPath: indexPath) as! RecordInfoTableViewCell
let record = records[indexPath.row]
cell.nameLabel.text = record.name
cell.priceLabel.text = record.price
cell.numberLabel.text = "\(record.number)"
cell.timeLabel.text = record.time
return cell
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cell = prototypeCell
let record = records[indexPath.row]
cell.priceLabel.text = record.price
cell.numberLabel.text = "\(record.number)"
cell.timeLabel.text = record.time
let height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
return height
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return records.count > 0
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let record = records[indexPath.row]
if editingStyle == UITableViewCellEditingStyle.Delete {
RecordManager().removeRecord(record)
records = RecordManager().showRecords()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
}
}
|
//
// Post.swift
// myHood
//
// Created by Alex Lombry on 10/10/15.
// Copyright © 2015 Alex Lombry. All rights reserved.
//
import Foundation
class Post: NSObject, NSCoding {
// Attribut and data encapsulation
private var _title: String!
private var _imagePath: String!
private var _pDescription: String!
var title: String {
return _title
}
var imagePath: String {
return _imagePath
}
var pDescription: String {
return _pDescription
}
// initializer (constructor)
init(imagePath: String, title: String, description: String) {
self._imagePath = imagePath
self._title = title
self._pDescription = description
}
override init() {
}
required convenience init?(coder aDecoder: NSCoder) {
self.init()
self._imagePath = aDecoder.decodeObjectForKey("imagePath") as? String
self._title = aDecoder.decodeObjectForKey("title") as? String
self._pDescription = aDecoder.decodeObjectForKey("description") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self._imagePath, forKey: "imagePath")
aCoder.encodeObject(self._title, forKey: "title")
aCoder.encodeObject(self._pDescription, forKey: "description")
}
} |
//
// TIFamilyDetailsViewController.swift
// TPLInsurance
//
// Created by Tahir Raza on 03/12/2018.
// Copyright © 2018 TPLHolding. All rights reserved.
//
import UIKit
class TIFamilyDetailsViewController: UIViewController {
//Variables
//FirstController
var coverage: String?
var travelTypeSelected: String?
var travelStartDate: String?
var travelEndDate: String?
var destination: String?
var selectedDestination: TIDestinationModel?
var studentTution: String?
//SecondController
var nameOfInsured: String?
var email: String?
var dob: String?
var passport: String?
var cnic: String?
var city: String?
var numberOfKids: Int = 0
var numberOfBrother: Int = 0
var numberOfFather: Int = 0
var numberOfHusband: Int = 0
var numberOfMother: Int = 0
var numberOfSister: Int = 0
var numberOfWife: Int = 0
var address: String?
//ThirdController
var bName: String?
var bAddress: String?
var bCnic: String?
var bContact: String?
var bRelation: String?
var selectedDate: Date?
var travelPackageDetail: [TravelPackageModel]?
//ThisController
var yourArray = [familyData]()
var api = travelInsuranceDataHandler()
lazy var pickerView = UIPickerView()
@IBOutlet weak var nameTextview: UnderLineTextField!
@IBOutlet weak var dobTextview: UnderLineTextField!
@IBOutlet weak var cnicTextview: UnderLineTextField!
@IBOutlet weak var relationTextview: UnderLineTextField!
@IBOutlet weak var addMemberOutlet: UIButton!
@IBOutlet weak var familyMemberTable: UITableView!
@IBAction func addMemberAction(_ sender: Any) {
if nameTextview.text == nil || nameTextview.text == ""{
self.showToast(message: "Please enter the name")
}else if dobTextview.text == nil || dobTextview.text == ""{
self.showToast(message: "Please enter the date of birth")
}else if cnicTextview.text != "", let cnic = cnicTextview.text, cnic.count != 13 {
self.showToast(message: "Please enter correct nic number")
}else if relationTextview.text == nil || relationTextview.text == ""{
self.showToast(message: "Please enter the relation")
}else{
if yourArray.count < 4{
var member = familyData(name: nameTextview.text ?? "", dob: selectedDate! , cnic: cnicTextview.text ?? "-", relation: relationTextview.text ?? "-")
let currentDate: Date = Date()
var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
calendar.timeZone = TimeZone(identifier: "UTC")!
var component: DateComponents = DateComponents()
component.calendar = calendar
component.year = -18
let maxDate: Date = calendar.date(byAdding: component, to: currentDate)!
component.year = -150
let minDate: Date = calendar.date(byAdding: component, to: currentDate)!
var minimumDate = minDate
var maximumDate = maxDate
//work here
if member.relation == api.TravelRelationships![1].name || member.relation == api.TravelRelationships![5].name {
if member.relation == api.TravelRelationships![1].name || member.relation == api.TravelRelationships![5].name{
if numberOfKids <= 3{
numberOfKids = numberOfKids + 1
}else{
self.showToast(message: "Number of kids can not be more then 3")
return
}
}
}
if (member.relation == api.TravelRelationships![5].name && member.dob <= maximumDate) {
self.showToast(message: "Not an Eligible \(api.TravelRelationships![5].name!)")
return
}else if (member.relation == api.TravelRelationships![1].name && member.dob <= maximumDate) {
self.showToast(message: "Not an Eligible \(api.TravelRelationships![1].name!)")
return
}else{
if yourArray.count > 0 {
yourArray.append(member)
}else{
if member.relation == api.TravelRelationships![5].name || member.relation == api.TravelRelationships![1].name{
numberOfKids = numberOfKids + 1
}
yourArray.insert(member, at: 0)
}
familyMemberTable.reloadData()
}
}else{
self.showToast(message: "Number of family member cannot be more then 4")
}
}
}
let datePicker :UIDatePicker = {
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
datePicker.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)
return datePicker
}()
@objc func datePickerValueChanged(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = TIDateFormats.surveyFormat
dobTextview!.text = dateFormatter.string(from: sender.date)
selectedDate = sender.date
print(selectedDate)
}
override func viewWillAppear(_ animated: Bool) {
getrelations()
}
override func viewDidLoad() {
super.viewDidLoad()
let toolBar = TIHelper.accessoryViewForTextField(target: self, selector: #selector(donePicker))
// getrelations()
self.dobTextview.inputView = datePicker
dobTextview.inputAccessoryView = toolBar
dobTextview.delegate = self
nameTextview.inputAccessoryView = toolBar
relationTextview.inputView = pickerView
relationTextview.inputAccessoryView = toolBar
cnicTextview.delegate = self
nameTextview.delegate = self
cnicTextview.inputAccessoryView = toolBar
pickerView.delegate = self
pickerView.dataSource = self
familyMemberTable.delegate = self
familyMemberTable.dataSource = self
familyMemberTable.allowsSelection = false
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func deleteMember(_ sender: UIButton) {
print("This click is done from \(sender.tag)")
if yourArray.count > 0{
let abc = yourArray[sender.tag]
if abc.relation == api.TravelRelationships![1].name || abc.relation == api.TravelRelationships![5].name{
numberOfKids = numberOfKids - 1
}
yourArray.remove(at: sender.tag)
print(yourArray)
familyMemberTable.reloadData()
}else{
self.showToast(message: "nothing to delete")
}
}
@objc func donePicker() {
self.view.endEditing(true)
}
}
extension TIFamilyDetailsViewController: UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "abcFamily") as? TIFamilyCellTableViewCell else {
return UITableViewCell()
}
cell.nameLabel.text = yourArray[indexPath.row].name
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = TIDateFormats.surveyFormat
cell.dobLabel.text = dateFormatter.string(from: yourArray[indexPath.row].dob)
// cell.dobLabel.text = yourArray[indexPath.row].dob
cell.cnicLabel.text = yourArray[indexPath.row].cnic
cell.relationLabel.text = yourArray[indexPath.row].relation
// cell.delBtn.tag = indexPath.row
// cell.delBtn.addTarget(self, action: #selector(self.deleteMember(_:)), for: .touchUpInside)
cell.clearBtn.tag = indexPath.row
cell.clearBtn.addTarget(self, action: #selector(self.deleteMember(_:)), for: .touchUpInside)
return cell
// cell.nameLabel.text = "Mohammed Ahsan"
// cell.dobLabel.text = "1/1/1995"
// cell.cnicLabel.text = "42301-670000-0"
// cell.relationLabel.text = "Father"
// return cell
}
}
extension TIFamilyDetailsViewController: UIPickerViewDelegate, UIPickerViewDataSource{
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return api.TravelRelationships?.count ?? 0
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return api.TravelRelationships![row].name ?? "no text"
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let text = api.TravelRelationships![row].name
relationTextview?.text = text
selectData(at: row)
}
func selectData(at index: Int) {
if let fieldForPicker = relationTextview {
api.selectedFamilyRelationships(at: index)
}
}
}
extension TIFamilyDetailsViewController{
func getrelations(){
if api.TravelRelationships != nil{
pickerView.reloadAllComponents()
}else{
self.showActivityIndicatory()
api.TIGetTravelRelationship(completionHandler: { (success) in
DispatchQueue.main.async {
self.stopIndicator()
if success{
print("fetched Relations successfully")
self.stopIndicator()
self.view.isUserInteractionEnabled = true
// self.relations = self.api.Relationships
}else{
print("No packages available")
}
}
})
}
}
}
extension TIFamilyDetailsViewController: UITextFieldDelegate{
// func textFieldDidBeginEditing(_ textField: UITextField) {
// //datePicker.isUserInteractionEnabled = false
// let currentDate: Date = Date()
// var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
// calendar.timeZone = TimeZone(identifier: "UTC")!
// var components: DateComponents = DateComponents()
// components.calendar = calendar
// components.year = -18
// let maxDate: Date = calendar.date(byAdding: components, to: currentDate)!
// components.year = -150
// let minDate: Date = calendar.date(byAdding: components, to: currentDate)!
// var minimumDate = minDate
// var maximumDate = maxDate
//
// if textField == self.dobTextview {
// datePicker.maximumDate = maximumDate
// datePicker.minimumDate = minimumDate
//// print("please select date after today")
// }
//// if textField == self.dobTextview{
//// datePicker.minimumDate = Date()
//// print("please select date after today")
//// }
// }
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == self.cnicTextview{
guard let text = textField.text else { return true }
let newLength = text.count + string.count - range.length
return newLength <= 13 // Bool
if let textField = textField as? UnderLineTextField,
textField.isValidatingLimit {
let shouldReplace = textField.validateForLength(changingIn: range, change: string)
if textField == self.cnicTextview,
shouldReplace {
textField.formatTextOnChange(changingIn: range, change: string, format: .cnic)
}
return shouldReplace
}
}else if textField == self.nameTextview { // 30 characters are allowed on first name
guard let text = textField.text else { return true }
let newLength = text.count + string.count - range.length
return newLength <= 30 // Bool
}
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// if textField == relationTextview{
// getrelations()
// }
//datePicker.isUserInteractionEnabled = false
let currentDate: Date = Date()
// var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
// calendar.timeZone = TimeZone(identifier: "UTC")!
// var components: DateComponents = DateComponents()
// components.calendar = calendar
// let maxDate: Date = calendar.date(byAdding: components, to: currentDate)!
// components.year = -150
// var maximumDate = maxDate
if textField == self.dobTextview {
// datePicker.maximumDate = maximumDate
datePicker.maximumDate = currentDate
print("please select date after today")
}
}
}
// MARK: - API CALLING
extension TIFamilyDetailsViewController{
// func getPackagesController(with controller: UIViewController, completionHandler: @escaping(Bool) -> Void) {
// api.TravelInsurancePackages(Coverage: self.coverage ?? "-", TravelType: self.travelTypeSelected ?? "International", WithTution: "N", StartDate: travelStartDate ?? "", EndDate: travelEndDate ?? "2018-12-31", DOB: self.dob ?? "1980-08-22") { (success, message) in
// self.view.hideToastActivity()
// self.view.isUserInteractionEnabled = true
// if success{
// if let controller = controller as? NewTIPackagesViewController {
//
// //first controller variable
// self.travelPackageDetail = message
// controller.coverage = self.coverage
// controller.travelTypeSelected = self.travelTypeSelected
// controller.travelStartDate = self.travelStartDate
// controller.travelEndDate = self.travelEndDate
// controller.destination = self.destination
// controller.selectedDestination = self.selectedDestination
// controller.api = self.api
//
// //first controller variable
// controller.nameOfInsured = self.nameOfInsured
// controller.dob = self.dob
// controller.passport = self.passport
// controller.cnic = self.cnic
// controller.city = self.city
// controller.address = self.address
//
// //third controller variable
// controller.bName = self.bName
// controller.bAddress = self.bAddress
// controller.bCnic = self.bCnic
// controller.bContact = self.bContact
// controller.bRelation = self.bRelation
// controller.travelPackageDetail = self.travelPackageDetail
//
// //Family Detail View Controller
// controller.yourArray = self.yourArray
//
// completionHandler(true)
// } else {
// completionHandler(false)
// }
// self.view.hideToastActivity()
// self.view.isUserInteractionEnabled = true
// } else {
// self.view.makeToast("not success")
// }
// }
//
// }
}
// MARK: - Pager moving
extension TIFamilyDetailsViewController: PagerViewDelegate{
func willMoveTo(next controller: UIViewController, completionHandler: @escaping (Bool) -> Void) {
// if(nameInsuredTextview.text == nil || nameInsuredTextview.text == ""){
// self.view.makeToast("Please fill your name.")
// completionHandler(false)
// return
// }
// if(dobTextview.text == nil || dobTextview.text == ""){
// self.view.makeToast("Please select Date of birth.")
// completionHandler(false)
// return
// }
// if(passportTextview.text == nil || passportTextview.text == ""){
// self.view.makeToast("Please fill your passport number.")
// completionHandler(false)
// return
// }
// if(cnicTextview.text == nil || cnicTextview.text == ""){
// self.view.makeToast("Please fill your cnic.")
// completionHandler(false)
// return
// }
// if(cityTextview.text == nil || cityTextview.text == ""){
// self.view.makeToast("Please select city.")
// completionHandler(false)
// return
// }
if(yourArray.count < 1){
self.showToast(message: "Please fill family details")
completionHandler(false)
return
}
if let controller = controller as? NewTIPackagesViewController {
//first controller variable
// self.travelPackageDetail = message
controller.coverage = self.coverage
controller.travelTypeSelected = self.travelTypeSelected
controller.travelStartDate = self.travelStartDate
controller.travelEndDate = self.travelEndDate
controller.destination = self.destination
controller.selectedDestination = self.selectedDestination
controller.api = self.api
//first controller variable
controller.nameOfInsured = self.nameOfInsured
controller.email = self.email
controller.dob = self.dob
controller.passport = self.passport
controller.cnic = self.cnic
controller.city = self.city
controller.address = self.address
//third controller variable
controller.bName = self.bName
controller.bAddress = self.bAddress
controller.bCnic = self.bCnic
controller.bContact = self.bContact
controller.bRelation = self.bRelation
controller.travelPackageDetail = self.travelPackageDetail
//Family Detail View Controller
controller.yourArray = self.yourArray
print("first controller from page 4:")
print("coverage: \(self.coverage) -- travelTypeSelected: \(self.travelTypeSelected) -- travelStartDate: \(self.travelStartDate) -- travelEndDate: \(self.travelEndDate) -- destination: \(self.destination) -- selectedDestination: \(self.selectedDestination) -- studentTution: \(self.studentTution)")
print("Second controller from page 4:")
print("nameOfInsured: \(self.nameOfInsured) -- dob: \(self.dob) -- passport: \(self.passport) -- cnic: \(self.cnic) -- city: \(self.city) -- address: \(self.address)")
print("third controller from page 4:")
print("bName: \(self.bName) -- bAddress: \(self.bAddress) -- bCnic: \(self.bCnic) -- bContact: \(self.bContact) -- bRelation: \(self.bRelation)")
print("family detail controller from page 4:")
print("yourArray: \(self.yourArray)")
completionHandler(true)
} else {
completionHandler(false)
}
// self.getPackagesController(with: controller, completionHandler: completionHandler)
}
}
//extra work for family array cehcking
// for value in yourArray{
// if value.relation == api.TravelRelationships![1].name || value.relation == api.TravelRelationships![5].name{
// if numberOfKids <= 3{
// numberOfKids = numberOfKids + 1
// }else{
// self.view.makeToast("Number of kids can not be more then 3")
// return
// }
// }else{
// var dataRelation = value.relation
// if member.relation == dataRelation{
// self.view.makeToast("This relationship already exist!")
// return
// }
// }
// }
|
//
// ViewController.swift
// LoveCalculator
//
// Created by Arman on 26.10.2021.
//
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var resultDescriptionLabel: UILabel!
@IBOutlet weak var pairLabel: UILabel!
@IBOutlet weak var percentageLabel: UILabel!
@IBOutlet weak var resultButtonOutlet: UIButton! {
didSet {
// adjusting corners
resultButtonOutlet.layer.cornerRadius = 20
resultButtonOutlet.layer.masksToBounds = true
// adding shadows
resultButtonOutlet.layer.shadowOffset = CGSize(width: 0, height: 5)
resultButtonOutlet.layer.shadowOpacity = 1
resultButtonOutlet.layer.shadowRadius = 20
}
}
var networkManager = PairNetworkManager()
override func viewDidLoad() {
super.viewDidLoad()
networkManager.onCompletion = {[weak self] currentPair in
guard let self = self else {return}
self.updateInterface(pair: currentPair)
}
networkManager.fetchCurrentPair(fname: "Me", sname: "Burgers")
}
func updateInterface(pair: CurrentPair) {
DispatchQueue.main.async {
if self.perfectCase(sname: pair.sname, fname: pair.fname) {
self.progressView.progress = 1
self.imageView.image = UIImage(systemName: "bolt.heart.fill")
self.resultDescriptionLabel.text = "This pair is the most perfect in this universe"
self.pairLabel.text = "\(pair.fname) and \(pair.sname)"
self.percentageLabel.text = "999%"
} else {
self.pairLabel.text = "\(pair.fname) and \(pair.sname)"
self.imageView.image = UIImage(systemName: pair.systemIconString)
self.resultDescriptionLabel.text = pair.result
self.percentageLabel.text = "\(pair.percentage)%"
self.progressView.progress = Float(pair.percentage)! / 100
}
}
}
@IBAction func requestResult(_ sender: UIButton) {
self.presentInsertNamesAlertController(withTitle: "Enter pair names", message: nil, style: .alert) { fname, sname in
self.networkManager.fetchCurrentPair(fname: fname, sname: sname)
}
}
}
|
//
// CommonData.swift
// ChartsTutorial
//
// Created by Israrul on 3/30/20.
// Copyright © 2020 iOSTemplates. All rights reserved.
//
import Foundation
//let players = ["Ozil", "Ramsey", "Laca", "Auba", "Xhaka", "Torreira"]
//let goals = [6, 8, 26, 30, 8, 10]
|
//
// MovieTableViewController.swift
// TMDbApp
//
// Created by Colton Swapp on 8/7/20.
// Copyright © 2020 Colton Swapp. All rights reserved.
//
import UIKit
class MovieTableViewController: UITableViewController {
// MARK: - Outlets
@IBOutlet weak var movieSearchBar: UISearchBar!
// MARK: - Properties
var movies: [Movie] = []
override func viewDidLoad() {
super.viewDidLoad()
movieSearchBar.delegate = self
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return movies.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath) as? MovieTableViewCell else { return UITableViewCell()}
let movie = self.movies[indexPath.row]
cell.movieTitleLabel.text = movie.title
cell.movieRatingLabel.text = "\(movie.vote_average ?? 0)"
cell.movieOverviewLabel.text = movie.overview
MovieController.fetchMoviePoster(for: movie) { (result) in
DispatchQueue.main.async {
switch result {
case .success(let image):
cell.moviePosterImageView.image = image
case .failure(let error):
print(error.localizedDescription)
cell.moviePosterImageView.image = UIImage(named: "posterNotAvail")
}
}
}
return cell
}
/*
// 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.
}
*/
}
extension MovieTableViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let searchTerm = searchBar.text, !searchTerm.isEmpty else { return }
MovieController.fetchMovie(for: searchTerm) { (result) in
DispatchQueue.main.async {
switch result {
case .success(let movie):
self.movies = movie
self.tableView.reloadData()
searchBar.text = ""
case .failure(let error):
print(error.localizedDescription)
self.presentErrorToUser(localizedError: error)
}
}
}
}
}
|
//
// CardViewController.swift
// CardsUI
//
// Created by Eugène Peschard on 24/04/2017.
//
import UIKit
class testViewController: UIViewController {
var darkStatusBar = true
let fullView: CGFloat = 100
var partialView: CGFloat {
return UIScreen.main.bounds.height - (UIApplication.shared.statusBarFrame.height)
// return UIScreen.main.bounds.height - (left.frame.maxY + UIApplication.shared.statusBarFrame.height)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.commonInit()
}
func commonInit() {
self.modalPresentationStyle = .custom
self.transitioningDelegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(panGesture(_:)))
view.addGestureRecognizer(panGesture)
roundViews()
}
@IBAction func test(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@objc func panGesture(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
let velocity = recognizer.velocity(in: self.view)
let y = self.view.frame.minY
if ( y + translation.y >= fullView) && (y + translation.y <= partialView ) {
self.view.frame = CGRect(x: 0, y: y + translation.y, width: view.frame.width, height: view.frame.height)
recognizer.setTranslation(CGPoint.zero, in: self.view)
}
if recognizer.state == .ended {
var duration = velocity.y < 0 ? Double((y - fullView) / -velocity.y) : Double((partialView - y) / velocity.y )
duration = duration > 1.3 ? 1 : duration
UIView.animate(withDuration: duration, delay: 0.0, options: [.allowUserInteraction], animations: {
if velocity.y >= 0 {
self.view.frame = CGRect(x: 0, y: self.partialView, width: self.view.frame.width, height: self.view.frame.height)
} else {
self.view.frame = CGRect(x: 0, y: self.fullView, width: self.view.frame.width, height: self.view.frame.height)
}
}, completion: nil)
}
}
func roundViews() {
view.layer.cornerRadius = 7
view.clipsToBounds = true
toggleStatusBar()
}
}
// MARK: - UIViewControllerTransitioningDelegate methods
extension testViewController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController? {
if presented == self {
return CardPresentationController(presentedViewController: presented, presenting: presenting)
}
return nil
}
func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if presented == self {
return CardAnimationController(isPresenting: true)
} else {
return nil
}
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if dismissed == self {
return CardAnimationController(isPresenting: false)
} else {
return nil
}
}
func toggleStatusBar() {
if darkStatusBar {
UIApplication.shared.statusBarStyle = .lightContent
} else {
UIApplication.shared.statusBarStyle = .default
}
}
}
|
//
// Chord.swift
// MusicTheory
//
// Created by Cem Olcay on 22.10.2017.
// Copyright © 2017 cemolcay. All rights reserved.
//
// https://github.com/cemolcay/MusicTheory
//
import Foundation
// MARK: - ChordPart
/// Protocol that defines a printable chord part.
public protocol ChordDescription: CustomStringConvertible, Codable {
/// Notation of chord.
var notation: String { get }
}
/// Protocol that defines a chord part.
public protocol ChordPart: ChordDescription {
/// Interval between the root.
var interval: Interval { get }
/// Initilize chord part with interval.
init?(interval: Interval)
}
extension Interval {
/// Returns the sum of two intervals semitones.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Sum of two intervals in terms of their semitones.
fileprivate static func + (lhs: Interval, rhs: Accidental) -> Int {
return lhs.semitones + rhs.rawValue
}
}
/// Defines third part of the chord. Second note after the root.
public enum ChordThirdType: Int, ChordPart {
/// Defines major chord. 4 halfsteps between root.
case major
/// Defines minor chord. 3 halfsteps between root.
case minor
/// Initilize chord part with interval.
public init?(interval: Interval) {
switch interval {
case ChordThirdType.major.interval:
self = .major
case ChordThirdType.minor.interval:
self = .minor
default:
return nil
}
}
/// Interval between root.
public var interval: Interval {
switch self {
case .major:
return .M3
case .minor:
return .m3
}
}
/// Notation of chord part.
public var notation: String {
switch self {
case .major: return ""
case .minor: return "m"
}
}
/// Description of chord part.
public var description: String {
switch self {
case .major: return "Major"
case .minor: return "Minor"
}
}
/// All values of `ChordThirdType`.
public static var all: [ChordThirdType] {
return [.major, .minor]
}
}
/// Defines fifth part of the chord. Third note after root note.
public enum ChordFifthType: Int, ChordPart {
/// Perfect fifth interval between root.
case perfect
/// Half step down of perfect fifth.
case diminished
/// Half step up of perfect fifth.
case augmented
/// Initilize chord part with interval.
public init?(interval: Interval) {
switch interval {
case ChordFifthType.perfect.interval:
self = .perfect
case ChordFifthType.diminished.interval:
self = .diminished
case ChordFifthType.augmented.interval:
self = .augmented
default:
return nil
}
}
/// Interval between root.
public var interval: Interval {
switch self {
case .perfect:
return .P5
case .diminished:
return .d5
case .augmented:
return .A5
}
}
/// Notation of chord part.
public var notation: String {
switch self {
case .perfect: return ""
case .augmented: return "♯5"
case .diminished: return "♭5"
}
}
/// Description of chord part.
public var description: String {
switch self {
case .perfect: return ""
case .augmented: return "Augmented"
case .diminished: return "Diminished"
}
}
/// All values of `ChordFifthType`.
public static var all: [ChordFifthType] {
return [.perfect, .diminished, .augmented]
}
}
/// Defiens sixth chords. If you add the sixth note, you have sixth chord.
public struct ChordSixthType: ChordPart {
/// Default initilizer.
public init() {}
/// Initilize chord part with interval.
public init?(interval: Interval) {
switch interval {
case .M6:
self.init()
default:
return nil
}
}
/// Interval between root.
public var interval: Interval {
return .M6
}
/// Notation of chord part.
public var notation: String {
return "6"
}
/// Description of chord part.
public var description: String {
return "Sixth"
}
}
/// Defiens seventh chords. If you add seventh note, you have seventh chord.
public enum ChordSeventhType: Int, ChordPart {
/// Seventh note of the chord. 11 halfsteps between the root.
case major
/// Halfstep down of a seventh note. 10 halfsteps between the root.
case dominant
/// Two halfsteps down of a seventh note. 9 halfsteps between the root.
case diminished
/// Initilize chord part with interval.
public init?(interval: Interval) {
switch interval {
case ChordSeventhType.major.interval:
self = .major
case ChordSeventhType.dominant.interval:
self = .dominant
case ChordSeventhType.diminished.interval:
self = .diminished
default:
return nil
}
}
/// Interval between root.
public var interval: Interval {
switch self {
case .major:
return .M7
case .dominant:
return .m7
case .diminished:
return Interval(quality: .diminished, degree: 7, semitones: 9)
}
}
/// Notation of chord part.
public var notation: String {
switch self {
case .major: return "M7"
case .dominant: return "7"
case .diminished: return "°7"
}
}
/// Description of chord part.
public var description: String {
switch self {
case .major: return "Major 7th"
case .dominant: return "Dominant 7th"
case .diminished: return "Diminished 7th"
}
}
/// All values of `ChordSeventhType`.
public static var all: [ChordSeventhType] {
return [.major, .dominant, .diminished]
}
}
/// Defines suspended chords.
/// If you play second or fourth note of chord, instead of thirds, than you have suspended chords.
public enum ChordSuspendedType: Int, ChordPart {
/// Second note of chord instead of third part. 2 halfsteps between root.
case sus2
/// Fourth note of chord instead of third part. 5 halfsteps between root.
case sus4
/// Initilize chord part with interval
public init?(interval: Interval) {
switch interval {
case ChordSuspendedType.sus2.interval:
self = .sus2
case ChordSuspendedType.sus4.interval:
self = .sus4
default:
return nil
}
}
/// Interval between root.
public var interval: Interval {
switch self {
case .sus2:
return .M2
case .sus4:
return .P4
}
}
/// Notation of chord part.
public var notation: String {
switch self {
case .sus2: return "(sus2)"
case .sus4: return "(sus4)"
}
}
/// Description of chord part.
public var description: String {
switch self {
case .sus2: return "Suspended 2nd"
case .sus4: return "Suspended 4th"
}
}
/// All values of `ChordSuspendedType`.
public static var all: [ChordSuspendedType] {
return [.sus2, .sus4]
}
}
/// Defines extended chords.
/// If you add one octave up of second, fourth or sixth notes of the chord, you have extended chords.
/// You can combine extended chords more than one in a chord.
public struct ChordExtensionType: ChordPart {
/// Defines type of the extended chords.
public enum ExtensionType: Int, ChordDescription {
/// 9th chord. Second note of the chord, one octave up from root.
case ninth = 9
/// 11th chord. Eleventh note of the chord, one octave up from root.
case eleventh = 11
/// 13th chord. Sixth note of the chord, one octave up from root.
case thirteenth = 13
/// Interval between root.
public var interval: Interval {
switch self {
case .ninth:
return .M9
case .eleventh:
return .P11
case .thirteenth:
return .M13
}
}
/// Notation of the chord part.
public var notation: String {
switch self {
case .ninth:
return "9"
case .eleventh:
return "11"
case .thirteenth:
return "13"
}
}
/// Description of the chord part.
public var description: String {
switch self {
case .ninth:
return "9th"
case .eleventh:
return "11th"
case .thirteenth:
return "13th"
}
}
/// All values of `ExtensionType`.
public static var all: [ExtensionType] {
return [.ninth, .eleventh, .thirteenth]
}
}
/// Type of extended chord.
public var type: ExtensionType
/// Accident of extended chord.
public var accidental: Accidental
/// If there are no seventh note and only one extended part is this. Defaults false
internal var isAdded: Bool
/// Initilizes extended chord.
///
/// - Parameters:
/// - type: Type of extended chord.
/// - accident: Accident of extended chord. Defaults natural.
public init(type: ExtensionType, accidental: Accidental = .natural) {
self.type = type
self.accidental = accidental
isAdded = false
}
/// Initilize chord part with interval
public init?(interval: Interval) {
switch interval.semitones {
case ExtensionType.ninth.interval + Accidental.natural:
self = ChordExtensionType(type: .ninth, accidental: .natural)
case ExtensionType.ninth.interval + Accidental.flat:
self = ChordExtensionType(type: .ninth, accidental: .flat)
case ExtensionType.ninth.interval + Accidental.sharp:
self = ChordExtensionType(type: .ninth, accidental: .sharp)
case ExtensionType.eleventh.interval + Accidental.natural:
self = ChordExtensionType(type: .eleventh, accidental: .natural)
case ExtensionType.eleventh.interval + Accidental.flat:
self = ChordExtensionType(type: .eleventh, accidental: .flat)
case ExtensionType.eleventh.interval + Accidental.sharp:
self = ChordExtensionType(type: .eleventh, accidental: .sharp)
case ExtensionType.thirteenth.interval + Accidental.natural:
self = ChordExtensionType(type: .thirteenth, accidental: .natural)
case ExtensionType.thirteenth.interval + Accidental.flat:
self = ChordExtensionType(type: .thirteenth, accidental: .flat)
case ExtensionType.thirteenth.interval + Accidental.sharp:
self = ChordExtensionType(type: .thirteenth, accidental: .sharp)
default:
return nil
}
}
/// Interval between root.
public var interval: Interval {
switch (type, accidental) {
case (.ninth, .natural): return .M9
case (.ninth, .flat): return .m9
case (.ninth, .sharp): return .A9
case (.eleventh, .natural): return .P11
case (.eleventh, .flat): return .P11
case (.eleventh, .sharp): return .A11
case (.thirteenth, .natural): return .M13
case (.thirteenth, .flat): return .m13
case (.thirteenth, .sharp): return .A13
case (.ninth, _): return .M9
case (.eleventh, _): return .P11
case (.thirteenth, _): return .M13
}
}
/// Notation of chord part.
public var notation: String {
return "\(isAdded ? "add" : "")\(accidental.notation)\(type.notation)"
}
/// Description of chord part.
public var description: String {
return "\(isAdded ? "Added " : "")\(accidental.description) \(type.description)"
}
/// All values of `ChordExtensionType`
public static var all: [ChordExtensionType] {
var all = [ChordExtensionType]()
for type in ExtensionType.all {
for accident in [Accidental.natural, Accidental.flat, Accidental.sharp] {
all.append(ChordExtensionType(type: type, accidental: accident))
}
}
return all
}
}
// MARK: - ChordType
/// Checks the equability between two `ChordType`s by their intervals.
///
/// - Parameters:
/// - left: Left handside of the equation.
/// - right: Right handside of the equation.
/// - Returns: Returns Bool value of equation of two given chord types.
public func == (left: ChordType?, right: ChordType?) -> Bool {
switch (left, right) {
case let (.some(left), .some(right)):
return left.intervals == right.intervals
case (.none, .none):
return true
default:
return false
}
}
/// Defines full type of chord with all chord parts.
public struct ChordType: ChordDescription, Hashable {
/// Thirds part. Second note of the chord.
public var third: ChordThirdType
/// Fifths part. Third note of the chord.
public var fifth: ChordFifthType
/// Defines a sixth chord. Defaults nil.
public var sixth: ChordSixthType?
/// Defines a seventh chord. Defaults nil.
public var seventh: ChordSeventhType?
/// Defines a suspended chord. Defaults nil.
public var suspended: ChordSuspendedType?
/// Defines extended chord. Defaults nil.
public var extensions: [ChordExtensionType]? {
didSet {
if extensions?.count == 1 {
extensions![0].isAdded = seventh == nil
// Add other extensions if needed
if let ext = extensions?.first, ext.type == .eleventh, !ext.isAdded {
extensions?.append(ChordExtensionType(type: .ninth))
} else if let ext = extensions?.first, ext.type == .thirteenth, !ext.isAdded {
extensions?.append(ChordExtensionType(type: .ninth))
extensions?.append(ChordExtensionType(type: .eleventh))
}
}
}
}
/// Initilze the chord type with its parts.
///
/// - Parameters:
/// - third: Thirds part.
/// - fifth: Fifths part. Defaults perfect fifth.
/// - sixth: Sixth part. Defaults nil.
/// - seventh: Seventh part. Defaults nil.
/// - suspended: Suspended part. Defaults nil.
/// - extensions: Extended chords part. Defaults nil. Could be add more than one extended chord.
/// - custom: Fill that with the custom intervals if it's not represented by the current data structures. Defaults nil.
public init(
third: ChordThirdType,
fifth: ChordFifthType = .perfect,
sixth: ChordSixthType? = nil,
seventh: ChordSeventhType? = nil,
suspended: ChordSuspendedType? = nil,
extensions: [ChordExtensionType]? = nil) {
self.third = third
self.fifth = fifth
self.sixth = sixth
self.seventh = seventh
self.suspended = suspended
self.extensions = extensions
if extensions?.count == 1 {
self.extensions![0].isAdded = seventh == nil
// Add other extensions if needed
if let ext = self.extensions?.first, ext.type == .eleventh, !ext.isAdded {
self.extensions?.append(ChordExtensionType(type: .ninth))
} else if let ext = self.extensions?.first, ext.type == .thirteenth, !ext.isAdded {
self.extensions?.append(ChordExtensionType(type: .ninth))
self.extensions?.append(ChordExtensionType(type: .eleventh))
}
}
}
/// Initilze the chord type with its intervals.
///
/// - Parameters:
/// - intervals: Intervals of chord notes distances between root note for each.
public init?(intervals: [Interval]) {
var third: ChordThirdType?
var fifth: ChordFifthType?
var sixth: ChordSixthType?
var seventh: ChordSeventhType?
var suspended: ChordSuspendedType?
var extensions = [ChordExtensionType]()
for interval in intervals {
if let thirdPart = ChordThirdType(interval: interval) {
third = thirdPart
} else if let fifthPart = ChordFifthType(interval: interval) {
fifth = fifthPart
} else if let sixthPart = ChordSixthType(interval: interval) {
sixth = sixthPart
} else if let seventhPart = ChordSeventhType(interval: interval) {
seventh = seventhPart
} else if let suspendedPart = ChordSuspendedType(interval: interval) {
suspended = suspendedPart
} else if let extensionPart = ChordExtensionType(interval: interval) {
extensions.append(extensionPart)
}
}
self = ChordType(
third: third ?? .major,
fifth: fifth ?? .perfect,
sixth: sixth,
seventh: seventh,
suspended: suspended,
extensions: extensions)
}
/// Intervals of parts between root.
public var intervals: [Interval] {
var parts: [ChordPart?] = [third, suspended, fifth, sixth, seventh]
parts += extensions?.sorted(by: { $0.type.rawValue < $1.type.rawValue }).map({ $0 as ChordPart? }) ?? []
return [.P1] + parts.compactMap({ $0?.interval })
}
/// Notation of the chord type.
public var notation: String {
var seventhNotation = seventh?.notation ?? ""
var sixthNotation = sixth == nil ? "" : "\(sixth!.notation)\(seventh == nil ? "" : "/")"
let suspendedNotation = suspended?.notation ?? ""
var extensionNotation = ""
let ext = extensions?.sorted(by: { $0.type.rawValue < $1.type.rawValue }) ?? []
var singleNotation = !ext.isEmpty && true
for i in 0 ..< max(0, ext.count - 1) {
if ext[i].accidental != .natural {
singleNotation = false
}
}
if singleNotation {
extensionNotation = "(\(ext.last!.notation))"
} else {
extensionNotation = ext
.compactMap({ $0.notation })
.joined(separator: "/")
extensionNotation = extensionNotation.isEmpty ? "" : "(\(extensionNotation))"
}
if seventh != nil {
// Don't show major seventh note if extended is a major as well
if (extensions ?? []).count > 0 {
switch seventh! {
case .diminished: seventhNotation = "°"
case .major: seventhNotation = "M"
case .dominant: seventhNotation = ""
}
sixthNotation = sixth == nil ? "" : sixth!.notation
}
// Show fifth note after seventh in parenthesis
if fifth == .augmented || fifth == .diminished {
return "\(third.notation)\(sixthNotation)\(seventhNotation)(\(fifth.notation))\(suspendedNotation)\(extensionNotation)"
}
}
return "\(third.notation)\(fifth.notation)\(sixthNotation)\(seventhNotation)\(suspendedNotation)\(extensionNotation)"
}
/// Description of the chord type.
public var description: String {
let seventhNotation = seventh?.description
let sixthNotation = sixth?.description
let suspendedNotation = suspended?.description
let extensionsNotation = extensions?
.sorted(by: { $0.type.rawValue < $1.type.rawValue })
.map({ $0.description as String? }) ?? []
let desc = [third.description, fifth.description, sixthNotation, seventhNotation, suspendedNotation] + extensionsNotation
return desc.compactMap({ $0 }).joined(separator: " ")
}
/// All possible chords could be generated.
public static var all: [ChordType] {
func combinations(_ elements: [ChordExtensionType], taking: Int = 1) -> [[ChordExtensionType]] {
guard elements.count >= taking else { return [] }
guard elements.count > 0 && taking > 0 else { return [[]] }
if taking == 1 {
return elements.map { [$0] }
}
var comb = [[ChordExtensionType]]()
for (index, element) in elements.enumerated() {
var reducedElements = elements
reducedElements.removeFirst(index + 1)
comb += combinations(reducedElements, taking: taking - 1).map { [element] + $0 }
}
return comb
}
var all = [ChordType]()
let allThird = ChordThirdType.all
let allFifth = ChordFifthType.all
let allSixth: [ChordSixthType?] = [ChordSixthType(), nil]
let allSeventh: [ChordSeventhType?] = ChordSeventhType.all + [nil]
let allSus: [ChordSuspendedType?] = ChordSuspendedType.all + [nil]
let allExt = combinations(ChordExtensionType.all) +
combinations(ChordExtensionType.all, taking: 2) +
combinations(ChordExtensionType.all, taking: 3)
for third in allThird {
for fifth in allFifth {
for sixth in allSixth {
for seventh in allSeventh {
for sus in allSus {
for ext in allExt {
all.append(ChordType(
third: third,
fifth: fifth,
sixth: sixth,
seventh: seventh,
suspended: sus,
extensions: ext
))
}
}
}
}
}
}
return all
}
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(intervals)
}
// MARK: Equatable
public static func == (lhs: ChordType, rhs: ChordType) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
// MARK: - Chord
/// Checks the equability between two chords by their base key and notes.
///
/// - Parameters:
/// - left: Left handside of the equation.
/// - right: Right handside of the equation.
/// - Returns: Returns Bool value of equation of two given chords.
public func == (left: Chord?, right: Chord?) -> Bool {
switch (left, right) {
case let (.some(left), .some(right)):
return left.key == right.key && left.type == right.type && left.inversion == right.inversion
case (.none, .none):
return true
default:
return false
}
}
/// Defines a chord with a root note and type.
public struct Chord: ChordDescription {
/// Type of the chord.
public var type: ChordType
/// Root key of the chord.
public var key: Key
/// Inversion index of the chord.
public private(set) var inversion: Int
/// Initilizes chord with root note and type.
///
/// - Parameters:
/// - key: Root key of the chord.
/// - type: Tyoe of the chord.
public init(type: ChordType, key: Key, inversion: Int = 0) {
self.type = type
self.key = key
self.inversion = inversion
}
/// Types of notes in chord.
public var keys: [Key] {
return pitches(octave: 1).map({ $0.key })
}
/// Possible inversions of the chord.
public var inversions: [Chord] {
return [Int](0 ..< keys.count).map({ Chord(type: type, key: key, inversion: $0) })
}
/// Notation of the chord.
public var notation: String {
let inversionNotation = inversion > 0 && inversion < keys.count ? "/\(keys[0])" : ""
return "\(key)\(type.notation)\(inversionNotation)"
}
/// Generates notes of the chord for octave.
///
/// - Parameter octave: Octave of the root note for the build chord from.
/// - Returns: Generates notes of the chord.
public func pitches(octave: Int) -> [Pitch] {
var intervals = type.intervals
for _ in 0 ..< inversion {
intervals = intervals.shifted
}
let root = Pitch(key: key, octave: octave)
let invertedPitches = intervals.map({ root + $0 })
return invertedPitches
.enumerated()
.map({ index, item in
index < type.intervals.count - inversion ? item : Pitch(key: item.key, octave: item.octave + 1)
})
}
/// Generates notes of the chord for octave range.
///
/// - Parameter octaves: Octaves of the root note to build chord from.
/// - Returns: Generates notes of the chord.
public func pitches(octaves: [Int]) -> [Pitch] {
return octaves.flatMap({ pitches(octave: $0) }).sorted(by: { $0.rawValue < $1.rawValue })
}
/// Returns the roman numeric string for a chord.
///
/// - Parameter scale: The scale that the chord in.
/// - Returns: Roman numeric string for the chord in a scale.
public func romanNumeric(for scale: Scale) -> String? {
guard let chordIndex = scale.keys.firstIndex(of: key)
else { return nil }
var roman = ""
switch chordIndex {
case 0: roman = "I"
case 1: roman = "II"
case 2: roman = "III"
case 3: roman = "IV"
case 4: roman = "V"
case 5: roman = "VI"
case 6: roman = "VII"
default: return nil
}
// Check if minor
if type.third == .minor {
roman = roman.lowercased()
}
// Check if sixth
if type.sixth != nil {
roman = "\(roman)6"
}
// Check if augmented
if type.fifth == .augmented {
roman = "\(roman)+"
}
// Check if diminished
if type.fifth == .diminished {
roman = "\(roman)°"
}
// Check if sevent
if type.seventh != nil, (type.extensions == nil || type.extensions?.isEmpty == true) {
roman = "\(roman)7"
}
// Check if extended
if let extensions = type.extensions,
let last = extensions.sorted(by: { $0.type.rawValue < $1.type.rawValue }).last {
roman = "\(roman)\(last.type.rawValue)"
}
// Check if inverted
if inversion > 0 {
roman = "\(roman)/\(inversion)"
}
return roman
}
// MARK: CustomStringConvertible
/// Description of the chord.
public var description: String {
let inversionNotation = inversion > 0 ? " \(inversion). Inversion" : ""
return "\(key) \(type)\(inversionNotation)"
}
}
// MARK: - Extensions
extension Array {
internal var shifted: Array {
guard let firstElement = first else { return self }
var arr = self
arr.removeFirst()
arr.append(firstElement)
return arr
}
}
|
//
// MusclesViewController.swift
// Schuylkill-App
//
// Created by Sam Hicks on 2/23/21.
//
import Combine
import Foundation
import Resolver
import SwiftUI
import UIKit
public class MuscleCollectionViewController: UIViewController {
@State var muscleSubscription: AnyCancellable?
private lazy var collectionsView = MusclesCollectionView()
lazy var viewModel: MusclesListViewModel = makeViewModel()
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override public func viewDidLoad() {
super.viewDidLoad()
self.addChild(collectionsView)
muscleSubscription = viewModel.queryAll()
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
}
extension MuscleCollectionViewController: Resolving {
func makeViewModel() -> MusclesListViewModel { return MusclesListViewModel() }
}
|
//
// Stock.swift
// AC-iOS-U3W1HW-Parsing
//
// Created by C4Q on 11/18/17.
// Copyright © 2017 C4Q . All rights reserved.
//
import Foundation
class Stocks {
let date: String?
let openingAmount: Double
let closingAmount: Double
var HeaderNames: String {
var dateAsArr = date?.split(separator: "-")
let year = dateAsArr![0]
let month = String(dateAsArr![1])
return "\(monthsAsDict[month]!)-\(year)"
}
let monthsAsDict = ["01": "January", "02": "February", "03": "March", "04": "April", "05": "May", "06": "June", "07": "July", "08": "August", "09": "September", "10": "October", "11": "November", "12": "December"]
init(date: String?, openingAmount: Double, closingAmount: Double) {
self.date = date
self.openingAmount = openingAmount
self.closingAmount = closingAmount
}
//failable convenience initialzer
convenience init?(from jsonDict: [String:Any]) {
guard
let openingAmount = jsonDict["open"] as? Double,
let closingAmount = jsonDict["close"] as? Double
else{
return nil
}
let date = jsonDict["date"] as? String
self.init(date: date, openingAmount: openingAmount, closingAmount: closingAmount)
}
//Returns an optional just incase an array cannot be created
//Data is converted into an object
static func createArrayOfStock(from data: Data) -> [Stocks]? {
var stockDetails: [Stocks] = []
do {
guard let stockJSONArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]] else {return nil}
for stockDict in stockJSONArray{
if let thisStock = Stocks(from: stockDict){
stockDetails.append(thisStock)
}
}
} catch {
print("Error: Could not convert data to JSON")
}
return stockDetails
}
}
|
//
// AttendanceDetailVC_PRO.swift
// EDUVance
//
// Created by KimJeonghwi on 2015. 11. 1..
// Copyright © 2015년 eeaa. All rights reserved.
//
import UIKit
class AttendanceDetailVC_PRO: BaseVC , UITableViewDelegate, UITableViewDataSource
{
@IBOutlet weak var hwi_label01_title: UILabel!
@IBOutlet weak var hwi_label02_01_classTime: UILabel!
@IBOutlet weak var hwi_label02_02_week: UILabel!
@IBOutlet weak var hwi_label02_03_score: UILabel!
@IBOutlet weak var hwi_label02_04_student: UILabel!
@IBOutlet weak var hwi_tableview: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.backBtnTemp.hidden = false
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(true)
self.onRefreshBtnTouchUpInside(UIView())
}
override func onBackBtnTouch(sender : UIButton)
{
self.dismissViewControllerAnimated(true) { () -> Void in
}
}
@IBAction func onRefreshBtnTouchUpInside(sender: AnyObject)
{
AttendanceManager.selected01_Subject = nil
if AttendanceManager.selectedAttendance01_lectureIdx != nil
{
AttendanceManager.getAttendanceOneSubList_professor(AttendanceManager.selectedAttendance01_lectureIdx!, callback: { (isSuccess, message) -> () in
self.hwi_label01_title.text = AttendanceManager.selected01_Subject?.subjectName
self.hwi_label02_01_classTime.text = AttendanceManager.selected01_Subject?.lessonTime
self.hwi_label02_02_week.text = AttendanceManager.selected01_Subject?.weekTime
self.hwi_label02_03_score.text = AttendanceManager.selected01_Subject?.score
self.hwi_label02_04_student.text = AttendanceManager.selected01_Subject?.studentCount
self.hwi_tableview.reloadData()
})
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if AttendanceManager.selected01_Subject?.attendanceList != nil
{
return (AttendanceManager.selected01_Subject?.attendanceList?.count)!
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let oneCell = tableView.dequeueReusableCellWithIdentifier("AttendanceDetailCell_PRO") as! AttendanceDetailCell_PRO
let oneData = AttendanceManager.selected01_Subject?.attendanceList![indexPath.row]
oneCell.hwi_label01_week.text = "\(oneData!.weekNum!)"
oneCell.hwi_label02_classTime.text = "\(oneData!.lessonDate!)"
oneCell.hwi_label03_count.text = "\(oneData!.timeNum!)"
print("테스트 004:: oneData?.attendanceCount : \(oneData?.attendanceCount)")
oneCell.hwi_label04_attendance.text = oneData?.attendanceCount![0] as? String
oneCell.hwi_label05_absense.text = oneData?.attendanceCount![3] as? String
oneCell.hwi_label06_late.text = oneData?.attendanceCount![1] as? String
oneCell.hwi_label07_early_leave.text = oneData?.attendanceCount![2] as? String
return oneCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let oneData = AttendanceManager.selected01_Subject?.attendanceList![indexPath.row]
AttendanceManager.selectedAttendance02_01_lessonDate = oneData?.lessonDate
AttendanceManager.selectedAttendance02_02_weekNum = String(oneData!.weekNum!)
AttendanceManager.selectedAttendance02_03_timeNum = String(oneData!.timeNum!)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.performSegueWithIdentifier("seg_proAtd01_proAtd02", sender: self)
}
}
|
//
// WebViewController.swift
// WorldTrotter
//
// Created by Devin Smaldore on 2/6/17.
// Copyright © 2017 Big Nerd Ranch. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
var webView: WKWebView!
override func loadView() {
webView = WKWebView()
let webConfig = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfig)
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myurl = URL(string: "https://www.google.com")
let request = URLRequest(url: myurl!)
webView.load(request)
print("WebViewController loaded its view.")
}
}
|
//: [Previous](@previous)
import Foundation
var i: Int?
i = 2
print(i)
i = nil
print(i)
//: [Next](@next)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.