text stringlengths 8 1.32M |
|---|
//
// ObjectMatrix.swift
// Boxnado
//
// Created by Matt Loflin on 7/12/16.
// Copyright © 2016 Awesomeness. All rights reserved.
//
import GLKit
class ObjectMatrix {
var translation = GLKVector3Make(0, 0, 0) {
didSet {
updateMatrix()
}
}
var centerOfRotation = GLKVector3Make(0, 0, 0) {
didSet {
updateMatrix()
}
}
var rotation = GLKVector3Make(0, 0, 0) {
didSet {
updateMatrix()
}
}
var scale = GLKVector3Make(1, 1, 1) {
didSet {
updateMatrix()
}
}
var modelMatrix = GLKMatrix4Identity
private func updateMatrix() {
let translationMatrix = GLKMatrix4MakeTranslation(translation.x, translation.y, translation.z)
let centerOfRotationMatrix = GLKMatrix4MakeTranslation(centerOfRotation.x, centerOfRotation.y, centerOfRotation.z)
let inverseCenterOfRotation = GLKVector3MultiplyScalar(centerOfRotation, -1)
let inverseCenterOfRotationMatrix = GLKMatrix4MakeTranslation(inverseCenterOfRotation.x,
inverseCenterOfRotation.y,
inverseCenterOfRotation.z)
let rotationMatrix = GLKMatrix4Multiply( GLKMatrix4Multiply(GLKMatrix4RotateX(GLKMatrix4Identity, rotation.x), GLKMatrix4RotateY(GLKMatrix4Identity, rotation.y)), GLKMatrix4RotateZ(GLKMatrix4Identity, rotation.z))
let scaleMatrix = GLKMatrix4MakeScale(scale.x, scale.y, scale.z)
modelMatrix = GLKMatrix4Multiply(GLKMatrix4Multiply(GLKMatrix4Multiply(GLKMatrix4Multiply(translationMatrix, centerOfRotationMatrix), rotationMatrix), inverseCenterOfRotationMatrix), scaleMatrix)
}
} |
//
// TxInput.swift
// BCWalletModel
//
// Created by Miroslav Djukic on 20/07/2020.
// Copyright © 2020 Miroslav Djukic. All rights reserved.
//
import Foundation
struct TxInput: Decodable {
let sequence: Int?
let witness: String?
let script: String?
let index: Int?
let prevOut: TxOutput?
enum CodingKeys: String, CodingKey {
case sequence = "sequence"
case witness = "witness"
case script = "script"
case index = "index"
case prevOut = "prev_out"
}
}
|
//
// IdValue.swift
// YumaApp
//
// Created by Yuma Usa on 2018-03-03.
// Copyright © 2018 Yuma Usa. All rights reserved.
//
import Foundation
public struct IdValue: Codable
{
let id: String
let value: String?
// init(id: String, value: String)
// {
// self.id = id
// self.value = value
// }
}
public struct IdAsString: Codable
{
let id: String
}
|
//
// SearchBar.swift
// Recipedia
//
// Created by Abhijana Agung Ramanda on 12/11/20.
//
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif
// House the UISearchController instance, and listen to its changes
public final class SearchBar: NSObject {
@Binding var text: String
@Binding var isEditing: Bool
private let canEdit: Bool
private var didClickSearchButton: (() -> Void)?
public let searchController: UISearchController = UISearchController(
searchResultsController: nil
)
public init(
canEdit: Bool = true,
text: Binding<String> = .constant(""),
isEditing: Binding<Bool> = .constant(false),
didClickSearchButton: (() -> Void)? = nil
) {
_text = text
_isEditing = isEditing
self.canEdit = canEdit
super.init()
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.obscuresBackgroundDuringPresentation = false
self.didClickSearchButton = didClickSearchButton
}
}
extension SearchBar: UISearchBarDelegate, UISearchControllerDelegate {
public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
isEditing.toggle()
return canEdit
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
isEditing = false
}
public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
return true
}
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard isEditing,
let didClickSearchButton = didClickSearchButton
else { return }
didClickSearchButton()
self.isEditing = false
}
public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
isEditing = true
}
}
extension SearchBar: UISearchResultsUpdating {
public func updateSearchResults(
for searchController: UISearchController
) {
guard let searchText = searchController.searchBar.text
else { return }
text = searchText
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var str = "定義function,接受3個參數,起始值,最大值和決定數字倍數的number, 回傳運算結果"
func sum(startno:Int, endno:Int,mulno:Int)->Int {
var sum=0
for i in startno ... endno
{
if i % mulno != 0
{
sum = sum + i
}
}
return sum
}
sum(startno: 1, endno: 100, mulno: 5)
|
//
// GenericPlayerActionAdapter.swift
// SailingThroughHistory
//
// Created by Herald on 20/4/19.
// Copyright © 2019 Sailing Through History Team. All rights reserved.
//
/**
* A class that controls how PlayerActions are executed in the context of a
* GenericTurnSystemNetwork.
*/
protocol GenericPlayerActionAdapter: class {
/// Attempts to process the player's actions for a given player.
/// - Parameters:
/// - action: The action to be executed.
/// - player: The player who wants to execute the action.
/// - Returns:
/// - The message resulting from the action.
/// - Throws:
/// - PlayerActionError, why is it not allowed.
func process(action: PlayerAction, for player: GenericPlayer) throws -> GameMessage?
/// Attempts to process the player's trade actions for a given player.
/// - Parameters:
/// - tradeAction: The trade action to be executed.
/// - player: The player who wants to execute the action.
/// - Returns:
/// - The message resulting from the action.
/// - Throws:
/// - PlayerActionError, why is it not allowed.
func handle(tradeAction: PlayerAction, by player: GenericPlayer) throws -> GameMessage?
/// Attempts to process the player's tax setting actions for a given player.
/// - Parameters:
/// - action: The tax setting action to be executed.
/// - player: The player who wants to execute the action.
/// - Returns:
/// - The message resulting from the action.
/// - Throws:
/// - PlayerActionError, why is it not allowed.
func register(portTaxAction action: PlayerAction,
by player: GenericPlayer) throws -> GameMessage?
/// Handles the setting of the tax using networkInfo
func handleSetTax()
/// Attempts to process the player's movement actions for a given player.
/// - Parameters:
/// - player: The player who wants to execute the action.
/// - nodeId: The id of the node the player wants to move to
/// - isEnd: Whether the player will stop here.
/// - Returns:
/// - The message resulting from the action.
func playerMove(_ player: GenericPlayer, _ nodeId: Int, isEnd: Bool) -> GameMessage?
}
|
//
// MapViewController.swift
// UserMap
//
// Created by Max Rybak on 11/15/18.
// Copyright © 2018 Max Rybak. All rights reserved.
//
import UIKit
import MapKit
import FirebaseAuth
class MapViewController: UIViewController {
var presenter: MapPresenterProtocol?
var allUsers: [UserCoords]?
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var tableView: UITableView!
var userLocation = CLLocationCoordinate2D()
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
MapRouter.configure(mapViewRef: self)
checkLocationServises()
tableView.dataSource = self
self.tableView.isHidden = true
}
// TODO: checkLocationServises(), checkLocationAuthorisation()
func checkLocationServises() {
if CLLocationManager.locationServicesEnabled() {
initLocationManager()
checkLocationAuthorisation()
// set up location manager
} else {
// show warning
}
}
func checkLocationAuthorisation() {
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse :
// do map stuff
break
case .denied :
break
case .notDetermined :
locationManager.requestWhenInUseAuthorization()
case .restricted :
// show alert
break
case .authorizedAlways :
break
}
}
@IBAction func logOutPressed(_ sender: UIBarButtonItem) {
presenter?.makeLogOutIntention()
}
// MARK: - Open/Close Tableview
@IBAction func userListPressed(_ sender: UIBarButtonItem) {
presenter?.view?.userListOpenClose()
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval)
{
UIView.animate(withDuration: 0.6, animations: {
if toInterfaceOrientation == .landscapeLeft || toInterfaceOrientation == .landscapeRight{
self.tableView.isHidden = false
}
else{
self.tableView.isHidden = true
}
})
}
}
extension MapViewController: CLLocationManagerDelegate {
// MARK: - Setup Locationmanager
func initLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
map.showsUserLocation = true
locationManager.startUpdatingLocation()
}
func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
manager.stopUpdatingHeading()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let coord = manager.location?.coordinate {
let center = CLLocationCoordinate2D(latitude: coord.latitude, longitude: coord.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.3, longitudeDelta: 0.3))
map.setRegion(region, animated: true)
userLocation = center
let currentUser = UserCoords(username: "Default", lat: userLocation.latitude, lon: userLocation.longitude)
presenter?.addUserIntention(userLocation: currentUser)
presenter?.mapUpdateIntention()
manager.stopUpdatingLocation()
}
}
}
extension MapViewController: UITableViewDelegate, UITableViewDataSource {
// MARK: - Tableview setup
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allUsers?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
if let username = allUsers?[indexPath.row].username {
cell.textLabel?.text = username
cell.textLabel?.textColor = .white
}
return cell
}
}
extension MapViewController: MapViewProtocol {
// MARK: MapViewProtocol fuctions
func addAnnotationsToMap(userLocation: inout [UserCoords]) {
allUsers = userLocation
var allAnnotations = [MKPointAnnotation]()
for elem in userLocation {
if elem.username != Auth.auth().currentUser?.email {
let newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = CLLocationCoordinate2D(latitude: elem.lat, longitude: elem.lon)
newAnnotation.title = elem.username
allAnnotations.append(newAnnotation)
}
}
map.removeAnnotations(map.annotations)
map.addAnnotations(allAnnotations)
}
func userListOpenClose() {
UIView.animate(withDuration: 0.6, animations: {
self.tableView.isHidden = !(self.tableView.isHidden)
})
}
}
|
//
// AudiobookDetailViewController.swift
// Buka3
//
// Created by mzk on 28/05/2017.
//
//
import UIKit
import AVFoundation
class AudiobookDetailViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var coverImageView: UIImageView!
@IBOutlet weak var toolbar: UIToolbar!
@IBOutlet weak var slider: UISlider!
var playButton: UIBarButtonItem!
var pauseButton: UIBarButtonItem!
var player: AVAudioPlayer?
var audiobook: Audiobook?
override func viewDidLoad() {
super.viewDidLoad()
coverImageView.image = audiobook?.cover
titleLabel.text = audiobook?.title
descriptionLabel.text = audiobook?.description
categoryLabel.text = audiobook?.category
playButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.play, target: self, action: #selector(AudiobookDetailViewController.playButtonTapped))
pauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.pause, target: self, action: #selector(AudiobookDetailViewController.pauseButtonTapped))
if let trackName = audiobook?.track, let track = NSDataAsset(name: trackName) {
do {
player = try AVAudioPlayer(data: track.data, fileTypeHint: AVFileType.mp3.rawValue)
player?.prepareToPlay()
} catch let error {
toolbar.isHidden = true
print(error.localizedDescription)
}
toolbar.items = [playButton];
// setup slider
if let duration = player?.duration {
slider.maximumValue = Float(duration)
} else {
slider.isHidden = true
}
playButtonTapped()
var _ = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateSlider), userInfo: nil, repeats: true)
} else {
slider.isHidden = true
toolbar.isHidden = true
}
}
override func viewDidAppear(_ animated: Bool) {
playButtonTapped()
}
override func viewWillDisappear(_ animated: Bool) {
pauseButtonTapped()
}
@objc func playButtonTapped() {
player?.play()
toolbar?.items = [pauseButton];
}
@objc func pauseButtonTapped() {
player?.stop()
toolbar?.items = [playButton];
}
@IBAction func changeTrackTime(_ sender: Any) {
player?.currentTime = TimeInterval(slider.value)
}
@objc func updateSlider() {
if let currentTime = player?.currentTime {
slider.value = Float(currentTime)
}
}
}
|
//
// ViewController.swift
// VirtualTour
//
// Created by Antarpunit Singh on 2012-05-09.
// Copyright © 2020 AntarpunitSingh. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class MapViewController: UIViewController {
var pins:[PinData] = []
var state:Bool = false
var persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
HoldGesture()
fetchPinsFromCoreData()
// print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
}
// Mark: Tap and Hold gesture method on mapView.
func HoldGesture(){
let tapHoldRecogniser = UILongPressGestureRecognizer(target: self,action: #selector(handleTapHold(_:)))
tapHoldRecogniser.minimumPressDuration = 0.5
mapView.addGestureRecognizer(tapHoldRecogniser)
}
@objc func handleTapHold(_ gestureRecognizer : UIGestureRecognizer){
if gestureRecognizer.state != .began { return }
let touchPoint = gestureRecognizer.location(in: mapView)
let touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = touchMapCoordinate
mapView.addAnnotation(annotation)
savePinToCoreData(coordinates: touchMapCoordinate)
}
func deletePinFromCoreData(cord:MKAnnotation , mapview:MKMapView){
let request:NSFetchRequest<PinData> = PinData.fetchRequest()
if let results = try? persistentContainer.viewContext.fetch(request){
for result in results {
if result.latitude == cord.coordinate.latitude && result.longitude == cord.coordinate.longitude {
persistentContainer.viewContext.delete(result)
mapview.removeAnnotation(cord)
}
}
try? persistentContainer.viewContext.save()
}
}
func savePinToCoreData(coordinates: CLLocationCoordinate2D){
let pinData = PinData(context: persistentContainer.viewContext)
pinData.latitude = coordinates.latitude
pinData.longitude = coordinates.longitude
pins.insert(pinData, at: 0)
try? persistentContainer.viewContext.save()
}
func fetchPinsFromCoreData(){
let request:NSFetchRequest<PinData> = PinData.fetchRequest()
if let result = try? persistentContainer.viewContext.fetch(request){
pins = result
}
annotatePinsOnMap()
}
func annotatePinsOnMap(){
for pin in pins {
let pinPoint = MKPointAnnotation()
let coordinates = CLLocationCoordinate2D(latitude: pin.latitude, longitude: pin.longitude)
pinPoint.coordinate = coordinates
mapView.addAnnotation(pinPoint)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showSegue" {
let vc = segue.destination as! PhotoViewController
let cords = sender as! MKAnnotation
// vc.selectedPin = cords
for pin in pins {
if (pin.latitude == cords.coordinate.latitude && pin.longitude == cords.coordinate.longitude){
vc.pin = pin
}
}
}
}
@IBAction func barButtonTapped(_ sender: UIBarButtonItem) {
state = !state
if state {
sender.tintColor = .red
navigationController?.navigationBar.topItem?.title = "Delete Pins"
}
else {
navigationController?.navigationBar.topItem?.title = ""
sender.tintColor = .opaqueSeparator
state = false
}
}
}
extension MapViewController: MKMapViewDelegate{
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if state == true {
deletePinFromCoreData(cord: view.annotation!, mapview: mapView)
}
else {
performSegue(withIdentifier: "showSegue", sender: view.annotation)
mapView.deselectAnnotation(view.annotation, animated: false)
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.pinTintColor = .red
pinView?.animatesDrop = true
}
else {
pinView?.animatesDrop = true
pinView!.annotation = annotation
}
return pinView
}
}
|
//
// Date+Extension.swift
// SpecialTraining
//
// Created by 尹涛 on 2018/11/24.
// Copyright © 2018 youpeixun. All rights reserved.
//
import Foundation
extension Date {
/// 获取当前 毫秒级 时间戳 - 13位
var milliStamp : String {
let timeInterval: TimeInterval = self.timeIntervalSince1970
let millisecond = CLongLong(round(timeInterval*1000))
return "\(millisecond)"
}
/// 获取当前 秒级 时间戳 - 10位
var timeStamp : String {
let timeInterval: TimeInterval = self.timeIntervalSince1970
let timeStamp = Int(timeInterval)
return "\(timeStamp)"
}
}
|
import UIKit
@available(iOS 9999, *)
class ViewController: UIViewController {
let cart = Cart()
override func viewDidLoad() {
super.viewDidLoad()
simulateCartOperations()
}
func simulateCartOperations() {
let group = DispatchGroup()
group.enter()
group.enter()
asyncDetached {
for i in 1...100 {
await self.cart.add(Offer(id: "abc"), count: i)
}
group.leave()
}
asyncDetached {
for i in 1...100 {
await self.cart.add(Offer(id: "abc"), count: i)
}
group.leave()
}
group.wait()
asyncDetached {
await print(cart.items)
}
}
}
|
//
// Operators.swift
// IDPDesign
//
// Created by Oleksa 'trimm' Korin on 9/2/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
precedencegroup LeftApplyPrecedence {
associativity: left
higherThan: AssignmentPrecedence
lowerThan: TernaryPrecedence
}
precedencegroup LeftChainPrecedence {
associativity: left
higherThan: LeftApplyPrecedence
}
precedencegroup FunctionCompositionPrecedence {
associativity: right
higherThan: LeftChainPrecedence
}
/// Apply parameter to function operator
infix operator |> : LeftApplyPrecedence
/// Chain operator
infix operator ~ : LeftChainPrecedence
/// Compose operator
infix operator • : FunctionCompositionPrecedence
|
//
// ColorManager.swift
// SpaceWatch
//
// Created by David Jöch on 05.06.20.
// Copyright © 2020 David Jöch. All rights reserved.
//
import SwiftUI
struct ColorManager {
static let containerBackgroundColor = Color("containerBackground")
}
|
import Quick
import Nimble
@testable import MessageGeneratorKit
final class DictionaryMessageMapperSpec: QuickSpec {
override func spec() {
var subject: DictionaryMessageMapper!
beforeEach {
subject = DictionaryMessageMapper(mappings: [
"foo": try! Message(name: "bar", fields: []),
"baz": try! Message(name: "qux", fields: [])
])
}
describe("map(type:)") {
it("returns the given mapping, if it exists") {
expect { return try subject.map(type: "foo") }.to(equal(try! Message(name: "bar", fields: [])))
expect { return try subject.map(type: "baz") }.to(equal(try! Message(name: "qux", fields: [])))
}
it("throws if a mapping is not found") {
expect { return try subject.map(type: "whatever") }.to(throwError(MessageMapperError.noSuchType("whatever")))
}
}
}
}
final class ComposedMessageMapperSpec: QuickSpec {
override func spec() {
var subject: ComposedMessageMapper!
beforeEach {
let mapper1 = DictionaryMessageMapper(mappings: [
"foo": try! Message(name: "bar", fields: []),
"snth": try! Message(name: "aoeu", fields: [])
])
let mapper2 = DictionaryMessageMapper(mappings: [
"baz": try! Message(name: "qux", fields: []),
"foo": try! Message(name: "baz", fields: [])
])
subject = ComposedMessageMapper(mappers: [mapper1, mapper2])
}
describe("map(type:)") {
it("returns the given mapping, if it exists") {
expect { return try subject.map(type: "snth") }.to(equal(try! Message(name: "aoeu", fields: [])))
expect { return try subject.map(type: "baz") }.to(equal(try! Message(name: "qux", fields: [])))
}
it("prefers the first mapping found over the last one") {
expect { return try subject.map(type: "foo") }.to(equal(try! Message(name: "bar", fields: [])))
expect { return try subject.map(type: "foo") }.to(equal(try! Message(name: "bar", fields: [])))
}
it("throws if a mapping is not found in any of the mappers") {
expect { return try subject.map(type: "whatever") }.to(throwError(MessageMapperError.noSuchType("whatever")))
}
}
}
}
final class DynamicMessageMapperSpec: QuickSpec {
override func spec() {
var subject: DynamicMessageMapper!
var shell: FakeShell!
var messageParser: MessageParser!
beforeEach {
shell = FakeShell()
let composedMessageMapper = ComposedMessageMapper(mappers: [BuiltInMessageMapper()])
messageParser = RosMessageParser(messageMapper: composedMessageMapper)
subject = DynamicMessageMapper(rosEnvironment: "/opt/ros/melodic", shell: shell, messageParser: messageParser)
composedMessageMapper.mappers.append(subject)
}
describe("map(type:)") {
describe("for a type that only depends on base types") {
let type = "foo"
let definition = """
[source/foo]:
int16 location
string whatever
""".trimmingCharacters(in: .whitespacesAndNewlines)
let message = try! Message(name: type, fields: [
MessageField(name: "location", type: .scalar(try! Message(name: "int16", fields: []))),
MessageField(name: "whatever", type: .scalar(try! Message(name: "string", fields: [])))
])
var receivedMessage: Message?
beforeEach {
shell.runReturns = { _ in definition }
receivedMessage = nil
do {
receivedMessage = try subject.map(type: type)
} catch let error {
fail("Expected to not throw an error, got \(error)")
}
}
it("converts what rosmsg returns into a message format") {
expect(receivedMessage).to(equal(message))
}
it("asks rosmsg on the given environment for the definition of the given message") {
expect(shell.runCalls).to(haveCount(1))
expect(shell.runCalls.last?.command).to(equal("/opt/ros/melodic/bin/rosmsg"))
expect(shell.runCalls.last?.arguments).to(equal(["show", type]))
}
describe("asking for the same type twice") {
var secondMessage: Message?
beforeEach {
secondMessage = nil
do {
secondMessage = try subject.map(type: type)
} catch let error {
fail("Expected to not throw an error, got \(error)")
}
}
it("returns the same result") {
expect(secondMessage).to(equal(receivedMessage))
}
it("does not ask rosmsg again (it caches the previous result)") {
expect(shell.runCalls).to(haveCount(1))
}
}
}
describe("for a type that depends on other non-base types") {
let definitions = [
"foo": "[]:\nbar whatever",
"bar": "[]:\nint32 a"
]
var receivedMessage: Message?
beforeEach {
shell.runReturns = { call in return definitions[call.arguments.last!]! }
receivedMessage = nil
do {
receivedMessage = try subject.map(type: "foo")
} catch let error {
fail("Expected to not throw an error, got \(error)")
}
}
let barMessage = try! Message(name: "bar", fields: [
MessageField(name: "a", type: .scalar(try! Message(name: "int32", fields: [])))
])
let fooMessage = try! Message(name: "foo", fields: [
MessageField(name: "whatever", type: .scalar(barMessage))
])
it("converts what rosmsg returns into a message format") {
expect(receivedMessage).to(equal(fooMessage))
}
it("asks rosmsg on the given environment for the definition of the given message and it's dependencies") {
expect(shell.runCalls).to(haveCount(2))
expect(shell.runCalls.first?.command).to(equal("/opt/ros/melodic/bin/rosmsg"))
expect(shell.runCalls.first?.arguments).to(equal(["show", "foo"]))
expect(shell.runCalls.last?.command).to(equal("/opt/ros/melodic/bin/rosmsg"))
expect(shell.runCalls.last?.arguments).to(equal(["show", "bar"]))
}
it("caches the results for the given message") {
expect { return try subject.map(type: "foo") }.to(equal(fooMessage))
expect(shell.runCalls).to(haveCount(2))
}
it("caches the results for any of the dependencies") {
expect { return try subject.map(type: "bar") }.to(equal(barMessage))
expect(shell.runCalls).to(haveCount(2))
}
}
describe("for a recursive message") {
let definitions = [
"foo": "[]\nbar name1",
"bar": "[]\nfoo name2"
]
beforeEach {
shell.runReturns = { call in return definitions[call.arguments.last!]! }
}
it("throws an error complaining about the recursion") {
expect { return try subject.map(type: "foo") }.to(throwError(MessageMapperError.recursiveMessageDefinition("foo", ["foo", "bar"])))
}
}
}
}
}
|
import UIKit
class VProjectsDetailCell:UICollectionViewCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
}
required init?(coder:NSCoder)
{
fatalError()
}
}
|
//
// SettingsTableCellView.swift
//
//
// Created by John Hurdle on 9/11/16.
//
//
import Foundation
import UIKit
public class SettingsView : UIView{
var textLabel2 : UILabel?
var subMenuButton: UIButton?
var toggleSwitch: UISwitch?
var settingName : String?
var settingLabel: String?
var targetProperty: PropertyObject?
var menuSettingObjects: [SettingsObject]?
var parentMenuView: SettingsMenuView?
var parentView: UIView?
var settingsObject: SettingsObject?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//Change initializer to accept settings object instead of pieces
init(frame: CGRect, settingsObject: SettingsObject, settingsParentView: UIView, parentMenuView: SettingsMenuView){
super.init(frame: frame)
self.parentView = settingsParentView
self.settingsObject = settingsObject
self.parentMenuView = parentMenuView
setUpView(settingsObject)
}
func setUpView(settingsObject: SettingsObject){
switch settingsObject{
case let .subMenu(objectLabel, settingsObjects):
settingName = objectLabel
settingLabel = objectLabel
menuSettingObjects = settingsObjects
addSubMenuButton()
case let .singleToggleObject(objectLabel, targetProperty):
settingName = objectLabel
settingLabel = objectLabel
self.targetProperty = targetProperty
addToggle1()
}
}
func addToggle1(){
textLabel2 = UILabel(frame: CGRectMake(self.frame.size.width*0.1, 0,self.frame.size.width*0.7,self.frame.size.height))
textLabel2!.text = settingName
textLabel2!.textAlignment = NSTextAlignment.Left
textLabel2!.textColor = UIColor.blackColor()
textLabel2!.font = textLabel2!.font.fontWithSize(12)
textLabel2!.numberOfLines = 0
self.addSubview(textLabel2!)
toggleSwitch = UISwitch(frame: CGRectMake(self.frame.size.width*0.8,self.frame.size.height/2-self.frame.size.height*0.2,self.frame.size.width*0.3,self.frame.size.height))
print("lskdfjldkf")
toggleSwitch!.on = targetProperty!.value as! Bool
toggleSwitch!.addTarget(self, action: #selector(updateTargetProperty(_:)), forControlEvents: UIControlEvents.ValueChanged)
self.addSubview(toggleSwitch!)
}
func updateTargetProperty(sender: UIView){
if let input = sender as? UISwitch{
targetProperty!.value = input.on
}
}
func addSubMenuButton(){
textLabel2 = UILabel(frame: CGRectMake(self.frame.size.width*0.1, 0,self.frame.size.width*0.7,self.frame.size.height))
textLabel2!.text = settingName
textLabel2!.textAlignment = NSTextAlignment.Left
textLabel2!.textColor = UIColor.blackColor()
textLabel2!.font = textLabel2!.font.fontWithSize(12)
textLabel2!.numberOfLines = 0
self.addSubview(textLabel2!)
subMenuButton = UIButton(frame: CGRectMake(0,0,self.frame.size.width, self.frame.size.height))
subMenuButton!.addTarget(self, action: #selector(createSubMenuView), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(subMenuButton!)
}
func createSubMenuView(){
var container : UIView
container = self.nextResponder() as! UIView
var subMenu : SettingsMenuView
subMenu = SettingsMenuView(frame: CGRectMake(0, 0, container.frame.size.width, container.frame.size.height), settingsObject: settingsObject!, menuName: settingName!, settingsParentView: parentView!, parentMenuView: parentMenuView)
parentView!.addSubview(subMenu)
superview?.removeFromSuperview()
}
}
|
//
// WeatherAppUITests.swift
// WeatherAppUITests
//
// Created by Aditya Athavale on 1/22/18.
// Copyright © 2018 Aditya Athavale. All rights reserved.
//
import XCTest
class WeatherAppUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCityWithoutSpace() {
let app = XCUIApplication()
let enterUsCityTextField = app.textFields["Enter US City"]
XCTAssertTrue(enterUsCityTextField.exists)
XCTAssertTrue(app.buttons["Fetch Weather"].exists)
enterUsCityTextField.tap()
enterUsCityTextField.typeText("Boston")
app.buttons["Fetch Weather"].tap()
XCTAssertFalse(enterUsCityTextField.exists)
XCTAssertFalse(app.buttons["Fetch Weather"].exists)
XCTAssertTrue(app.staticTexts["Temperature :"].exists)
XCTAssertTrue(app.staticTexts["Pressure :"].exists)
XCTAssertTrue(app.staticTexts["Humidity :"].exists)
XCTAssertTrue( app.navigationBars["Weather"].buttons["Done"].exists)
app.navigationBars["Weather"].buttons["Done"].tap()
XCTAssertFalse(app.staticTexts["Temperature"].exists)
XCTAssertFalse(app.staticTexts["Pressure"].exists)
XCTAssertFalse(app.staticTexts["Humidity"].exists)
XCTAssertTrue(enterUsCityTextField.exists)
XCTAssertTrue(app.buttons["Fetch Weather"].exists)
}
func testCityWithSpace() {
let app = XCUIApplication()
let enterUsCityTextField = app.textFields["Enter US City"]
XCTAssertTrue(enterUsCityTextField.exists)
XCTAssertTrue(app.buttons["Fetch Weather"].exists)
enterUsCityTextField.tap()
enterUsCityTextField.typeText("New York")
app.buttons["Fetch Weather"].tap()
XCTAssertFalse(enterUsCityTextField.exists)
XCTAssertFalse(app.buttons["Fetch Weather"].exists)
XCTAssertTrue(app.staticTexts["Temperature :"].exists)
XCTAssertTrue(app.staticTexts["Pressure :"].exists)
XCTAssertTrue(app.staticTexts["Humidity :"].exists)
XCTAssertTrue( app.navigationBars["Weather"].buttons["Done"].exists)
app.navigationBars["Weather"].buttons["Done"].tap()
XCTAssertFalse(app.staticTexts["Temperature"].exists)
XCTAssertFalse(app.staticTexts["Pressure"].exists)
XCTAssertFalse(app.staticTexts["Humidity"].exists)
XCTAssertTrue(enterUsCityTextField.exists)
XCTAssertTrue(app.buttons["Fetch Weather"].exists)
}
func testNonUSCity() {
let app = XCUIApplication()
let enterUsCityTextField = app.textFields["Enter US City"]
XCTAssertTrue(enterUsCityTextField.exists)
XCTAssertTrue(app.buttons["Fetch Weather"].exists)
enterUsCityTextField.tap()
enterUsCityTextField.typeText("Pune")
app.buttons["Fetch Weather"].tap()
XCTAssertFalse(enterUsCityTextField.exists)
XCTAssertFalse(app.buttons["Fetch Weather"].exists)
XCTAssertTrue(app.alerts["Error"].exists)
app.alerts["Error"].buttons["OK"].tap()
XCTAssertTrue(enterUsCityTextField.exists)
XCTAssertTrue(app.buttons["Fetch Weather"].exists)
}
}
|
import Foundation
class FriendDetailRepository: FriendDetailRepositoryProtocol {
private var friend: Friend?
private let imageStorage: ImagePersisting
private let taskQueue: HttpTaskQueueing
private let database: ManagedObjectProviding
private var name: String {
return friend?.name ?? "unknown"
}
init(provider: FriendDetailRepositoryDependencyProviding) {
imageStorage = provider.provideImageStorage()
taskQueue = provider.provideTaskQueue()
database = provider.provideDatabase()
}
func setFriend(_ friend: Friend) {
self.friend = friend
}
func getName() -> String {
return name
}
func getAwards() -> [Award] {
if let awards = friend?.awards {
return Array(awards)
}
return []
}
func deleteFriend() {
guard let friend = friend else {
return
}
let deleteTask = TaskBuilder().buildTask(delete: friend)
taskQueue.enqueue(httpTask: deleteTask)
taskQueue.sendData()
imageStorage.deleteImage(uuid: friend.uuid)
try? database.deleteManagedObject(friend)
try? database.saveChanges()
self.friend = nil
}
func takethAway(award: Award) {
guard let friend = friend else {
return
}
friend.awards.remove(award)
try? database.saveChanges()
let updateTask = TaskBuilder().buildTask(delete: award)
taskQueue.enqueue(httpTask: updateTask)
taskQueue.sendData()
}
}
|
//
// ViewController.swift
// NewsFeed
//
// Created by Sathish Kumar G on 9/25/20.
// Copyright © 2020 Sathish Kumar G. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let tableView = UITableView()
var safeArea = UILayoutGuide()
let stackView = UIStackView()
let CellIdentifier = Constants.CellIdentifier
var feedManager = FeedManager()
var totalResult: [Child] = []
//To Fetch next sets of data
var afterLink: String?
var beforeLink: String?
override func loadView() {
super.loadView()
showLoader()
initialSetup()
setupTableView()
fetchFeedResult(url: Constants.baseUrl)
}
// MARK: - Private Methods
private func initialSetup() {
view.backgroundColor = .white
safeArea = view.layoutMarginsGuide
self.title = Constants.feedTitle
}
private func setupTableView() {
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.register(FeedCellTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(FeedCellTableViewCell.self))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: CellIdentifier)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
}
private func fetchFeedResult(url: String) {
feedManager.getFeedResult( urlString: url, completionHandler:{ receivedModel in
guard let modelData = receivedModel else {
//Error Handling
let alert = UIAlertController(title: "Alert", message: Constants.genericErrorMessage, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
self.totalResult.append(contentsOf: modelData.children)
self.afterLink = modelData.after
self.tableView.reloadData()
self.hideLoader()
})
}
private func showLoader() {
self.tableView.isHidden = true
feedManager.showHUD(thisView: self.view)
}
private func hideLoader() {
self.tableView.isHidden = false
feedManager.hideHUD()
}
private func loadMore() {
// To prevent multiple API call
if self.beforeLink == self.afterLink{
return
}
if let after = self.afterLink {
self.beforeLink = self.afterLink
fetchFeedResult(url: Constants.fetchMoreUrl + after)
}
}
}
// MARK: - Extension
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.totalResult.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(FeedCellTableViewCell.self), for: indexPath) as? FeedCellTableViewCell{
//Setting the data to the custom cell
let cellData = totalResult[indexPath.row]
cell.childData = cellData
//Load more data if reach bottom of tableview
if indexPath.row == totalResult.count - 5 {
self.loadMore()
}
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
//
// ViewController.swift
// Day 18 - Drag and Drop Item Out of CollectionView
//
// Created by 杜赛 on 2020/3/15.
// Copyright © 2020 Du Sai. All rights reserved.
//
import UIKit
class AnimalCollectionCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDragDelegate, UICollectionViewDropDelegate, UICollectionViewDelegateFlowLayout, UIDropInteractionDelegate
{
// MARK: - Parameters
private var animals = "🐶🐱🐭🐹🐰🦊🐻🐼🐨🐯🦁🐮🐷".map { String($0) }
private let animalCellIdentifier = "Animal Cell"
// MARK: - Outlets and Actions
@IBOutlet weak var animalCollection: UICollectionView!
@IBOutlet weak var trashView: UIView! {
didSet {
trashView.addInteraction(UIDropInteraction(delegate: self))
}
}
@IBOutlet weak var trashImageView: UIImageView!
// MARK: - Life Circle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
animalCollection.delegate = self
animalCollection.dataSource = self
animalCollection.dragInteractionEnabled = true
animalCollection.dragDelegate = self
animalCollection.dropDelegate = self
}
// MARK: - Collection and DataSource Delegate
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return animals.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: animalCellIdentifier, for: indexPath)
if let emojiCell = cell as? AnimalCollectionCell {
emojiCell.label.text = animals[indexPath.item]
}
return cell
}
// MARK: - Drag and Drop Delegate
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
if let attributedString = (collectionView.cellForItem(at: indexPath) as? AnimalCollectionCell)?.label.attributedText {
let dragItem = UIDragItem(itemProvider: NSItemProvider(object: attributedString))
dragItem.localObject = indexPath
session.localContext = animalCollection
return [dragItem]
} else {
return []
}
}
func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: NSAttributedString.self)
}
func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
if let indexPath = destinationIndexPath, indexPath.section == 0 {
return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
} else {
return UICollectionViewDropProposal(operation: .cancel)
}
}
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
let destinationIndexPath = coordinator.destinationIndexPath ?? IndexPath(item: 0, section: 0)
for item in coordinator.items {
if let sourceIndexPath = item.sourceIndexPath {
if let _ = item.dragItem.localObject as? IndexPath {
collectionView.performBatchUpdates({
let element = animals.remove(at: sourceIndexPath.item)
animals.insert(element, at: destinationIndexPath.item)
collectionView.deleteItems(at: [sourceIndexPath])
collectionView.insertItems(at: [destinationIndexPath])
})
coordinator.drop(item.dragItem, toItemAt: destinationIndexPath)
}
}
}
}
// MARK: - FlowLayout Delegate
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 80 , height: 80)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return CGFloat(2.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return CGFloat(2.0)
}
// MARK: - DropInteraction Delegate
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: NSAttributedString.self)
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
return UIDropProposal(operation: .copy)
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnter session: UIDropSession) {
UIView.animate(withDuration: 0.5) {
self.trashImageView.transform = .init(scaleX: 1.2, y: 1.2)
}
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnd session: UIDropSession) {
UIView.animate(withDuration: 0.5) {
self.trashImageView.transform = .identity
}
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidExit session: UIDropSession) {
UIView.animate(withDuration: 0.5) {
self.trashImageView.transform = .identity
}
}
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
session.loadObjects(ofClass: NSAttributedString.self) { (providers) in
if let collectionView = (session.localDragSession?.localContext as? UICollectionView),
let indexPath = session.localDragSession?.items.first?.localObject as? IndexPath
{
collectionView.performBatchUpdates ({ [weak self] in
self?.animals.remove(at: indexPath.item)
collectionView.deleteItems(at: [indexPath])
})
}
}
}
}
|
//
// ShareBtns.swift
// gjs_user
//
// Created by 大杉网络 on 2019/8/28.
// Copyright © 2019 大杉网络. All rights reserved.
//
import UIKit
class ShareBtns: UIView {
var btnShare = [UIButton]()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .white
self.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.alignItems = .center
layout.width = YGValue(kScreenW)
layout.height = YGValue(80)
layout.paddingLeft = 15
layout.paddingRight = 15
}
let btnArr = [
[
"name" : "分享链接",
"img" : "share-2"
],
[
"name" : "分享海报",
"img" : "share-3"
],
[
"name" : "地推二维码",
"img" : "share-4"
],
[
"name" : "拉新红包设置",
"img" : "share-5"
]
]
for (index,item) in btnArr.enumerated() {
let btnItem = UIButton()
btnItem.tag = index + 1
btnItem.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .column
layout.alignItems = .center
layout.width = YGValue((kScreenW - 30) * 0.25)
}
self.addSubview(btnItem)
let btnImg = UIImageView(image: UIImage(named: item["img"]!))
btnImg.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 36
layout.height = 36
}
btnItem.addSubview(btnImg)
let btnTitle = UILabel()
btnTitle.text = item["name"]!
btnTitle.textColor = kMainTextColor
btnTitle.font = FontSize(12)
btnTitle.configureLayout { (layout) in
layout.isEnabled = true
layout.marginTop = 10
}
btnItem.addSubview(btnTitle)
btnShare.append(btnItem)
}
self.yoga.applyLayout(preservingOrigin: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ViewController.swift
// FBLoginSwift
//
// Created by bec martin on 5/4/15.
// Copyright (c) 2015 Bec Martin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let ref = Firebase(url: "https://budi.firebaseio.com")
override func viewDidLoad() {
super.viewDidLoad()
ref.observeAuthEventWithBlock({ authData in
if authData != nil {
// user authenticated with Firebase
println(authData)
} else {
self.performSegueWithIdentifier("login", sender: self)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func logout(sender: AnyObject) {
ref.unauth()
NSLog("should be logged out")
}
}
|
//
// AspectRatio_Devices.swift
// 100Views
//
// Created by Mark Moeykens on 8/23/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct AspectRatio_Devices: View {
var body: some View {
VStack(spacing: 20) {
Text("Aspect Ratio")
.font(.largeTitle)
Text("Resizing for Devices")
.font(.title)
.foregroundColor(.gray)
Text("You might have a situation where you want the size of some view to always be half the width of the device but still maintain the same aspect ratio.")
.frame(maxWidth: .infinity)
.padding()
.background(Color.blue)
.foregroundColor(Color.white)
.font(.title).layoutPriority(1)
GeometryReader { geometry in
RoundedRectangle(cornerRadius: 15)
.frame(width: geometry.size.width/2)
.aspectRatio(1.5, contentMode: .fit)
.foregroundColor(.purple)
.overlay(Text("2:3 Aspect Ratio")
.foregroundColor(.white))
}
}
}
}
struct AspectRatio_Devices_Previews: PreviewProvider {
static var previews: some View {
AspectRatio_Devices()
}
}
|
//
// DEDayTableView.swift
// AHWeather
//
// Created by Ara Hakobyan on 3/5/16.
// Copyright © 2016 AroHak LLC. All rights reserved.
//
class DEDayTableView: UITableView, UITableViewDataSource, UITableViewDelegate {
let cellIdentifire = "cellIdentifire"
var days = Array<ForecastDay>()
//MARK: - Initialize
init() {
super.init(frame: .zero, style: .plain)
backgroundColor = CLEAR
dataSource = self
delegate = self
// separatorStyle = .None
separatorColor = GRAY_119
showsVerticalScrollIndicator = false
contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return days.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifire) as? DayCell
let day = days[indexPath.row]
if cell == nil {
cell = DayCell(day: day, reuseIdentifier: cellIdentifire)
} else {
cell!.setValues(forecastDay: day)
}
return cell!
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return LA_CELL_HEIGHT/4
}
}
//MARK: - DayCell
class DayCell: UITableViewCell {
//MARK: - Create UIElements
var cellContentView = DayCellContentView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = CLEAR
self.selectionStyle = .none
}
convenience init(day: ForecastDay, reuseIdentifier: String?) {
self.init(style: .default, reuseIdentifier: reuseIdentifier)
contentView.addSubview(cellContentView)
cellContentView.autoPinEdgesToSuperviewEdges()
setValues(forecastDay: day)
}
func setValues(forecastDay: ForecastDay) {
cellContentView.titleLabel.text = forecastDay.date.weekDay
cellContentView.iconImageView.kf.setImage(with: URL(string: "http:" + forecastDay.day.condition.icon)!)
cellContentView.tempLabel.text = forecastDay.day.maxTemp + " " + forecastDay.day.minTemp
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - DayCellContentView
class DayCellContentView: UIView {
//MARK: - Create UIElements
lazy var titleLabel: AHWLabel = {
let view = AHWLabel.newAutoLayout()
view.font = DE_TITLE_FONT
return view
}()
lazy var iconImageView: UIImageView = {
let view = UIImageView.newAutoLayout()
// view.backgroundColor = BLUE_LIGHT
// view.layer.cornerRadius = LA_ICON_SIZE/2
return view
}()
lazy var tempLabel: AHWLabel = {
let view = AHWLabel.newAutoLayout()
view.font = DE_TITLE_FONT
return view
}()
//MARK: - Initialize
init() {
super.init(frame: .zero)
backgroundColor = CLEAR
addAllUIElements()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Privat Methods
func addAllUIElements() {
addSubview(iconImageView)
addSubview(titleLabel)
addSubview(tempLabel)
setConstraints()
}
//MARK: - Constraints
func setConstraints() {
titleLabel.autoAlignAxis(toSuperviewAxis: .horizontal)
titleLabel.autoPinEdge(toSuperviewEdge: .left, withInset: LA_INSET)
iconImageView.autoCenterInSuperview()
iconImageView.autoSetDimensions(to: CGSize(width: LA_ICON_SIZE, height: LA_ICON_SIZE))
tempLabel.autoAlignAxis(toSuperviewAxis: .horizontal)
tempLabel.autoPinEdge(toSuperviewEdge: .right, withInset: LA_INSET)
}
}
|
//
// PolicyDetailView.swift
// FatlossPro
//
// Created by Apple on 2019/11/7.
// Copyright © 2019 YaorongHuang. All rights reserved.
//
import Foundation
import UIKit
import WebKit
let titleBarColorpdv:UIColor = .white
let bottomBarColorpdv:UIColor = .white
let titleFontpdv:UIFont = UIFont.boldSystemFont(ofSize: CGFloat(18))
let titleTextColorpdv:UIColor = .black
let windowMaskColorpdv:UIColor = UIColor(displayP3Red: 0.0, green: 0.0, blue: 0.0, alpha: 0.75)
let btnBackgroundColorpdv:UIColor = .white
let btnOnLineColorpdv:UIColor = UIColor(displayP3Red: 0.0, green: 0.0, blue: 0.0, alpha: 0.68)
//let btnOnLineColorpdv:UIColor = .init(red: 230/255, green: 57/255, blue: 70/255, alpha: 1.0)
let btnOffLineColorpdv:UIColor = .lightGray
class PolicyDetailView: UIViewController, WKNavigationDelegate {
var wkWebViewpdv:WKWebView!
var backBtnpdv:UIButton!
var forwardBtnpdv:UIButton!
var titleDescpdv:String = " "
var isInitpdv = false
var multiUrlpdv:[String] = [String]()
var backUrlpdv:String?
var callbackpdv: (() -> Void)?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(policytitle:String, policyU:[String]?) {
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
titleDescpdv = policytitle
if (policyU != nil) {
multiUrlpdv = policyU!
}
}
override func viewDidLoad() {
super.viewDidLoad()
let mainViewpdv = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
self.view.addSubview(mainViewpdv)
mainViewpdv.translatesAutoresizingMaskIntoConstraints = false
mainViewpdv.backgroundColor = windowMaskColorpdv
let leftViewpdv = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
mainViewpdv.addSubview(leftViewpdv)
leftViewpdv.translatesAutoresizingMaskIntoConstraints = false
leftViewpdv.backgroundColor = UIColor.clear
let rightViewpdv = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
mainViewpdv.addSubview(rightViewpdv)
rightViewpdv.translatesAutoresizingMaskIntoConstraints = false
rightViewpdv.backgroundColor = UIColor.clear
let topViewpdv = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
mainViewpdv.addSubview(topViewpdv)
topViewpdv.translatesAutoresizingMaskIntoConstraints = false
topViewpdv.backgroundColor = UIColor.clear
let bottmViewpdv = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
mainViewpdv.addSubview(bottmViewpdv)
bottmViewpdv.translatesAutoresizingMaskIntoConstraints = false
bottmViewpdv.backgroundColor = UIColor.clear
let titleViewpdv = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
mainViewpdv.addSubview(titleViewpdv)
titleViewpdv.translatesAutoresizingMaskIntoConstraints = false
titleViewpdv.clipsToBounds = true
titleViewpdv.backgroundColor = titleBarColorpdv
let toolsViewpdv = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
mainViewpdv.addSubview(toolsViewpdv)
toolsViewpdv.translatesAutoresizingMaskIntoConstraints = false
toolsViewpdv.backgroundColor = bottomBarColorpdv
wkWebViewpdv = WKWebView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
mainViewpdv.addSubview(wkWebViewpdv)
wkWebViewpdv.translatesAutoresizingMaskIntoConstraints = false
wkWebViewpdv.backgroundColor = UIColor.groupTableViewBackground
let titleLabelpdv = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
titleViewpdv.addSubview(titleLabelpdv)
titleLabelpdv.translatesAutoresizingMaskIntoConstraints = false
titleLabelpdv.numberOfLines = 1
titleLabelpdv.backgroundColor = UIColor.clear
titleLabelpdv.font = titleFontpdv
titleLabelpdv.textAlignment = NSTextAlignment.center
let homeBtnpdv = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
toolsViewpdv.addSubview(homeBtnpdv)
homeBtnpdv.translatesAutoresizingMaskIntoConstraints = false
homeBtnpdv.backgroundColor = btnBackgroundColorpdv
homeBtnpdv.imageView?.contentMode = .scaleAspectFit
homeBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.vertical)
homeBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.horizontal)
homeBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.vertical)
homeBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.horizontal)
homeBtnpdv.imageView?.contentMode = .scaleAspectFit
homeBtnpdv.setImage(getNaviHomeLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOnLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
homeBtnpdv.setImage(getNaviHomeLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.highlighted)
backBtnpdv = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
toolsViewpdv.addSubview(backBtnpdv)
backBtnpdv.translatesAutoresizingMaskIntoConstraints = false
backBtnpdv.backgroundColor = btnBackgroundColorpdv
backBtnpdv.imageView?.contentMode = .scaleAspectFit
backBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.vertical)
backBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.horizontal)
backBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.vertical)
backBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.horizontal)
backBtnpdv.imageView?.contentMode = .scaleAspectFit
backBtnpdv.setImage(getNaviBackLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOnLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
backBtnpdv.setImage(getNaviBackLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.highlighted)
forwardBtnpdv = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
toolsViewpdv.addSubview(forwardBtnpdv)
forwardBtnpdv.translatesAutoresizingMaskIntoConstraints = false
forwardBtnpdv.backgroundColor = btnBackgroundColorpdv
forwardBtnpdv.imageView?.contentMode = .scaleAspectFit
forwardBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.vertical)
forwardBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.horizontal)
forwardBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.vertical)
forwardBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.horizontal)
forwardBtnpdv.imageView?.contentMode = .scaleAspectFit
forwardBtnpdv.setImage(getNaviForwardLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOnLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
forwardBtnpdv.setImage(getNaviForwardLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.highlighted)
let refreshBtnpdv = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
toolsViewpdv.addSubview(refreshBtnpdv)
refreshBtnpdv.translatesAutoresizingMaskIntoConstraints = false
refreshBtnpdv.backgroundColor = btnBackgroundColorpdv
refreshBtnpdv.imageView?.contentMode = .scaleAspectFit
refreshBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.vertical)
refreshBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.horizontal)
refreshBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.vertical)
refreshBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.horizontal)
refreshBtnpdv.imageView?.contentMode = .scaleAspectFit
refreshBtnpdv.setImage(getNaviRefreshLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOnLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
refreshBtnpdv.setImage(getNaviRefreshLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.highlighted)
let exitBtnpdv = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
toolsViewpdv.addSubview(exitBtnpdv)
exitBtnpdv.translatesAutoresizingMaskIntoConstraints = false
exitBtnpdv.backgroundColor = btnBackgroundColorpdv
exitBtnpdv.imageView?.contentMode = .scaleAspectFit
exitBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.vertical)
exitBtnpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 100), for: NSLayoutConstraint.Axis.horizontal)
exitBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.vertical)
exitBtnpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.horizontal)
exitBtnpdv.imageView?.contentMode = .scaleAspectFit
exitBtnpdv.setImage(getNaviExitLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOnLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
exitBtnpdv.setImage(getNaviExitLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.highlighted)
let linview = UIView()
linview.backgroundColor = .lightGray
toolsViewpdv.addSubview(linview)
linview.translatesAutoresizingMaskIntoConstraints = false
linview.topAnchor.constraint(equalTo: toolsViewpdv.topAnchor).isActive = true
linview.leadingAnchor.constraint(equalTo: toolsViewpdv.leadingAnchor).isActive = true
linview.trailingAnchor.constraint(equalTo: toolsViewpdv.trailingAnchor).isActive = true
linview.bottomAnchor.constraint(equalTo: toolsViewpdv.topAnchor, constant: 0.3).isActive = true
let closeBtnpdv = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
toolsViewpdv.addSubview(closeBtnpdv)
closeBtnpdv.translatesAutoresizingMaskIntoConstraints = false
closeBtnpdv.backgroundColor = titleBarColorpdv
closeBtnpdv.imageView?.contentMode = .scaleAspectFit
closeBtnpdv.setImage(getNaviExitLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: titleTextColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
closeBtnpdv.setImage(getNaviExitLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.highlighted)
let titleLabelHeightpdv = NSLayoutConstraint(item: titleLabelpdv,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 21.0)
titleLabelHeightpdv.priority = UILayoutPriority(rawValue: 249)
titleLabelpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: NSLayoutConstraint.Axis.vertical)
titleLabelpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 750), for: NSLayoutConstraint.Axis.vertical)
titleLabelpdv.setContentHuggingPriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.horizontal)
titleLabelpdv.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 50), for: NSLayoutConstraint.Axis.horizontal)
titleLabelpdv.addConstraint(titleLabelHeightpdv)
titleViewpdv.addConstraints([NSLayoutConstraint(item: titleLabelpdv,
attribute: NSLayoutConstraint.Attribute.centerY,
relatedBy: .equal,
toItem: titleViewpdv,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: titleLabelpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: titleViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: titleLabelpdv,
attribute: .leading,
relatedBy: .equal,
toItem: titleViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: titleLabelpdv,
attribute: .height,
relatedBy: .equal,
toItem: titleViewpdv,
attribute: .height,
multiplier: 0.5,
constant: 0.0)])
self.view.addConstraints([NSLayoutConstraint(item: mainViewpdv,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: mainViewpdv,
attribute: .top,
relatedBy: .equal,
toItem: self.topLayoutGuide,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: mainViewpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: self.view,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: mainViewpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: self.bottomLayoutGuide,
attribute: .top,
multiplier: 1.0,
constant: 0.0)])
mainViewpdv.addConstraints([NSLayoutConstraint(item: leftViewpdv,
attribute: .leading,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv,
attribute: .top,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: bottmViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: wkWebViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: titleViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: topViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: leftViewpdv, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: titleViewpdv, attribute: NSLayoutConstraint.Attribute.height, multiplier: 0.5, constant: 0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .top,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .leading,
relatedBy: .equal,
toItem: bottmViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .leading,
relatedBy: .equal,
toItem: topViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .leading,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .leading,
relatedBy: .equal,
toItem: titleViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv,
attribute: .leading,
relatedBy: .equal,
toItem: wkWebViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: rightViewpdv, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: titleViewpdv, attribute: NSLayoutConstraint.Attribute.height, multiplier: 0.5, constant: 0),
NSLayoutConstraint(item: topViewpdv,
attribute: .top,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: topViewpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: titleViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: topViewpdv, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: titleViewpdv, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1.5, constant: 0),
NSLayoutConstraint(item: bottmViewpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: mainViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: bottmViewpdv,
attribute: .top,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: bottmViewpdv, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: titleViewpdv, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1.5, constant: 0),
NSLayoutConstraint(item: titleViewpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: wkWebViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: toolsViewpdv,
attribute: .top,
relatedBy: .equal,
toItem: wkWebViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)])
toolsViewpdv.addConstraints([NSLayoutConstraint(item: closeBtnpdv,
attribute: .leading,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: closeBtnpdv,
attribute: .top,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: closeBtnpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: closeBtnpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: toolsViewpdv,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 44.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .leading,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .leading,
multiplier: 1.0,
constant: 5.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .top,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 5.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: backBtnpdv,
attribute: .leading,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .width,
relatedBy: .equal,
toItem: backBtnpdv,
attribute: .width,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .width,
relatedBy: .equal,
toItem: forwardBtnpdv,
attribute: .width,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .width,
relatedBy: .equal,
toItem: refreshBtnpdv,
attribute: .width,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: homeBtnpdv,
attribute: .width,
relatedBy: .equal,
toItem: exitBtnpdv,
attribute: .width,
multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: backBtnpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: backBtnpdv,
attribute: .top,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 5.0),
NSLayoutConstraint(item: backBtnpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: forwardBtnpdv,
attribute: .leading,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: forwardBtnpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: forwardBtnpdv,
attribute: .top,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 5.0),
NSLayoutConstraint(item: forwardBtnpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: refreshBtnpdv,
attribute: .leading,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: refreshBtnpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: refreshBtnpdv,
attribute: .top,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 5.0),
NSLayoutConstraint(item: refreshBtnpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: exitBtnpdv,
attribute: .leading,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: exitBtnpdv,
attribute: .bottom,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .bottom,
multiplier: 1.0,
constant: -5.0),
NSLayoutConstraint(item: exitBtnpdv,
attribute: .top,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .top,
multiplier: 1.0,
constant: 5.0),
NSLayoutConstraint(item: exitBtnpdv,
attribute: .trailing,
relatedBy: .equal,
toItem: toolsViewpdv,
attribute: .trailing,
multiplier: 1.0,
constant: -5.0)])
self.view.layoutIfNeeded()
titleViewpdv.backgroundColor = titleBarColorpdv
titleLabelpdv.textColor = titleTextColorpdv
toolsViewpdv.backgroundColor = bottomBarColorpdv
homeBtnpdv.backgroundColor = btnBackgroundColorpdv
backBtnpdv.backgroundColor = btnBackgroundColorpdv
forwardBtnpdv.backgroundColor = btnBackgroundColorpdv
refreshBtnpdv.backgroundColor = btnBackgroundColorpdv
exitBtnpdv.backgroundColor = btnBackgroundColorpdv
closeBtnpdv.backgroundColor = titleBarColorpdv
titleLabelpdv.text = titleDescpdv
if (titleLabelpdv.text!.count > 0) {
toolsViewpdv.backgroundColor = titleBarColorpdv
closeBtnpdv.isHidden = false
} else {
toolsViewpdv.backgroundColor = bottomBarColorpdv
closeBtnpdv.isHidden = true
}
wkWebViewpdv.navigationDelegate = self
homeBtnpdv.addTarget(self, action: #selector(homeBtnClickpdv(sender:)), for: UIControl.Event.touchUpInside)
forwardBtnpdv.addTarget(self, action: #selector(forwardBtnClickpdv(sender:)), for: UIControl.Event.touchUpInside)
backBtnpdv.addTarget(self, action: #selector(backBtnClickpdv(sender:)), for: UIControl.Event.touchUpInside)
refreshBtnpdv.addTarget(self, action: #selector(refreshBtnClickpdv(sender:)), for: UIControl.Event.touchUpInside)
exitBtnpdv.addTarget(self, action: #selector(exitBtnClickpdv(sender:)), for: UIControl.Event.touchUpInside)
closeBtnpdv.addTarget(self, action: #selector(closeBtnClickpdv(sender:)), for: UIControl.Event.touchUpInside)
resetBtnColorpdv(pdvx: nil, pdvy: nil, pdvz: nil)
if (multiUrlpdv.count > 0) {
isInitpdv = true
while (multiUrlpdv.count > 0) {
if let gotoUrlpdv:URL = URL(string: multiUrlpdv[0]) {
let requestpdv:URLRequest = URLRequest(url: gotoUrlpdv)
self.multiUrlpdv.removeFirst()
self.wkWebViewpdv.load(requestpdv)
break
} else {
self.multiUrlpdv.removeFirst()
if (self.multiUrlpdv.count == 0) {
isInitpdv = false
}
}
}
}
}
func setPDVCall(emwkwe: String?, vkwe: String?, cvkmw: String?, asfmkw: (() -> Void)?) {
callbackpdv = asfmkw
}
func loadMultipdv(pdvx: String?, pdvy: String?, pdvz: String?, urlspdv:[String]) {
multiUrlpdv = urlspdv
if (multiUrlpdv.count > 0) {
while (multiUrlpdv.count > 0) {
if let gotoUrlpdv:URL = URL(string: multiUrlpdv[0]) {
let requestpdv:URLRequest = URLRequest(url: gotoUrlpdv)
self.multiUrlpdv.removeFirst()
self.wkWebViewpdv.load(requestpdv)
break
} else {
self.multiUrlpdv.removeFirst()
}
}
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
self.resetBtnColorpdv(pdvx: nil, pdvy: nil, pdvz: nil)
if let urlpdv = navigationAction.request.url {
let htpdv:[Character] = ["h", "-", "t", "-", "t", "-", "p", "-", ":", "-", "/", "-", "/"]
let htspdv:[Character] = ["h", "-", "t", "-", "t", "-", "p", "-", "s", "-", ":", "-", "/", "-", "/"]
let ftpdv:[Character] = ["f", "-", "t", "-", "p", "-", ":", "-", "/", "-", "/"]
if (!(urlpdv.absoluteString.hasPrefix(String(htpdv).replacingOccurrences(of: "-", with: "")) || urlpdv.absoluteString.hasPrefix(String(htspdv).replacingOccurrences(of: "-", with: "")) || urlpdv.absoluteString.hasPrefix(String(ftpdv).replacingOccurrences(of: "-", with: "")))) {
decisionHandler(WKNavigationActionPolicy.cancel)
if (self.wkWebViewpdv.backForwardList.backList.count > 0) {
backUrlpdv = self.wkWebViewpdv.backForwardList.backList[self.wkWebViewpdv.backForwardList.backList.count - 1].url.absoluteString
} else {
backUrlpdv = nil
}
UIApplication.shared.open(urlpdv, options: [:], completionHandler: nil)
return
}
}
backUrlpdv = nil
decisionHandler(.allow)
return
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.resetBtnColorpdv(pdvx: nil, pdvy: nil, pdvz: nil)
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
self.resetBtnColorpdv(pdvx: nil, pdvy: nil, pdvz: nil)
if (isInitpdv) {
if (multiUrlpdv.count > 0) {
while (multiUrlpdv.count > 0) {
if let gotoUrlpdv:URL = URL(string: multiUrlpdv[0]) {
let requestpdv:URLRequest = URLRequest(url: gotoUrlpdv)
self.multiUrlpdv.removeFirst()
self.wkWebViewpdv.load(requestpdv)
break
} else {
self.multiUrlpdv.removeFirst()
if (self.multiUrlpdv.count == 0) {
isInitpdv = false
}
}
}
} else {
isInitpdv = false
}
} else {
if (multiUrlpdv.count > 0) {
while (multiUrlpdv.count > 0) {
if let gotoUrlpdv:URL = URL(string: multiUrlpdv[0]) {
let requestpdv:URLRequest = URLRequest(url: gotoUrlpdv)
self.multiUrlpdv.removeFirst()
self.wkWebViewpdv.load(requestpdv)
break
} else {
self.multiUrlpdv.removeFirst()
}
}
}
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.resetBtnColorpdv(pdvx: nil, pdvy: nil, pdvz: nil)
}
func resetBtnColorpdv(pdvx: String?, pdvy: String?, pdvz: String?) {
DispatchQueue.main.async {
if (self.wkWebViewpdv.canGoBack) {
self.backBtnpdv.setImage(getNaviBackLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOnLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
} else {
self.backBtnpdv.setImage(getNaviBackLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
}
if (self.wkWebViewpdv.canGoForward) {
self.forwardBtnpdv.setImage(getNaviForwardLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOnLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
} else {
self.forwardBtnpdv.setImage(getNaviForwardLineImagepdv(pdvx: nil, pdvy: nil, pdvz: nil, imageSizepdv: 100, arrowStrokeWidthpdv: 8, arrowColorpdv: btnOffLineColorpdv, backgroundColorpdv: .clear), for: UIControl.State.normal)
}
}
}
@objc func homeBtnClickpdv(sender: UIButton) {
if (self.wkWebViewpdv.canGoBack) {
self.wkWebViewpdv.load(URLRequest(url: self.wkWebViewpdv.backForwardList.backList[0].url))
}
}
@objc func backBtnClickpdv(sender: UIButton) {
if (self.titleDescpdv.count > 0) {
if (self.wkWebViewpdv.canGoBack) {
self.wkWebViewpdv.goBack()
} else {
self.dismiss(animated: true) {
if (self.callbackpdv != nil) {
self.callbackpdv!()
}
}
}
} else {
if (self.wkWebViewpdv.canGoBack) {
if (backUrlpdv != nil) {
var lastIndexpdv = self.wkWebViewpdv.backForwardList.backList.count - 1
for i in 0..<self.wkWebViewpdv.backForwardList.backList.count {
if (self.wkWebViewpdv.backForwardList.backList[self.wkWebViewpdv.backForwardList.backList.count - i - 1].url.absoluteString == backUrlpdv!) {
lastIndexpdv = self.wkWebViewpdv.backForwardList.backList.count - i - 1
break
}
}
self.wkWebViewpdv.go(to: self.wkWebViewpdv.backForwardList.backList[lastIndexpdv])
} else {
self.wkWebViewpdv.goBack()
}
}
}
}
@objc func forwardBtnClickpdv(sender: UIButton) {
if (self.wkWebViewpdv.canGoForward) {
self.wkWebViewpdv.goForward()
}
}
@objc func refreshBtnClickpdv(sender: UIButton) {
self.wkWebViewpdv.reload()
}
@objc func exitBtnClickpdv(sender: UIButton) {
if (self.titleDescpdv.count > 0) {
self.dismiss(animated: true) {
if (self.callbackpdv != nil) {
self.callbackpdv!()
}
}
} else {
exit(0)
}
}
@objc func closeBtnClickpdv(sender: UIButton) {
self.dismiss(animated: true) {
if (self.callbackpdv != nil) {
self.callbackpdv!()
}
}
}
}
func radiansToDegreespdv(pdvx: String?, pdvy: String?, pdvz: String?, radianspdv:CGFloat) -> CGFloat {
//
// 弧度轉成角度
return radianspdv * 180 / CGFloat.pi
}
func degreesToRadianspdv(pdvx: String?, pdvy: String?, pdvz: String?, degreespdv:CGFloat) -> CGFloat {
//
// 角度轉成弧度
return degreespdv * CGFloat.pi / 180
}
func getXrightPlusByRadiuspdv(pdvx: String?, pdvy: String?, pdvz: String?, lengthpdv:CGFloat, degreesRightpdv:CGFloat) -> CGFloat {
//
// 中心向右為0度,逆時針旋轉,X左為正Y上為正
return lengthpdv * cos(degreesRightpdv * CGFloat.pi / 180)
}
func getYtopPlusByRadiuspdv(pdvx: String?, pdvy: String?, pdvz: String?, lengthpdv:CGFloat, degreesRightpdv:CGFloat) -> CGFloat {
//
// 中心向右為0度,逆時針旋轉,X左為正Y上為正
return lengthpdv * sin(degreesRightpdv * CGFloat.pi / 180)
}
func getSideLengthByXpdv(pdvx: String?, pdvy: String?, pdvz: String?, lengthpdv:CGFloat, degreesRightpdv:CGFloat) -> CGFloat {
//
// 中心向右為0度,逆時針旋轉,X左為正Y上為正
let yLenpdv = lengthpdv * tan(degreesRightpdv * CGFloat.pi / 180)
return sqrt(lengthpdv*lengthpdv + yLenpdv*yLenpdv)
}
func getSideLengthByYpdv(pdvx: String?, pdvy: String?, pdvz: String?, lengthpdv:CGFloat, degreesRightpdv:CGFloat) -> CGFloat {
//
// 中心向右為0度,逆時針旋轉,X左為正Y上為正
let xLenpdv = lengthpdv / tan(degreesRightpdv * CGFloat.pi / 180)
return sqrt(lengthpdv*lengthpdv + xLenpdv*xLenpdv)
}
func getYtopPlusByXpdv(pdvx: String?, pdvy: String?, pdvz: String?, lengthpdv:CGFloat, degreesRightpdv:CGFloat) -> CGFloat {
//
// 中心向右為0度,逆時針旋轉,X左為正Y上為正
return lengthpdv * tan(degreesRightpdv * CGFloat.pi / 180)
}
func getXrightPlusByYpdv(pdvx: String?, pdvy: String?, pdvz: String?, lengthpdv:CGFloat, degreesRightpdv:CGFloat) -> CGFloat {
//
// 中心向右為0度,逆時針旋轉,X左為正Y上為正
return lengthpdv / tan(degreesRightpdv * CGFloat.pi / 180)
}
func imageToBase64pdv(pdvx: String?, pdvy: String?, pdvz: String?, imagepdv:UIImage) -> String {
//
// 將圖片轉為 base64 字串
if let imageDatapdv = imagepdv.pngData() {
return imageDatapdv.base64EncodedString()
} else {
if let imageDatapdv = imagepdv.jpegData(compressionQuality: 0.75) {
return imageDatapdv.base64EncodedString()
} else {
return ""
}
}
}
func base64ToImagepdv(pdvx: String?, pdvy: String?, pdvz: String?, base64pdv:String) -> UIImage? {
if let dataDecodedpdv = Data(base64Encoded: base64pdv, options: Data.Base64DecodingOptions.init()) {
if let decodedimagepdv = UIImage(data: dataDecodedpdv) {
return decodedimagepdv
}
}
return nil
}
func getNaviHomeLineImagepdv(pdvx: String?, pdvy: String?, pdvz: String?, imageSizepdv:CGFloat?, arrowStrokeWidthpdv:CGFloat?, arrowColorpdv:UIColor?, backgroundColorpdv:UIColor?) -> UIImage? {
var contextSizepdv:CGFloat = 100
if (imageSizepdv != nil) {
contextSizepdv = imageSizepdv!
}
let sideLangthpdv:CGFloat = contextSizepdv * 0.8
var strokeWidthpdv:CGFloat = 4
if (arrowStrokeWidthpdv != nil) {
strokeWidthpdv = arrowStrokeWidthpdv!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: contextSizepdv, height: contextSizepdv), false, 0.0)
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.move(to: CGPoint(x: 0, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: contextSizepdv))
contextpdv.addLine(to: CGPoint(x: 0, y: contextSizepdv))
contextpdv.closePath()
if let colorpdv = backgroundColorpdv {
contextpdv.setFillColor(colorpdv.cgColor)
} else {
contextpdv.setFillColor(UIColor.clear.cgColor)
}
contextpdv.fillPath()
}
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.setLineCap(.round)
contextpdv.setLineJoin(.round)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 , y: contextSizepdv * 0.1 + sideLangthpdv / 2.0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2, y: contextSizepdv * 0.1))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv, y: contextSizepdv * 0.1 + sideLangthpdv / 2.0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.85, y: contextSizepdv * 0.1 + sideLangthpdv / 2.0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.85, y: contextSizepdv * 0.1 + sideLangthpdv))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.7, y: contextSizepdv * 0.1 + sideLangthpdv))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.7, y: contextSizepdv * 0.1 + sideLangthpdv * 0.7))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.3, y: contextSizepdv * 0.1 + sideLangthpdv * 0.7))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.3, y: contextSizepdv * 0.1 + sideLangthpdv))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.15, y: contextSizepdv * 0.1 + sideLangthpdv))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.15, y: contextSizepdv * 0.1 + sideLangthpdv / 2.0))
contextpdv.setLineWidth(strokeWidthpdv)
if let colorpdv = arrowColorpdv {
contextpdv.setStrokeColor(colorpdv.cgColor)
} else {
contextpdv.setStrokeColor(UIColor.clear.cgColor)
}
contextpdv.strokePath()
}
let imgpdv = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imgpdv
}
func getNaviBackLineImagepdv(pdvx: String?, pdvy: String?, pdvz: String?, imageSizepdv:CGFloat?, arrowStrokeWidthpdv:CGFloat?, arrowColorpdv:UIColor?, backgroundColorpdv:UIColor?) -> UIImage? {
var contextSizepdv:CGFloat = 100
if (imageSizepdv != nil) {
contextSizepdv = imageSizepdv!
}
let sideLangthpdv:CGFloat = contextSizepdv * 0.8
var strokeWidthpdv:CGFloat = 4
if (arrowStrokeWidthpdv != nil) {
strokeWidthpdv = arrowStrokeWidthpdv!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: contextSizepdv, height: contextSizepdv), false, 0.0)
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.move(to: CGPoint(x: 0, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: contextSizepdv))
contextpdv.addLine(to: CGPoint(x: 0, y: contextSizepdv))
contextpdv.closePath()
if let colorpdv = backgroundColorpdv {
contextpdv.setFillColor(colorpdv.cgColor)
} else {
contextpdv.setFillColor(UIColor.clear.cgColor)
}
contextpdv.fillPath()
}
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.setLineCap(.round)
contextpdv.setLineJoin(.round)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.4, y: contextSizepdv * 0.1 + sideLangthpdv * 0.9))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1, y: contextSizepdv * 0.1 + sideLangthpdv * 0.5))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.4, y: contextSizepdv * 0.1 + sideLangthpdv * 0.1))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.4, y: contextSizepdv * 0.1 + sideLangthpdv * 0.3))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv, y: contextSizepdv * 0.1 + sideLangthpdv * 0.3))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv, y: contextSizepdv * 0.1 + sideLangthpdv * 0.7))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.4, y: contextSizepdv * 0.1 + sideLangthpdv * 0.7))
contextpdv.setLineWidth(strokeWidthpdv)
if let colorpdv = arrowColorpdv {
contextpdv.setStrokeColor(colorpdv.cgColor)
} else {
contextpdv.setStrokeColor(UIColor.clear.cgColor)
}
contextpdv.strokePath()
}
let imgpdv = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imgpdv
}
func getNaviForwardLineImagepdv(pdvx: String?, pdvy: String?, pdvz: String?, imageSizepdv:CGFloat?, arrowStrokeWidthpdv:CGFloat?, arrowColorpdv:UIColor?, backgroundColorpdv:UIColor?) -> UIImage? {
var contextSizepdv:CGFloat = 100
if (imageSizepdv != nil) {
contextSizepdv = imageSizepdv!
}
let sideLangthpdv:CGFloat = contextSizepdv * 0.8
var strokeWidthpdv:CGFloat = 4
if (arrowStrokeWidthpdv != nil) {
strokeWidthpdv = arrowStrokeWidthpdv!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: contextSizepdv, height: contextSizepdv), false, 0.0)
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.move(to: CGPoint(x: 0, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: contextSizepdv))
contextpdv.addLine(to: CGPoint(x: 0, y: contextSizepdv))
contextpdv.closePath()
if let colorpdv = backgroundColorpdv {
contextpdv.setFillColor(colorpdv.cgColor)
} else {
contextpdv.setFillColor(UIColor.clear.cgColor)
}
contextpdv.fillPath()
}
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.setLineCap(.round)
contextpdv.setLineJoin(.round)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.6, y: contextSizepdv * 0.1 + sideLangthpdv * 0.9))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv, y: contextSizepdv * 0.1 + sideLangthpdv * 0.5))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.6, y: contextSizepdv * 0.1 + sideLangthpdv * 0.1))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.6, y: contextSizepdv * 0.1 + sideLangthpdv * 0.3))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1, y: contextSizepdv * 0.1 + sideLangthpdv * 0.3))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1, y: contextSizepdv * 0.1 + sideLangthpdv * 0.7))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.6, y: contextSizepdv * 0.1 + sideLangthpdv * 0.7))
contextpdv.setLineWidth(strokeWidthpdv)
if let colorpdv = arrowColorpdv {
contextpdv.setStrokeColor(colorpdv.cgColor)
} else {
contextpdv.setStrokeColor(UIColor.clear.cgColor)
}
contextpdv.strokePath()
}
let imgpdv = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imgpdv
}
func getNaviRefreshLineImagepdv(pdvx: String?, pdvy: String?, pdvz: String?, imageSizepdv:CGFloat?, arrowStrokeWidthpdv:CGFloat?, arrowColorpdv:UIColor?, backgroundColorpdv:UIColor?) -> UIImage? {
var contextSizepdv:CGFloat = 100
if (imageSizepdv != nil) {
contextSizepdv = imageSizepdv!
}
let sideLangthpdv:CGFloat = contextSizepdv * 0.8
var strokeWidthpdv:CGFloat = 4
if (arrowStrokeWidthpdv != nil) {
strokeWidthpdv = arrowStrokeWidthpdv!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: contextSizepdv, height: contextSizepdv), false, 0.0)
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.move(to: CGPoint(x: 0, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: contextSizepdv))
contextpdv.addLine(to: CGPoint(x: 0, y: contextSizepdv))
contextpdv.closePath()
if let colorpdv = backgroundColorpdv {
contextpdv.setFillColor(colorpdv.cgColor)
} else {
contextpdv.setFillColor(UIColor.clear.cgColor)
}
contextpdv.fillPath()
}
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.setLineCap(.round)
contextpdv.setLineJoin(.round)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0 + getXrightPlusByRadiuspdv(pdvx: nil, pdvy: nil, pdvz: nil, lengthpdv: sideLangthpdv * 0.4, degreesRightpdv: 150), y: contextSizepdv * 0.1 + sideLangthpdv / 2.0 - getYtopPlusByRadiuspdv(pdvx: nil, pdvy: nil, pdvz: nil, lengthpdv: sideLangthpdv * 0.4, degreesRightpdv: 150)))
contextpdv.addArc(center: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0, y: contextSizepdv * 0.1 + sideLangthpdv / 2.0), radius: sideLangthpdv * 0.4, startAngle: 210 * CGFloat.pi / 180 , endAngle: 0, clockwise: false)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.8, y: contextSizepdv * 0.1 + sideLangthpdv * 0.4))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.9, y: contextSizepdv * 0.1 + sideLangthpdv * 0.5))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 1, y: contextSizepdv * 0.1 + sideLangthpdv * 0.4))
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0 + getXrightPlusByRadiuspdv(pdvx: nil, pdvy: nil, pdvz: nil, lengthpdv: sideLangthpdv * 0.4, degreesRightpdv: 330), y: contextSizepdv * 0.1 + sideLangthpdv / 2.0 - getYtopPlusByRadiuspdv(pdvx: nil, pdvy: nil, pdvz: nil, lengthpdv: sideLangthpdv * 0.4, degreesRightpdv: 330)))
contextpdv.addArc(center: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0, y: contextSizepdv * 0.1 + sideLangthpdv / 2.0), radius: sideLangthpdv * 0.4, startAngle: 30 * CGFloat.pi / 180 , endAngle: 180 * CGFloat.pi / 180, clockwise: false)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.2, y: contextSizepdv * 0.1 + sideLangthpdv * 0.6))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv * 0.1, y: contextSizepdv * 0.1 + sideLangthpdv * 0.5))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1, y: contextSizepdv * 0.1 + sideLangthpdv * 0.6))
contextpdv.setLineWidth(strokeWidthpdv)
if let colorpdv = arrowColorpdv {
contextpdv.setStrokeColor(colorpdv.cgColor)
} else {
contextpdv.setStrokeColor(UIColor.clear.cgColor)
}
contextpdv.strokePath()
}
let imgpdv = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imgpdv
}
func getNaviExitLineImagepdv(pdvx: String?, pdvy: String?, pdvz: String?, imageSizepdv:CGFloat?, arrowStrokeWidthpdv:CGFloat?, arrowColorpdv:UIColor?, backgroundColorpdv:UIColor?) -> UIImage? {
var contextSizepdv:CGFloat = 100
if (imageSizepdv != nil) {
contextSizepdv = imageSizepdv!
}
let sideLangthpdv:CGFloat = contextSizepdv * 0.8
var strokeWidthpdv:CGFloat = 4
if (arrowStrokeWidthpdv != nil) {
strokeWidthpdv = arrowStrokeWidthpdv!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: contextSizepdv, height: contextSizepdv), false, 0.0)
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.move(to: CGPoint(x: 0, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: 0))
contextpdv.addLine(to: CGPoint(x: contextSizepdv, y: contextSizepdv))
contextpdv.addLine(to: CGPoint(x: 0, y: contextSizepdv))
contextpdv.closePath()
if let colorpdv = backgroundColorpdv {
contextpdv.setFillColor(colorpdv.cgColor)
} else {
contextpdv.setFillColor(UIColor.clear.cgColor)
}
contextpdv.fillPath()
}
if let contextpdv = UIGraphicsGetCurrentContext() {
contextpdv.beginPath()
contextpdv.setLineCap(.round)
contextpdv.setLineJoin(.round)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0 + getXrightPlusByRadiuspdv(pdvx: nil, pdvy: nil, pdvz: nil, lengthpdv: sideLangthpdv * 0.4, degreesRightpdv: 120), y: contextSizepdv * 0.1 + sideLangthpdv / 2.0 - getYtopPlusByRadiuspdv(pdvx: nil, pdvy: nil, pdvz: nil, lengthpdv: sideLangthpdv * 0.4, degreesRightpdv: 120)))
contextpdv.addArc(center: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0, y: contextSizepdv * 0.1 + sideLangthpdv / 2.0), radius: sideLangthpdv * 0.4, startAngle: 240 * CGFloat.pi / 180 , endAngle: 300 * CGFloat.pi / 180, clockwise: true)
contextpdv.move(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0, y: contextSizepdv * 0.1))
contextpdv.addLine(to: CGPoint(x: contextSizepdv * 0.1 + sideLangthpdv / 2.0, y: contextSizepdv * 0.1 + sideLangthpdv * 0.4))
contextpdv.setLineWidth(strokeWidthpdv)
if let colorpdv = arrowColorpdv {
contextpdv.setStrokeColor(colorpdv.cgColor)
} else {
contextpdv.setStrokeColor(UIColor.clear.cgColor)
}
contextpdv.strokePath()
}
let imgpdv = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imgpdv
}
|
//
// Home.swift
// Instaframe
//
// Created by Jean-Baptiste Waring on 2021-02-07.
//
import SwiftUI
struct Home: View {
@Environment(\.managedObjectContext) var managedObjectContext
@State var showSettings = false
@Binding var currentUser:InstaUser
var body: some View {
TabView {
ContentView(showSettings: $showSettings, currentUser: $currentUser).environment(\.managedObjectContext, managedObjectContext)
.tabItem {
Image(systemName: "newspaper")
Text("Home")
}
PostCreatorView(currentUser: $currentUser).environment(\.managedObjectContext, managedObjectContext)
.tabItem {
Image(systemName: "plus.rectangle.portrait")
Text("New Post")
}
HomeFeedView(username: currentUser.userName ?? "", currentuser: currentUser)
.tabItem {
Image(systemName: "person")
Text("Me")
}
}.sheet(isPresented: $showSettings, onDismiss: {updateUser()}, content: {
SettingsView( currentUser: $currentUser).environment(\.managedObjectContext, managedObjectContext)
})
}
}
struct Home_Previews: PreviewProvider {
static var previews: some View {
Home(currentUser: .constant(sampleUser))
}
}
extension Home {
func updateUser() {
}
}
|
//
// benchMarker.swift
// Maps Benchmark
//
// Created by Gideon Rabson on 11/4/18.
// Copyright © 2018 Gideon Rabson. All rights reserved.
//
import Foundation
class BenchMarker {
let n: Int
let operations: Int
let directory: String
let mapCount: Int
var randomLists: [[Int]] = []
var extraLists: [[Int]] = []
var shuffledLists: [[Int]] = []
lazy var lm: [LinearMap<Int, Int>] = {
var out = [LinearMap<Int, Int>](repeating: LinearMap<Int, Int>(), count: mapCount)
fillMaps(&out)
return out
}()
lazy var bm: [BinaryMap<Int, Int>] = {
var out = [BinaryMap<Int, Int>](repeating: BinaryMap<Int, Int>(), count: mapCount)
fillMaps(&out)
return out
}()
lazy var hm: [HashMap<Int, Int>] = {
var out = [HashMap<Int, Int>](repeating: HashMap<Int, Int>(initialArraySize: 2 * n), count: mapCount)
fillMaps(&out)
return out
}()
init (n: Int, operations: Int, mapCount: Int, directory: String) {
self.n = n
self.operations = operations
self.directory = directory
self.mapCount = mapCount
randomLists.reserveCapacity(mapCount)
extraLists.reserveCapacity(mapCount)
shuffledLists.reserveCapacity(mapCount)
for i in 0..<mapCount {
randomLists.append(makeRandomList(n))
extraLists.append(makeRandomList(operations))
shuffledLists.append(makeShuffledList(from: randomLists[i], count: operations))
}
}
enum OperationType {
case add
case update
case get
}
enum MapType {
case linearMap
case binaryMap
case hashMap
}
func makeRandomList (_ length: Int) -> [Int] {
var randomList = [Int]()
randomList.reserveCapacity(length)
for _ in 0..<length {
randomList.append(Int.random(in: Int.min...Int.max))
}
return randomList
}
func makeShuffledList <Element> (from list: [Element], count: Int) -> [Element] {
var shuffledList = [Element]()
shuffledList.reserveCapacity(count)
for _ in 0..<count {
shuffledList.append(list[Int.random(in: 0..<list.count)])
}
return shuffledList
}
func fillMaps <BenchMap: BenchMapProtocol> (_ maps: inout [BenchMap]){
for index in 0..<maps.count {
for i in randomLists[index] {
maps[index].set(i, i)
}
}
}
func testAddFunc <BenchMap: BenchMapProtocol> (_ maps: inout [BenchMap]) -> Double {
var time: Double = 0
for index in 0..<maps.count {
for i in extraLists[index] {
var mapCopy = maps[index]
let startDate = Date()
mapCopy.set(i, i)
let elapsed = Date().timeIntervalSince(startDate)
time += elapsed
}
}
return time / Double(operations * mapCount)
}
func testUpdateFunc <BenchMap: BenchMapProtocol> (_ maps: inout [BenchMap]) -> Double {
let startDate = Date()
for index in 0..<maps.count {
for i in shuffledLists[index] {
maps[index].set(i, i)
}
}
let elapsed = Date().timeIntervalSince(startDate)
return elapsed / Double(operations * mapCount)
}
func testGetFunc <BenchMap: BenchMapProtocol> (_ maps: inout [BenchMap]) -> Double {
let startDate = Date()
for index in 0..<maps.count {
for i in shuffledLists[index] {
maps[index].get(i)
}
}
let elapsed = Date().timeIntervalSince(startDate)
return elapsed / Double(operations * mapCount)
}
func writeAddTest <BenchMap: BenchMapProtocol> (_ maps: inout [BenchMap]) {
let fileName = generateFileNameFor(map: &maps[0], operation: .add)
let toWrite = "\(n), \(testAddFunc(&maps))"
updateFile(fileName, data: toWrite)
}
func writeUpdateTest <BenchMap: BenchMapProtocol> (_ maps: inout [BenchMap]) {
let fileName = generateFileNameFor(map: &maps[0], operation: .update)
let toWrite = "\(n), \(testUpdateFunc(&maps))"
updateFile(fileName, data: toWrite)
}
func writeGetTest <BenchMap: BenchMapProtocol> (_ maps: inout [BenchMap]) {
let fileName = generateFileNameFor(map: &maps[0], operation: .get)
let toWrite = "\(n), \(testGetFunc(&maps))"
updateFile(fileName, data: toWrite)
}
func runTest (_ map: MapType, _ operation: OperationType) { //I had to use nested switch statements because swift didn't like my generics. Any other way, including helper functions, caused an error. Please don't take off points here. Swift forced me to do it.
switch map {
case .linearMap:
switch operation {
case .add:
writeAddTest(&lm)
case .update:
writeUpdateTest(&lm)
case .get:
writeGetTest(&lm)
}
case .binaryMap:
switch operation {
case .add:
writeAddTest(&bm)
case .update:
writeUpdateTest(&bm)
case .get:
writeGetTest(&bm)
}
case .hashMap:
switch operation {
case .add:
writeAddTest(&hm)
case .update:
writeUpdateTest(&hm)
case .get:
writeGetTest(&hm)
}
}
}
func updateFile (_ fileName: String, data: String) {
var maybeFile = FileHandle(forUpdatingAtPath: directory + "/" + fileName)
if maybeFile == nil {
FileManager.default.createFile(atPath: directory + "/" + fileName, contents: nil, attributes: nil)
maybeFile = FileHandle(forUpdatingAtPath: directory + "/" + fileName)
}
guard let file = maybeFile else {
print("Directory of file does not exist.")
return
}
file.seekToEndOfFile()
let toWrite = data + "\n"
file.write(toWrite.data(using: String.Encoding.utf8)!)
file.closeFile()
}
func generateFileNameFor <BenchMap: BenchMapProtocol> (map: inout BenchMap, operation: OperationType) -> String {
var fileName = ""
switch map.myType {
case "LinearMap<Int, Int>":
fileName += "linearMap"
case "BinaryMap<Int, Int>":
fileName += "binaryMap"
case "HashMap<Int, Int>":
fileName += "hashMap"
default:
fileName += "This isn't a linear, binary, or hash map so idk what just happened"
}
switch operation {
case .add:
fileName += "Add"
case .update:
fileName += "Update"
case .get:
fileName += "Get"
}
fileName += ".csv"
return fileName
}
}
|
//
// LineView.swift
// LineChart
//
// Created by András Samu on 2019. 09. 02..
// Copyright © 2019. András Samu. All rights reserved.
//
import SwiftUI
public struct CustomLineView: View {
@ObservedObject var data: ChartData
public var title: String?
public var legend: String?
public var style: ChartStyle
@Environment(\.colorScheme) var colorScheme: ColorScheme
@State private var showLegend = false
@State private var dragLocation:CGPoint = .zero
@State private var indicatorLocation:CGPoint = .zero
@State private var closestPoint: CGPoint = .zero
@State private var opacity:Double = 0
@State private var currentDataNumber: String = ""
@State private var hideHorizontalLines: Bool = false
public init(data: [Int],date:[String], title: String? = nil, legend: String? = nil, style: ChartStyle? = Styles.lineChartStyleOne){
self.data = ChartData(points: data,date: date)
self.title = title
self.legend = legend
self.style = style!
}
public var body: some View {
GeometryReader{ geometry in
VStack(alignment: .leading, spacing: 5) {
ZStack{
GeometryReader{ reader in
Rectangle().foregroundColor(self.colorScheme == .dark ? Color.black : self.style.backgroundColor)
Line(data: self.data, frame: .constant(CGRect(x: 0, y: 0, width: reader.frame(in: .local).width - 30, height: reader.frame(in: .local).height-20)), touchLocation: self.$indicatorLocation,showIndicator: self.$hideHorizontalLines ,showBackground: true).offset(x: 30, y: 0)
.onAppear(){
self.showLegend.toggle()
}
if(self.showLegend){
CustomLegend(data: self.data, frame: .constant(CGRect(x: 0, y: 0, width: reader.frame(in: .local).width + 30, height: reader.frame(in: .local).height-20)), hideHorizontalLines: self.$hideHorizontalLines)
.transition(.opacity)
.animation(Animation.easeOut(duration: 0.4).delay(0.4))
}
}.frame(width: geometry.frame(in: .local).size.width, height: 200)
MagnifierRect(currentNumber: self.$currentDataNumber)
.opacity(self.opacity)
.offset(x: self.dragLocation.x - geometry.frame(in: .local).size.width/2, y: 0)
}
.frame(width: geometry.frame(in: .local).size.width, height: 200)
.gesture(DragGesture()
.onChanged({ value in
self.dragLocation = value.location
self.indicatorLocation = CGPoint(x: max(value.location.x-30,0), y: 0)
self.opacity = 1
self.closestPoint = self.getClosestDataPoint(toPoint: value.location, width: geometry.frame(in: .local).size.width-30, height: 200)
self.hideHorizontalLines = true
})
.onEnded({ value in
self.opacity = 0
self.hideHorizontalLines = false
})
)
Text((self.data.date.first ?? "") + " - " + (self.data.date.last ?? "") )
.foregroundColor(Color("Primary"))
.bold()
.padding(.top,5)
}
}
}
func getClosestDataPoint(toPoint: CGPoint, width:CGFloat, height: CGFloat) -> CGPoint {
let stepWidth: CGFloat = width / CGFloat(data.points.count-1)
let stepHeight: CGFloat = height / CGFloat(data.points.max()! + data.points.min()!)
let index:Int = Int(floor((toPoint.x-15)/stepWidth))
if (index >= 0 && index < data.points.count){
self.currentDataNumber = self.data.date[index]
return CGPoint(x: CGFloat(index)*stepWidth, y: CGFloat(self.data.points[index])*stepHeight)
}
return .zero
}
}
struct LineView_Previews: PreviewProvider {
static var previews: some View {
CustomLineView(data: [0,30,30,65,100,30,30,65,30], date: ["11 Nov","12 Nov","13 Nov","14 Nov","15 Nov","16 Nov","17 Nov","18 Nov","19 Nov"], title: "Demam", legend: "in last 23 days").frame(width: 400, height: 300).padding().offset(x: 0, y: -60)
}
}
struct IndicatorCircle: View {
var body: some View {
Circle()
.size(width: 12, height: 12)
.fill(Colors.BorderBlue)
}
}
struct MagnifierRect: View {
@Binding var currentNumber:String
@Environment(\.colorScheme) var colorScheme: ColorScheme
var body: some View {
ZStack{
Text(currentNumber)
.font(.system(size: 14, weight: .bold))
.offset(x: 0, y:-90)
.animation(.spring())
.foregroundColor(self.colorScheme == .dark ? Color("Primary") : Color.black)
if (self.colorScheme == .dark ){
RoundedRectangle(cornerRadius: 16)
.stroke(Color.white, lineWidth: self.colorScheme == .dark ? 2 : 0)
.frame(width: 60, height: 800)
}else{
RoundedRectangle(cornerRadius: 16)
.frame(width: 60, height: 260)
.foregroundColor(Color.white)
.shadow(color: Color("Primary"), radius: 12, x: 0, y: 6 )
.blendMode(.multiply)
}
}.animation(.linear)
}
}
|
//
// BusView.swift
// CollegeTransit
//
// Created by Jacob Miller on 2/25/20.
// Copyright © 2020 Jacob Miller. All rights reserved.
//
import SwiftUI
struct BusView: View {
@EnvironmentObject var uPrefs: UPrefDelegate
@State var showDetail = false;
var bus: Bus
var body: some View {
VStack(alignment: .leading){
HStack{
Text(bus.patternName)
.font(.headline)
.foregroundColor(Color.gray)
Spacer()
VStack{
if (uPrefs.starredRoutes.contains(bus.routeId)){
Image(systemName: "star.fill")
.foregroundColor(Color.systemYellow)
}
}
}
if(showDetail){
VStack(alignment: .leading){
HStack{
Text("Route:")
Spacer()
Text("\(bus.routeId)")
}
HStack{
Text("Passengers:")
Spacer()
Text("\(bus.passengers!)")
}
HStack{
Text("Stop ID:")
Spacer()
Text("\(bus.stopId)")
}
HStack{
Text("ID:")
Spacer()
Text("\(bus.id)")
}
}
.font(.caption)
.foregroundColor(Color.gray)
}
}
.onTapGesture{
self.showDetail.toggle()
}
.animation(.spring(response: 0.01, dampingFraction: 1, blendDuration: 1))
}
}
|
//
// Config.swift
// Shift
//
// Created by Scaria on 4/20/16.
// Copyright © 2016 Meredith Moore. All rights reserved.
//
import Foundation
import SwiftLoader
import ionicons
class Config: NSObject {
static let sharedInstance = Config()
var config : SwiftLoader.Config;
var menuIcons: NSDictionary;
let menuItems = ["Home","Exercises","Performance", "Settings", "Logout"]
let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let allExercises:Array<String> = ["Clock Reach", "Side Hip Raise"]
let exerciseInfo = [
"Clock Reach-enable" : true,
"Clock Reach-video": "yi01KXc7laY",
"Side Hip Raise-enable": true,
"Side Hip Raise-video": "eW0xZApmUyo"
]
private override init(){
self.config = SwiftLoader.Config();
self.menuIcons = [:]
if(defaults.arrayForKey("exercises") == nil){
defaults.setObject(allExercises, forKey: "exercises")
defaults.setValuesForKeysWithDictionary(exerciseInfo)
}
}
func getExercises() -> (exercises: Array<String>, videos: Array<String>){
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let exercises = defaults.arrayForKey("exercises")
var ex:Array<String> = []
var videos:Array<String> = []
exercises?.forEach({exercise in
if(defaults.valueForKey("\(exercise)-enable") as! Bool){
ex.append(exercise as! String)
videos.append(defaults.stringForKey("\(exercise)-video")!)
}
})
return (ex, videos)
}
func doConfig(){
config.size = 150
config.backgroundColor = Constants.ui.complimentaryBGColor
config.spinnerColor = Constants.ui.backgroundColor
config.titleTextColor = Constants.ui.backgroundColor
config.foregroundAlpha = 0.4
SwiftLoader.setConfig(config)
self.menuSetup()
}
func menuSetup(){
let size = CGFloat(30.0)
let imageSize = CGSizeMake(30.0, 50.0)
self.menuIcons = [
"Home": IonIcons.imageWithIcon(ion_ios_home, iconColor: Constants.ui.complimentaryBGColor, iconSize: size, imageSize: imageSize),
"Exercises": IonIcons.imageWithIcon(ion_android_walk, iconColor: Constants.ui.complimentaryBGColor, iconSize: size, imageSize: imageSize),
"Performance": IonIcons.imageWithIcon(ion_ios_pulse, iconColor: Constants.ui.complimentaryBGColor, iconSize: size, imageSize: imageSize),
"Settings": IonIcons.imageWithIcon(ion_ios_cog, iconColor: Constants.ui.complimentaryBGColor, iconSize: size, imageSize: imageSize),
"Logout": IonIcons.imageWithIcon(ion_log_out, iconColor: UIColor.redColor(), iconSize: size, imageSize: imageSize)
]
}
} |
//
// ItemsViewController.swift
// CALayerDemo
//
// Created by wizard on 12/23/15.
// Copyright © 2015 Alchemist. All rights reserved.
//
import UIKit
class MenuItemsViewController : UITableViewController {
var menuItems: [(String, String)] {
get {
return [
("SimpleCALayer", "Just the basic sample"),
("CALayer", "Manage and animate visual content"),
("CAScrollLayer", "Display portion of a scrollable layer"),
("CATextLayer", "Render plain text or attributed strings"),
("AVPlayerLayer", "Display an AV player "),
("CAGradientLayer", "Apply a color gradient over the background"),
("CAReplicatorLayer", "Duplicate a source layer"),
("CATiledLayer", "Asynchronously draw layer content in tiles"),
("CAShapeLayer", "Draw using scalable vector paths"),
("CAEAGLLayer", "Draw OpenGL content"),
("CATransformLayer", "Draw 3D structures"),
("CAEmitterLayer", "Render animated particles")
]
}
}
var navController : UINavigationController!
var detailViewController : UIViewController!
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuItemCell")!
cell.textLabel?.text = menuItems[indexPath.row].0
cell.detailTextLabel?.text = menuItems[indexPath.row].1
cell.imageView?.image = UIImage(named: menuItems[indexPath.row].0)
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let identifier = menuItems[indexPath.row].0
navController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier) as! UINavigationController
detailViewController = navController.topViewController
detailViewController?.navigationItem.leftBarButtonItem = splitViewController!.displayModeButtonItem
detailViewController?.navigationItem.leftItemsSupplementBackButton = true
splitViewController?.showDetailViewController(navController, sender: nil)
}
}
|
//
// ViewController.swift
// Listas
//
// Created by Alumno on 9/28/21.
// Copyright © 2021 Alumno. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let nombres = ["Jose", "Ana", "Pedro", "Juan"]
let matriculas = ["99999", "99998", "99997", "99996"]
let promedios = ["9.1", "8.5", "9.3", "8.7"]
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nombres.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let celda = tableView.dequeueReusableCell(withIdentifier: "celdaAlumno")
return celda!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
|
//
// Mapa.swift
// CarFinder
//
// Created by Mauri on 27/4/17.
// Copyright © 2017 Mauri. All rights reserved.
//
import Foundation
class Mapa: conexion {
private let mapa : String = "Mapa.php"
func insertarPosicion(matricula:String, latitud:String, longitud: String, finished: @escaping ((_ respuesta: NSDictionary)->Void)) {
let datos = "action=insertar&matricula="+matricula+"&longitud="+longitud+"&latitud="+latitud
ejecutar(peticion: datos, tipo: self.mapa) {
respuesta in
finished(respuesta)
}
}
func cargarPosiciones(usuario:String, finished: @escaping ((_ respuesta: NSDictionary)->Void)) {
let datos = "action=leerPorUsuario&email="+usuario
ejecutar(peticion: datos, tipo: self.mapa) {
respuesta in
finished(respuesta)
}
}
func eliminarPosicion(matricula: String, finished: @escaping ((_ respuesta: NSDictionary)->Void)) {
let datos = "action=borrar&matricula="+matricula
ejecutar(peticion: datos, tipo: self.mapa) {
respuesta in
finished(respuesta)
}
}
}
|
//: [Previous](@previous)
import Foundation
let intArray: Array<Int> = [1, 2, 3]
let newArray = intArray.map { String($0) } // produces Array<String>
print(newArray)
let intSet: Set<Int> = [1, 2, 3]
let newSet = intSet.map { String($0) } // produces Set<String>
print(newSet)
//protocol Functor {
// associatedtype A
// func fmap<FB where FB ~= Self>(f: A -> FB.A) -> FB
//}
//: [Next](@next)
|
//
// SingleLocation.swift
// SwiftTool
//
// Created by liujun on 2021/5/24.
// Copyright © 2021 yinhe. All rights reserved.
//
import Foundation
import CoreLocation
/// 单次定位
public final class SingleLocation: NSObject {
/// Error
public enum Error: LocalizedError {
case error(String?)
public var errorDescription: String? {
switch self {
case .error(let des):
return des
}
}
public var localizedDescription: String? {
switch self {
case .error(let des):
return des
}
}
}
/// 单例
public static let `default` = SingleLocation()
private var locationManager: CLLocationManager?
private var completion: ((CLPlacemark?, SingleLocation.Error?) -> Void)?
private override init() {
super.init()
}
}
extension SingleLocation {
/// 开始单次定位
///
/// GLSingleLocation.default.startSingleLocation { (place, err) in
///
/// }
///
/// - Parameters:
/// - desiredAccuracy: 定位精度
/// - completion: 定位回调
public func startSingleLocation(desiredAccuracy: CLLocationAccuracy = kCLLocationAccuracyBest,
completion: ((CLPlacemark?, SingleLocation.Error?) -> Void)?) {
if !CLLocationManager.locationServicesEnabled() {
self.completion?(nil, SingleLocation.Error.error("location services not enabled"))
return
}
self.completion = nil
self.locationManager = nil
self.completion = completion
self.locationManager = CLLocationManager()
self.locationManager?.delegate = self
self.locationManager?.desiredAccuracy = desiredAccuracy
self.locationManager?.startUpdatingLocation()
}
}
extension SingleLocation: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Swift.Error) {
self.locationManager?.stopUpdatingLocation()
self.locationManager = nil
self.completion?(nil, SingleLocation.Error.error(error.localizedDescription))
self.completion = nil
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager?.stopUpdatingLocation()
self.locationManager = nil
guard let location = locations.first else {
self.locationManager = nil
self.completion?(nil, SingleLocation.Error.error("no location"))
self.completion = nil
return
}
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { [weak self] (placemarks, error) in
guard let self = self else { return }
if let error = error {
self.locationManager = nil
self.completion?(nil, SingleLocation.Error.error(error.localizedDescription))
self.completion = nil
return
}
guard let placemark = placemarks?.first else {
self.locationManager = nil
self.completion?(nil, SingleLocation.Error.error("no placemarks"))
self.completion = nil
return
}
_printPlacemarkInfo(placemark: placemark)
self.locationManager = nil
self.completion?(placemark, SingleLocation.Error.error(error?.localizedDescription))
self.completion = nil
}
}
}
private func _printPlacemarkInfo(placemark: CLPlacemark) {
#if DEBUG
// 四大直辖市的城市信息无法通过`CLPlacemark`的`locality`属性获得,
// 只能通过访问`administrativeArea`属性来获得(如果`locality`为空,则可知为直辖市)
var addressDictionary: [String: Any] = [:]
(placemark.addressDictionary ?? [:]).forEach { (value) in
addressDictionary["\(value.key)"] = value.value
}
let message: String =
"\n"
+ "***************************************************************"
+ "\n"
+ "name(具体位置) = \((placemark.name ?? "nil"))"
+ "\n"
+ "thoroughfare(街道) = \((placemark.thoroughfare ?? "nil"))"
+ "\n"
+ "subThoroughfare(子街道) = \((placemark.subThoroughfare ?? "nil"))"
+ "\n"
+ "locality(市) = \((placemark.locality ?? "nil"))"
+ "\n"
+ "subLocality(区) = \((placemark.subLocality ?? "nil"))"
+ "\n"
+ "administrativeArea(省或者州) = \((placemark.administrativeArea ?? "nil"))"
+ "\n"
+ "subAdministrativeArea(其他行政信息,可能是县镇乡等) = \((placemark.subAdministrativeArea ?? "nil"))"
+ "\n"
+ "postalCode(邮政编码) = \((placemark.postalCode ?? "nil"))"
+ "\n"
+ "isoCountryCode(国家代码) = \((placemark.isoCountryCode ?? "nil"))"
+ "\n"
+ "country(国家) = \((placemark.country ?? "nil"))"
+ "\n"
+ "inlandWater(水源、湖泊) = \((placemark.inlandWater ?? "nil"))"
+ "\n"
+ "ocean(海洋) = \((placemark.ocean ?? "nil"))"
+ "\n"
+ "areasOfInterest(获取关联的或利益相关的地标) = \((placemark.areasOfInterest ?? []))"
+ "\n"
+ "addressDictionary = \(addressDictionary as NSDictionary)"
+ "\n"
+ "***************************************************************"
+ "\n"
print(message)
#endif
}
|
//
// gradiate.swift
// coalay
//
// Created by 落合裕也 on 2020/11/07.
// Copyright © 2020 落合裕也. All rights reserved.
//
import SwiftUI
struct Gradation:View {
var body: some View{
LinearGradient(gradient: Gradient(colors: [.black, .gray]), startPoint: .top, endPoint: .bottom)
.edgesIgnoringSafeArea(.all)
}
}
|
//
// InitialModel.swift
// MVVMCDependencyInjection
//
// Created by Steven Curtis on 03/06/2020.
// Copyright © 2020 Steven Curtis. All rights reserved.
//
import Foundation
struct InitialModel : Codable {
let dataString : String
}
|
// Copyright © 2018 Nazariy Gorpynyuk.
// All rights reserved.
import Foundation
import Cornerstones
import ReactiveSwift
import Alamofire
public extension Reactive where Base: SessionManager {
/// Reactively makes an HTTP data request with "application/protobuf" expected content type in the response.
func makingProtobuf(request: HTTPRequest) -> SpEr<HTTPDataResponse> {
var httpRequest = request
httpRequest.expectedContentType = .protobuf
return makingForData(request: httpRequest, acceptForValidation: [.protobuf])
}
}
|
//
// HTTPURLResponseExtension.swift
// CoreML_test
//
// Created by owl on 18.03.18.
// Copyright © 2018 Осина П.М. All rights reserved.
//
import Foundation
extension HTTPURLResponse {
func isSuccessful() -> Bool{
return 200 ..< 300 ~= statusCode
}
}
|
// Copyright 2019 Kakao Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public class Properties {
static let sdkVersionKey = "com.kakao.sdk.version"
public static func saveCodable<T: Codable>(key: String, data:T?) {
if let encoded = try? JSONEncoder().encode(data) {
SdkLog.d("save-plain : \(encoded as NSData)")
guard let crypted = SdkCrypto.shared.encrypt(data: encoded) else { return }
SdkLog.d("save-crypted : \(crypted as NSData)")
UserDefaults.standard.set(crypted, forKey:key)
UserDefaults.standard.synchronize()
}
}
public static func loadCodable<T: Codable>(key: String) -> T? {
if let data = UserDefaults.standard.data(forKey: key) {
SdkLog.d("load-crypted : \(data as NSData)")
guard let plain = SdkCrypto.shared.decrypt(data: data) else { return nil }
SdkLog.d("load-plain : \(plain as NSData)")
return try? JSONDecoder().decode(T.self, from:plain)
}
return nil
}
public static func delete(_ key: String) {
UserDefaults.standard.removeObject(forKey: key)
}
static func save(key: String, string:String?) {
UserDefaults.standard.set(string, forKey:key)
UserDefaults.standard.synchronize()
}
static func load(key: String) -> String? {
UserDefaults.standard.string(forKey:key)
}
public static func markedSdkVersion() -> String? {
return Properties.load(key: sdkVersionKey)
}
public static func markSdkVersion() {
Properties.save(key: Properties.sdkVersionKey, string: KakaoSDKCommon.shared.sdkVersion())
}
}
|
//
// LoginLoginRouterInput.swift
// DroneDeployViper
//
// Created by James Talano on 6/7/21.
// Copyright © 2021 James. All rights reserved.
//
import UIKit
protocol LoginRouterInput {
func showNextViewController(fromVC: UIViewController, identifier: String)
func popupViewController(fromVC: UIViewController)
func logOut(fromVC: UIViewController)
}
|
//
// ItemModifyViewController.swift
// Inventory Management System
//
// Created by 邱凯 on 11/8/19.
// Copyright © 2019 MountainPeak. All rights reserved.
//
import Foundation
import UIKit
class ItemModifyViewController: UIViewController {
var amount = -1
var itemIndex:Int = -1
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var backBtn: UIButton!
@IBOutlet weak var deleteBtn: UIButton!
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var noteTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
backBtn.layer.cornerRadius = 4
deleteBtn.layer.cornerRadius = 4
saveBtn.layer.cornerRadius = 4
setupTextFields_Note()
// amount = Utils.tempPurchaseList[itemIndex][3]
amountLabel.text = Utils.tempPurchaseList[itemIndex][3]
noteTextField.text = Utils.tempPurchaseList[itemIndex][4]
slider.value = Float(Utils.tempPurchaseList[itemIndex][3]) as! Float
}
@IBAction func onSlide(_ sender: Any) {
amountLabel.text = String(Int(slider.value))
}
@IBAction func onTapSaveBtn(_ sender: Any) {
Utils.tempPurchaseList[itemIndex][3] = amountLabel.text!
Utils.tempPurchaseList[itemIndex][4] = noteTextField.text!
}
//This would show a Done button when user click the BarcodeTextField
func setupTextFields_Note() {
let toolbar = UIToolbar(frame: CGRect(origin: .zero, size: .init(width: view.frame.size.width, height: 30)))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBtn = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonAction_Note))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
noteTextField.inputAccessoryView = toolbar
}
@objc func doneButtonAction_Note(){
self.view.endEditing(true)
}
@IBAction func onTapDeleteBtn(_ sender: Any) {
let alert = UIAlertController(title: "Delete Item", message: "Are you sure to delete this item?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
Utils.tempPurchaseList.remove(at: self.itemIndex)
self.performSegue(withIdentifier: "BackToListMakingView", sender: sender)
}))
self.present(alert, animated: true)
}
}
|
//
// AddCluesViewController.swift
// ScavengerHunter
//
// Created by Sergio Mollica on 2016-04-18.
// Copyright © 2016 Sergio Mollica. All rights reserved.
//
import UIKit
import MapKit
import Parse
import ParseUI
let smallCell: Double = 50
let largeCell: Double = 280
let smallTopConstraint = CGFloat(smallCell - 52)
let largeTopConstraint = CGFloat(largeCell - 52)
class AddCluesViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, MKMapViewDelegate, CreateClueTableViewCellDelegate {
// MARK: Outlets
@IBOutlet weak var huntImageView: PFImageView!
@IBOutlet weak var huntNameLabel: SHLabel!
@IBOutlet weak var createHuntButton: SHButton!
@IBOutlet weak var tableView: SHTableView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
// MARK: Properties
var newHunt = Hunt()
var indexClicked: NSIndexPath?
// MARK: viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
getFields()
self.huntNameLabel.adjustsFontSizeToFitWidth = true
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style:.Plain, target:nil, action:nil)
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
self.createHuntButton.titleLabel!.adjustsFontSizeToFitWidth = true
}
// MARK: Actions
@IBAction func createHuntButtonPressed(sender: AnyObject) {
var clueCountWarning = "Your Hunt has " + String(self.newHunt.clues.count) + " Clue"
if self.newHunt.clues.count > 1 {
clueCountWarning += "s"
}
if newHunt.name == "" {
warningAlert("Missing Hunt Name", optional: false)
} else if newHunt.prize == "" {
warningAlert("Missing Hunt Prize", optional: false)
} else if newHunt.clues.count == 0 {
warningAlert("Your Hunt has Zero Clues", optional: false)
} else if newHunt.desc == "" {
warningAlert("Missing Hunt Description\n" + clueCountWarning, optional: true)
} else {
warningAlert(clueCountWarning, optional: true)
}
}
// MARK: UITableViewDataSource/Delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return newHunt.clues.count
} else {
return 1
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("createClueCell") as! CreateClueTableViewCell
cell.delegate = self
if indexPath.section == 0 {
cell.editButton.setTitle(" Edit Clue ", forState: UIControlState.Normal)
cell.editButtonTopConstraint.constant = largeTopConstraint
cell.clueNumberLabel.hidden = false
cell.clueImageView!.hidden = false
cell.mapView.hidden = false
cell.clueLabel.hidden = false
cell.expandButton.hidden = false
let clue = newHunt.clues[indexPath.row]
cell.clue = clue
cell.clueLabel.text = clue.clue
cell.clueNumberLabel.text = "Clue # " + "\(indexPath.row + 1)"
let clueImage = clue.image
clueImage.getDataInBackgroundWithBlock({ (data, error) in
if error == nil {
cell.clueImageView.image = UIImage(data: data!)
}
})
let defaultPFGeoPoint = PFGeoPoint(latitude: 0, longitude: 0)
if clue.solution != defaultPFGeoPoint {
let range = 0.002 / defaultAccuracy * clue.accuracy
let span = MKCoordinateSpan(latitudeDelta: range, longitudeDelta: range)
self.showGeoFence(cell)
let center = CLLocationCoordinate2D(latitude: cell.clue!.solution.latitude, longitude: (cell.clue?.solution.longitude)!)
let region = MKCoordinateRegion(center: center, span: span)
cell.mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = center
annotation.title = "clue"
cell.mapView.addAnnotation(annotation)
}
cell.editButton.tag = indexPath.row
cell.expandButton.hidden = false
cell.mapView.layer.cornerRadius = cornerRadius
if clue.isExpanded {
cell.expandButton.setImage(UIImage(named: "minus_math-25"), forState: UIControlState.Normal)
} else {
cell.expandButton.setImage(UIImage(named: "plus_math-25"), forState: UIControlState.Normal)
}
} else {
cell.editButton.setTitle(" Create New Clue ", forState: UIControlState.Normal)
cell.editButton.tag = -1
cell.editButtonTopConstraint.constant = smallTopConstraint
cell.clueNumberLabel.hidden = true
cell.clueImageView!.hidden = true
cell.mapView.hidden = true
cell.clueLabel.hidden = true
cell.expandButton.hidden = true
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if indexPath.row > newHunt.clues.count {
return CGFloat(largeCell)
} else {
if !newHunt.clues[indexPath.row].isExpanded {
return CGFloat(smallCell)
} else {
return CGFloat(largeCell)
}
}
} else {
return CGFloat(smallCell)
}
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if indexPath.section == 0 {
return .Delete
} else {
return .None
}
}
func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath) {
let clue = newHunt.clues[indexPath.row]
if clue.isExpanded == false {
clue.isExpanded = true
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
newHunt.clues.removeAtIndex(indexPath.row)
var renumberClue = 1
for clue in newHunt.clues {
clue.number = renumberClue
renumberClue += 1
}
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
self.tableView.reloadData()
}
}
// MARK CreateClueTableViewCellDelegate
func reloadTable() {
self.tableView.reloadData()
}
func triggerClueDetailSegue(sender: UIButton) {
if sender.tag == -1 {
self.indexClicked = NSIndexPath(forRow: 0, inSection: 1)
} else {
let row = sender.tag
self.indexClicked = NSIndexPath(forRow: row, inSection: 0)
}
performSegueWithIdentifier("clueDetails", sender: self)
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
// MARK: MKMapViewDelegate
func showGeoFence(cell: CreateClueTableViewCell) {
let center = CLLocationCoordinate2D(latitude: cell.clue!.solution.latitude, longitude: (cell.clue?.solution.longitude)!)
let visualGeoFence = MKCircle(centerCoordinate: center, radius: cell.clue!.accuracy)
cell.mapView.addOverlay(visualGeoFence)
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let circleView = MKCircleRenderer(overlay: overlay)
circleView.fillColor = UIColor.orangeColor().colorWithAlphaComponent(0.4)
circleView.strokeColor = UIColor.redColor()
circleView.lineWidth = 1
return circleView
}
// MARK: Helper Functions
func getFields() {
self.huntNameLabel.text = self.newHunt.name
let huntImage = newHunt.image
huntImage.getDataInBackgroundWithBlock({ (data, error) in
if error == nil {
self.huntImageView.image = UIImage(data: data!)
}
})
self.loadingIndicator.hidden = true
}
func createHunt() {
newHunt.creator = PFUser.currentUser()
self.loadingIndicator.hidden = false
self.createHuntButton.hidden = true
self.loadingIndicator.startAnimating()
newHunt.saveInBackgroundWithBlock { (result, error) in
self.loadingIndicator.hidden = true
self.createHuntButton.hidden = false
self.loadingIndicator.stopAnimating()
self.performSegueWithIdentifier("backToSelection", sender: self)
}
}
// MARK: Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "clueDetails" {
let vc = segue.destinationViewController as! ClueCreatorViewController
vc.newHunt = self.newHunt
vc.clueIndex = self.indexClicked
}
}
// MARK: Unwind Segue
@IBAction func unwindToClues(segue: UIStoryboardSegue) {
//
}
// MARK: Alert
func warningAlert(string: String, optional: Bool) {
let alertController = UIAlertController(title: "Warning!", message: string, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
if optional {
alertController.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.Default, handler: { action in
self.createHunt()
}))
}
self.presentViewController(alertController, animated: true, completion: nil)
}
} |
//
// Contact.swift
// CompanyDirectory
//
// Created by Brian Bernberg on 10/3/16.
// Copyright © 2016 Shared. All rights reserved.
//
import UIKit
class Contact: NSObject {
var firstName: String?
var lastName: String?
var title: String?
var emails: [String: String]
var website: String?
var social: [String: String]
var birthday: Date?
var photoURLPath: String?
var phoneNumbers: [String: String]
var photo: UIImage?
var displayName: String {
if let firstName = self.firstName, let lastName = self.lastName {
return "\(firstName) \(lastName)"
} else if let firstName = self.firstName {
return firstName
} else {
return self.lastName ?? String()
}
}
var sortingName: String {
if let lastName = self.lastName {
return lastName.uppercased()
} else {
return self.displayName.uppercased()
}
}
init(firstName: String? = nil,
lastName: String? = nil,
title: String? = nil,
emails: [String: String],
website: String? = nil,
social: [String: String],
birthday: Date? = nil,
photoURLPath: String? = nil,
phoneNumbers: [String: String]) {
self.firstName = firstName
self.lastName = lastName
self.title = title
self.emails = emails
self.website = website
self.social = social
self.birthday = birthday
self.photoURLPath = photoURLPath
self.phoneNumbers = phoneNumbers
}
static func == (left: Contact, right: Contact) -> Bool {
return left.firstName == right.firstName &&
left.lastName == right.lastName &&
left.title == right.title &&
left.emails == right.emails &&
left.website == right.website &&
left.social == right.social &&
left.birthday == right.birthday &&
left.photoURLPath == right.photoURLPath &&
left.phoneNumbers == right.phoneNumbers
}
}
|
import Foundation
import TMDb
extension Department {
static func mock(
name: String = .randomString,
jobs: [String] = [.randomString, .randomString]
) -> Self {
.init(
name: name,
jobs: jobs
)
}
static var costumeAndMakeUp: Self {
.mock(
name: "Costume & Make-Up",
jobs: [
"Set Costumer",
"Co-Costume Designer"
]
)
}
static var production: Self {
.mock(
name: "Production",
jobs: [
"Casting",
"ADR Voice Casting",
"Production Accountant"
]
)
}
}
extension Array where Element == Department {
static var mocks: [Department] {
[.costumeAndMakeUp, .production]
}
}
|
//
// GetServiceVC.swift
// SlipItIn
//
// Created by Parvinder Singh on 12/03/17.
// Copyright © 2017 Parvinder Singh. All rights reserved.
//
import UIKit
var getServiceRowsImageIcon = [UIImage]()
var getServiceRowsLabel = [String]()
class GetServiceVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var servicesMenuButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
getServiceRowsImageIcon = [UIImage(named:"book-slip")!, UIImage(named:"hire-caption")!, UIImage(named:"hire-crew-member")!,
UIImage(named:"repair")!, UIImage(named:"clean-boat")!, UIImage(named:"gas")!, UIImage(named:"sea-tow")!, UIImage(named:"charter")!]
getServiceRowsLabel = ["Book a Slip", "Hire a Caption", "Hire a Crew Member", "Repair Boat", "Clean Boat", "Gas", "Sea Tow/Boat US", "Charter"]
servicesMenuButton.target = self.revealViewController()
servicesMenuButton.action = #selector(SWRevealViewController.revealToggle(_:))
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return getServiceRowsLabel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let serviceCell = tableView.dequeueReusableCell(withIdentifier: "GetServiceCell") as! GetServiceCell
serviceCell.getServiceCellLabel.text = getServiceRowsLabel[indexPath.row]
serviceCell.getServiceCellImage.image = getServiceRowsImageIcon[indexPath.row]
return serviceCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! GetServiceCell
if cell.getServiceCellLabel.text! == "Book a Slip" {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let destinyVC = mainStoryboard.instantiateViewController(withIdentifier: "SlipVC") as! SlipVC
navigationController?.pushViewController(destinyVC, animated: true)
}
if cell.getServiceCellLabel.text == "Hire a Caption" {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let destinyVC = mainStoryboard.instantiateViewController(withIdentifier: "HireVC") as! HireVC
navigationController?.pushViewController(destinyVC, animated: true)
}
if cell.getServiceCellLabel.text == "Hire a Crew Member"{
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let destinyVC = mainStoryboard.instantiateViewController(withIdentifier: "HireVC") as! HireVC
navigationController?.pushViewController(destinyVC, animated: true)
}
}
}
|
//
// CoverageViewController.swift
// Coverage Dirs
//
// Created by Dušan Tadić on 24.11.19.
// Copyright © 2019 Dušan Tadić. All rights reserved.
//
import Cocoa
import SwiftUI
class CoverageViewController: NSViewController {
@IBOutlet weak var outlineView: NSOutlineView!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
var rootDirectory: CoverageDirectory? {
didSet {
self.outlineView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.outlineView.dataSource = self
self.outlineView.delegate = self
}
func showLoading() {
self.progressIndicator.startAnimation(self)
}
func hideLoading() {
self.progressIndicator.stopAnimation(self)
}
}
extension CoverageViewController: NSOutlineViewDataSource, NSOutlineViewDelegate {
func outlineView(_ outlineView: NSOutlineView,
child index: Int,
ofItem item: Any?) -> Any {
if item == nil,
let item = self.rootDirectory {
var subItems = (item.children as [Any])
subItems.append(contentsOf: item.files)
return subItems[index]
}
guard let item = item as? CoverageDirectory else {
fatalError("Item should be directory")
}
var subItems = (item.children as [Any])
subItems.append(contentsOf: item.files)
return subItems[index]
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
guard let item = item as? CoverageDirectory else {
return false
}
return !item.children.isEmpty || !item.files.isEmpty
}
func outlineView(_ outlineView: NSOutlineView,
numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return (self.rootDirectory?.children.count ?? 0) +
(self.rootDirectory?.files.count ?? 0)
}
guard let item = item as? CoverageDirectory else {
return 0
}
return item.children.count + item.files.count
}
func outlineView(_ outlineView: NSOutlineView,
viewFor tableColumn: NSTableColumn?,
item: Any) -> NSView? {
if let item = item as? CoverageDirectory {
if tableColumn!.identifier.rawValue == "filename" {
let textView = FilenameCellView()
textView.filename = item.name
return textView
} else if tableColumn!.identifier.rawValue == "coverage_percentage" {
return makeCoveragePercentageView(coverage: item.coverage)
} else if tableColumn?.identifier.rawValue == "coverage" {
return makeCoverageView(coverage: item.coverage)
}
} else if let item = item as? CoverageFile {
if tableColumn!.identifier.rawValue == "filename" {
let textView = FilenameCellView()
textView.filename = item.name
return textView
} else if tableColumn!.identifier.rawValue == "coverage_percentage" {
return makeCoveragePercentageView(coverage: item.coverage)
} else if tableColumn?.identifier.rawValue == "coverage" {
return makeCoverageView(coverage: item.coverage)
}
}
return nil
}
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
return 20
}
private func makeCoveragePercentageView(coverage: CoverageData) -> NSView {
let textView = NSTextField()
textView.drawsBackground = false
textView.isBezeled = false
textView.isEditable = false
textView.alignment = .right
textView.stringValue = "\(Int(coverage.coverage * 100))%"
return textView
}
private func makeCoverageView(coverage: CoverageData) -> NSView {
let view = PercentageView(percentage: coverage.coverage)
let hostingView = NSHostingView(rootView: view)
let holderView = NSView()
holderView.addSubview(hostingView)
hostingView.translatesAutoresizingMaskIntoConstraints = false
hostingView
.heightAnchor
.constraint(equalToConstant: 5)
.isActive = true
hostingView
.leadingAnchor
.constraint(equalTo: holderView.leadingAnchor)
.isActive = true
hostingView
.trailingAnchor
.constraint(equalTo: holderView.trailingAnchor)
.isActive = true
hostingView
.centerYAnchor
.constraint(equalTo: holderView.centerYAnchor)
.isActive = true
return holderView
}
}
|
//
// ZXDrugDetailCell.swift
// YDHYK
//
// Created by 120v on 2017/11/23.
// Copyright © 2017年 screson. All rights reserved.
//
import UIKit
class ZXDrugDetailCell: UITableViewCell {
static let ZXDrugDetailCellID: String = "ZXDrugDetailCell"
@IBOutlet weak var nameLb: UILabel!
@IBOutlet weak var countLb: UILabel!
@IBOutlet weak var remarkLb: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.nameLb.textColor = UIColor.zx_textColorTitle
self.countLb.textColor = UIColor.zx_textColorTitle
self.remarkLb.textColor = UIColor.zx_textColorMark
self.nameLb.font = UIFont.zx_titleFont
self.countLb.font = UIFont.zx_titleFont
self.remarkLb.font = UIFont.zx_markFont
}
func loadData(_ model: ZXRemindModel) {
self.nameLb.text = model.drugName
self.remarkLb.text = model.notes
self.countLb.text = "\(model.dosage)\(model.unit)"
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// Asteroid.swift
// TestApp
//
// Created by Михаил Красильник on 27.04.2021.
//
import Foundation
// MARK: - Welcome
struct AsteroidModel: Codable {
let nearEarthObjects: [NearEarthObject]
enum CodingKeys: String, CodingKey {
case nearEarthObjects = "near_earth_objects"
}
}
// MARK: - NearEarthObject
struct NearEarthObject: Codable, Hashable {
let links: NearEarthObjectLinks
let id, neoReferenceID, name, nameLimited: String
let designation: String
let nasaJplURL: String
let absoluteMagnitudeH: Double
let estimatedDiameter: EstimatedDiameter
let isPotentiallyHazardousAsteroid: Bool
let closeApproachData: [CloseApproachDatum]
let orbitalData: OrbitalData
let isSentryObject: Bool
enum CodingKeys: String, CodingKey {
case links, id
case neoReferenceID = "neo_reference_id"
case name
case nameLimited = "name_limited"
case designation
case nasaJplURL = "nasa_jpl_url"
case absoluteMagnitudeH = "absolute_magnitude_h"
case estimatedDiameter = "estimated_diameter"
case isPotentiallyHazardousAsteroid = "is_potentially_hazardous_asteroid"
case closeApproachData = "close_approach_data"
case orbitalData = "orbital_data"
case isSentryObject = "is_sentry_object"
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: NearEarthObject, rhs: NearEarthObject) -> Bool {
lhs.id == rhs.id
}
}
// MARK: - CloseApproachDatum
struct CloseApproachDatum: Codable {
let closeApproachDate, closeApproachDateFull: String
let epochDateCloseApproach: Int
let relativeVelocity: RelativeVelocity
let missDistance: MissDistance
let orbitingBody: OrbitingBody
enum CodingKeys: String, CodingKey {
case closeApproachDate = "close_approach_date"
case closeApproachDateFull = "close_approach_date_full"
case epochDateCloseApproach = "epoch_date_close_approach"
case relativeVelocity = "relative_velocity"
case missDistance = "miss_distance"
case orbitingBody = "orbiting_body"
}
}
// MARK: - MissDistance
struct MissDistance: Codable {
let astronomical, lunar, kilometers, miles: String
}
enum OrbitingBody: String, Codable {
case earth = "Earth"
case juptr = "Juptr"
case mars = "Mars"
case merc = "Merc"
case venus = "Venus"
}
// MARK: - RelativeVelocity
struct RelativeVelocity: Codable {
let kilometersPerSecond, kilometersPerHour, milesPerHour: String
enum CodingKeys: String, CodingKey {
case kilometersPerSecond = "kilometers_per_second"
case kilometersPerHour = "kilometers_per_hour"
case milesPerHour = "miles_per_hour"
}
}
// MARK: - EstimatedDiameter
struct EstimatedDiameter: Codable {
let kilometers, meters, miles, feet: Feet
}
// MARK: - Feet
struct Feet: Codable {
let estimatedDiameterMin, estimatedDiameterMax: Double
enum CodingKeys: String, CodingKey {
case estimatedDiameterMin = "estimated_diameter_min"
case estimatedDiameterMax = "estimated_diameter_max"
}
}
// MARK: - NearEarthObjectLinks
struct NearEarthObjectLinks: Codable {
let linksSelf: String
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
}
}
// MARK: - OrbitalData
struct OrbitalData: Codable {
let orbitID, orbitDeterminationDate, firstObservationDate, lastObservationDate: String
let dataArcInDays, observationsUsed: Int
let orbitUncertainty, minimumOrbitIntersection, jupiterTisserandInvariant, epochOsculation: String
let eccentricity, semiMajorAxis, inclination, ascendingNodeLongitude: String
let orbitalPeriod, perihelionDistance, perihelionArgument, aphelionDistance: String
let perihelionTime, meanAnomaly, meanMotion: String
let equinox: Equinox
let orbitClass: OrbitClass
enum CodingKeys: String, CodingKey {
case orbitID = "orbit_id"
case orbitDeterminationDate = "orbit_determination_date"
case firstObservationDate = "first_observation_date"
case lastObservationDate = "last_observation_date"
case dataArcInDays = "data_arc_in_days"
case observationsUsed = "observations_used"
case orbitUncertainty = "orbit_uncertainty"
case minimumOrbitIntersection = "minimum_orbit_intersection"
case jupiterTisserandInvariant = "jupiter_tisserand_invariant"
case epochOsculation = "epoch_osculation"
case eccentricity
case semiMajorAxis = "semi_major_axis"
case inclination
case ascendingNodeLongitude = "ascending_node_longitude"
case orbitalPeriod = "orbital_period"
case perihelionDistance = "perihelion_distance"
case perihelionArgument = "perihelion_argument"
case aphelionDistance = "aphelion_distance"
case perihelionTime = "perihelion_time"
case meanAnomaly = "mean_anomaly"
case meanMotion = "mean_motion"
case equinox
case orbitClass = "orbit_class"
}
}
enum Equinox: String, Codable {
case j2000 = "J2000"
}
// MARK: - OrbitClass
struct OrbitClass: Codable {
let orbitClassType: OrbitClassType
let orbitClassDescription: String
let orbitClassRange: OrbitClassRange
enum CodingKeys: String, CodingKey {
case orbitClassType = "orbit_class_type"
case orbitClassDescription = "orbit_class_description"
case orbitClassRange = "orbit_class_range"
}
}
enum OrbitClassRange: String, Codable {
case aSemiMajorAxis10AUQPerihelion1017AU = "a (semi-major axis) > 1.0 AU; q (perihelion) < 1.017 AU"
case the1017AUQPerihelion13AU = "1.017 AU < q (perihelion) < 1.3 AU"
}
enum OrbitClassType: String, Codable {
case amo = "AMO"
case apo = "APO"
}
|
//
// Assistance.swift
// YumaApp
//
// Created by Yuma Usa on 2018-05-06.
// Copyright © 2018 Yuma Usa. All rights reserved.
//
import UIKit
private let reuseIdentifier = "helpCell"
class Assistance: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate
{
var array: [String] = []
var myCollectionView: UICollectionView!
let dialogWindow: UIView =
{
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.isUserInteractionEnabled = true
view.backgroundColor = UIColor.white
view.cornerRadius = 20
view.shadowColor = R.color.YumaDRed
view.shadowRadius = 5
view.shadowOffset = .zero
view.shadowOpacity = 1
return view
}()
let titleLabel: UILabel =
{
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = R.color.YumaRed
view.text = "Title"
view.textColor = UIColor.white
view.textAlignment = .center
view.layer.masksToBounds = true
// view.cornerRadius = 20
// view.clipsToBounds = true
let titleShadow: NSShadow =
{
let view = NSShadow()
view.shadowColor = UIColor.black
view.shadowOffset = CGSize(width: 1, height: 1)
return view
}()
view.attributedText = NSAttributedString(string: view.text!, attributes: [NSAttributedStringKey.font : UIFont(name: "AvenirNext-Bold", size: 20)!, NSAttributedStringKey.shadow : titleShadow])
view.font = UIFont(name: "ArialRoundedMTBold", size: 20)
view.shadowColor = UIColor.black
view.shadowRadius = 3
view.shadowOffset = CGSize(width: 1, height: 1)
return view
}()
let buttonSingle: GradientButton =
{
let view = GradientButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.setTitle(R.string.close.uppercased(), for: .normal)
view.titleLabel?.shadowOffset = CGSize(width: 2, height: 2)
view.titleLabel?.shadowRadius = 3
view.titleLabel?.textColor = UIColor.white
view.setTitleShadowColor(R.color.YumaDRed, for: .normal)
view.backgroundColor = R.color.YumaRed.withAlphaComponent(0.8)
view.cornerRadius = 3
view.shadowColor = UIColor.darkGray
view.shadowOffset = CGSize(width: 1, height: 1)
view.shadowRadius = 3
let titleShadow: NSShadow =
{
let view = NSShadow()
view.shadowColor = UIColor.black
// view.shadowRadius = 3
view.shadowOffset = CGSize(width: 1, height: 1)
return view
}()
view.setAttributedTitle(NSAttributedString(string: view.title(for: .normal)!, attributes: [NSAttributedStringKey.font : UIFont(name: "AvenirNext-DemiBold", size: 18)!, NSAttributedStringKey.shadow : titleShadow]), for: .normal)
view.borderColor = R.color.YumaDRed
view.borderWidth = 1
view.shadowOpacity = 0.9
return view
}()
let buttonPrev: UILabel =
{
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.text = " \(FontAwesome.caretLeft.rawValue) "
view.font = R.font.FontAwesomeOfSize(pointSize: 24)
return view
}()
let buttonNext: UILabel =
{
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.text = " \(FontAwesome.caretRight.rawValue) "
view.font = R.font.FontAwesomeOfSize(pointSize: 24)
return view
}()
let backgroundAlpha: CGFloat = 0.7
let titleBarHeight: CGFloat = 50
let buttonHeight: CGFloat = 42
let pageControl: UIPageControl =
{
let view = UIPageControl()
view.translatesAutoresizingMaskIntoConstraints = false
view.currentPage = 0
view.pageIndicatorTintColor = R.color.YumaYel
view.currentPageIndicatorTintColor = R.color.YumaRed
view.isUserInteractionEnabled = false
return view
}()
let pageControlHeight: CGFloat = 40
let stack: UIStackView =
{
let view = UIStackView()
return view
}()
let minWidth: CGFloat = 300
let maxWidth: CGFloat = 600
let minHeight: CGFloat = 300
let maxHeight: CGFloat = 600
var collectionViewHeight: CGFloat = 0
var dialogWidth: CGFloat = 0
var dialogHeight: CGFloat = 0
let store = DataStore.sharedInstance
override func viewDidLoad()
{
super.viewDidLoad()
dialogWidth = min(max(view.frame.width/2, minWidth), maxWidth)
dialogHeight = min(max(view.frame.height/2, minHeight), maxHeight)
if array.count == 0
{
array = R.array.help_cart_guide
}
buttonPrev.textColor = UIColor.lightGray
buttonNext.textColor = UIColor.lightGray
self.view.backgroundColor = R.color.YumaRed.withAlphaComponent(backgroundAlpha)
drawTitle()
drawStack()
drawCollection()
drawButton()
let str = "V:|[v0(\(titleBarHeight))][v1(\(pageControlHeight))][v2][v3(\(buttonHeight))]-5-|"
dialogWindow.addConstraintsWithFormat(format: str, views: titleLabel, buttonPrev, myCollectionView, buttonSingle)
drawDialog()
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
let _ = buttonSingle.addBackgroundGradient(colors: [R.color.YumaRed.cgColor, R.color.YumaYel.cgColor], isVertical: true)
buttonSingle.layer.addGradienBorder(colors: [R.color.YumaYel, R.color.YumaRed], width: 3.6, isVertical: true)
}
func drawTitle()
{
titleLabel.text = title//R.string.help
// titleLabel.font = UIFont.systemFont(ofSize: 21)
dialogWindow.addSubview(titleLabel)
dialogWindow.addConstraintsWithFormat(format: "H:|[v0]|", views: titleLabel)
dialogWindow.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0, constant: titleBarHeight))
}
func drawStack()
{
pageControl.numberOfPages = array.count
dialogWindow.addSubview(pageControl)
dialogWindow.addSubview(buttonPrev)
dialogWindow.addSubview(buttonNext)
if pageControl.numberOfPages > 1
{
buttonNext.textColor = R.color.YumaRed
}
buttonPrev.isUserInteractionEnabled = true
buttonPrev.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(doPrev(_:))))
buttonNext.isUserInteractionEnabled = true
buttonNext.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(doNext(_:))))
dialogWindow.addConstraintsWithFormat(format: "H:|-3-[v0(25)]-2-[v1]-2-[v2(25)]|", views: buttonPrev, pageControl, buttonNext)
dialogWindow.addConstraint(NSLayoutConstraint(item: buttonPrev, attribute: .centerY, relatedBy: .equal, toItem: pageControl, attribute: .centerY, multiplier: 1, constant: 0))
dialogWindow.addConstraint(NSLayoutConstraint(item: buttonNext, attribute: .centerY, relatedBy: .equal, toItem: pageControl, attribute: .centerY, multiplier: 1, constant: 0))
}
func drawCollection()
{
let layout = UICollectionViewFlowLayout()
collectionViewHeight = dialogHeight-titleBarHeight-pageControlHeight-buttonHeight-10
layout.itemSize = CGSize(width: dialogWidth, height: collectionViewHeight)
layout.scrollDirection = .horizontal
myCollectionView = UICollectionView(frame: CGRect(x: 38, y: 0, width: Int(dialogWidth), height: Int(collectionViewHeight)), collectionViewLayout: layout)
myCollectionView.dataSource = self
myCollectionView.delegate = self
myCollectionView.register(AssistanceCell.self, forCellWithReuseIdentifier: reuseIdentifier)
myCollectionView.showsVerticalScrollIndicator = false
myCollectionView.showsHorizontalScrollIndicator = false
myCollectionView.isPagingEnabled = true
myCollectionView.backgroundColor = UIColor.white
dialogWindow.addSubview(myCollectionView)
dialogWindow.addConstraintsWithFormat(format: "H:|[v0]|", views: myCollectionView)
}
func drawButton()
{
buttonSingle.setTitle(R.string.dismiss.uppercased(), for: .normal)
dialogWindow.addSubview(buttonSingle)
// buttonSingle.alpha = 0
// UIView.animate(withDuration: 5.5, delay: 0, options: .curveEaseInOut, animations: {
// self.buttonSingle.alpha = 1
// }, completion: nil)
dialogWindow.addConstraint(NSLayoutConstraint(item: buttonSingle, attribute: .width, relatedBy: .equal, toItem: dialogWindow, attribute: .width, multiplier: 0, constant: dialogWidth / 2))
dialogWindow.addConstraint(NSLayoutConstraint(item: buttonSingle, attribute: .centerX, relatedBy: .equal, toItem: dialogWindow, attribute: .centerX, multiplier: 1, constant: 0))
dialogWindow.addConstraint(NSLayoutConstraint(item: buttonSingle, attribute: .height, relatedBy: .equal, toItem: dialogWindow, attribute: .height, multiplier: 0, constant: buttonHeight))
buttonSingle.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buttonSingleTapped(_:))))
}
func drawDialog()
{
view.addSubview(dialogWindow)
// dialogWindow.alpha = 0
// UIView.animate(withDuration: 5.5, delay: 0, options: .curveEaseInOut, animations: {
// self.dialogWindow.alpha = 1
// }, completion: nil)
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0, constant: dialogWidth))
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0, constant: dialogHeight))
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: dialogWindow, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0))
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
@objc func buttonSingleTapped(_ sender: UITapGestureRecognizer)
{
store.flexView(view: buttonSingle)
self.dismiss(animated: true, completion: nil)
}
@objc func doPrev(_ sender: AnyObject)
{
if pageControl.currentPage > 0
{
pageControl.currentPage -= 1
myCollectionView.scrollToItem(at: IndexPath(item: pageControl.currentPage, section: 0), at: .centeredHorizontally, animated: true)
let page = pageControl.currentPage
buttonPrev.textColor = page == 0 ? UIColor.lightGray : R.color.YumaRed
buttonNext.textColor = page < array.count-1 ? R.color.YumaRed : UIColor.lightGray
}
}
@objc func doNext(_ sender: AnyObject)
{
if pageControl.currentPage < array.count
{
pageControl.currentPage += 1
myCollectionView.scrollToItem(at: IndexPath(item: pageControl.currentPage, section: 0), at: .centeredHorizontally, animated: true)
let page = pageControl.currentPage
buttonPrev.textColor = page == 0 ? UIColor.lightGray : R.color.YumaRed
buttonNext.textColor = page < array.count-1 ? R.color.YumaRed : UIColor.lightGray
}
}
// MARK: Method
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
pageControl.currentPage = Int(targetContentOffset.pointee.x/dialogWindow.frame.width)
let page = pageControl.currentPage
buttonPrev.textColor = page == 0 ? UIColor.lightGray : R.color.YumaRed
buttonNext.textColor = page < array.count-1 ? R.color.YumaRed : UIColor.lightGray
}
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return array.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! AssistanceCell
cell.titleLabel.text = array[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
return 0
}
// MARK: UICollectionViewDelegate
}
|
//
// DetailsViewControllerCollectionViewController.swift
// MovieApp
//
// Created by Ahmad Aulia Noorhakim on 27/02/21.
//
import UIKit
import Nuke
class DetailsViewController: UICollectionViewController {
struct Data {
let id : Int
let title : String
let overview: String
let rating : Float?
let poster : URL?
let backdrop: URL?
}
enum CellType: CaseIterable {
case primary
case overview
case casts
var identifier: String {
switch self {
case .primary : return "DetailsPrimary"
case .overview: return "DetailsOverview"
case .casts : return "DetailsCasts"
}
}
var nibName: String {
switch self {
case .primary : return "DetailsPrimaryCell"
case .overview: return "DetailsOverviewCell"
case .casts : return "DetailsCastsCell"
}
}
}
var cells: [CellType] = [.primary, .overview, .casts]
var model: Details.ViewModel {
didSet {
collectionView.reloadData()
}
}
private(set) lazy var output: DetailsInteractorInput = {
return DetailsInteractor(DetailsPresenter(self), DetailsWorker())
}()
init(data: Data) {
self.model = Details.ViewModel(
id : data.id,
title : data.title,
overview: data.overview,
rating : data.rating,
poster : data.poster,
backdrop: data.backdrop,
casts : []
)
let flowLayout = UICollectionViewFlowLayout()
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
super.init(collectionViewLayout: flowLayout)
}
required init?(coder: NSCoder) {
fatalError("movieId required")
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = UIColor.systemBackground
collectionView.showsVerticalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
CellType.allCases.forEach { type in
let nib = UINib(nibName: type.nibName, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: type.identifier)
}
output.fetchCredits(movieId: model.id)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
collectionView.bounces = collectionView.contentOffset.y > 100
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cells.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let type = cells[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: type.identifier, for: indexPath)
if let section = cell as? DetailsCell {
section.render(parentView: collectionView, model: self.model)
}
return cell
}
}
extension DetailsViewController: DetailsPresenterOutput {
func showSuccess(_ casts: [Details.ViewModel.Cast]) {
if casts.isEmpty {
return
}
self.model = self.model.copy(casts: casts)
}
}
|
import UIKit
import CPaaSSDK
class DashboardViewController: BaseViewController, UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectioVw: UICollectionView!
var mainContens = ["SMS", "Chat", "Voice/Video Call", "Addressbook","Presence","Group Chat"]
let sourceNumber: String = "+19492657842"
let destinationNumber: String = "+19492657843"
var cpaas: CPaaS!
override func viewDidLoad() {
super.viewDidLoad()
self.setNavigationBarColorForViewController(viewController: self, type: 0, titleString: "DASHBOARD")
self.navigationItem.hidesBackButton = true
let nibName = UINib(nibName: "DashboardTypeCustomCollectionCell", bundle: nil)
self.collectioVw.register(nibName, forCellWithReuseIdentifier: "DashboardTypeCustomCollectionCell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return mainContens.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DashboardTypeCustomCollectionCell", for: indexPath) as! DashboardTypeCustomCollectionCell
let book = mainContens[indexPath.row]
cell.displayContent(image: UIImage.init(named: "SMS")!, title: book)
cell.imgBg.layer.borderColor = UIColor.lightGray.cgColor
cell.imgBg.layer.borderWidth = 1.0
cell.imgBg.layer.shadowOffset = CGSize(width: 0, height: 2)
cell.imgBg.layer.shadowOpacity = 0.6
cell.imgBg.layer.shadowRadius = 2.0
cell.imgBg.layer.shadowColor = UIColor.red.cgColor
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item == 0{
self.navigateToSMS()
}
else if indexPath.item == 1 {
self.navigateToChat()
}
else if indexPath.item == 2 {
self.navigateToVoiceVideo()
}
else if indexPath.item == 3 {
self.navigateToAddressbook()
}
else if indexPath.item == 4 {
self.navigateToPresence()
}
else if indexPath.item == 5 {
self.navigatoGroupChat()
}
else{
}
}
}
extension DashboardViewController {
//@objc(collectionView:layout:sizeForItemAtIndexPath:)
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width - 20
let cellSquareSize: CGFloat = (screenWidth / 2.0) //- 10 - 40
return CGSize.init(width: cellSquareSize, height: 120.0)
}
//@objc(collectionView:layout:insetForSectionAtIndex:)
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
//@objc(collectionView:layout:minimumLineSpacingForSectionAtIndex:)
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
//@objc(collectionView:layout:minimumInteritemSpacingForSectionAtIndex:)
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
extension DashboardViewController {
func navigateToSMS() {
let vc = SMSViewController(nibName:"SMSViewController",bundle:nil)
vc.cpaas = self.cpaas
self.navigationController?.pushViewController(vc, animated: true)
}
func navigateToChat() {
let vc = ChatViewController(nibName:"ChatViewController",bundle:nil)
vc.cpaas = self.cpaas
vc.viewOpenFromGroup = false
self.navigationController?.pushViewController(vc, animated: true)
}
func navigateToAddressbook() {
let vc = AddressDirectoryViewController(nibName:"AddressDirectoryViewController",bundle:nil)
vc.cpaas = self.cpaas
self.navigationController?.pushViewController(vc, animated: true)
}
func navigateToVoiceVideo() {
let vc = VoiceVideoViewController(nibName:"VoiceVideoViewController",bundle:nil)
vc.cpaas = self.cpaas
self.navigationController?.pushViewController(vc, animated: true)
}
func navigateToPresence() {
let vc = PresenceViewController(nibName:"PresenceViewController",bundle:nil)
vc.cpaas = self.cpaas
self.navigationController?.pushViewController(vc, animated: true)
}
func navigatoGroupChat() {
let vc = GroupChatViewController(nibName:"GroupChatViewController",bundle:nil)
vc.cpaas = self.cpaas
self.navigationController?.pushViewController(vc, animated: true)
}
}
|
//
// CustomCellTableViewCell.swift
// ToDoListApp2
//
// Created by Mac on 3/26/16.
// Copyright © 2016 Mac. All rights reserved.
//
import UIKit
class CustomCellTableViewCell: UITableViewCell {
@IBOutlet weak var photoImageViewOutlet: UIImageView!
@IBOutlet weak var lblTask: UILabel!
@IBOutlet weak var lblDescription: UILabel!
@IBOutlet weak var ViewInCellOutlet: UIView!
override func awakeFromNib() {
super.awakeFromNib()
self.photoImageViewOutlet.layer.cornerRadius = 7
self.photoImageViewOutlet.clipsToBounds = true
}
}
|
//
// CategoriesRepository.swift
// FoodicsAssesment
//
// Created by mohamed gamal on 12/19/20.
//
import Foundation
import Promises
protocol CategoriesRepositoryProtocol: class {
func changeMCacheToDirty()
func fetchStock(pageSize: Int, pageNumber: Int) -> Promise<[CategoryModel]>
@discardableResult func clear() -> Promise<Void>
}
class CategoriesRepository: CategoriesRepositoryProtocol {
// MARK: - Dependencies
@Injected(name: .local) private var localDataSource: CategoriesDataSource
@Injected(name: .remote) private var remoteDataSource: CategoriesDataSource
@Injected private var internetManager: InternetManagerProtocol
// MARK: - Queues
private let fetchingQueue = DispatchQueue(label: "CategoriesRepository.fetch")
private let savingQueue = DispatchQueue(label: "CategoriesRepository.save")
private let cacheStateAccessQueue = DispatchQueue(label: "CategoriesRepo.safe.cache.State",
attributes: .concurrent)
private let cachedCategoriesAccessQueue = DispatchQueue(label: "CategoriesRepo.safe.cached.Categories",
attributes: .concurrent)
// MARK: - Cached Properties
private var _mCachedCategories: [CategoryModel]?
private var mCachedCategories: [CategoryModel]? {
return cachedCategoriesAccessQueue.sync { [weak self] in
return self?._mCachedCategories
}
}
private var _mCacheIsDirty = false
private var mCacheIsDirty: Bool {
return cacheStateAccessQueue.sync { [weak self] in
return self?._mCacheIsDirty ?? true
}
}
// MARK: - Logs Categories Repository Protocol
func changeMCacheToDirty() {
cacheStateAccessQueue.async( flags: .barrier, execute: {
self._mCacheIsDirty = true
})
}
func fetchStock(pageSize: Int, pageNumber: Int) -> Promise<[CategoryModel]> {
let result = Promise<[CategoryModel]>.pending()
fetchingQueue.async {[weak self] in
guard let self = self else { return }
if let mCachedCategories = self.mCachedCategories, !self.mCacheIsDirty,
mCachedCategories.count >= pageNumber * pageSize {
let rangeStart = (pageNumber - 1) * pageSize
let categories = Array(mCachedCategories[rangeStart...rangeStart+(pageSize-1)])
result.fulfill(categories)
return
}
self.fetchStockFromLocal(pageSize: pageSize, pageNumber: pageNumber)
.recover { (error)-> Promise<[CategoryModel]> in
if self.internetManager.isInternetConnectionAvailable() {
return self.fetchStockFromRemote(pageSize: pageSize, pageNumber: pageNumber)
}
return .init(NSError.noInternet)
}.then { (categories) in
result.fulfill(categories)
}.catch(result.reject(_:))
}
return result
}
func clear() -> Promise<Void> {
localDataSource.distroy()
}
// MARK: - Fetching Logic
private func fetchStockFromLocal(pageSize: Int, pageNumber: Int) -> Promise<[CategoryModel]> {
let reseult = Promise<[CategoryModel]>.pending()
localDataSource.fetch(pageSize: pageSize, pageNumber: pageNumber)
.then { [weak self] categories in
guard let self = self else { return }
self.refreshMCashed(categories: categories)
self.changeMCacheToHealthy()
reseult.fulfill(categories)
}.catch(reseult.reject(_:))
return reseult
}
private func fetchStockFromRemote(pageSize: Int, pageNumber: Int) -> Promise<[CategoryModel]> {
let reseult = Promise<[CategoryModel]>.pending()
remoteDataSource.fetch(pageSize: pageSize, pageNumber: pageNumber)
.then { [weak self] categories in
guard let self = self else { return }
self.refreshMCashed(categories: categories)
self.localDataSource.save(categories)
self.changeMCacheToHealthy()
reseult.fulfill(categories)}
.catch(reseult.reject(_:))
return reseult
}
private func changeMCacheToHealthy() {
cacheStateAccessQueue.async( flags: .barrier, execute: {
self._mCacheIsDirty = false
})
}
private func refreshMCashed(categories: [CategoryModel]) {
cachedCategoriesAccessQueue.async( flags: .barrier, execute: {
self._mCachedCategories = categories
})
}
}
|
//
// Reusable.swift
// NewListForEye
//
// Created by 任前辈 on 16/8/30.
// Copyright © 2016年 任前辈. All rights reserved.
//
import Foundation
protocol Reusable {
static var identifier : String {get}
}
extension Reusable{
static var identifier : String {
return String(Self)
}
}
/*
extension Reusable where Self : FirstCell {
static var identifier : String {
return String(Self)
}
}
*/ |
//
// LoginResponseModel.swift
// Standard Chartered
//
// Created by Sidra Jabeen on 25/08/2021.
//
import Foundation
struct LoginResponseModel: Codable {
let success: Bool
var params: [String:Any] {
return [
"success": success
]
}
}
struct decryptedResponseModel: Codable {
let decryptedResponse: String
var params: [String:Any] {
return [
"decryptedResponse": decryptedResponse
]
}
}
|
//
// ShopScreenInfoView.swift
// Project
//
// Created by 张凯强 on 2019/8/17.
// Copyright © 2019年 HHCSZGD. All rights reserved.
//
import UIKit
protocol ShopScreenInfoViewDelegate: NSObjectProtocol {
///跳转到评价详情页面
func evaluateWeihu(info: AnyObject?)
///跳转到评价列表页面
func evaluateListWeihu(info: AnyObject?)
}
class ShopScreenInfoView: UIScrollView {
override init(frame: CGRect) {
super.init(frame: frame)
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
}
let width: CGFloat = frame.width
let height: CGFloat = 44
self.backgroundColor = UIColor.colorWithHexStringSwift("f0f0f0")
self.weiHuContainerView.addSubview(self.weihuInfo)
self.weiHuContainerView.addSubview(self.weihuMember)
self.weiHuContainerView.addSubview(self.weihuTime)
self.weiHuContainerView.addSubview(self.weihuContent)
///维护信息
self.weihuInfo.frame = CGRect.init(x: 0, y: 0, width: width, height: 50)
self.weihuMember.frame = CGRect.init(x: 0, y: self.weihuInfo.max_Y + 1, width: width, height: height)
self.weihuTime.frame = CGRect.init(x: 0, y: self.weihuMember.max_Y + 1, width: width, height: height)
self.weihuContent.frame = CGRect.init(x: 0, y: self.weihuTime.max_Y + 1, width: width, height: height)
self.weiHuContainerView.frame = CGRect.init(x: 0, y: 0, width: width, height: 185)
// self.weiHuContainerView.isHidden = true
self.weihuInfo.shopInfoBtnClick = { [weak self] (bo) in
mylog("最新维护信息")
self?.mydelegate?.evaluateListWeihu(info: nil)
}
self.weihuMember.shopInfoBtnClick = { [weak self] (bo) in
mylog("旺财")
self?.mydelegate?.evaluateWeihu(info: nil)
}
//个人信息
let userInfo = ShopInfoCell.init(frame: CGRect.init(x: 0, y: 0, width: width, height: 50), title: "shop_admit_title"|?|, rightImage: "")
self.aduitTime.frame = CGRect.init(x: 0, y: userInfo.max_Y + 1, width: width, height: height)
self.editInstallCount.frame = CGRect.init(x: 0, y: self.aduitTime.max_Y + 1, width: width, height: height)
self.admitContainerView.addSubview(userInfo)
self.admitContainerView.addSubview(self.aduitTime)
self.admitContainerView.addSubview(self.editInstallCount)
self.admitContainerView.frame = CGRect.init(x: 0, y: self.weiHuContainerView.max_Y + 15, width: width, height: 140)
self.admitContainerView.isHidden = true
//公司信息
let companyInfo = ShopInfoCell.init(frame: CGRect.init(x: 0, y: 0, width: width, height: 50), title: "shopManagerInfo"|?|, rightImage: "")
self.name.frame = CGRect.init(x: 0, y: companyInfo.max_Y + 1, width: width, height: height)
self.phone.frame = CGRect.init(x: 0, y: name.max_Y + 1, width: width, height: height)
self.managerContainerView.addSubview(companyInfo)
self.managerContainerView.addSubview(self.phone)
self.managerContainerView.addSubview(self.name)
self.managerContainerView.frame = CGRect.init(x: 0, y: self.admitContainerView.max_Y + 15, width: width, height: 140)
//图片信息
self.addSubview(self.pingMuTitleView)
self.pingMuTitleView.frame = CGRect.init(x: 0, y: self.managerContainerView.max_Y + 15, width: width, height: 50)
self.addSubview(self.screenView)
self.screenView.frame = CGRect.init(x: 0, y: self.pingMuTitleView.max_Y + 1, width: width, height: 40)
}
weak var mydelegate: ShopScreenInfoViewDelegate?
var pingMuTitleView = ShopInfoCell.init(frame: CGRect.zero, title: "shop_screenStatusInfo_title"|?|, rightImage: "")
let weihuInfo = ShopInfoCell.init(frame: CGRect.zero, title: "shop_weihu_info_title"|?|, rightImage: "smallarrow")
let weihuMember = ShopInfoCell.init(frame: CGRect.zero, title: "shop_weihu_member"|?|, subTitle: "旺财", btnImage: "evaluate", btnSelectImage: "evaluate")
let weihuTime = ShopInfoCell.init(frame: CGRect.zero, title: "shop_weihu_time"|?|)
let weihuContent = ShopInfoCell.init(frame: CGRect.zero, title: "shop_weihu_content"|?|)
let aduitTime: ShopInfoCell = ShopInfoCell.init(frame: CGRect.init(x: 0, y: 13, width: SCREENWIDTH, height: 44), title: "shop_admit_time"|?|)
let editInstallCount: ShopInfoCell = ShopInfoCell.init(frame: CGRect.zero, title: "shop_admit_changeInsatall"|?|)
let name: ShopInfoCell = ShopInfoCell.init(frame: CGRect.zero, title: "shop_manager_name"|?|)
let phone: ShopInfoCell = ShopInfoCell.init(frame: CGRect.zero, title: "shop_manager_mobile"|?|)
let screenView: ShopScreenStatusView = ShopScreenStatusView.init(frame: CGRect.init(x: 0, y: 0, width: SCREENWIDTH, height: 44))
func configScreensHeight(count: Int) -> CGFloat {
let top: Float = 13
let bottom: Float = 13
let margin: Float = 6
var line: Int = 0
if count % 2 == 0 {
line = count / 2
}else {
line = (count + 1) / 2
}
let height = top + bottom + Float(line - 1) * margin + Float(line) * Float(40)
return CGFloat(height)
}
lazy var weiHuContainerView: UIView = {
let view = UIView.init()
self.addSubview(view)
view.backgroundColor = UIColor.colorWithHexStringSwift("f0f0f0f")
return view
}()
lazy var admitContainerView: UIView = {
let view = UIView.init()
self.addSubview(view)
view.backgroundColor = UIColor.colorWithHexStringSwift("f0f0f0f")
return view
}()
lazy var managerContainerView: UIView = {
let view = UIView.init()
self.addSubview(view)
view.backgroundColor = UIColor.colorWithHexStringSwift("f0f0f0f")
return view
}()
func configSection() {
if self.model?.shop?.status == "6" {
self.weihuMember.rightBtn.isEnabled = false
}else {
self.weihuMember.rightBtn.isEnabled = true
}
if let screens = self.model?.shop?.screens, screens.count > 0 {
if let maintain = self.model?.shop?.maintain {
self.weiHuContainerView.isHidden = false
self.weihuMember.subTitle.text = maintain.member_name
self.weihuTime.subTitle.text = maintain.create_at
self.weihuContent.subTitle.text = maintain.content
self.weiHuContainerView.frame = CGRect.init(x: 0, y: 0, width: self.weiHuContainerView.width, height: self.weiHuContainerView.height)
self.managerContainerView.isHidden = false
self.managerContainerView.frame = CGRect.init(x: 0, y: self.weiHuContainerView.max_Y + 5, width: self.weiHuContainerView.width, height: self.managerContainerView.height)
}else {
self.weiHuContainerView.isHidden = true
self.weiHuContainerView.frame = CGRect.init(x: 0, y: 0, width: self.weiHuContainerView.width, height: self.weiHuContainerView.height)
self.managerContainerView.isHidden = false
self.managerContainerView.frame = CGRect.init(x: 0, y: 0, width: self.managerContainerView.width, height: self.managerContainerView.height)
}
self.pingMuTitleView.frame = CGRect.init(x: 0, y: self.managerContainerView.max_Y + 5, width: self.pingMuTitleView.width, height: self.pingMuTitleView.height)
self.pingMuTitleView.isHidden = false
self.screenView.frame = CGRect.init(x: 0, y: self.pingMuTitleView.max_Y + 1, width: self.width, height: self.configScreensHeight(count: screens.count))
self.screenView.screens = screens
self.screenView.isHidden = false
}else {
if let maintain = self.model?.shop?.maintain {
self.weiHuContainerView.isHidden = false
self.weihuMember.subTitle.text = maintain.member_name
self.weihuTime.subTitle.text = maintain.create_at
self.weihuContent.subTitle.text = maintain.content
self.weiHuContainerView.frame = CGRect.init(x: 0, y: 0, width: self.weiHuContainerView.width, height: self.weiHuContainerView.height)
self.managerContainerView.isHidden = false
self.managerContainerView.frame = CGRect.init(x: 0, y: self.weiHuContainerView.max_Y + 5, width: self.managerContainerView.width, height: self.managerContainerView.height)
}else {
self.weiHuContainerView.isHidden = true
self.weiHuContainerView.frame = CGRect.init(x: 0, y: 0, width: self.weiHuContainerView.width, height: self.weiHuContainerView.height)
self.managerContainerView.isHidden = false
self.managerContainerView.frame = CGRect.init(x: 0, y: 0, width: self.managerContainerView.width, height: self.managerContainerView.height)
}
self.pingMuTitleView.isHidden = true
self.screenView.isHidden = true
}
self.weihuTime.subTitle.text = model?.shop?.maintain?.create_at
self.name.subTitleValue = model?.shop?.memberName
self.phone.subTitleValue = model?.shop?.mobile
self.pingMuTitleView.subTitle.text = model?.shop?.screen_start_at
}
var model: ShopDetailModel<ShopInfoModel, ShopImagesModel, ScreensModel>? {
didSet{
self.configSection()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func judgeMemberInfo() -> Bool {
if let name = self.model?.shop?.memberName, name.count > 0 {
return true
}else if let mobile = self.model?.shop?.mobile, mobile.count > 0 {
return true
}else {
return false
}
}
func judgeAuditInfo() -> Bool {
if let name = self.model?.shop?.auditingTime, name.count > 0 {
return true
}else {
return false
}
}
}
class ShopScreenStatusView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
}
var screens: [ScreensModel] = [ScreensModel]() {
didSet{
self.subviews.forEach { (subView) in
subView.removeFromSuperview()
}
let top: CGFloat = 6
let leftMargin: CGFloat = 13
var line: Int = 0
let count = screens.count
let margin = 6
if count % 2 == 0 {
line = count / 2
}else {
line = (count + 1) / 2
}
for i in 0...(count - 1) {
//取余,列
let lienCount = i % 2
let privateX: CGFloat = CGFloat(lienCount + 1) * leftMargin + CGFloat(lienCount) * (self.width - 39) / 2.0
let hangIndex = i / 2
let privateY: CGFloat = top + CGFloat(hangIndex * 40) + CGFloat(hangIndex * 6)
let contentView = StatusCell.init(frame: CGRect.init(x: privateX, y: privateY, width: (self.width - 39) / 2.0, height: 40))
contentView.model = screens[i]
self.addSubview(contentView)
}
}
}
class StatusCell: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let leftImageView = UIImageView.init()
leftImageView.image = UIImage.init(named: "screen")
self.addSubview(leftImageView)
leftImageView.snp.makeConstraints { (make) in
make.width.equalTo(16)
make.height.equalTo(14)
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(10)
}
self.addSubview(titleLabel)
self.titleLabel.sizeToFit()
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(leftImageView.snp.right).offset(6)
make.centerY.equalToSuperview()
}
self.backgroundColor = UIColor.colorWithHexStringSwift("fcecd5")
self.statusLabel = UILabel.init()
self.statusLabel.textAlignment = .center
self.statusLabel.textColor = UIColor.white
self.statusLabel.font = UIFont.systemFont(ofSize: 10)
self.addSubview(statusLabel)
self.statusLabel.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalToSuperview().offset(-8)
make.width.equalTo(60 * SCALE)
make.height.equalTo(25)
}
self.statusLabel.layer.masksToBounds = true
self.statusLabel.layer.cornerRadius = 12.5
self.statusLabel.textAlignment = .center
}
let titleLabel = UILabel.configlabel(font: UIFont.systemFont(ofSize: 14), textColor: UIColor.colorWithHexStringSwift("323232"), text: "")
var statusLabel: UILabel!
var model: ScreensModel? {
didSet{
self.titleLabel.text = model?.name ?? ""
if let status = model?.status {
if status == "1" {
self.statusLabel.text = "screenStatusNormal"|?|
self.statusLabel.backgroundColor = UIColor.colorWithHexStringSwift("cdb179")
}else {
self.statusLabel.backgroundColor = UIColor.colorWithHexStringSwift("f06968")
self.statusLabel.text = "screenStatusUnNormal"|?|
}
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
// Copyright 2019 Kakao Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// 카카오링크 호출 결과
///
/// 카카오링크 메시지 공유에 성공했더라도 템플릿과 입력 값에 위험요소가 있을 경우 warningMsg, argumentMsg에 기록될 수 있습니다. 개발 단계에서 꼼꼼히 체크하시길 권장합니다.
public struct LinkResult {
// MARK: Fields
/// 카카오링크 URL
///
/// 이 URL을 열면 카카오톡이 실행되고 카카오링크 메시지를 공유할 수 있습니다.
public let url: URL
/// 템플릿 내부 구성요소 유효성 검증결과
/// - key: 메시지 템플릿 요소의 key path
/// - value: 경고 내용
public let warningMsg : [String:String]?
/// templateArgs 입력 값 유효성 검증결과
/// - key: templateArgs에 전달된 key 이름
/// - value: 경고 내용
public let argumentMsg : [String:String]?
public init(url: URL, warningMsg: [String:String]?, argumentMsg: [String:String]?) {
self.url = url
self.warningMsg = warningMsg
self.argumentMsg = argumentMsg
}
}
|
//
// GridTests.swift
// MarsRoverTests
//
// Created by Edwin Bosire on 15/03/2020.
// Copyright © 2020 Edwin Bosire. All rights reserved.
//
import XCTest
@testable import MarsRover
class GridTests: XCTestCase {
func testCreationOfASquareGrid() {
let planetSize = CGSize(width: 10, height: 10)
let planet = Grid<Int>(with: planetSize)
XCTAssertNotNil(planet, "A planet object should not be nil")
}
func testSettersForGrid() {
let planetSize = CGSize(width: 10, height: 10)
let planet = Grid<Int>(with: planetSize)
// A 10x10 plane should have 100 items (all nil by default)
// zero offset so the bottom left most location is planet[planetSize.width - 1, planetSize.height - 1]
XCTAssert(planet[9,9] == nil, "Should be a nil")
planet[9,9] = 100
XCTAssertEqual(planet[9,9], 100, "location 9,9 should contain the int 100")
}
}
|
//
// PickerManager.swift
// OrgTech
//
// Created by Maksym Balukhtin on 30.04.2020.
// Copyright © 2020 Maksym Balukhtin. All rights reserved.
//
import UIKit
enum PickerManagerEvent {
case onPickerAction(String)
}
class PickerManager: NSObject {
private var data: [String]
private var pickerView: UIPickerView
var eventHandler: EventHandler<PickerManagerEvent>?
init(_ pickerView: UIPickerView, data: [String]) {
self.pickerView = pickerView
self.data = data
super.init()
pickerView.delegate = self
pickerView.dataSource = self
pickerView.reloadAllComponents()
}
func selectCurrent() -> String {
let row = pickerView.selectedRow(inComponent: 0)
pickerView.selectRow(row, inComponent: 0, animated: false)
return data[row]
}
}
extension PickerManager: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return data.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return data[row]
}
}
extension PickerManager: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let item = data[row]
eventHandler?(.onPickerAction(item))
}
}
|
//
// ViewController.swift
// hang
//
// Created by Joe Kennedy on 4/15/18.
// Copyright © 2018 Joe Kennedy. All rights reserved.
//
import UIKit
import Firebase
import SnapKit
class FriendsController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate {
//fonts
let semiBoldLabel = UIFont(name: "Nunito-SemiBold", size: UIFont.labelFontSize)
let semiBoldLabelSmall = UIFont(name: "Nunito-SemiBold", size: UIFont.smallSystemFontSize)
let boldLabel = UIFont(name: "Nunito-Bold", size: UIFont.labelFontSize)
let cellid = "cellid"
let sections = ["Available", "Unavailable"]
var users = [Users]()
var availableUsers = [Users]()
var unavailableUsers = [Users]()
var cellSelected = 0
let tableView = UITableView()
var pickerRowVariable = 0
let pickerView = UIPickerView()
var rotationAngle: CGFloat!
let width:CGFloat = 300
let height:CGFloat = 100
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "navlogo")
let logoImageView = UIImageView(image:logo)
self.navigationItem.titleView = logoImageView
self.navigationItem.title = "Friends"
self.view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.snp.makeConstraints { (make) in
make.top.bottom.left.right.equalTo(self.view)
}
//adds logout item to left of navigation controller
let settingsButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named:"settings"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(handleSettings))
navigationItem.leftBarButtonItem = settingsButton
let addButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named:"add"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(handleAdd))
navigationItem.rightBarButtonItem = addButton
tableView.register(UserCell.self, forCellReuseIdentifier: cellid)
pickerView.delegate = self
pickerView.dataSource = self
//Status picker rotation
rotationAngle = -90 * (.pi/180)
pickerView.transform = CGAffineTransform(rotationAngle: rotationAngle)
//pickerView.center = self.view.center
self.view.addSubview(pickerView)
pickerView.backgroundColor = UIColor.white
//pickerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
// pickerView.snp.makeConstraints { (make) in
// make.bottom.left.right.equalTo(self.view)
// make.width.equalTo(self.view)
// }
//
fetchUser()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pickerView.frame = CGRect(x: 0 - 150 , y: view.frame.height-120, width: view.frame.width + 300, height: 120)
tableView.contentInset = UIEdgeInsetsMake(0, 0, 120, 0)
tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 120, 0)
}
func fetchUser() {
DispatchQueue.main.async { self.tableView.reloadData() }
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "name")
query.observe(.value) { (snapshot) in
self.availableUsers.removeAll()
self.unavailableUsers.removeAll()
for child in snapshot.children.allObjects as! [DataSnapshot] {
if let value = child.value as? NSDictionary {
let user = Users()
//let key = child.key
let availability = value["available"] as? String ?? "Availability not found"
let name = value["name"] as? String ?? "Name not found"
let email = value["email"] as? String ?? "Email not found"
let status = value["status"] as? String ?? "Status not found"
user.name = name
user.email = email
user.availability = availability
user.status = status
self.users.append(user)
if(user.availability == "true"){
//self.availableUsers.append(key)
self.availableUsers.append(user)
print("got that");
}else{
//self.unavailableUsers.append(key)
self.unavailableUsers.append(user)
}
print("availableUsers --")
print(self.availableUsers)
print("unavailableUsers --")
print(UIFont.familyNames)
print(self.unavailableUsers)
DispatchQueue.main.async { self.tableView.reloadData()
}
}
}
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = UIColor(red:0.94, green:0.94, blue:0.96, alpha:1.00)
let label = UILabel()
label.text = self.sections[section]
if #available(iOS 11.0, *) {
label.font = UIFontMetrics.default.scaledFont(for: boldLabel!)
} else {
// Fallback on earlier versions
}
label.adjustsFontForContentSizeCategory = true
label.frame = CGRect(x: 12, y: 5, width: 100, height: 35)
view.addSubview(label)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return availableUsers.count
}
return unavailableUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//hack for now
let cell = tableView.dequeueReusableCell(withIdentifier: cellid, for: indexPath)
let user = indexPath.section == 0 ? availableUsers[indexPath.row] : unavailableUsers[indexPath.row]
if #available(iOS 11.0, *) {
cell.textLabel?.font = UIFontMetrics.default.scaledFont(for: semiBoldLabel!)
} else {
// Fallback on earlier versions
}
cell.textLabel?.adjustsFontForContentSizeCategory = true
cell.textLabel?.text = user.name
if(user.availability == "true"){
cell.detailTextLabel?.text = user.status
}else{
cell.detailTextLabel?.text = "unavailable"
if #available(iOS 11.0, *) {
cell.detailTextLabel?.font = UIFontMetrics.default.scaledFont(for: semiBoldLabelSmall!)
} else {
// Fallback on earlier versions
}
cell.detailTextLabel?.adjustsFontForContentSizeCategory = true
}
if indexPath.section == 0 && pickerRowVariable != 0 {
cell.selectionStyle = .gray
cell.accessoryType = .disclosureIndicator
} else {
cell.selectionStyle = .none
cell.accessoryType = .none
}
return cell
}
class UserCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section != 0 || pickerRowVariable == 0 {
return
}
let mapController = MapController()
mapController.user = availableUsers[indexPath.row]
self.navigationController?.pushViewController(mapController, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
checkIfUserIsLogeedIn()
if statusAdded == true {
pickerView.reloadAllComponents()
print("reloaded components")
}
}
func checkIfUserIsLogeedIn() {
if Auth.auth().currentUser?.uid == nil {
perform(#selector(handleLogout), with: nil, afterDelay: 0)
} else {
let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
// if let dictionary = snapshot.value as? [String: AnyObject] {
//
// //self.navigationItem.title = dictionary["name"] as? String
//
// }
}, withCancel: nil)
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return status.count
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 200
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 100
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
pickerRowVariable = row
// use the row to get the selected row from the picker view
// using the row extract the value from your datasource (array[row])
guard let currentGuy = Auth.auth().currentUser?.uid else{
return
}
let ref = Database.database().reference(fromURL: "https://hang-8b734.firebaseio.com/")
let usersReference = ref.child("users").child(currentGuy)
var values = ["available":"", "status":""]
if(row == 0){
values = ["available":"false", "status":"unavailable"]
}else{
values = ["available":"true", "status":status[row]]
}
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
if err != nil {
print(err!)
return
}
self.dismiss(animated: true, completion: nil)
print("updated that thing")
// self.availableUsers = [Users]()
// self.unavailableUsers = [Users]()
})
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: width, height: height)
let label = UILabel()
label.frame = CGRect(x: 0, y: 0, width: width, height: height)
label.textAlignment = .center
if #available(iOS 11.0, *) {
label.font = UIFontMetrics.default.scaledFont(for: boldLabel!)
} else {
// Fallback on earlier versions
}
label.text = status[row]
let label2 = UILabel()
label2.frame = CGRect(x:0, y:20, width:width, height:height)
label2.textAlignment = .center
if #available(iOS 11.0, *) {
label2.font = UIFontMetrics.default.scaledFont(for: semiBoldLabel!)
} else {
// Fallback on earlier versions
}
label2.text = statusText[row]
view.addSubview(label2)
view.addSubview(label)
//View rotation
view.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180))
return view
}
@objc func handleMap() {
let addController = MapController()
self.navigationController?.pushViewController(addController, animated: true)
}
@objc func handleSettings() {
let alert = UIAlertController(title: "Settings", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Sign Out", style: .destructive , handler:{ (UIAlertAction)in
print("User click Sign Out button")
do {
try Auth.auth().signOut()
} catch let logoutError {
print(logoutError)
}
let loginController = LoginController()
self.present(loginController, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
self.present(alert, animated: true, completion: {
print("completion block")
})
}
@objc func handleLogout() {
do {
try Auth.auth().signOut()
} catch let logoutError {
print(logoutError)
}
let loginController = LoginController()
self.present(loginController, animated: true, completion: nil)
}
@objc func handleAdd() {
//presents login view
let addController = CreateStatusController()
let navigationController = UINavigationController(rootViewController: addController)
present(navigationController, animated: true, completion: nil)
// perform(#selector(removeNavigationText), with: nil, afterDelay: 1)
}
// @objc func removeNavigationText() {
// self.navigationItem.title = " "
// }
}
|
//
// Players.swift
// Hangman
//
// Created by katty y marte on 1/10/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import Foundation
enum Player : String {
case player1 = "😇"
case player2 = "👻"
}
|
//
// AuthViewModel.swift
// WorldChatDidac
//
// Created by Dídac Edo Gibert on 15/4/21.
//
import SwiftUI
import Firebase
class AuthViewModel: ObservableObject {
@Published var userSession : FirebaseAuth.User?
@Published var currentUser : User?
@Published var didSendResetPasswordLink = false
static let shared = AuthViewModel()
init() {
userSession = Auth.auth().currentUser
fetchUser()
}
func login(withEmail email: String, password: String) {
Auth.auth().signIn(withEmail: email, password: password) { result, error in
if let error = error {
print("DEBUG: Login failed \(error.localizedDescription)")
return
}
guard let user = result?.user else { return }
self.userSession = user
self.fetchUser()
}
}
func register(withEmail email: String, password: String, image: UIImage?, fullname: String, username: String) {
guard let image = image else { return }
ImageUploader.uploadImage(image: image, type: .profile) { imageUrl in
Auth.auth().createUser(withEmail: email, password: password) { result, error in
if let error = error {
print(error.localizedDescription)
return
}
guard let user = result?.user else { return }
print("Successfully registered user...")
let data = ["email" : email,
"username" : username,
"fullname" : fullname,
"profileImageUrl" : imageUrl,
"uid" : user.uid]
COLLECTION_USERS.document(user.uid).setData(data) { _ in
print("Successfully uploaded user data...")
self.userSession = user
self.fetchUser()
}
}
}
}
func signout() {
self.userSession = nil
try? Auth.auth().signOut()
}
func resetPassword(withEmail email: String) {
Auth.auth().sendPasswordReset(withEmail: email) { error in
if let error = error {
print("Failed to send link with error \(error.localizedDescription)")
return
}
self.didSendResetPasswordLink = true
}
}
func fetchUser() {
guard let uid = userSession?.uid else { return }
COLLECTION_USERS.document(uid).getDocument { snapshot, _ in
guard let user = try? snapshot?.data(as: User.self) else { return }
self.currentUser = user
}
}
}
|
import UIKit
import SnapKit
import SectionsTableView
import RxSwift
import ThemeKit
import ComponentKit
class SendConfirmationViewController: ThemeViewController, SectionsDataSource {
private let disposeBag = DisposeBag()
private let viewModel: SendConfirmationViewModel
private let tableView = SectionsTableView(style: .grouped)
private let bottomWrapper = BottomGradientHolder()
private let sendButton = SliderButton()
private var viewItems = [[SendConfirmationViewModel.ViewItem]]()
init(viewModel: SendConfirmationViewModel) {
self.viewModel = viewModel
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "confirm".localized
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "button.cancel".localized, style: .done, target: self, action: #selector(onTapCancel))
tableView.sectionDataSource = self
tableView.separatorStyle = .none
tableView.backgroundColor = .clear
tableView.delaysContentTouches = false
view.addSubview(tableView)
tableView.snp.makeConstraints { maker in
maker.leading.top.trailing.equalToSuperview()
}
bottomWrapper.add(to: self, under: tableView)
bottomWrapper.addSubview(sendButton)
sendButton.title = "send.confirmation.slide_to_send".localized
sendButton.finalTitle = "send.confirmation.sending".localized
sendButton.slideImage = UIImage(named: "arrow_medium_2_right_24")
sendButton.finalImage = UIImage(named: "check_2_24")
sendButton.onTap = { [weak self] in
self?.viewModel.send()
}
subscribe(disposeBag, viewModel.sendEnabledDriver) { [weak self] in self?.sendButton.isEnabled = $0 }
subscribe(disposeBag, viewModel.viewItemDriver) { [weak self] in self?.sync(viewItems: $0) }
subscribe(disposeBag, viewModel.sendingSignal) { HudHelper.instance.show(banner: .sending) }
subscribe(disposeBag, viewModel.sendSuccessSignal) { [weak self] in self?.handleSendSuccess() }
subscribe(disposeBag, viewModel.sendFailedSignal) { [weak self] in self?.handleSendFailed(error: $0) }
}
private func sync(viewItems: [[SendConfirmationViewModel.ViewItem]]) {
self.viewItems = viewItems
tableView.reload()
}
@objc private func onTapCancel() {
dismiss(animated: true)
}
func handleSendSuccess() {
HudHelper.instance.show(banner: .sent)
dismiss(animated: true)
}
private func handleSendFailed(error: String) {
HudHelper.instance.show(banner: .error(string: error))
sendButton.reset()
}
private func row(viewItem: SendConfirmationViewModel.ViewItem, rowInfo: RowInfo) -> RowProtocol {
switch viewItem {
case let .subhead(iconName, title, value):
return CellComponent.actionTitleRow(tableView: tableView, rowInfo: rowInfo, iconName: iconName, iconDimmed: true, title: title, value: value)
case let .amount(iconUrl, iconPlaceholderImageName, coinAmount, currencyAmount, type):
return CellComponent.amountRow(tableView: tableView, rowInfo: rowInfo, iconUrl: iconUrl, iconPlaceholderImageName: iconPlaceholderImageName, coinAmount: coinAmount, currencyAmount: currencyAmount, type: type)
case let .address(title, value, valueTitle, contactAddress):
var onAddToContact: (() -> ())? = nil
if let contactAddress {
onAddToContact = { [weak self] in
ContactBookModule.showAddition(contactAddress: contactAddress, parentViewController: self)
}
}
return CellComponent.fromToRow(tableView: tableView, rowInfo: rowInfo, title: title, value: value, valueTitle: valueTitle, onAddToContact: onAddToContact)
case let .value(iconName, title, value, type):
return CellComponent.valueRow(tableView: tableView, rowInfo: rowInfo, iconName: iconName, title: title, value: value, type: type)
}
}
}
extension SendConfirmationViewController {
func buildSections() -> [SectionProtocol] {
var sections = [SectionProtocol]()
viewItems.enumerated().forEach { index, viewItems in
sections.append(
Section(
id: "section-\(index)",
headerState: .margin(height: .margin12),
rows: viewItems.enumerated().map { index, viewItem in
row(viewItem: viewItem, rowInfo: RowInfo(index: index, isFirst: index == 0, isLast: index == viewItems.count - 1))
}))
}
return sections
}
}
|
//
// CarDetailsViewModel.swift
// ListGridProject
//
// Created by Zuhaib Imtiaz on 2/24/21.
// Copyright © 2021 Zuhaib Imtiaz. All rights reserved.
//
import Foundation
import UIKit
protocol CarDetailsViewModelDelegate {
func onSuccess()
func onFaild(with error: String)
}
class CarDetailsViewModel: NSObject {
var delegate: CarDetailsViewModelDelegate?
var viewController: UIViewController!
var saleCarDetails: SaleCarDetailsModel = SaleCarDetailsModel.init()
// var totalCarsForSale: Int {
// return self.carForSalesList.count
// }
// func carForSale(at index: Int) -> CarsList {
// return self.carForSalesList[index]
// }
init(delegate: CarDetailsViewModelDelegate, viewController: UIViewController) {
self.viewController = viewController
self.delegate = delegate
}
func getCarDetails(recordId:Int){
let param: [String:Any] = [
"ModeOfLanguage" : NSLocale.current.languageCode == "ar" ? "ar" : "en",
"RecordID" : recordId,
"IsPending" : 0
]
let service = CarsForSaleService()
GCD.async(.Default) {
service.carsDetailsRequest(params: param) { (serviceResponse) in
switch serviceResponse.serviceResponseType {
case .Success :
GCD.async(.Main) {
if let carsInfo = serviceResponse.data as? SaleCarDetailsModel {
self.saleCarDetails = carsInfo
self.delegate?.onSuccess()
}
else {
self.delegate?.onFaild(with: "failing")
print("Cars not found")
}
}
case .Failure :
GCD.async(.Main) {
self.delegate?.onFaild(with: "failing")
print("Cars not found")
}
default :
GCD.async(.Main) {
self.delegate?.onFaild(with: "failing")
print("Cars not found")
}
}
}
}
}
}
|
//
// ReusableView.swift
// POP_SWIFT
//
// Created by Benobab on 23/06/16.
// Copyright © 2016 Benobab. All rights reserved.
//
import UIKit
protocol ReusableView { }
extension ReusableView where Self:UIView {
static var reuseIdentifier:String {
return String(self)
}
}
extension UITableViewCell : ReusableView { }
extension UITableView {
func register<T: UITableViewCell where T: ReusableView, T: NibLoadableView>(_: T.Type) {
let Nib = UINib(nibName: T.NibName, bundle: nil)
registerNib(Nib, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell where T: ReusableView>(forIndexPath indexPath: NSIndexPath) -> T {
guard let cell = dequeueReusableCellWithIdentifier(T.reuseIdentifier, forIndexPath: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
}
|
//
// ReloadTableViewController.swift
// RxSwift-Study
//
// Created by apple on 2019/1/17.
// Copyright © 2019 incich. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ReloadTableViewController: BaseViewController {
let bag = DisposeBag()
fileprivate let cellID = "cellId"
lazy var tableView: UITableView = {
let table = UITableView(frame: view.bounds)
table.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
return table
}()
lazy var refreshBtn: UIButton = {
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
btn.setTitle("刷新", for: .normal)
btn.setTitleColor(.black, for: .normal)
return btn
}()
lazy var cancelBtn: UIButton = {
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
btn.setTitle("取消", for: .normal)
btn.setTitleColor(.black, for: .normal)
return btn
}()
lazy var searchBar: UISearchBar = {
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 35))
return searchBar
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(self.tableView)
self.tableView.tableHeaderView = self.searchBar
let cancelBarItem = UIBarButtonItem(customView: self.cancelBtn)
let refreshBarItem = UIBarButtonItem(customView: self.refreshBtn)
navigationItem.rightBarButtonItems = [refreshBarItem, cancelBarItem]
let randomResult = self.refreshBtn.rx.tap.asObservable().startWith(()).flatMapLatest{self.getRandomResult().takeUntil(self.cancelBtn.rx.tap)}.flatMap(filterResult).share(replay: 1)
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Int>>(configureCell: { ds, tb, index, element in
let cell = tb.dequeueReusableCell(withIdentifier: self.cellID)!
cell.textLabel?.text = "条目\(index.row): \(element)"
return cell
})
randomResult.bind(to: self.tableView.rx.items(dataSource: dataSource)).disposed(by: bag)
}
}
extension ReloadTableViewController {
fileprivate func getRandomResult() -> Observable<[SectionModel<String, Int>]>{
print("正在请求数据....")
let items = (0..<5).map{ _ in
Int(arc4random())
}
//throttle, 设定时间后发生一个事件, 中间改变多少次不会重新计算也不会发生事件, 直到设定时间到了就会执行(如果在1秒内有多次点击则只取最后一次,那么自然也就只发送一次数据请求。)
//debounce, 只有间隔超过设定时间才发送, 多次触发不足设定时间会重新计算直到设定时间到了事件才发送, 譬如搜索, 文字输入多次间隔不足设定时间都会重新计算,不会触发事件, 文字输入超过设定时间才会发出搜索事件
let observable = Observable.just([SectionModel.init(model: "S", items: items)])
return observable.delay(2, scheduler: MainScheduler.instance)
}
fileprivate func filterResult(data: [SectionModel<String, Int>]) -> Observable<[SectionModel<String, Int>]> {
return self.searchBar.rx.text.orEmpty
.debounce(1, scheduler: MainScheduler.instance) //只有间隔超过1秒才发送, 多次触发不足1s会重新计算知道1s后事件才发送
.flatMapLatest{
query -> Observable<[SectionModel<String, Int>]> in
print("正在筛选数据(条件为:\(query))")
//输入条件为空,则直接返回原始数据
if query.isEmpty {
return Observable.just(data)
} else {//输入条件为不空,则只返回包含有该文字的数据
var newData:[SectionModel<String, Int>] = []
for sectionModel in data {
let items = sectionModel.items.filter{ "\($0)".contains(query) }
newData.append(SectionModel(model: sectionModel.model, items: items))
}
return Observable.just(newData)
}
}
}
}
/*
防止表格多次刷新的说明
(1)flatMapLatest 的作用是当在短时间内(上一个请求还没回来)连续点击多次“刷新”按钮,虽然仍会发起多次请求,但表格只会接收并显示最后一次请求。避免表格出现连续刷新的现象。
//随机的表格数据
let randomResult = refreshButton.rx.tap.asObservable()
.startWith(()) //加这个为了让一开始就能自动请求一次数据
.flatMapLatest(getRandomResult) //连续请求时只取最后一次数据
.share(replay: 1)
(2)也可以改用 flatMapFirst 来防止表格多次刷新,它与 flatMapLatest 刚好相反,如果连续发起多次请求,表格只会接收并显示第一次请求。
//随机的表格数据
let randomResult = refreshButton.rx.tap.asObservable()
.startWith(()) //加这个为了让一开始就能自动请求一次数据
.flatMapFirst(getRandomResult) //连续请求时只取第一次数据
.share(replay: 1)
(3)我们还可以在源头进行限制下。即通过 throttle 设置个阀值(比如 1 秒),如果在1秒内有多次点击则只取最后一次,那么自然也就只发送一次数据请求。
//随机的表格数据
let randomResult = refreshButton.rx.tap.asObservable()
.throttle(1, scheduler: MainScheduler.instance) //在主线程中操作,1秒内值若多次改变,取最后一次
.startWith(()) //加这个为了让一开始就能自动请求一次数据
.flatMapLatest(getRandomResult)
.share(replay: 1)
*/
|
//
// StartLevelOperationTests.swift
// Tests
//
// Created by Ceri on 31/05/2020.
//
import XCTest
@testable import MexicanTrain
class StartLevelOperationTests: OperationTestCase {
private var initialGame: Game!
private var operation: StartLevelOperation!
override func setUp() {
super.setUp()
let player = createPlayer(id: "P1", dominoes: [])
initialGame = Game.empty
.with(players: [player])
operation = StartLevelOperation(gameEngine: gameEngine, shuffler: shuffler)
gameEngine.createState(localPlayerId: "P1")
}
override func tearDown() {
operation = nil
super.tearDown()
}
func testDominoDistribution() {
let game = operation.perform(game: initialGame, stationValue: .twelve)
XCTAssertEqual(game.pool.count, 75)
XCTAssertEqual(game.players.count, 1)
XCTAssertEqual(game.players[0].dominoes.count, 15)
XCTAssertEqual(game.mexicanTrain.dominoes.count, 0)
XCTAssertEqual(game.players[0].train.dominoes.count, 0)
}
func testRandomPickups() {
let game = operation.perform(game: initialGame, stationValue: .twelve)
let expectedDominoes = [
domino(.eleven, .twelve),
domino(.eleven, .eleven),
domino(.ten, .twelve),
domino(.ten, .eleven),
domino(.ten, .ten),
domino(.nine, .twelve),
domino(.nine, .eleven),
domino(.nine, .ten),
domino(.nine, .nine),
domino(.eight, .twelve),
domino(.eight, .eleven),
domino(.eight, .ten),
domino(.eight, .nine),
domino(.eight, .eight),
domino(.seven, .twelve)
]
XCTAssertEqual(game.players.count, 1)
XCTAssertEqual(game.players[0].dominoes, expectedDominoes)
}
}
private func domino(_ value1: DominoValue, _ value2: DominoValue) -> UnplayedDomino {
UnplayedDomino(value1: value1, value2: value2)
}
|
//
// CountArray.swift
// Past Paper Crawler
//
// Created by 吴浩榛 on 2019/4/20.
// Copyright © 2019 吴浩榛. All rights reserved.
//
import Foundation
extension Array where Element == Bool {
var trueCount: Int {
return reduce(into: 0) { if $1 { $0 += 1 } }
}
}
extension Array {
subscript(indices: [Int]) -> [Element] {
return indices.map { self[$0] }
}
}
extension ArraySlice where Element == Bool {
var trueCount: Int {
return reduce(into: 0) { if $1 { $0 += 1 } }
}
}
|
//
// UIBarItemProtocol.swift
// IDPDesign
//
// Created by Oleksa 'trimm' Korin on 9/2/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
protocol UIBarItemProtocol: UIObjectType {
var isEnabled: Bool { get set }
var title: String? { get set }
var image: UIImage? { get set }
var landscapeImagePhone: UIImage? { get set }
var imageInsets: UIEdgeInsets { get set }
var landscapeImagePhoneInsets: UIEdgeInsets { get set }
var tag: Int { get set }
func titleTextAttributes(for state: UIControl.State) -> [NSAttributedString.Key : Any]?
func setTitleTextAttributes(_ attributes: [NSAttributedString.Key : Any]?, for state: UIControl.State)
}
|
//
// NetworkSessionManager.swift
// Employee
//
// Created by mahabaleshwar hegde on 04/12/19.
// Copyright © 2019 mahabaleshwar hegde. All rights reserved.
//
import Foundation
protocol NetworkSessionConfigurable {
var session: URLSession { get }
init(session: URLSession)
}
extension NetworkSessionConfigurable {
var session: URLSession {
return URLSession(configuration: .default, delegate: nil, delegateQueue: .main)
}
}
class NetworkSessionManager: NetworkSessionConfigurable, Response {
private let accessToken: String = "b03a7f738c9b4d958028e277114dcb9d"
static let `default`: NetworkSessionManager = NetworkSessionManager(session: URLSession(configuration: .default, delegate: nil, delegateQueue: .main))
private(set) var session: URLSession
required init(session: URLSession) {
self.session = session
}
}
|
//
// Keys.swift
// Rainfall
//
// Created by Aleksandr Khalupa on 13.06.2021.
//
import Foundation
struct K {
static let keyAPI = "fdd067b2507c42abb6465bbd5d3f1d34"
static let keyAPI2 = "fdd067b2507c42abb6465bbd5d3f1d34"
}
|
//
// PostModel.swift
// DoReMi
//
// Created by Conor Smith on 7/6/21.
//
import Foundation
struct PostModel {
let identifier: String
let user: User
var filename: String = ""
var caption: String = ""
var isLikedByCurrentUser = false
static func mockModels() -> [PostModel] {
var posts = [PostModel]()
for _ in 0...100 {
let post = PostModel(
identifier: UUID().uuidString,
user: User(
username: "kanyewest",
profilePictureURL: nil,
coverPictureURL: nil,
identifier: UUID().uuidString
)
)
posts.append(post)
}
return posts
}
/// Represents database child path for this post in a given user node
var videoChildPath: String {
return "videos/\(user.username.lowercased())/\(filename)"
}
}
|
//: Playground - noun: a place where people can play
import Cocoa
infix operator |> { associativity left precedence 80}
func |> <T, U>(value: T, function: (T -> U)) -> U {
return function(value)
}
//struct Year {
// var year = 0
// init(calendarYear: Int) {
// year = calendarYear
// }
//
// var isLeapYear: Bool {
// return (year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0
// }
//
//}
class Year {
var year = 0
init(calendarYear: Int) {
year = calendarYear
}
var isLeapYear: Bool {
switch 0 {
case year % 400:
return true
case year % 100:
return false
case year % 4:
return true
default:
return false
}
// return (year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0
}
}
let year = Year(calendarYear: 1900)
year.isLeapYear
|
//
// ActivityCell.swift
// Eureka Sheet Demo
//
// Created by Dhiraj Jadhao on 28/12/16.
// Copyright © 2016 Dhiraj Jadhao. All rights reserved.
//
import Foundation
import Eureka
public class ActivityCell: Cell<Bool>, CellType{
@IBOutlet weak var activityView: UIActivityIndicatorView!
public override func setup() {
super.setup()
activityView.startAnimating()
}
public override func update() {
super.update()
}
}
public final class ActivityRow: Row<ActivityCell>, RowType {
required public init(tag: String?) {
super.init(tag: tag)
// We set the cellProvider to load the .xib corresponding to our cell
cellProvider = CellProvider<ActivityCell>(nibName: "ActivityCell")
}
}
|
//
// RoutineCell.swift
// Routine Manager
//
// Created by Robert Zalog on 5/1/16.
// Copyright © 2016 Robert Zalog. All rights reserved.
//
import UIKit
class RoutineCell: UITableViewCell {
@IBOutlet var minutesLabel: UILabel!
@IBOutlet var routineLabel: UILabel!
}
|
import XCTest
class PilesDataSourceTests: XCTestCase {
private var sut: PilesDataSource!
private var delegate: PilesDataSourceDelegateSpy!
private var tstCurrntDate: Date!
private var tstNextMonth: Date!
private var tstNextYear: Date!
override func setUp() {
super.setUp()
tstCurrntDate = Date()
tstNextMonth = Date().nextMonth()
tstNextYear = Date().nextYear()
sut = PilesDataSource()
delegate = PilesDataSourceDelegateSpy()
sut.delegate = delegate
}
override func tearDown() {
tstCurrntDate = nil
tstNextMonth = nil
tstNextYear = nil
delegate = nil
sut = nil
super.tearDown()
}
func test_initialState_itemsCounts_0() {
assert_AllItemsCountsIs_0()
}
func test_0PilesFetched_itemsCounts_0() {
sut.onPilesFetched([])
assert_AllItemsCountsIs_0()
}
private func assert_AllItemsCountsIs_0() {
XCTAssertEqual(sut.sectionsCount, 0)
XCTAssertEqual(sut.rowsCount(for: 0), 0)
XCTAssertEqual(sut.rowsCount(for: 1), 0)
XCTAssertEqual(sut.rowsCount(for: 100), 0)
}
func test_rowCountForInvalidSection() {
XCTAssertEqual(sut.rowsCount(for: -1), 0)
}
func test_1PileFetched_itemsCount_1() {
sut.onPilesFetched([PileItem.testNewItem])
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.rowsCount(for: 0), 1)
XCTAssertEqual(sut.rowsCount(for: 10), 0)
}
func test_multiplePilesWithTheSameDate_1section_multipleRows() {
let count2Array = [PileItem.testNewItem, PileItem.testNewItem]
sut.onPilesFetched(count2Array)
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.rowsCount(for: 0), count2Array.count)
XCTAssertEqual(sut.rowsCount(for: 11), 0)
}
func test_revisableItems_on1section() {
sut.onPilesFetched([PileItem.needToReviseTestItem(),
PileItem.needToReviseTestItem(1)])
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.rowsCount(for: 0), 2)
}
func test_revisableItemAndNotRevisable_onDifferentSections() {
sut.onPilesFetched([PileItem.testNewItem,
PileItem.needToReviseTestItem()])
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.rowsCount(for: 0), 1)
XCTAssertEqual(sut.rowsCount(for: 1), 1)
}
func test_onFetchReplaceItems_doesntAddButReplace() {
sut.onPilesFetched([PileItem.testNewItem])
XCTAssertEqual(sut.sectionsCount, 1)
sut.onPilesFetched([])
XCTAssertEqual(sut.sectionsCount, 0)
}
func test_onFetched_revisableItemsFirst() {
sut.onPilesFetched([PileItem.testNewItem,
PileItem.needToReviseTestItem(title: "revisable")])
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "revisable")
}
func test_revisableSortedRelatedToCreatedDate() {
sut.onPilesFetched([PileItem.needToReviseTestItem(title: "1"),
PileItem.needToReviseTestItem(1, title: "0")])
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "0")
XCTAssertEqual(sut.itemIn(section: 0, row: 1).title, "1")
}
func test_revisableSortedRelatedToLastRevisedDate() {
sut.onPilesFetched([PileItem.revisedNeedToReviseTestItem(title: "1",
createdData: Date()),
PileItem.revisedNeedToReviseTestItem(1, title: "0",
createdData: Date().addingTimeInterval(100))])
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "0")
XCTAssertEqual(sut.itemIn(section: 0, row: 1).title, "1")
}
func test_onlyDay_Month_Year_affectToSectionCount() {
sut.onPilesFetched([PileItem.pileItem(createdDate: Date()),
PileItem.pileItem(createdDate: Date().nextHour()),
PileItem.pileItem(createdDate: Date().nextDay()),
PileItem.pileItem(createdDate: Date().nextDay()),
PileItem.pileItem(createdDate: Date().nextMonth()),
PileItem.pileItem(createdDate: Date().nextYear())])
XCTAssertEqual(sut.sectionsCount, 4)
}
func test_mixedItemsRevisableAndNot() {
sut.onPilesFetched([PileItem.pileItem(createdDate: Date()),
PileItem.pileItem(createdDate: Date().nextHour()),
PileItem.pileItem(createdDate: Date().nextDay()),
PileItem.pileItem(createdDate: Date().nextMonth()),
PileItem.needToReviseTestItem(),
PileItem.needToReviseTestItem(1)])
XCTAssertEqual(sut.sectionsCount, 4)
}
func test_dateSorting() {
sut.onPilesFetched([PileItem.pileItem(createdDate: Date()),
PileItem.pileItem(createdDate: Date().nextDay()),
PileItem.pileItem(createdDate: Date().nextMonth())])
let section0Item = sut.itemIn(section: 0, row: 0)
XCTAssertEqual(section0Item.createdDate.timeIntervalSinceNow,
Date().nextMonth().timeIntervalSinceNow, accuracy: 0.1)
let section1Item = sut.itemIn(section: 1, row: 0)
XCTAssertEqual(section1Item.createdDate.timeIntervalSinceNow,
Date().nextDay().timeIntervalSinceNow, accuracy: 0.1)
let section2Item = sut.itemIn(section: 2, row: 0)
XCTAssertEqual(section2Item.createdDate.timeIntervalSinceNow,
Date().timeIntervalSinceNow, accuracy: 0.1)
}
func test_sectionInfoForMixedFetchedItems() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstCurrntDate),
PileItem.pileItem(createdDate: tstNextYear),
PileItem.needToReviseTestItem()])
XCTAssertEqual(sut.sectionInfo(at: 0), .forRevise)
XCTAssertEqual(sut.sectionInfo(at: 1), .date(tstNextYear))
XCTAssertEqual(sut.sectionInfo(at: 2), .date(tstCurrntDate))
}
func test_sectionInfoOnlyForNotRevisableItems() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstCurrntDate),
PileItem.pileItem(createdDate: tstNextMonth)])
XCTAssertEqual(sut.sectionInfo(at: 0), .date(tstNextMonth))
XCTAssertEqual(sut.sectionInfo(at: 1), .date(tstCurrntDate))
}
func test_onPileRemoved_changesPileData() {
sut.onPilesFetched([PileItem.pileItem(createdDate: Date().nextMonth()),
PileItem.pileItem(createdDate: Date().nextMonth()),
PileItem.pileItem(createdDate: Date()),
PileItem.pileItem(createdDate: Date())])
sut.onPileRemoved(at: 2)
XCTAssertEqual(sut.rowsCount(for: 0), 2)
XCTAssertEqual(sut.rowsCount(for: 1), 1)
sut.onPileRemoved(at: 2)
XCTAssertEqual(sut.rowsCount(for: 0), 2)
XCTAssertEqual(sut.sectionsCount, 1)
}
func test_onPileRemoved_atTheBeginning_andAtTheEnd() {
fetch2Sections0123()
sut.onPileRemoved(at: 0)
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "1")
sut.onPileRemoved(at: 2)
XCTAssertEqual(sut.itemIn(section: 1, row: 0).title, "2")
}
private func fetch2Sections0123() {
sut.onPilesFetched([PileItem.pileItem(createdDate: Date().nextMonth()
.addingTimeInterval(10), title: "0"),
PileItem.pileItem(createdDate: Date()
.nextMonth(), title: "1"),
PileItem.pileItem(createdDate: Date()
.addingTimeInterval(10), title: "2"),
PileItem.pileItem(createdDate: Date(), title: "3")])
}
func test_onPileAdded_changesPileData() {
let date = Date().nextYear().nextMonth()
sut.onPileAdded(pile: PileItem.pileItem(createdDate: date), at: 0)
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.rowsCount(for: 0), 1)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).createdDate, date)
XCTAssertEqual(sut.sectionInfo(at: 0), .date(date))
}
func test_multipleAdditionWithSameDates() {
sut.onPileAdded(pile: PileItem.testNewItem, at: 0)
sut.onPileAdded(pile: PileItem.testNewItem, at: 0)
XCTAssertEqual(sut.sectionsCount, 1)
}
func test_multipleAdditionWithDifferentDates_checkSectionsCount() {
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 0)
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 0)
XCTAssertEqual(sut.sectionsCount, 2)
}
func test_add_c1Nm2Ny3_checkSorting() {
addC1()
addNm2()
addNy3()
checkNy3Nm2c1()
}
func test_add_c1Ny3Nm2_checkSorting() {
addC1()
addNy3()
addNm2()
checkNy3Nm2c1()
}
func test_add_Nm2c1Ny3_checkSorting() {
addNm2()
addC1()
addNy3()
checkNy3Nm2c1()
}
func test_add_Nm2Ny3c1_checkSorting() {
addNm2()
addNy3()
addC1()
checkNy3Nm2c1()
}
func test_add_Ny3Nm2c1_checkSorting() {
addNy3()
addNm2()
addC1()
checkNy3Nm2c1()
}
func test_add_Ny3c1Nm2_checkSorting() {
addNy3()
addC1()
addNm2()
checkNy3Nm2c1()
}
private func addC1() {
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 0)
}
private func addNm2() {
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 0)
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 0)
}
private func addNy3() {
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
}
private func checkNy3Nm2c1() {
XCTAssertEqual(sut.rowsCount(for: 0), 3)
XCTAssertEqual(sut.rowsCount(for: 1), 2)
XCTAssertEqual(sut.rowsCount(for: 2), 1)
}
func test_addRevisableItem_createsRevisableSection() {
sut.onPileAdded(pile: PileItem.needToReviseTestItem(), at: 0)
sut.onPileAdded(pile: PileItem.needToReviseTestItem(), at: 0)
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.sectionInfo(at: 0), .forRevise)
}
func test_addRevisableItemAfterNotRevisableWithSameCreationDate() {
let rDate = Date()
sut.onPileAdded(pile: PileItem.nonReviseTestItem(createdDate: rDate), at: 0)
sut.onPileAdded(pile: PileItem.reviseTestItem(createdDate: rDate) , at: 0)
XCTAssertEqual(sut.sectionInfo(at: 0), .forRevise)
XCTAssertEqual(sut.sectionInfo(at: 1), .date(rDate))
}
func test_checkIndexChangesAfterOnPileAddedByCallingOnRemove() {
addPile(date: tstNextYear, title: "2", at: 0)
addPile(date: tstNextMonth, title: "1", at: 0)
addPile(date: tstNextMonth, title: "0", at: 0)
sut.onPileRemoved(at: 0)
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.itemIn(section: 1, row: 0).title, "1")
}
func test_checkIndexChanges_addToTheEnd() {
addPile(date: tstNextMonth, title: "2", at: 0)
addPile(date: tstNextMonth, title: "0", at: 0)
addPile(date: tstNextMonth, title: "1", at: 1) //end of 0[1]1
sut.onPileRemoved(at: 1)
XCTAssertEqual(sut.rowsCount(for: 0), 2)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "2")
XCTAssertEqual(sut.itemIn(section: 0, row: 1).title, "0")
}
func test_checkIndexChanges_addIntoMiddle() {
addPile(date: tstNextMonth, title: "0", at: 0)
addPile(date: tstNextMonth, title: "2", at: 1)
addPile(date: tstNextMonth, title: "3", at: 2)
addPile(date: tstNextMonth, title: "1", at: 1) //middle of 1[1]23
sut.onPileRemoved(at: 1)
XCTAssertEqual(sut.rowsCount(for: 0), 3)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "0")
XCTAssertEqual(sut.itemIn(section: 0, row: 1).title, "2")
XCTAssertEqual(sut.itemIn(section: 0, row: 2).title, "3")
}
private func addPile(date: Date, title: String, at index: Int) {
let pile = PileItem.pileItem(createdDate: date,title: title)
sut.onPileAdded(pile: pile, at: index)
}
func test_sortingByCreationDateOnNotRevisableSection() {
sut.onPilesFetched(testItemsForSorting)
check0123Sorting()
}
func test_sortingOnAddingToDateSection() {
sut.onPileAdded(pile: testItemsForSorting[0], at: 0)
sut.onPileAdded(pile: testItemsForSorting[1], at: 0)
sut.onPileAdded(pile: testItemsForSorting[2], at: 0)
sut.onPileAdded(pile: testItemsForSorting[3], at: 0)
check0123Sorting()
}
private var testItemsForSorting: [PileItem] {
return [PileItem.pileItem(createdDate: tstCurrntDate, title: "3"),
PileItem.pileItem(createdDate: tstCurrntDate.addingTimeInterval(100), title: "0"),
PileItem.pileItem(createdDate: tstCurrntDate.addingTimeInterval(10), title: "2"),
PileItem.pileItem(createdDate: tstCurrntDate.addingTimeInterval(40), title: "1")]
}
private func check0123Sorting() {
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "0")
XCTAssertEqual(sut.itemIn(section: 0, row: 1).title, "1")
XCTAssertEqual(sut.itemIn(section: 0, row: 2).title, "2")
XCTAssertEqual(sut.itemIn(section: 0, row: 3).title, "3")
}
func test_sortingOnAddingToRevisableSection() {
sut.onPileAdded(pile: PileItem.revisedNeedToReviseTestItem(title: "1",
createdData: Date()), at: 0)
sut.onPileAdded(pile: PileItem.revisedNeedToReviseTestItem(1, title: "0",
createdData: Date().addingTimeInterval(100)), at: 0)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "0")
XCTAssertEqual(sut.itemIn(section: 0, row: 1).title, "1")
}
func test_onPileAdded_delegateEventsAndChangesOrder() {
delegate.insertSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 0)
}
delegate.insertBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 1)
}
sut.onPileAdded(pile: PileItem.testNewItem, at: 0)
}
func test_onRevisablePileAdded_delegateEventsAndChangesOrder() {
delegate.insertSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 0)
}
delegate.insertBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 1)
}
sut.onPileAdded(pile: PileItem.needToReviseTestItem(), at: 0)
}
func test_onPileRemovedWhenEmptyOrWithInvalidIndex_doesntCallDelete() {
sut.onPileRemoved(at: 0)
sut.onPileRemoved(at: -1)
XCTAssertEqual(delegate.deleteCallCount, 0)
}
func test_onPileRemoved_delete() {
fetch2Sections0123()
sut.onPileRemoved(at: 0)
XCTAssertEqual(delegate.deleteCallCount, 1)
XCTAssertEqual(delegate.deletedPositions, [ItemPosition(0, 0)])
sut.onPileRemoved(at: 2)
XCTAssertEqual(delegate.deleteCallCount, 2)
XCTAssertEqual(delegate.deletedPositions, [ItemPosition(1, 1)])
}
func test_onPileRemovedRemoveDataFirstThen_delete() {
fetch2Sections0123()
delegate.deleteBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 1), 1)
}
sut.onPileRemoved(at: 2)
delegate.deleteBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 1), 0)
}
sut.onPileRemoved(at: 2)
}
func test_onPileRemovedDeleteSection() {
fetch2Sections0123()
sut.onPileRemoved(at: 2)
XCTAssertEqual(delegate.deleteSectionCallCount, 0)
delegate.deleteSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.sectionsCount, 1)
XCTAssertEqual(self.delegate.deleteCallCount, 2)
}
sut.onPileRemoved(at: 2)
XCTAssertEqual(delegate.deleteSectionCallCount, 1)
XCTAssertEqual(delegate.deletedSectionIndex, 1)
}
func test_onRemoveSection_delegateEventsOrder() {
sut.onPilesFetched([PileItem.testNewItem])
delegate.deleteBlock = {[unowned self] in
XCTAssertEqual(self.sut.sectionsCount, 1)
}
delegate.deleteSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.sectionsCount, 0)
}
sut.onPileRemoved(at: 0)
}
func test_onNotRevisablePileAdded_insertSection() {
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
XCTAssertEqual(delegate.insertSectionCallCount, 1)
XCTAssertEqual(delegate.insertedSectionIndex, 0)
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
XCTAssertEqual(delegate.insertSectionCallCount, 1)
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 0)
XCTAssertEqual(delegate.insertSectionCallCount, 2)
XCTAssertEqual(delegate.insertedSectionIndex, 1)
}
func test_onNotRevisablePileAdded_dataChangesBeforeDelegateEvents() {
delegate.insertSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.sectionsCount, 1)
}
sut.onPileAdded(pile: PileItem.testNewItem, at: 0)
}
func test_onRevisablePileAdded_insertSection() {
sut.onPileAdded(pile: PileItem.needToReviseTestItem(0), at: 0)
XCTAssertEqual(delegate.insertSectionCallCount, 1)
XCTAssertEqual(delegate.insertedSectionIndex, 0)
sut.onPileAdded(pile: PileItem.needToReviseTestItem(1), at: 0)
XCTAssertEqual(delegate.insertSectionCallCount, 1)
sut.onPileAdded(pile: PileItem.needToReviseTestItem(2), at: 0)
XCTAssertEqual(delegate.insertSectionCallCount, 1)
}
func test_onRevisablePileAdded_dataChangesBeforeDelegateEvents() {
delegate.insertSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.sectionsCount, 1)
}
sut.onPileAdded(pile: PileItem.needToReviseTestItem(), at: 0)
}
func test_onNonRevisableAdded_insertRows() {
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear.addingTimeInterval(10)), at: 0)
XCTAssertEqual(delegate.insertCallCount, 1)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(0, 0)])
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
XCTAssertEqual(delegate.insertCallCount, 2)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(0, 1)])
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear.addingTimeInterval(5)), at: 0)
XCTAssertEqual(delegate.insertCallCount, 3)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(0, 1)])
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 2)
XCTAssertEqual(delegate.insertCallCount, 4)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(1, 0)])
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstCurrntDate.addingTimeInterval(10)), at: 2)
XCTAssertEqual(delegate.insertCallCount, 5)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(1, 0)])
}
func test_onRevisableAdded_insertRows() {
delegate.insertBlock = {[unowned self] in
XCTAssertEqual(self.delegate.insertSectionCallCount, 1)
}
sut.onPileAdded(pile: PileItem.needToReviseTestItem(1), at: 0)
XCTAssertEqual(delegate.insertCallCount, 1)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(0, 0)])
sut.onPileAdded(pile: PileItem.needToReviseTestItem(), at: 0)
XCTAssertEqual(delegate.insertCallCount, 2)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(0, 1)])
delegate.insertBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 3)
}
sut.onPileAdded(pile: PileItem.needToReviseTestItem(2), at: 0)
XCTAssertEqual(delegate.insertCallCount, 3)
XCTAssertEqual(delegate.insertedPositions, [ItemPosition(0, 0)])
}
func test_onNonRevisableAdded_insertRowsAfterSectionAndData() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstCurrntDate)])
delegate.insertBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 2)
}
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 0)
delegate.insertBlock = {[unowned self] in
XCTAssertEqual(self.delegate.insertSectionCallCount, 1)
}
sut.onPileAdded(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
}
func test_onPileChanged_changesPileAtGivenIndex_withoutDateChanges() {
sut.onPilesFetched([PileItem.pileItem(title: "tst0",
createdDate: tstCurrntDate,
revisedCount: 1),
PileItem.pileItem(title: "tst1",
createdDate: tstNextMonth,
revisedCount: 0)])
sut.onPileChanged(pile: PileItem.pileItem(title: "test0",
createdDate: tstCurrntDate, revisedCount: 10), at: 0)
XCTAssertEqual(sut.itemIn(section: 1, row: 0).title, "test0")
XCTAssertEqual(sut.itemIn(section: 1, row: 0).revisedCount, 10)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "tst1")
sut.onPileChanged(pile: PileItem.pileItem(title: "test1",
createdDate: tstNextMonth, revisedCount: 11), at: 1)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "test1")
XCTAssertEqual(sut.itemIn(section: 0, row: 0).revisedCount, 11)
}
func test_onPileChanged_updateInvokes() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(10)),
PileItem.pileItem(createdDate: tstNextMonth)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(10)), at: 1)
XCTAssertEqual(delegate.updateCallCount, 1)
XCTAssertEqual(delegate.updatedPositions, [ItemPosition(1, 0)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 2)
XCTAssertEqual(delegate.updateCallCount, 2)
XCTAssertEqual(delegate.updatedPositions, [ItemPosition(1, 1)])
}
func test_onPileChangedAtInvalidIndex_dontInvokeUpdate() {
sut.onPileChanged(pile: PileItem.testNewItem, at: -1)
sut.onPileChanged(pile: PileItem.testNewItem, at: 0)
sut.onPileChanged(pile: PileItem.testNewItem, at: 10)
XCTAssertEqual(delegate.updateCallCount, 0)
}
func test_updateInvokesAfterDataChanges() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear,
title: "original")])
delegate.updateBlock = {[unowned self] in
XCTAssertEqual(self.sut.itemIn(section: 0, row: 0).title, "changed")
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear,
title: "changed"), at: 0)
}
func test_changeRevisableToNonRevisableWithExistedCreationDateSection() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextMonth),
PileItem.needToReviseTestItem()])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 2)
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.sectionInfo(at: 1), .date(tstNextMonth))
XCTAssertEqual(sut.rowsCount(for: 1), 2)
}
func test_changeRevisableToNonRevisable() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.needToReviseTestItem()])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 1)
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.sectionInfo(at: 1), .date(tstNextMonth))
XCTAssertEqual(sut.rowsCount(for: 1), 1)
}
func test_changeRevisableDate_sortingItemsOnExistedSection() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextYear.addingTimeInterval(10)),
PileItem.needToReviseTestItem()])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear.addingTimeInterval(5)), at: 2)
XCTAssertEqual(sut.itemIn(section: 0, row: 1).createdDate,
tstNextYear.addingTimeInterval(5))
}
func test_changeRevisableDate_sortingSections() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstCurrntDate),
PileItem.needToReviseTestItem()])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 2)
XCTAssertEqual(sut.sectionInfo(at: 1), .date(tstNextMonth))
}
func test_changeRevisableSectionWithMultipleItems() {
sut.onPilesFetched([PileItem.needToReviseTestItem(),
PileItem.needToReviseTestItem(),
PileItem.pileItem(createdDate: tstNextYear)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear), at: 1)
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.rowsCount(for: 0), 1)
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.rowsCount(for: 0), 3)
}
func test_changeDate_changesSections() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextMonth)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.sectionInfo(at: 0), .date(tstNextYear))
}
func test_changeDateNotEnoughForSectionName_notChangeSection() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextMonth)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(10)), at: 0)
XCTAssertEqual(sut.sectionsCount, 1)
XCTAssertEqual(sut.sectionInfo(at: 0), .date(tstNextMonth))
}
func test_changeDateOnSectionWithMultipleItems() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextMonth),
PileItem.pileItem(createdDate: tstNextMonth),
PileItem.pileItem(createdDate: tstNextMonth)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 1)
XCTAssertEqual(sut.sectionsCount, 3)
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear), at: 2)
XCTAssertEqual(sut.sectionsCount, 3)
XCTAssertEqual(sut.rowsCount(for: 0), 2)
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear), at: 3)
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.rowsCount(for: 0), 3)
}
func test_sortingOnChangeDate() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(10)),
PileItem.pileItem(createdDate: tstNextMonth)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(5)), at: 0)
XCTAssertEqual(sut.itemIn(section: 0, row: 1).createdDate,
tstNextMonth.addingTimeInterval(5))
}
func test_onPileChangedInvokesDelegatesUpdateOnlyIfNoDateChanges() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextMonth),
PileItem.pileItem(createdDate: tstNextMonth)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
XCTAssertEqual(delegate.updateCallCount, 0)
sut.onPilesFetched([PileItem.needToReviseTestItem(),
PileItem.needToReviseTestItem()])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextYear), at: 0)
XCTAssertEqual(delegate.updateCallCount, 0)
}
func test_onPileChangedInvokesMoveRowToNewSection() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(10)),
PileItem.pileItem(createdDate: tstNextMonth)])
delegate.moveBlock = {[unowned self] in
XCTAssertEqual(self.delegate.insertSectionCallCount, 1)
XCTAssertEqual(self.delegate.insertedSectionIndex, 2)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 2)
XCTAssertEqual(delegate.insertCallCount, 0)
XCTAssertEqual(delegate.moveCallCount, 1)
XCTAssertEqual(delegate.moveFrom, ItemPosition(1, 1))
XCTAssertEqual(delegate.moveTo, ItemPosition(2, 0))
}
func test_onPileChangedMoveSectionWhenItemMoveToUpperSection() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstCurrntDate),
PileItem.pileItem(createdDate: tstCurrntDate)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth), at: 3)
XCTAssertEqual(delegate.moveFrom, ItemPosition(2, 1))
XCTAssertEqual(delegate.moveTo, ItemPosition(1, 0))
}
func test_onPileChangedInvokesMoveRowToExistedSection() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(10)),
PileItem.pileItem(createdDate: tstNextMonth),
PileItem.pileItem(createdDate: tstCurrntDate.addingTimeInterval(10))])
delegate.moveBlock = {[unowned self] in
XCTAssertEqual(self.delegate.insertSectionCallCount, 0)
XCTAssertEqual(self.sut.rowsCount(for: 2), 2)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 2)
XCTAssertEqual(delegate.insertCallCount, 0)
XCTAssertEqual(delegate.moveCallCount, 1)
XCTAssertEqual(delegate.moveFrom, ItemPosition(1, 1))
XCTAssertEqual(delegate.moveTo, ItemPosition(2, 1))
}
func test_onPileChangedInvokesDeleteSection() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextMonth),
PileItem.pileItem(createdDate: tstCurrntDate)])
delegate.moveBlock = {[unowned self] in
XCTAssertEqual(self.sut.sectionsCount, 3)
}
delegate.deleteSectionBlock = {[unowned self] in
XCTAssertEqual(self.delegate.moveCallCount, 1)
XCTAssertEqual(self.sut.sectionsCount, 2)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 1)
XCTAssertEqual(delegate.deleteSectionCallCount, 1)
XCTAssertEqual(delegate.deletedSectionIndex, 1)
}
func test_onRevisablePileChangedInvokesMoveRowToNewSection() {
sut.onPilesFetched([PileItem.needToReviseTestItem(1),
PileItem.needToReviseTestItem(),
PileItem.pileItem(createdDate: tstNextMonth)])
delegate.moveBlock = {[unowned self] in
XCTAssertEqual(self.delegate.insertSectionCallCount, 1)
XCTAssertEqual(self.delegate.insertedSectionIndex, 2)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 1)
XCTAssertEqual(delegate.insertCallCount, 0)
XCTAssertEqual(delegate.moveCallCount, 1)
XCTAssertEqual(delegate.moveFrom, ItemPosition(0, 1))
XCTAssertEqual(delegate.moveTo, ItemPosition(2, 0))
}
func test_onRevisablePileChanged_delegateInserSectionBeforeRemoveItems() {
sut.onPilesFetched([PileItem.needToReviseTestItem(),
PileItem.needToReviseTestItem()])
delegate.insertSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 2)
XCTAssertEqual(self.sut.rowsCount(for: 1), 0)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 0)
}
func test_onNonRevisablePileChanged_delegateInserSectionBeforeRemoveItems() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextYear),
PileItem.pileItem(createdDate: tstNextYear)])
delegate.insertSectionBlock = {[unowned self] in
XCTAssertEqual(self.sut.rowsCount(for: 0), 2)
XCTAssertEqual(self.sut.rowsCount(for: 1), 0)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 0)
}
func test_onRevisablePileChangedInvokesMoveRowToExistedSection() {
sut.onPilesFetched([PileItem.needToReviseTestItem(1),
PileItem.needToReviseTestItem(),
PileItem.pileItem(createdDate: tstNextMonth),
PileItem.pileItem(createdDate: tstCurrntDate.addingTimeInterval(10))])
delegate.moveBlock = {[unowned self] in
XCTAssertEqual(self.delegate.insertSectionCallCount, 0)
XCTAssertEqual(self.sut.rowsCount(for: 0), 1)
XCTAssertEqual(self.sut.rowsCount(for: 2), 2)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 1)
XCTAssertEqual(delegate.insertCallCount, 0)
XCTAssertEqual(delegate.moveCallCount, 1)
XCTAssertEqual(delegate.moveFrom, ItemPosition(0, 1))
XCTAssertEqual(delegate.moveTo, ItemPosition(2, 1))
}
func test_onRevisablePileChangedInvokesDeleteSection() {
sut.onPilesFetched([PileItem.needToReviseTestItem(),
PileItem.pileItem(createdDate: tstNextMonth),
PileItem.pileItem(createdDate: tstCurrntDate)])
delegate.moveBlock = {[unowned self] in
XCTAssertEqual(self.sut.sectionsCount, 3)
}
delegate.deleteSectionBlock = {[unowned self] in
XCTAssertEqual(self.delegate.moveCallCount, 1)
XCTAssertEqual(self.sut.sectionsCount, 2)
}
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstCurrntDate), at: 0)
XCTAssertEqual(delegate.deleteSectionCallCount, 1)
XCTAssertEqual(delegate.deletedSectionIndex, 0)
}
func test_sortingOfRevisablesWhenOnChangeOccur() {
sut.onPilesFetched([PileItem.testNewItem,
PileItem.testNewItem])
sut.onPileChanged(pile: PileItem.revisedNeedToReviseTestItem(title: "1",
createdData: Date()), at: 0)
XCTAssertEqual(sut.sectionsCount, 2)
XCTAssertEqual(sut.sectionInfo(at: 0), .forRevise)
sut.onPileChanged(pile: PileItem.revisedNeedToReviseTestItem(1, title: "0",
createdData: Date().addingTimeInterval(100)), at: 1)
XCTAssertEqual(delegate.moveCallCount, 2)
XCTAssertEqual(sut.itemIn(section: 0, row: 0).title, "0")
XCTAssertEqual(sut.itemIn(section: 0, row: 1).title, "1")
XCTAssertEqual(sut.sectionsCount, 1)
}
func test_changePilesOrderIfDateChangedButNotEnoughForSectionChange() {
sut.onPilesFetched([PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(5)),
PileItem.pileItem(createdDate: tstNextMonth)])
sut.onPileChanged(pile: PileItem.pileItem(createdDate: tstNextMonth.addingTimeInterval(10)), at: 1)
XCTAssertEqual(delegate.updateCallCount, 0)
XCTAssertEqual(delegate.moveCallCount, 1)
XCTAssertEqual(delegate.moveFrom, ItemPosition(0, 1))
XCTAssertEqual(delegate.moveTo, ItemPosition(0, 0))
}
}
extension PileSectionInfo: Equatable {
public static func ==(lhs: PileSectionInfo, rhs: PileSectionInfo) -> Bool {
return String(describing: lhs) == String(describing: rhs)
}
}
extension ItemPosition: Equatable {
public static func ==(lhs: ItemPosition, rhs: ItemPosition) -> Bool {
return lhs.section == rhs.section && lhs.row == rhs.row
}
}
|
//
// DetailHeaderView.swift
// PocketDex
//
// Created by Thomas Tenzin on 7/27/20.
// Copyright © 2020 Thomas Tenzin. All rights reserved.
//
import SwiftUI
struct DetailHeaderView: View {
@EnvironmentObject var selectedTheme: UserTheme
let pkmn: Pokemon
var pokemonTypeList: [PokemonType]
var typeList: [Type]
var otherForms: [Pokemon]
var otherFormsDetails: [Pokemon_Forms]
@State var chosenFormImgIndex = 0
var types: [PokemonType] {
return self.getTypes(typeList: self.pokemonTypeList, pkmnID: self.pkmn.id)
}
var body: some View {
VStack{
HStack{
Text(String(format: "%03d", self.pkmn.id))
.font(.system(.body, design: .monospaced))
Spacer()
HStack{
ForEach(types, id: \.type_id) { type1 in
Text("\(self.typeList[type1.type_id - 1].wrappedName)")
.frame(width: 56, height: 28)
.background(typeColor(type: self.typeList[type1.type_id - 1].wrappedName))
.cornerRadius(6)
.font(.caption)
}
}
}
if selectedTheme.showSprites {
if self.otherFormsDetails[self.chosenFormImgIndex].form_identifier == nil {
Image(String(pkmn.id))
.interpolation(.none)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 150)
} else {
Image(String(pkmn.id)+"-"+String(self.otherFormsDetails[self.chosenFormImgIndex].form_identifier ?? ""))
.interpolation(.none)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 150)
}
}
if otherFormsDetails.count > 1 {
Picker(selection: self.$chosenFormImgIndex, label: Text("What form do you want to display?")) {
ForEach(0 ..< self.otherFormsDetails.count) { index in
Text(self.otherFormsDetails[index].wrappedform_identifier)
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
}
func getTypes(typeList: [PokemonType], pkmnID: Int) -> [PokemonType] {
var resultTypes = [PokemonType]()
if let i = typeList.firstIndex(where: {$0.pokemon_id == pkmnID }) {
resultTypes.append(typeList[i])
if typeList[i+1].pokemon_id == pkmnID {
resultTypes.append(typeList[i+1])
}
}
return resultTypes
}
func typeColor(type: String) -> Color {
// Returns the type for a corresponding color.
if type == "Bug" {
return Color(red: 0.682, green: 0.737, blue: 0.129, opacity: 1.000)
} else if type == "Dark" {
return Color(red: 0.443, green: 0.345, blue: 0.286, opacity: 1.000)
} else if type == "Dragon" {
return Color(red: 0.463, green: 0.373, blue: 0.839, opacity: 1.000)
} else if type == "Electric" {
return Color(red: 0.988, green: 0.769, blue: 0.200, opacity: 1.000)
} else if type == "Fairy" {
return Color(red: 0.969, green: 0.706, blue: 0.969, opacity: 1.000)
} else if type == "Fighting" {
return Color(red: 0.655, green: 0.318, blue: 0.224, opacity: 1.000)
} else if type == "Fire" {
return Color(red: 0.969, green: 0.322, blue: 0.192, opacity: 1.000)
} else if type == "Flying" {
return Color(red: 0.620, green: 0.675, blue: 0.941, opacity: 1.000)
} else if type == "Ghost" {
return Color(red: 0.427, green: 0.427, blue: 0.612, opacity: 1.000)
} else if type == "Grass" {
return Color(red: 0.478, green: 0.804, blue: 0.318, opacity: 1.000)
} else if type == "Ground" {
return Color(red: 0.784, green: 0.659, blue: 0.329, opacity: 1.000)
} else if type == "Ice" {
return Color(red: 0.361, green: 0.808, blue: 0.910, opacity: 1.000)
} else if type == "Normal" {
return Color(red: 0.569, green: 0.545, blue: 0.498, opacity: 1.000)
} else if type == "Poison" {
return Color(red: 0.694, green: 0.361, blue: 0.639, opacity: 1.000)
} else if type == "Psychic" {
return Color(red: 0.859, green: 0.451, blue: 0.600, opacity: 1.000)
} else if type == "Rock" {
return Color(red: 0.733, green: 0.639, blue: 0.345, opacity: 1.000)
} else if type == "Steel" {
return Color(red: 0.678, green: 0.678, blue: 0.780, opacity: 1.000)
} else if type == "Water" {
return Color(red: 0.235, green: 0.561, blue: 0.894, opacity: 1.000)
} else if type == "Shadow" {
return Color(red: 0.251, green: 0.196, blue: 0.275, opacity: 1.000)
} else {
return Color.white
}
}
}
//
//struct DetailHeaderView_Previews: PreviewProvider {
// var pokemonList: [Pokemon] = Bundle.main.decodeCSV("pokemon.csv")
//
// static var previews: some View {
// DetailHeaderView(pkmn: pokemonList[1])
// }
//}
|
//
// LoginViewController.swift
// myselfWeiboDemo
//
// Created by 傅中正 on 16/6/21.
// Copyright © 2016年 Eric‘s Project. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
var accessToken: String? = nil
var refreshToken: String? = nil
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad")
self.view.backgroundColor = UIColor.whiteColor()
let loginButton = UIButton(frame: CGRectMake(50, 150, 100, 40))
loginButton.backgroundColor = UIColor.blueColor()
loginButton.titleLabel?.text = "微博帐号登录"
loginButton.setTitle("微博帐号登录", forState: .Normal)
loginButton.addTarget(self, action: #selector(LoginViewController.trans2Login), forControlEvents: .TouchUpInside)
self.view.addSubview(loginButton)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
print("viewDidAppear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func trans2Login() {
let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
appDelegate?.login()
}
func trans2HomePage() {
print("trans2HomePage")
// let delayInSeconds = 0.5
// let popTime = dispatch_time(dispatch_time_t(delayInSeconds), Int64(NSEC_PER_SEC))
// dispatch_after(popTime, dispatch_get_main_queue()) {
print("跳转。。。")
let tabbar = UITabBarController()
UITabBar.appearance().tintColor = UIColor.redColor()
tabbar.hidesBottomBarWhenPushed = true
let navi_1 = UINavigationController(rootViewController: HomeViewController())
navi_1.title = "首页"
let navi_2 = UINavigationController(rootViewController: MessageViewController())
navi_2.title = "消息"
tabbar.viewControllers = [navi_1, navi_2]
tabbar.selectedIndex = 0
self.presentViewController(tabbar, animated: false, completion: nil)
// }
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// NavigationSegue.swift
// PlanningPoker
//
// Created by david.gonzalez on 17/10/16.
// Copyright © 2016 BEEVA. All rights reserved.
//
enum NavigationSegue: String {
case SplashDeckType = "segueSplashDeckType"
case HeaderSubBar = "headerSubBar"
}
|
/*-
* Copyright (c) 2020 Sygic
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
//
// Alert.swift
// Covid
//
// Created by Boris Kolozsi on 19/05/2020.
//
import UIKit
final class Alert {
class func show(title: String?,
message: String?,
cancelTitle: String = "Zavrieť",
defaultTitle: String? = nil,
cancelAction: ((UIAlertAction) -> Void)? = nil,
defaultAction: ((UIAlertAction) -> Void)? = nil) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelAction)
alert.addAction(action)
if let defaultTitle = defaultTitle {
let action = UIAlertAction(title: defaultTitle, style: .default, handler: defaultAction)
alert.addAction(action)
alert.preferredAction = action
}
if #available(iOS 13.0, *) {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
topController.present(alert, animated: true, completion: nil)
}
} else {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = .alert + 1
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
}
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.warning)
}
}
}
|
//
// NewsFeedGetResponse.swift
// SocialApp
//
// Created by Дима Давыдов on 30.12.2020.
//
import Foundation
struct Likes: Decodable, JsonObjectInitProtocol {
// число пользователей, которым понравилась запись
var count: Int
// наличие отметки «Мне нравится» от текущего пользователя
var userLikes: Bool
// информация о том, может ли текущий пользователь поставить отметку «Мне нравится»
var canLike: Bool?
// информация о том, может ли текущий пользователь сделать репост записи
var canPublish: Bool?
private enum CodingKeys: String, CodingKey {
case count = "count"
case userLikes = "user_likes"
case canLike = "can_like"
case canPublish = "can_publish"
}
init(from decoder: Decoder) throws {
let main = try decoder.container(keyedBy: CodingKeys.self)
self.count = try main.decode(Int.self, forKey: .count)
self.userLikes = try main.decode(Int.self, forKey: .userLikes) == 1
self.canLike = try main.decode(Int.self, forKey: .canLike) == 1
self.canPublish = try main.decode(Int.self, forKey: .canPublish) == 1
}
init(from anyMap: [String: Any]) {
self.count = anyMap[CodingKeys.count.rawValue] as! Int
self.userLikes = anyMap[CodingKeys.userLikes.rawValue] as! Int == 1
self.canLike = (anyMap[CodingKeys.canLike.rawValue] as? Int == 1)
self.canPublish = (anyMap[CodingKeys.canPublish.rawValue] as? Int == 1)
}
}
struct Reposts: Decodable, JsonObjectInitProtocol {
// число пользователей, сделавших репост
var count: Int
// наличие репоста от текущего пользователя
var userReposted: Bool
private enum CodingKeys: String, CodingKey {
case count
case userReposted = "user_reposted"
}
init(from decoder: Decoder) throws {
let main = try decoder.container(keyedBy: CodingKeys.self)
self.count = try main.decode(Int.self, forKey: .count)
self.userReposted = try main.decode(Int.self, forKey: .userReposted) == 1
}
init(from anyMap: [String: Any]) {
self.count = anyMap[CodingKeys.count.rawValue] as! Int
self.userReposted = anyMap[CodingKeys.userReposted.rawValue] as! Int == 1
}
}
struct Comments: Decodable, JsonObjectInitProtocol {
var count: Int
init(from anyMap: [String: Any]) {
self.count = anyMap["count"] as! Int
}
}
struct NewsFeedPhotosDto: Decodable, JsonObjectInitProtocol {
var likes: Likes?
var reposts: Reposts?
var comments: Comments?
var canComment: Int = 0
var canRepost: Int = 0
// идентификатор фотографии.
var id: Int
// идентификатор альбома, в котором находится фотография.
var albumId: Int
// идентификатор владельца фотографии.
var ownerId: Int
// идентификатор пользователя, загрузившего фото (если фотография размещена в сообществе).
//текст описания фотографии.
var text: String
// дата добавления в формате Unixtime.
var date: Int
// массив с копиями изображения в разных размерах
var sizes: [PhotoSize]
// ширина оригинала фотографии в пикселах.
var width: Int?
// высота оригинала фотографии в пикселах.
var height: Int?
var src: String?
var srcBig: String?
enum CodingKeys: String, CodingKey {
case likes
case reposts
case comments
case canComment = "can_comment"
case canRepost = "can_repost"
case id
case albumId = "album_id"
case ownerId = "owner_id"
case text
case date
case sizes
case width
case height
case src
case srcBig = "src_big"
}
init(from anyMap: [String : Any]) {
if let likes = anyMap[CodingKeys.likes.rawValue] as? [String: Any] {
self.likes = Likes(from: likes)
}
if let reposts = anyMap[CodingKeys.reposts.rawValue] as? [String: Any] {
self.reposts = Reposts(from: reposts)
}
if let comments = anyMap[CodingKeys.comments.rawValue] as? [String: Any] {
self.comments = Comments(from: comments)
}
self.canComment = anyMap[CodingKeys.canComment.rawValue] as! Int
self.canRepost = anyMap[CodingKeys.canRepost.rawValue] as! Int
self.id = anyMap[CodingKeys.id.rawValue] as! Int
self.albumId = anyMap[CodingKeys.albumId.rawValue] as! Int
self.ownerId = anyMap[CodingKeys.ownerId.rawValue] as! Int
self.text = anyMap[CodingKeys.text.rawValue] as! String
self.date = anyMap[CodingKeys.date.rawValue] as! Int
let sizes = anyMap[CodingKeys.sizes.rawValue] as! [[String: Any]]
self.sizes = sizes.map{PhotoSize.init(from: $0)}
self.width = anyMap[CodingKeys.width.rawValue] as? Int
self.height = anyMap[CodingKeys.height.rawValue] as? Int
self.src = anyMap[CodingKeys.src.rawValue] as? String
self.srcBig = anyMap[CodingKeys.srcBig.rawValue] as? String
}
}
struct Comment: Decodable {
var count: Int
var canPost: Bool
enum CodingKeys: String, CodingKey {
case count = "count"
case canPost = "can_post"
}
init(from decoder: Decoder) throws {
let main = try decoder.container(keyedBy: CodingKeys.self)
self.count = try main.decode(Int.self, forKey: .count)
self.canPost = try main.decode(Int.self, forKey: .canPost) == 1
}
init(from anyMap: [String: Any]) {
self.count = anyMap["count"] as! Int
self.canPost = anyMap["can_post"] as! Int == 1
}
}
struct ItemGeo: Decodable {
// идентификатор места;
var placeId: Int
// название места;
var title: String
// тип места
var type: String
// идентификатор страны;
var countryId: Int
// идентификатор города;
var cityId: Int
// строка с указанием адреса места в городе;
var address: String
private enum CodingKeys: String, CodingKey {
case placeId = "place_id"
case title
case type
case countryId = "country_id"
case cityId = "city_id"
case address
}
init(from anyMap: [String: Any]) {
self.placeId = anyMap[CodingKeys.placeId.rawValue] as! Int
self.title = anyMap[CodingKeys.title.rawValue] as! String
self.type = anyMap[CodingKeys.type.rawValue] as! String
self.countryId = anyMap[CodingKeys.countryId.rawValue] as! Int
self.cityId = anyMap[CodingKeys.cityId.rawValue] as! Int
self.address = anyMap[CodingKeys.address.rawValue] as! String
}
}
struct NewsFeedItem: Decodable {
// тип списка новости, соответствующий одному из значений параметра filters
var type: String
// идентификатор источника новости (положительный — новость пользователя, отрицательный — новость группы)
var source_id: Int
// время публикации новости в формате unixtime
var date: Int
// находится в записях со стен и содержит идентификатор записи на стене владельца
var post_id: Int?
// находится в записях со стен, содержит тип новости (post или copy)
var post_type: String
// передается в случае, если этот пост сделан при удалении
var final_post: String?
// находится в записях со стен и содержит текст записи
var text: String
// true, если текущий пользователь может редактировать запись
var can_edit: Bool?
// возвращается, если пользователь может удалить новость, всегда содержит true
var can_delete: Bool?
// находится в записях со стен и содержит информацию о комментариях к записи, содержит поля
var comments: Comment
// находится в записях со стен и содержит информацию о числе людей, которым понравилась данная запись
var likes: Likes
// находится в записях со стен и содержит информацию о числе людей, которые скопировали данную запись на свою страницу
var reposts: Reposts
// находится в записях со стен и содержит массив объектов, которые прикреплены к текущей новости (фотография, ссылка и т.п.)
var attachments: [Attachment]?
// находится в записях со стен, в которых имеется информация о местоположении
var geo: ItemGeo?
var photos: [NewsFeedPhotosDto]?
}
extension NewsFeedItem: JsonObjectInitProtocol {
init(from anyMap: [String : Any]) {
self.type = anyMap["type"] as! String
self.source_id = anyMap["source_id"] as! Int
self.date = anyMap["date"] as! Int
self.post_id = anyMap["post_id"] as? Int
self.post_type = anyMap["post_type"] as! String
self.final_post = (anyMap["final_post"] as? String) ?? nil
self.text = anyMap["text"] as! String
self.can_edit = (anyMap["can_edit"] as? Bool) ?? nil
self.can_delete = (anyMap["can_delete"] as? Bool) ?? nil
self.comments = Comment(from: anyMap["comments"] as! [String: Any])
self.likes = Likes(from: anyMap["likes"] as! [String: Any])
self.reposts = Reposts(from: anyMap["reposts"] as! [String: Any])
var att: [Attachment] = []
for attItem in anyMap["attachments"] as! [[String: Any]] {
att.append(Attachment(from: attItem))
}
self.attachments = att
if let geo = anyMap["geo"] {
self.geo = ItemGeo.init(from: geo as! [String: Any])
}
self.photos = nil
}
}
struct NewsFeedProfile: Decodable, JsonObjectInitProtocol {
struct OnlineInfo: Decodable, JsonObjectInitProtocol {
var visible: Bool
var isOnline: Bool
var isMobile: Bool
private enum CodingKeys: String, CodingKey {
case visible
case isOnline = "is_online"
case isMobile = "is_mobile"
}
init(from anyMap: [String : Any]) {
self.visible = anyMap[CodingKeys.visible.rawValue] as! Bool
self.isOnline = anyMap[CodingKeys.isOnline.rawValue] as! Bool
self.isMobile = anyMap[CodingKeys.isMobile.rawValue] as! Bool
}
}
var firstName: String?
var id: UserID
var lastName: String
var canAccessClosed: Bool
var isClosed: Bool
var sex: Int
var screenName: String
var photo50: String
var photo100: String
var online: Int
var onlineInfo: OnlineInfo
private enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case id
case lastName = "last_name"
case canAccessClosed = "can_access_closed"
case isClosed = "is_closed"
case sex
case screenName = "screen_name"
case photo50 = "photo_50"
case photo100 = "photo_100"
case online
case onlineInfo = "online_info"
}
init(from anyMap: [String : Any]) {
self.firstName = anyMap[CodingKeys.firstName.rawValue] as? String
self.id = anyMap[CodingKeys.id.rawValue] as! UserID
self.lastName = anyMap[CodingKeys.lastName.rawValue] as! String
self.canAccessClosed = anyMap[CodingKeys.canAccessClosed.rawValue] as! Bool
self.isClosed = anyMap[CodingKeys.isClosed.rawValue] as! Bool
self.sex = anyMap[CodingKeys.sex.rawValue] as! Int
self.screenName = anyMap[CodingKeys.screenName.rawValue] as! String
self.photo50 = anyMap[CodingKeys.photo50.rawValue] as! String
self.photo100 = anyMap[CodingKeys.photo100.rawValue] as! String
self.online = anyMap[CodingKeys.online.rawValue] as! Int
self.onlineInfo = OnlineInfo(from: anyMap[CodingKeys.onlineInfo.rawValue] as! [String: Any])
}
}
struct NewsFeedGroup: Decodable, JsonObjectInitProtocol {
var id: Int
var name: String
var screenName: String
var isClosed: Int?
var type: String
var isAdmin: Int?
var isMember: Int?
var isAdvertiser: Int?
var photo50: String?
var photo100: String?
var photo200: String?
private enum CodingKeys: String, CodingKey {
case id
case name
case screenName = "screen_name"
case isClosed = "is_closed"
case type
case isAdmin = "is_admin"
case isMember = "is_member"
case isAdvertiser = "is_advertiser"
case photo50 = "photo_50"
case photo100 = "photo_100"
case photo200 = "photo_200"
}
init(from anyMap: [String : Any]) {
self.id = anyMap[CodingKeys.id.rawValue] as! Int
self.name = anyMap[CodingKeys.name.rawValue] as! String
self.screenName = anyMap[CodingKeys.screenName.rawValue] as! String
self.isClosed = anyMap[CodingKeys.isClosed.rawValue] as? Int
self.type = anyMap[CodingKeys.type.rawValue] as! String
self.isAdmin = anyMap[CodingKeys.isAdmin.rawValue] as? Int
self.isMember = anyMap[CodingKeys.isMember.rawValue] as? Int
self.isAdvertiser = anyMap[CodingKeys.isAdvertiser.rawValue] as? Int
self.photo50 = anyMap[CodingKeys.photo50.rawValue] as? String
self.photo100 = anyMap[CodingKeys.photo100.rawValue] as? String
self.photo200 = anyMap[CodingKeys.photo200.rawValue] as? String
}
}
class NewsFeedGetResponse: NotifiableDecodableGroup {
var items: [NewsFeedItem]?
var profiles: [NewsFeedProfile]?
var groups: [NewsFeedGroup]?
var group: DispatchGroup
var queue: DispatchQueue
required init(queue: DispatchQueue, group: DispatchGroup) {
self.queue = queue
self.group = group
}
func decode(from data: Data) throws {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
let response = json["response"] as! [String: Any]
let items = response["items"] as! [[String: Any]]
let profiles = response["profiles"] as! [[String: Any]]
let groups = response["groups"] as! [[String: Any]]
self.items = [NewsFeedItem]()
self.groups = [NewsFeedGroup]()
self.profiles = [NewsFeedProfile]()
print("items start")
for item in items {
queue.async(group: group, flags: .barrier) {
self.items?.append(NewsFeedItem.init(from: item))
}
}
print("items end")
print("profiles start")
for profile in profiles {
queue.async(group: group, flags: .barrier) {
self.profiles?.append(NewsFeedProfile.init(from: profile))
}
}
print("profiles end")
print("groups start")
for groupItem in groups {
queue.async(group: group, flags: .barrier) {
self.groups?.append(NewsFeedGroup(from: groupItem))
}
}
print("groups end")
//
// queue.async(group: group, flags: .barrier) {
// print("profiles start")
//
// let container = try! root.nestedContainer(keyedBy: CodingKeys.self, forKey: .response)
// self.profiles = try? container.decode([NewsFeedProfile].self, forKey: .profiles)
// print("profiles end")
// }
// queue.async(group: group, flags: .barrier) {
// print("groups start")
//
// let container = try! root.nestedContainer(keyedBy: CodingKeys.self, forKey: .response)
// self.groups = try? container.decode([NewsFeedGroup].self, forKey: .groups)
// print("groups end")
//
// }
print("main")
}
func getNotifyGroup() -> DispatchGroup? {
return group
}
}
protocol JsonObjectInitProtocol {
init(from anyMap: [String: Any])
}
protocol NotifiableDecodableGroup: class {
func getNotifyGroup() -> DispatchGroup?
func decode(from data: Data) throws
init(queue: DispatchQueue, group: DispatchGroup)
}
|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
protocol Pasteboard {
func set(_ text: String)
func get() -> String?
}
|
//
// LeetCodeApp.swift
// LeetCode
//
// Created by dos Santos, Diego on 06/03/21.
//
import SwiftUI
@main
struct LeetCodeApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
|
//
// TodayTodayInteractorInput.swift
// Weather
//
// Created by KONSTANTIN KUSAINOV on 21/03/2018.
// Copyright © 2018 Konstantin. All rights reserved.
//
import Foundation
protocol TodayInteractorInput: BaseInteractorInput {
var items: [TodayViewModel] {get}
}
|
//
// ApiClient.swift
// GiphySearchApp
//
// Created by Dmitry Kyrskiy on 21.12.16.
// Copyright © 2016 Dmitry Kyrskiy. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
class ApiClient {
let networkManager = Alamofire.SessionManager()
func getGifs(completion: @escaping ( _ gifs: [Gif]? , _ error : Error?) -> Void) {
let baseUrl = URL(string: "http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC")
networkManager.request(baseUrl!, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate()
.responseJSON() { responce in
if responce.result.isSuccess {
if let JSONObject = responce.result.value as AnyObject? {
let gifsJSONArray = JSONObject["data"]
let gifs = Mapper<Gif>().mapArray(JSONObject: gifsJSONArray)
completion(gifs, nil)
}
}
completion(nil, responce.result.error)
}
}
func searchGifs(searchText: String, completion: @escaping ( _ gifs: [Gif]? , _ error : Error?) -> Void) {
let str = searchText.lowercased().replace(target: " ", withString: "+")
let baseUrl = URL(string: "http://api.giphy.com/v1/gifs/search?q=\(str)&api_key=dc6zaTOxFJmzC")
networkManager.request(baseUrl!, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate()
.responseJSON() { responce in
if responce.result.isSuccess {
if let JSONObject = responce.result.value as AnyObject? {
let gifsJSONArray = JSONObject["data"]
let gifs = Mapper<Gif>().mapArray(JSONObject: gifsJSONArray)
completion(gifs, nil)
}
}
completion(nil, responce.result.error)
}
}
}
extension String {
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
|
//
// PokeDetail.swift
// Pokedex Final Exam
//
// Created by SBAUser on 4/27/20.
// Copyright © 2020 Michelle Espinosa. All rights reserved.
//
import Foundation
class PokeDetail {
var height = 0.0
var weight = 0.0
var base_experience = 0.0
var imageURL = ""
var url = ""
private struct Returned: Codable {
var height: Double
var weight: Double
var base_experience: Double
var sprites: Sprites
}
private struct Sprites: Codable {
var front_default: String
}
func getData(completed: @escaping ()->()) {
let urlString = url
print("We are accessing the url \(urlString)")
guard let url = URL(string: urlString) else {
print("ERROR: Could not create a URL from \(urlString)")
completed()
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) { (data, respone, error) in
if let error = error {
print("ERROR: \(error.localizedDescription)")
}
do {
let returned = try JSONDecoder().decode(Returned.self, from: data!)
self.height = returned.height
self.weight = returned.weight
self.base_experience = returned.base_experience
self.imageURL = returned.sprites.front_default
} catch {
print("JSON ERROR: \(error.localizedDescription)")
}
completed()
}
task.resume()
}
}
|
//
// Copyright © 2016 Landet. All rights reserved.
//
import Foundation
class User: DictionaryInitializable {
let id: Int
let username: String
let name: String
required init(dictionary: [String : AnyObject]) {
self.id = dictionary["id"] as! Int
self.username = dictionary["username"] as! String
self.name = dictionary["name"] as! String
}
} |
//
// Configurations.swift
// ApproachCleanArchitecture
//
// Created by Rone Loza on 6/11/18.
// Copyright © 2018 Rone Loza. All rights reserved.
//
import Foundation
class Configuration {
var baseURL = ""
init() {
if let dictionary = Bundle.main.infoDictionary,
let configuration = dictionary["Configuration"] as? String,
let path = Bundle.main.path(forResource: "Configurations", ofType: "plist") ,
let config = NSDictionary(contentsOfFile: path) {
for (key, value) in config {
if let key = key as? String,
let value = value as? [String:String] {
if key == configuration {
self.baseURL = value["baseURL"] ?? ""
}
}
}
}
}
}
|
//
// SwiftUIView2.swift
// Udemy1-05
//
// Created by Mauro Ciargo on 4/21/20.
// Copyright © 2020 Mauro Ciargo. All rights reserved.
//
import SwiftUI
struct SwiftUIView2: View {
var body: some View {
VStack{
Spacer()
// limite del boton ---------------------------------------
Button(action: {
print("boton 2 hola pulsado")
}) {
Text("hola mundo 2")
.foregroundColor(.white)
.font(.title)
.padding()
.background(Color.green)
.cornerRadius(5)
.padding(10) /*Le pongo otro limite y lo separa 10 p del background*/
.border(Color.blue, width: 6)
.cornerRadius(10)
}
// limite del boton ---------------------------------------
Spacer()
Button(action: {
print("boton 2 hola pulsado")
}) {
HStack{
Image(systemName: "trash")
Text("Eliminar")
}
.padding(20)
// .background(LinearGradient(gradient: Gradient(colors: [Color.pink, Color.orange]), startPoint: .leadind, endPoint: .trailing))
// www.uigradients.xom
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkOcean1"), Color("DarkOcean2")]), startPoint: .leading, endPoint: .trailing))
.foregroundColor(.white)
.font(.title)
.cornerRadius(30)
.shadow(color: .blue, radius: 20, x: 20, y: 10)
}
Spacer()
Button(action: {
print("boton 2 hola pulsado")
}) {
HStack{
Image(systemName: "trash")
Text("Eliminar")
}
.frame(minWidth:0, maxWidth: 200)
// .frame(minWidth:0, maxWidth: 200) -> va de punta a punta del horizontal
.padding(20)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkOcean1"), Color("DarkOcean2")]), startPoint: .leading, endPoint: .trailing))
.foregroundColor(.white)
.font(.title)
.cornerRadius(30)
.shadow(color: .blue, radius: 20, x: 20, y: 10)
}
Spacer()
}
}
}
struct SwiftUIView2_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView2()
}
}
|
import ComponentKit
import ThemeKit
import SnapKit
import UIKit
class CoinMajorHolderChartCell: BaseThemeCell {
static let height: CGFloat = 55
private let percentLabel = UILabel()
private let descriptionLabel = UILabel()
private let countLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
wrapperView.addSubview(countLabel)
countLabel.snp.makeConstraints { maker in
maker.leading.equalToSuperview().inset(CGFloat.margin16)
maker.top.equalToSuperview()
}
countLabel.font = .subhead2
countLabel.textColor = .themeGray
wrapperView.addSubview(percentLabel)
percentLabel.snp.makeConstraints { maker in
maker.leading.equalToSuperview().inset(CGFloat.margin16)
maker.top.equalTo(countLabel.snp.bottom).offset(CGFloat.margin12)
}
percentLabel.font = .headline1
percentLabel.textColor = .themeBran
wrapperView.addSubview(descriptionLabel)
descriptionLabel.snp.makeConstraints { maker in
maker.leading.equalTo(percentLabel.snp.trailing).offset(CGFloat.margin8)
maker.lastBaseline.equalTo(percentLabel)
}
descriptionLabel.font = .subhead1
descriptionLabel.textColor = .themeGray
descriptionLabel.text = "coin_analytics.holders.in_top_10_addresses".localized
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bind(percent: String?, count: String?) {
percentLabel.text = percent
countLabel.text = count.map { "coin_analytics.holders.count".localized($0) }
}
}
|
import UIKit
import SkeletonView
class CeldaPeliculaTableViewCell: UITableViewCell {
//MARK: Outlets
@IBOutlet weak var imagen: UIImageView!
@IBOutlet weak var titulo: UILabel!
//MARK: Properties
public var id: Int!
//MARK: Ciclo de vida
override func awakeFromNib() {
super.awakeFromNib()
}
//MARK: Metodos
public func llenarInfo(tvShows: TvShowRes) -> Void {
self.startSkeleton()
guard let urlString = tvShows.image?.medium, let nombre = tvShows.name, let idshow = tvShows.id else {
return
}
guard let url = URL(string: urlString) else { return }
guard let imgUrl = try? Data.init(contentsOf: url) else { return }
self.stopSkeleton()
imagen.image = UIImage(data: imgUrl)
titulo.text = nombre
id = idshow
}
public func llenarDatosBase(tvShow: Series) -> Void {
guard let imagenData = tvShow.image, let nombre = tvShow.name else {
return
}
imagen.image = UIImage(data: imagenData)
titulo.text = nombre
id = Int(tvShow.id)
}
private func startSkeleton() -> Void {
self.imagen.showAnimatedGradientSkeleton()
self.titulo.showAnimatedGradientSkeleton()
}
private func stopSkeleton() -> Void {
self.imagen.hideSkeleton()
self.titulo.hideSkeleton()
}
//MARK: atributos
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
import Foundation
/**
A structure left behind when an event is either completed or aborted, to quickly list what happened within it.
*/
public struct EventRecord {
/// The name of the event.
var eventName: String
/// The type of the event.
var eventType: EventType
/// The player who triggered the event.
var trigger: UserProxy?
/// Any other players that participated in the event.
var participants: [UserProxy]?
/// Any transactions that occurred during the event.
var transactions: [(UserProxy, PointReceipt)]
/// Any additional states or changes the record should hold.
var states: [String: Any]
public init(name: String,
type: EventType,
trigger: UserProxy?,
participants: [UserProxy]?,
transactions: [(UserProxy, PointReceipt)] = [],
states: [String: Any] = [:]) {
self.eventName = name
self.eventType = type
self.trigger = trigger
self.participants = participants
self.transactions = transactions
self.states = states
}
}
|
//
// Implementation of msgpack bin family format.
// https://github.com/msgpack/msgpack/blob/master/spec.md#formats-bin
//
import Foundation
extension Bool: MsgPackValueType {
public func pack(data: NSMutableData) -> NSMutableData {
var value = self ? 0xc3 : 0xc2
data.appendBytes(&value, length: 1)
return data
}
}
|
//
// ViewController.swift
// OpenGLSample
//
// Created by Yamamoto Kensuke on 6/5/15.
// Copyright (c) 2015 Yamamoto Kensuke. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let triangleView = TriangleView(frame: CGRect(x: 0,y: 0,width: self.view.frame.width,height: self.view.frame.height));
self.view.addSubview(triangleView)
}
}
|
//
// TabBarViewController.swift
// Parstagram
//
// Created by Anshul Jha on 3/18/21.
//
import UIKit
import Parse
class TabBarViewController: UITabBarController {
@IBOutlet weak var tabBarNavigation: UITabBar!
override func viewDidLoad() {
super.viewDidLoad()
let userQuery = PFUser.query()
userQuery!.whereKey("objectId", equalTo: PFUser.current()!.objectId)
do {
var user = try userQuery!.findObjects().first as! PFUser
if user["profile_photo"] != nil {
let imageFile = user["profile_photo"] as! PFFileObject
let urlString = imageFile.url!
let url = URL(string: urlString)!
var img = UIImage(data: try Data(contentsOf: url))
img = scaleImage(img: img!)
let tabBarItem1 = (self.tabBar.items?[1])! as UITabBarItem
tabBarItem1.image = (img)?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
}
} catch let error {
print("Error finding user, \(error)")
}
}
func scaleImage(img: UIImage) -> UIImage{
let size = CGSize(width: 30, height: 30)
let scaledImage = img.af_imageAspectScaled(toFit: size)
return scaledImage
}
}
|
//
// BlankWindow.swift
// JacktripGui
//
// Created by Yunhan on 23/3/18.
// Copyright © 2018 NSI Lab. All rights reserved.
//
import Cocoa
/*
* Resolve: Unknown Window class (null) in Interface Builder file, creating generic Window instead
* Issue happens only in version below 10.13
*/
class BlankWindow: NSWindow {}
|
//
// EarthquakeTableViewController.swift
// EarthQuakesParsing
//
// Created by tejasree vangapalli on 6/1/20.
// Copyright © 2020 tejasree vangapalli. All rights reserved.
//
import UIKit
class EarthquakeTableViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var curentPage = 0
var isFetching = false
// MARK: - Props
var earthquakeManager = EarthquakesManager()
fileprivate var earthQuakes = [Features]()
var limit = 20
var totalEntries = 20000
var reachability: Reachability?
override func viewDidLoad() {
super.viewDidLoad()
title = "Earth quakes list"
fetchEarthquakes()
reachability = try? Reachability(hostname: "www.google.com")
try? self.reachability?.startNotifier()
NotificationCenter.default.addObserver(self, selector: #selector(reachableStatus), name: NSNotification.Name(Notification.Name.reachabilityChanged.rawValue), object: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// fetchs earthquakes records from the API of every page
func fetchEarthquakesPerPage() {
if (reachability?.connection == .unavailable) {
self.ErrorMessage(titleStr: "No Internet Connection", messageStr: "Please try again")
return
}
isFetching = true
earthquakeManager.fetchLatestEarthQuakes(pageNumber: self.curentPage) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let earthquakes):
self.earthQuakes += earthquakes
DispatchQueue.main.async {
self.tableView.reloadData()
}
self.isFetching = false
case .failure(let error):
DispatchQueue.main.async {
self.ErrorMessage(titleStr: "Error Displaying Earthquakes", messageStr: error.localizedDescription)
}
self.isFetching = false
}
}
}
// Checks the internet connection and displays records accordingly
@objc func reachableStatus() {
if (reachability?.connection != .unavailable) {
fetchEarthquakesPerPage()
} else {
self.ErrorMessage(titleStr: "No Internet Connection", messageStr: "Please try again")
}
}
func fetchEarthquakes() {
fetchEarthquakesPerPage()
}
// MARK: - Initializers
init(earthquakeManager: EarthquakesManager) {
self.earthquakeManager = earthquakeManager
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// pagination -- checks the requests from user at 3/4th of the scroll view everytime
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let scrollViewHeight = scrollView.frame.size.height
let scrollViewContentSizeHeight = scrollView.contentSize.height
let scrollOffset = scrollView.contentOffset.y
if (scrollOffset + scrollViewHeight > ((scrollViewContentSizeHeight * 3)/4)) && !isFetching {
self.curentPage += 1
print(self.curentPage)
fetchEarthquakesPerPage()
}
}
}
// MARK: - Table view data source
extension EarthquakeTableViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return earthQuakes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath) as? EarthquakeTableViewCell else { return UITableViewCell() }
let earthquake = earthQuakes[indexPath.row]
cell.placeLabel.text = earthquake.properties?.place
cell.dateLabel.text = earthquake.properties?.date!.dateToString()
cell.magLabel.text = "\(Double(Int(((earthquake.properties?.mag) ?? 0.0)*100))/100.0)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? EarthquakeTableViewCell else { return }
cell.isAccessibilityElement = true
let earthquake = self.earthQuakes[indexPath.row]
guard let detailedViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as? EarthquakeDetailViewController else { return }
detailedViewController.earthquakes = earthquake
self.navigationController?.pushViewController(detailedViewController, animated: true)
}
}
|
//
// ViewController.swift
// MapSearch_Swift
//
// Created by Rama Chandra on 10/10/2014.
// Copyright (c) 2014 Rama Chandra. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var mapView: MKMapView!
func searchBarSearchButtonClicked(sender:UISearchBar)
{
self.searchBar.resignFirstResponder()
var geocoder=CLGeocoder()
geocoder.geocodeAddressString(searchBar.text, completionHandler:
{ (placemarks, error) -> Void in
if (error != nil) {
println("failed with error" + error.localizedDescription)
return
}
var placemark:CLPlacemark=placemarks[0] as CLPlacemark
var location:CLLocationCoordinate2D=placemark.location.coordinate
var annoation=MKPointAnnotation()
annoation.coordinate=location
annoation.title=self.searchBar.text
self.mapView.addAnnotation(annoation)
var mr:MKMapRect=self.mapView.visibleMapRect
var pt:MKMapPoint=MKMapPointForCoordinate(annoation.coordinate)
mr.origin.x=pt.x-mr.size.width*0.5
mr.origin.y=pt.y-mr.size.height*0.25
self.mapView.setVisibleMapRect(mr, animated: true)
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// MainIndoorActivityViewController.swift
//
//
// Created by Helen Cao on 7/14/17.
//
//
import UIKit
class MainIndoorActivityViewController: UIViewController {
@IBOutlet weak var gamesRow: GamesCellView!
@IBOutlet weak var craftsRow: GamesCellView!
let activities = ["Games", "Movies", "Crafts"]
@IBOutlet weak var moviesRow: GamesCellView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension MainIndoorActivityViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 3
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "Games", for: indexPath) as! GamesCellView
let activity = activities[indexPath.row]
cell.gamesLabel.text = activity
return cell
}
}
extension MainIndoorActivityViewController: UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 201
}
}
extension MainIndoorActivityViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sampleGame", for: indexPath) as! GamesCollectionViewCell
return cell
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.