text
stringlengths 8
1.32M
|
|---|
//
// ChallengesOverviewPresenter.swift
// StudyPad
//
// Created by Roman Levinzon on 03/02/2019.
// Copyright (c) 2019 Roman Levinzon. All rights reserved.
//
import Foundation
class ChallengesOverviewPresenter {
// MARK: - Properties
let interactor: ChallengesOverviewInteractorInput
weak var coordinator: ChallengesOverviewCoordinatorInput?
weak var output: ChallengesOverviewPresenterOutput?
// MARK: - Init
init(interactor: ChallengesOverviewInteractorInput, coordinator: ChallengesOverviewCoordinatorInput) {
self.interactor = interactor
self.coordinator = coordinator
}
}
// MARK: - User Events -
extension ChallengesOverviewPresenter: ChallengesOverviewPresenterInput {
func viewCreated() {
}
func handle(_ action: ChallengesOverview.Action) {
switch action {
case .typeSelected(let type):
coordinator?.navigate(to: .notebookSelection(type: type))
default:
print("another")
}
}
}
// MARK: - Presentation Logic -
// INTERACTOR -> PRESENTER (indirect)
extension ChallengesOverviewPresenter: ChallengesOverviewInteractorOutput {
}
|
//
// Photo.swift
// GalleryApp
//
// Created by Eojin Yang on 2021/01/08.
//
import Foundation
struct Photo: Codable {
let id: String?
let width: Int?
let height: Int?
let urls: Urls?
let user: User?
struct Urls: Codable {
let regular: String?
}
struct User: Codable {
let name: String?
}
}
extension Photo {
/// 디바이스 width 받아서 photo height 결정하는 함수
func photoHeightForDevice(_ deviceWidth: Float) -> Float? {
guard let width = self.width,
let height = self.height else { return nil}
let floatWidth = Float(width), floatHeight = Float(height)
let resizedWidth = floatWidth * (deviceWidth / floatWidth)
let resizedHeight = resizedWidth * floatHeight / floatWidth
return resizedHeight
}
}
|
//
// Render.swift
// EasyList
//
// Created by Alexey Zverev on 26.11.2019.
// Copyright © 2019 Alexey Zverev. All rights reserved.
//
import UIKit
// MARK: - View
public typealias AZView = UIView & AZConfigurable & AZAnyModelConfigurableView
public protocol AZConfigurable {
associatedtype Model: ViewAssociateable
func configure(with model: Model)
}
public protocol AZAnyModelConfigurableView: UIView {
func configure(with: AZAnyModel)
}
extension AZAnyModelConfigurableView where Self: UIView, Self: AZConfigurable {
public func configure(with item: AZAnyModel) {
guard let model = item as? Self.Model else {
assert(false, "model is not \"\(Self.Model.self)\" type")
return
}
self.configure(with: model)
}
}
// MARK: - Model
public typealias AZModel = ViewAssociateable & AZAnyModel
public protocol ViewAssociateable {
associatedtype View: UIView where View: AZConfigurable
}
public typealias AZAction = () -> Void
public protocol AZActionAvailable {
var tapAction: AZAction { get set}
}
public protocol AZAnyModel {
func cellType() -> UITableViewCell.Type
func viewType() -> UIView.Type
var reuseId: String { get }
}
public extension AZAnyModel where Self: ViewAssociateable, Self.View: AZAnyModelConfigurableView, Self.View.Model == Self {
func cellType() -> UITableViewCell.Type {
return CellWithGenericContent<Self.View>.self
}
func viewType() -> UIView.Type {
return Self.View.self
}
var reuseId: String {
return TypeDescriptor.key(from: self)
}
}
// MARK: - Utils
public final class TypeDescriptor {
public static func key(from item: Any) -> String {
return String(reflecting: type(of: item))
}
}
final class ViewMaker {
public static func makeView(with component: AZAnyModel) -> AZAnyModelConfigurableView {
let type = component.viewType()
let view = type.canBeLoadedFromNib() ? type.makeFromNib() : type.init(frame: .zero)
guard let result = view as? AZAnyModelConfigurableView else {
fatalError("view isn't AZView. It doesn't confirm AZAnyModelConfigurableView")
}
return result
}
}
//
//extension AZAnyModel {
// mutating func make(tap: @escaping Action) {
// let t = Tap(tapAction: tap, model: self)
//// self = t
// }
//}
//
//struct Tap {
// var tapAction: Action?
// var model: AZAnyModel
//}
|
//
// JSONCompareMatch.swift
// Foci
//
// Created by Losonczi László on 22/04/16.
// Copyright © 2016 Losi. All rights reserved.
//
import UIKit
import SwiftyJSON
class JSONCompareMatch: NSObject {
init(json: JSON) {
home = json["home"].stringValue;
away = json["away"].stringValue;
home_flag = json["home_flag"].stringValue;
away_flag = json["away_flag"].stringValue;
//if(json["final_score"] != JSON.null) {
final_score = JSONScore(json: json["final_score"]);
//}
//if(json["mine"] != JSON.null) {
mine = JSONBet(json: json["mine"]);
//}
//if(json["other"] != JSON.null) {
other = JSONBet(json: json["other"]);
//}
}
var home : String = "";
var away : String = "";
var home_flag : String = "";
var away_flag : String = "";
var final_score : JSONScore;
var mine : JSONBet;
var other : JSONBet;
}
|
//
// ViewController.swift
// app02
//
// Created by developer on 04.02.2021.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var imgView: UIImageView?
@IBOutlet var speedField: UITextField?
@IBOutlet var btnRotation: UIButton?
var isRotating = true
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let centerX = UIScreen.main.bounds.width / 2
let centerY = UIScreen.main.bounds.height / 2
imgView?.center.x = centerX
imgView?.center.y = centerY
}
var angle: Float = 0.0
@objc func calcRotation() {
if angle == 360 {
angle = 0
}
let sizeScreeen = UIScreen.main.bounds
let centerX = sizeScreeen.width / 2
let centerY = sizeScreeen.height / 2
let speedStr: String? = speedField?.text
if let speedStr = speedStr, let speed = Float(speedStr) {
let radius: CGFloat = 100.0
let cosValue = CGFloat(cos(angle * .pi / 180))
let sinValue = CGFloat(sin(angle * .pi / 180))
imgView?.center.x = radius * cosValue + centerX
imgView?.center.y = radius * sinValue + centerY
angle += 5 * speed
}
}
@IBAction func doRotation() {
if isRotating == true {
btnRotation?.setTitle("Stop", for: .normal)
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(calcRotation), userInfo: nil, repeats: true)
} else {
btnRotation?.setTitle("Start", for: .normal)
timer.invalidate()
}
isRotating = !isRotating
}
}
|
//
// OverlayView.swift
// MobileCapture2SDKTest
//
// Created by PF Olthof on 30/08/16.
// Copyright © 2016 CumulusPro. All rights reserved.
//
import UIKit
public class OverlayView : UIView {
public var start: CGPoint!
public var end: CGPoint!
override public init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clearColor()
}
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()!
// transparency layer
CGContextSaveGState(context)
CGContextBeginTransparencyLayer(context, nil)
CGContextSetLineWidth(context, 1.0)
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0)
//-----------------------------------------------------------------
// Create complex path as intersection of subpath 1 with subpath 2
//-----------------------------------------------------------------
// Create subpath 1 with the whole image size
CGContextSetRGBFillColor(context, 0, 0, 0, 0.4);
CGContextAddRect(context, self.bounds);
// Create subpath 2 which cuts a page area from the subpath 1
CGContextMoveToPoint(context, start.x, start.y)
CGContextAddLineToPoint(context, end.x, start.y)
CGContextAddLineToPoint(context, end.x, end.y)
CGContextAddLineToPoint(context, start.x, end.y)
CGContextAddLineToPoint(context, start.x, start.y)
CGContextEOFillPath(context)
CGContextEndTransparencyLayer(context)
}
}
|
//
// UIColor+LGL.swift
// LGLExtension
//
// Created by Passer on 2021/2/17.
//
import UIKit
extension UIColor: LGLCompatible {}
public extension LGL where Base == UIColor {
/**
创建一个适配暗黑模式的颜色
- parameter darkColor: 暗黑模式的时候展示的颜色
- parameter lightColor: 其他模式的时候展示的颜色
*/
static func traitColor(_ darkColor:UIColor, _ lightColor:UIColor) -> UIColor {
if #available(iOS 13.0, *) {
let color = UIColor{ (traitCollection) -> UIColor in
if traitCollection.userInterfaceStyle == .dark {
return darkColor
} else {
return lightColor
}
}
return color
} else {
return lightColor
}
}
/**
获取一个随机色
*/
static func randomColor() -> UIColor {
let red = CGFloat(arc4random()%256)/255.0
let green = CGFloat(arc4random()%256)/255.0
let blue = CGFloat(arc4random()%256)/255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
/**
定义UInt颜色
- parameter hex: 16进制值颜色字符串
*/
static func color(_ hex: UInt, _ alpha: CGFloat = 1.0) -> UIColor {
return Base(red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: alpha)
}
/**
定义16进制字符串值颜色
- parameter hex: 16进制值颜色字符串
*/
static func color(_ hex: String, _ alpha: CGFloat = 1.0) -> UIColor {
var cstr = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString;
if(cstr.length < 6){
return UIColor.clear;
}
if(cstr.hasPrefix("0X")){
cstr = cstr.substring(from: 2) as NSString
}
if(cstr.hasPrefix("#")){
cstr = cstr.substring(from: 1) as NSString
}
if(cstr.length != 6){
return UIColor.clear;
}
var rgbValue: UInt64 = 0
Scanner(string: cstr as String).scanHexInt64(&rgbValue)
return Base(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha);
}
}
|
//
// ChaosBag.swift
// ArkhamHorrorKit
//
// Created by Tiago Bras on 10/11/2017.
// Copyright © 2017 Tiago Bras. All rights reserved.
//
import Foundation
public struct ChaosBag: Equatable {
public let id: Int
public var p1: Int
public var zero: Int
public var m1: Int
public var m2: Int
public var m3: Int
public var m4: Int
public var m5: Int
public var m6: Int
public var m7: Int
public var m8: Int
public var skull: Int
public var autofail: Int
public var tablet: Int
public var cultist: Int
public var eldersign: Int
public var elderthing: Int
subscript(token: ChaosToken) -> Int {
get {
switch token {
case .p1: return p1
case .zero: return zero
case .m1: return m1
case .m2: return m2
case .m3: return m3
case .m4: return m4
case .m5: return m5
case .m6: return m6
case .m7: return m7
case .m8: return m8
case .skull: return skull
case .autofail: return autofail
case .tablet: return tablet
case .cultist: return cultist
case .eldersign: return eldersign
case .elderthing: return elderthing
}
}
set {
switch token {
case .p1: p1 = newValue
case .zero: zero = newValue
case .m1: m1 = newValue
case .m2: m2 = newValue
case .m3: m3 = newValue
case .m4: m4 = newValue
case .m5: m5 = newValue
case .m6: m6 = newValue
case .m7: m7 = newValue
case .m8: m8 = newValue
case .skull: skull = newValue
case .autofail: autofail = newValue
case .tablet: tablet = newValue
case .cultist: cultist = newValue
case .eldersign: eldersign = newValue
case .elderthing: elderthing = newValue
}
}
}
public var tokensDictionary: [ChaosToken: Int] {
get {
var dict = [ChaosToken: Int]()
ChaosToken.allValues.forEach { (token) in
dict[token] = self[token]
}
return dict
}
set {
for (token, quantity) in newValue {
self[token] = quantity
}
}
}
public var tokens: [ChaosToken] {
var array = [ChaosToken]()
for (token, quantity) in tokensDictionary {
guard quantity > 0 else { continue }
for _ in 0..<quantity {
array.append(token)
}
}
return array
}
public static func ==(lhs: ChaosBag, rhs: ChaosBag) -> Bool {
if lhs.id != rhs.id { return false }
if lhs.p1 != rhs.p1 { return false }
if lhs.zero != rhs.zero { return false }
if lhs.m1 != rhs.m1 { return false }
if lhs.m2 != rhs.m2 { return false }
if lhs.m3 != rhs.m3 { return false }
if lhs.m4 != rhs.m4 { return false }
if lhs.m5 != rhs.m5 { return false }
if lhs.m6 != rhs.m6 { return false }
if lhs.m7 != rhs.m7 { return false }
if lhs.m8 != rhs.m8 { return false }
if lhs.skull != rhs.skull { return false }
if lhs.autofail != rhs.autofail { return false }
if lhs.tablet != rhs.tablet { return false }
if lhs.cultist != rhs.cultist { return false }
if lhs.eldersign != rhs.eldersign { return false }
if lhs.elderthing != rhs.elderthing { return false }
return true
}
public func update(_ database: ChaosBagDatabase) throws {
try database.dbQueue.write({ (db) in
guard let record = try ChaosBagRecord.fetchOne(
db, key: ["id": id]) else {
throw ChaosBagDatabaseError.chaosBagNotFound(id)
}
record.updateTokens(dictionary: tokensDictionary)
if record.hasDatabaseChanges {
try record.update(db)
}
})
}
public func delete(_ database: ChaosBagDatabase) throws {
try database.dbQueue.write({ (db) in
guard let record = try ChaosBagRecord.fetchOne(
db, key: ["id": id]) else {
throw ChaosBagDatabaseError.chaosBagNotFound(id)
}
try record.delete(db)
})
}
public static func create(_ database: ChaosBagDatabase,
tokens: [ChaosToken: Int],
protected: Bool) throws -> ChaosBag {
let record = ChaosBagRecord(tokens: tokens, protected: protected)
return try database.dbQueue.write { (db) -> ChaosBag in
try record.insert(db)
return ChaosBag.makeChaosBag(record: record)
}
}
static func makeChaosBag(record: ChaosBagRecord) -> ChaosBag {
return ChaosBag(id: record.id!,
p1: record.p1,
zero: record.zero,
m1: record.m1,
m2: record.m2,
m3: record.m3,
m4: record.m4,
m5: record.m5,
m6: record.m6,
m7: record.m7,
m8: record.m8,
skull: record.skull,
autofail: record.autofail,
tablet: record.tablet,
cultist: record.cultist,
eldersign: record.eldersign,
elderthing: record.elderthing)
}
}
|
//
// RenderableAssetManager.swift
// Visualiser
//
// Created by Douglas Finlay on 06/03/2017.
// Copyright © 2017 Douglas Finlay. All rights reserved.
//
import MetalKit
enum RenderableAssetError: Error {
case couldNotLoad
}
class RenderableAssetManager {
private var meshStore = [Mesh]()
private var device: MTLDevice
private var mdlVertexDescriptor: MDLVertexDescriptor
private var meshBufferAllocator: MTKMeshBufferAllocator
init(device: MTLDevice, vertexDescriptor: MTLVertexDescriptor) {
self.device = device
self.meshBufferAllocator = MTKMeshBufferAllocator(device: self.device)
self.mdlVertexDescriptor = MTKModelIOVertexDescriptorFromMetal(vertexDescriptor)
(mdlVertexDescriptor.attributes[VertexAttributes.VertexAttributePosition.rawValue] as! MDLVertexAttribute).name = MDLVertexAttributePosition
(mdlVertexDescriptor.attributes[VertexAttributes.VertexAttributeNormal.rawValue] as! MDLVertexAttribute).name = MDLVertexAttributeNormal
(mdlVertexDescriptor.attributes[VertexAttributes.VertexAttributeTexCoord.rawValue] as! MDLVertexAttribute).name = MDLVertexAttributeTextureCoordinate
}
// Loads a renderable model from the specified URL. Returns nil if loading fails.
//
// TODO: this should not duplicate meshes already in the store
func renderableModel(forModel model: Model) -> RenderableModel? {
print("Loading " + model.path)
guard let modelURL = URL(string: model.path) else {
print("ERROR: invalid model URL: \(model.path)")
return nil
}
let asset = MDLAsset(url: modelURL, vertexDescriptor: self.mdlVertexDescriptor, bufferAllocator: self.meshBufferAllocator)
var mdlMeshes: NSArray? = NSArray.init()
var mtkMeshes: [MTKMesh] = []
do {
try mtkMeshes = MTKMesh.newMeshes(from: asset, device: device, sourceMeshes: &mdlMeshes)
} catch let error {
print("ERROR: could not load mesh: \(error)")
return nil
}
assert(mtkMeshes.count == mdlMeshes!.count, "mdlMesh and mtkMesh arrays differ in size")
if mtkMeshes.count > 1 {
print("ERROR: too many meshes loaded")
return nil
}
let mesh = Mesh(mtkMesh: mtkMeshes[0], mdlMesh: mdlMeshes![0] as! MDLMesh, device: device)
self.meshStore.append(mesh)
let renderableModel = RenderableModel(model: model, mesh: mesh, device: self.device)
return renderableModel
}
func renderableDirectionalLight(forDirectionalLight directionalLight: DirectionalLight) -> RenderableDirectionalLight? {
return RenderableDirectionalLight(directionalLight: directionalLight, device: self.device)
}
}
|
//
// HTTPTask.swift
// EvaluationTestiOS
//
// Created by Денис Магильницкий on 16.01.2021.
// Copyright © 2021 Денис Магильницкий. All rights reserved.
//
import Foundation
public typealias HTTPHeaders = [String: String]
// Configure request parameters
public enum HTTPTask {
case request
case requestParameters(bodyParameters: Parameters?, urlParameters: Parameters?)
case requestParametersAndHeaders(bodyParameters: Parameters?, urlParameters: Parameters?, additionHeaders: HTTPHeaders?)
}
|
//
// Stack.swift
// ChaosKit
//
// Created by Fu Lam Diep on 11.06.15.
// Copyright (c) 2015 Fu Lam Diep. All rights reserved.
//
import Foundation
public struct Stack<T> : Collection, CountLimited {
public typealias Element = T
private var _array : [T] = []
public var count : Int {get {return _array.count}}
public let max : Int
public var full : Bool {get {return count == max}}
public var isEmpty : Bool {get {return count == 0}}
public var top : T? {get {return isEmpty ? nil : _array[count - 1]}}
public var bottom : T? {get {return isEmpty ? nil : _array[0]}}
public var array : [T] {get {return _array}}
public init () {
max = Int.max
}
public init (_ max: Int) {
self.max = max
}
public init (_ elements: [T], _ max: Int = Int.max) {
self.max = max
_array = elements
}
public mutating func push (element: T) -> Bool {
if full {return false}
_array.append(element)
return true
}
public mutating func pop () -> T? {
if isEmpty {return nil}
return _array.removeLast()
}
public mutating func removeAll() -> [T] {
let array = _array
_array = []
return array
}
}
//extension Stack : ArrayLiteralConvertible {
// public init(arrayLiteral elements: Element...) {
// _array = elements
// max = Int.max
// }
//}
|
//
// SecondViewController.swift
// Delegates and Protocols
//
// Created by Yamusa Dalhatu on 10/6/20.
//
import UIKit
protocol CanRecieve {
func dataReceived(data: String)
}
class SecondViewController: UIViewController {
var delegate : CanRecieve?
@IBOutlet weak var messageLabel2: UILabel!
@IBOutlet weak var messageTextField: UITextField!
var data = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
messageLabel2.text = data
}
@IBAction func sendBackButtonPressed(_ sender: Any) {
delegate?.dataReceived(data: messageTextField.text!)
dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ServerJsonManager.swift
// ISOSuSwiftV
//
// Created by Amit Tiwari on 5/18/17.
// Copyright © 2017 amit tiwari. All rights reserved.
//
import UIKit
protocol ReponseObjectOfJson: class
{
func Respondata(_ text: Any)
}
class ServerJsonManager: NSObject
{
// class var sharedInstance: ServerJsonManager
// {
// struct Static {
// static var instance: ServerJsonManager?
// static var token = {0}()
// }
//
// _ = Static.token
//
// return Static.instance!
// }
weak var delegateResponsData: ReponseObjectOfJson?
func CallAPIwithRequest(urlReq:URLRequest)
{
let session = URLSession.shared
let task = session.dataTask(with: urlReq as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
self.delegateResponsData?.Respondata(json)
// print(json as Any)
}
task.resume()
}
}
|
import UIKit
extension UIImage {
func scaleImageToSize(newSize: CGSize) -> UIImage? {
let widthRatio = newSize.width / size.width
let heightRatio = newSize.height / size.height
let ratio = max(widthRatio, heightRatio)
var scaledImageRectangle = CGRect.zero
scaledImageRectangle.size.width = size.width * ratio
scaledImageRectangle.size.height = size.height * ratio
scaledImageRectangle.origin.x = (newSize.width - scaledImageRectangle.size.width) / 2
scaledImageRectangle.origin.y = (newSize.height - scaledImageRectangle.size.height) / 2
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
draw(in: scaledImageRectangle)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
func roundedToRadius(_ radius: CGFloat? = nil) -> UIImage? {
let maxRadius = min(size.width, size.height) / 2
let cornerRadius: CGFloat
if let radius = radius, radius > 0 && radius <= maxRadius {
cornerRadius = radius
} else {
cornerRadius = maxRadius
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let rect = CGRect(origin: .zero, size: size)
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
|
//
// PersistenceManager.swift
// login
//
// Created by Lim Teck Kian, Adam (HLB) on 26/09/2019.
// Copyright © 2019 Lim Teck Kian, Adam (HLB). All rights reserved.
//
import UIKit
class PersistencyManager: NSObject {
func saveImage(_ image: UIImage, filename: String) {
let path = NSHomeDirectory() + "/Documents/\(filename)"
let data = image.pngData()
try? data!.write(to: URL(fileURLWithPath: path), options: [.atomic])
}
func getImage(_ filename: String) -> UIImage? {
let path = NSHomeDirectory() + "/Documents/\(filename)"
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .uncachedRead)
return UIImage(data: data)
} catch {
return nil
}
}
}
|
//
// FooterView.swift
// Freesurf
//
// Created by Sahand Nayebaziz on 9/17/16.
// Copyright © 2016 Sahand Nayebaziz. All rights reserved.
//
import UIKit
@objc protocol FooterViewDelegate {
func didTapAdd()
}
class FooterView: UIView {
let delegate: FooterViewDelegate
init(delegate: FooterViewDelegate) {
self.delegate = delegate
super.init(frame: CGRect.zero)
let spitcastButton = UIButton(type: .system)
spitcastButton.setImage(#imageLiteral(resourceName: "SpitcastLogo"), for: .normal)
addSubview(spitcastButton)
spitcastButton.snp.makeConstraints { make in
make.centerX.equalTo(self.snp.centerX)
make.top.equalTo(45)
make.size.equalTo(45)
}
spitcastButton.tintColor = UIColor.white
spitcastButton.addTarget(self, action: #selector(didTapSpitcast), for: .touchUpInside)
let addButton = UIButton(type: .contactAdd)
addButton.tintColor = UIColor.white
addSubview(addButton)
addButton.snp.makeConstraints { make in
make.top.equalTo(20)
make.right.equalTo(-24)
}
addButton.addTarget(delegate, action: #selector(delegate.didTapAdd), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func didTapSpitcast() {
UIApplication.shared.openURL(URL(string: "http://www.spitcast.com")!)
}
}
|
//
// ParcelableModel.swift
// BTCUSDChart
//
// Created by Андрей Ежов on 28.10.17.
// Copyright © 2017 Андрей Ежов. All rights reserved.
//
import Foundation
import ObjectMapper
class ParcelableModel: Mappable {
// MARK: - Construction
required init?(map: Map) {
self.mapping(map: map)
}
// MARK: - Functions
func mapping(map: Map) { }
}
|
//
// JournalNotification.swift
// InoJournal
//
// Created by Luis Orozco on 3/25/17.
// Copyright © 2017 Luis Orozco. All rights reserved.
//
import Foundation
class JournalNotification: NSObject, NSUserNotificationCenterDelegate{
static let shared = JournalNotification()
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
return true
}
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
}
func send(_ title: String, informativeText: String){
let noti = NSUserNotification()
noti.identifier = "\(NSDate().timeIntervalSince1970)"
noti.title = title
noti.informativeText = informativeText
NSUserNotificationCenter.default.deliver(noti)
}
}
|
//
// IconCollectionViewCell.swift
// ToDoList
//
// Created by Roy Park on 12/15/20.
//
import UIKit
class IconCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var testImage: UIImageView!
@IBOutlet weak var iconImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// let tap = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
// testImage.addGestureRecognizer(tap)
// testImage.isUserInteractionEnabled = true
}
// @objc func imageTapped() {
// self.isSelected = true
// self.alpha = 0.5
// }
}
|
//
// LightTableViewCell.swift
// PicassoHouse
//
// Created by Antony Alkmim on 26/03/17.
// Copyright © 2017 CoderUP. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class LightTableViewCell: UITableViewCell {
var disposeBag = DisposeBag()
var viewModel: LightItemViewModel? = nil {
didSet {
bindViews()
}
}
private let switchButton = UISwitch()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
accessoryView = switchButton
selectionStyle = .none
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
disposeBag = DisposeBag()
}
private func setupUI() {
backgroundColor = #colorLiteral(red: 0.06666666667, green: 0.06666666667, blue: 0.06666666667, alpha: 1)
textLabel?.textColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
switchButton.onTintColor = Styles.tintColor
}
private func bindViews() {
guard let viewModel = viewModel else { return }
imageView?.image = viewModel.roomType.image.withColor(#colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1))
textLabel?.text = viewModel.roomTitle
switchButton.isOn = viewModel.isLightOn
switchButton.rx.isOn.changed
.bindTo(viewModel.didChangeLightStatusTo)
.disposed(by: disposeBag)
}
}
|
import UIKit
class VariableTitleValueCell: EditableTitleValueTableViewCell {
override class var textLabelDefaultTextColor: UIColor { return AppColor.Text.VariableName }
override class var detailTextLabelDefaultTextColor: UIColor { return AppColor.Text.VariableValue }
}
extension VariableTitleValueCell : VariableSceneDataItemConfigurable, VariableSceneDataItemEditable {
func configure(variableSceneDataItem item: VariableSceneDataItem) {
self.textLabel?.text = item.title
self.textField.text = item.title
self.textField.placeholder = item.title
self.detailTextLabel?.text = item.detail
self.detailTextField.text = item.detail
self.detailTextField.placeholder = item.detail
}
}
|
//
// TicTacToeViewController.swift
// Pruebas
//
// Created by Julio Banda on 11/23/18.
// Copyright © 2018 Julio Banda. All rights reserved.
//
import UIKit
class TicTacToeViewController: UIViewController {
let X: String = "X"
let O: String = "O"
var game: [[String]] = [["", "", ""],
["", "", ""],
["", "", ""]]
var isX: Bool = false
var turn: Int = 0 {
didSet {
isX = !isX
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func touch(in button: UIButton){
if button.titleLabel?.text == X || button.titleLabel?.text == O { return }
let tag: String = String(button.tag)
let row: Int = Int(String(tag.first!))! - 1
let column: Int = Int(String(tag.last!))! - 1
turn += 1
let boxValue: String = isX ? X : O
button.setTitle(boxValue, for: .normal)
game[row][column] = boxValue
if turn > 2 {
for row in 0 ..< game.count {
if (game[row][1] == game[row][0]) && (game[row][1] == game[row][2]) {
print("Alguien ganó")
}
}
}
}
}
|
//
// ViewController.swift
// Window
//
// Created by mac on 12/3/15.
// Copyright © 2015 JY. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var text: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
// 显示或者隐藏标尺
text.toggleRuler(nil)
}
@IBAction func showWordCountWindow(sender: AnyObject) {
// 1. instantiate the word count wimdow controller, using the storyboard ID you specified before.
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let wordCountWindowController = storyboard.instantiateControllerWithIdentifier("WordCountWindowController") as! NSWindowController
if let wordCountWindow = wordCountWindowController.window, textStorage = text.textStorage {
// 2. set the values retrieved from the text view in the word count window count outlets
let wordCountViewController = wordCountWindow.contentViewController as! WordCountViewController
wordCountViewController.wordCount.stringValue = "\(textStorage.words.count)"
wordCountViewController.paragraphCount.stringValue = "\(textStorage.paragraphs.count)"
// 3. show the word count window modally
let application = NSApplication.sharedApplication()
application.runModalForWindow(wordCountWindow)
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
|
//
// ZGraphEditor.swift
// Seriously
//
// Created by Jonathan Sand on 10/29/16.
// Copyright © 2016 Jonathan Sand. All rights reserved.
//
import Foundation
import CloudKit
#if os(OSX)
import Cocoa
#elseif os(iOS)
import UIKit
#endif
let gGraphEditor = ZMapEditor()
// mix of zone mutations and web services requestss
class ZMapEditor: ZBaseEditor {
override var canHandleKey: Bool { return gIsGraphOrEditIdeaMode }
var priorHere: Zone?
// MARK:- events
// MARK:-
class ZStalledEvent: NSObject {
var event: ZEvent?
var isWindow: Bool = true
convenience init(_ iEvent: ZEvent, iIsWindow: Bool) {
self.init()
isWindow = iIsWindow
event = iEvent
}
}
var undoManager: UndoManager {
if let w = gCurrentlyEditingWidget,
w.undoManager != nil {
return w.undoManager!
}
return gUndoManager
}
@discardableResult override func handleKey(_ iKey: String?, flags: ZEventFlags, isWindow: Bool) -> Bool { // false means key not handled
if !gIsEditingStateChanging,
var key = iKey {
let CONTROL = flags.isControl
let COMMAND = flags.isCommand
let OPTION = flags.isOption
var SHIFT = flags.isShift
let SPECIAL = flags.isSpecial
let ALL = COMMAND && OPTION && CONTROL
let IGNORED = OPTION && CONTROL
let HARD = COMMAND && CONTROL
let FLAGGED = COMMAND || OPTION || CONTROL
let arrow = key.arrow
if key != key.lowercased() {
key = key.lowercased()
SHIFT = true
}
gCurrentKeyPressed = key
if gIsEditIdeaMode {
if !gTextEditor.handleKey(iKey, flags: flags) {
if !FLAGGED {
return false
} else {
gCurrentKeyPressed = key
switch key {
case "a": gCurrentlyEditingWidget?.selectAllText()
case "d": gCurrentlyEditingWidget?.widgetZone?.tearApartCombine(ALL, HARD)
case "f": gSearching.showSearch(OPTION)
case "g": refetch(COMMAND, OPTION)
case "n": grabOrEdit(true, OPTION)
case "p": printCurrentFocus()
case "/": if IGNORED { return false } else { popAndUpdate(CONTROL, kind: .eEdited) }
case ",", ".": commaAndPeriod(COMMAND, OPTION, with: key == ",")
case kTab: addSibling(OPTION)
case kSpace: gSelecting.currentMoveable.addIdea()
case kReturn: if COMMAND { grabOrEdit(COMMAND, OPTION) }
case kEscape: grabOrEdit( true, OPTION, true)
case kBackspace,
kDelete: if CONTROL { focusOnTrash() }
default: return false // false means key not handled
}
}
}
} else if isValid(key, flags) {
let widget = gWidgets.currentMovableWidget
widget?.widgetZone?.needWrite()
if let a = arrow, isWindow {
handleArrow(a, flags: flags)
} else if kMarkingCharacters.contains(key), !COMMAND, !CONTROL {
prefix(with: key)
} else if !super.handleKey(iKey, flags: flags, isWindow: isWindow) {
gCurrentKeyPressed = key
switch key {
case "a": if COMMAND { gSelecting.currentMoveable.selectAll(progeny: OPTION) } else { gSelecting.simplifiedGrabs.alphabetize(OPTION); gRedrawGraph() }
case "b": gSelecting.firstSortedGrab?.addBookmark()
case "c": if COMMAND && !OPTION { copyToPaste() } else { gGraphController?.recenter(SPECIAL) }
case "d": if FLAGGED { widget?.widgetZone?.combineIntoParent() } else { duplicate() }
case "e": gSelecting.firstSortedGrab?.editTrait(for: .tEmail)
case "f": gSearching.showSearch(OPTION)
case "g": refetch(COMMAND, OPTION)
case "h": gSelecting.firstSortedGrab?.editTrait(for: .tHyperlink)
case "l": alterCase(up: false)
case "k": toggleColorized()
case "m": gSelecting.simplifiedGrabs.sortByLength(OPTION); gRedrawGraph()
case "n": grabOrEdit(true, OPTION)
case "o": gSelecting.currentMoveable.importFromFile(OPTION ? .eOutline : .eSeriously) { gRedrawGraph() }
case "p": printCurrentFocus()
case "r": reverse()
case "s": gHere.exportToFile(OPTION ? .eOutline : .eSeriously)
case "t": if SPECIAL { gControllers.showEssay(forGuide: false) } else { swapWithParent() }
case "u": if SPECIAL { gControllers.showEssay(forGuide: true) } else { alterCase(up: true) }
case "v": if COMMAND { paste() }
case "w": rotateWritable()
case "x": if COMMAND { delete(permanently: SPECIAL && isWindow) } else { gCurrentKeyPressed = nil; return false }
case "z": if !SHIFT { gUndoManager.undo() } else { gUndoManager.redo() }
case "+": divideChildren()
case "-": return handleHyphen(COMMAND, OPTION)
case "'": swapSmallMap(OPTION)
case "/": if IGNORED { gCurrentKeyPressed = nil; return false } else { popAndUpdate(CONTROL, COMMAND, kind: .eSelected) }
case "\\": gGraphController?.toggleGraphs(); gRedrawGraph()
case "]", "[": smartGo(up: key == "]")
case "?": if CONTROL { openBrowserForFocusWebsite() } else { gCurrentKeyPressed = nil; return false }
case kEquals: if COMMAND { updateSize(up: true) } else { gSelecting.firstSortedGrab?.invokeTravel() { gRedrawGraph() } }
case ",", ".": commaAndPeriod(COMMAND, OPTION, with: key == ",")
case kTab: addSibling(OPTION)
case kSpace: if OPTION || CONTROL || isWindow { gSelecting.currentMoveable.addIdea() } else { gCurrentKeyPressed = nil; return false }
case kBackspace,
kDelete: if CONTROL { focusOnTrash() } else if OPTION || isWindow || COMMAND { delete(permanently: SPECIAL && isWindow, preserveChildren: FLAGGED && isWindow, convertToTitledLine: SPECIAL) } else { gCurrentKeyPressed = nil; return false }
case kReturn: grabOrEdit(COMMAND, OPTION)
case kEscape: grabOrEdit(true, OPTION, true)
default: return false // indicate key was not handled
}
}
}
}
gCurrentKeyPressed = nil
return true // indicate key was handled
}
func handleArrow(_ arrow: ZArrowKey, flags: ZEventFlags) {
if gIsEditIdeaMode || gArrowsDoNotBrowse {
gTextEditor.handleArrow(arrow, flags: flags)
return
}
let COMMAND = flags.isCommand
let OPTION = flags.isOption
let SHIFT = flags.isShift
if (OPTION && !gSelecting.currentMoveable.userCanMove) || gIsHelpFrontmost {
return
}
switch arrow {
case .up, .down: move(up: arrow == .up, selectionOnly: !OPTION, extreme: COMMAND, growSelection: SHIFT)
default:
if let moveable = gSelecting.rootMostMoveable {
if !SHIFT || moveable.isInSmallMap {
switch arrow {
case .left,
.right: move(out: arrow == .left, selectionOnly: !OPTION, extreme: COMMAND) {
gSelecting.updateAfterMove() // relayout graph when travelling through a bookmark
}
default: break
}
} else {
// ///////////////
// GENERATIONAL //
// ///////////////
var show = true
switch arrow {
case .right: break
case .left: show = false
default: return
}
if OPTION {
browseBreadcrumbs(arrow == .left)
} else {
moveable.applyGenerationally(show, extreme: COMMAND)
}
}
}
}
}
func menuType(for key: String, _ flags: ZEventFlags) -> ZMenuType {
let alterers = "ehltuw\r" + kMarkingCharacters
let ALTERER = alterers.contains(key)
let COMMAND = flags.isCommand
let CONTROL = flags.isControl
let FLAGGED = COMMAND || CONTROL
if !FLAGGED && ALTERER { return .eAlter
} else {
switch key {
case "f": return .eFind
case "k": return .eColor
case "m": return .eCloud
case "z": return .eUndo
case "o", "s": return .eFiles
case "r", "#": return .eSort
case "t", "u", "?", "/": return .eHelp
case "x", kSpace: return .eChild
case "b", kTab, kBackspace: return .eParent
case kDelete: return CONTROL ? .eAlways : .eParent
case kEquals: return COMMAND ? .eAlways : .eTravel
case "d": return COMMAND ? .eAlter : .eParent
default: return .eAlways
}
}
}
override func isValid(_ key: String, _ flags: ZEventFlags, inWindow: Bool = true) -> Bool {
if !gIsGraphOrEditIdeaMode {
return false
}
if key.arrow != nil {
return true
}
let type = menuType(for: key, flags)
var valid = !gIsEditIdeaMode
if valid,
type != .eAlways {
let undo = undoManager
let select = gSelecting
let wGrabs = select.writableGrabsCount
let paste = select.pasteableZones.count
let grabs = select.currentGrabs .count
let shown = select.currentGrabsHaveVisibleChildren
let mover = select.currentMoveable
let canColor = mover.isReadOnlyRoot || mover.bookmarkTarget?.isReadOnlyRoot ?? false
let write = mover.userCanWrite
let sort = mover.userCanMutateProgeny
let parent = mover.userCanMove
switch type {
case .eParent: valid = parent
case .eChild: valid = sort
case .eAlter: valid = write
case .eColor: valid = canColor || write
case .ePaste: valid = paste > 0 && write
case .eUseGrabs: valid = wGrabs > 0 && write
case .eMultiple: valid = grabs > 1
case .eSort: valid = (shown && sort) || (grabs > 1 && parent)
case .eUndo: valid = undo.canUndo
case .eRedo: valid = undo.canRedo
case .eTravel: valid = mover.canTravel
case .eCloud: valid = gHasInternet && gCloudStatusIsActive
default: break
}
}
return valid
}
// MARK:- features
// MARK:-
func swapSmallMap(_ OPTION: Bool) {
let currentID : ZDatabaseID = gIsRecentlyMode ? .recentsID : .favoritesID
let newID : ZDatabaseID = gIsRecentlyMode ? .favoritesID : .recentsID
gSmallMapMode = gIsRecentlyMode ? .favorites : .recent
if OPTION { // if any grabs are in current small map, move them to other map
gSelecting.swapGrabsFrom(currentID, toID: newID)
}
gSignal([.sDetails])
}
func addSibling(_ OPTION: Bool) {
gTextEditor.stopCurrentEdit()
gSelecting.currentMoveable.addNextAndRedraw(containing: OPTION)
}
func browseBreadcrumbs(_ out: Bool) {
if let here = out ? gHere.parentZone : gBreadcrumbs.nextCrumb(false) {
let last = gSelecting.currentGrabs
gHere = here
here.traverseAllProgeny { child in
child.concealChildren()
}
gSelecting.grab(last)
gSelecting.firstGrab?.asssureIsVisible()
gRedrawGraph(for: here)
}
}
func duplicate() {
var grabs = gSelecting.simplifiedGrabs
grabs.duplicate()
}
func popAndUpdate(_ CONTROL: Bool, _ COMMAND: Bool = false, kind: ZFocusKind) {
if !CONTROL {
gRecords?.maybeRefocus(kind, COMMAND, shouldGrab: true) { // complex grab logic
gRedrawGraph()
}
} else {
gRecents.popAndUpdateRecents()
if let here = gRecents.currentBookmark?.bookmarkTarget {
gHere = here
}
gRedrawGraph()
}
}
func updateSize(up: Bool) {
let delta = CGFloat(up ? 1 : -1)
var size = gGenericOffset.offsetBy(0, delta)
size = size.force(horizotal: false, into: NSRange(location: 2, length: 7))
gGenericOffset = size
gRedrawGraph()
}
func handleHyphen(_ COMMAND: Bool = false, _ OPTION: Bool = false) -> Bool {
let SPECIAL = COMMAND && OPTION
if SPECIAL {
convertToTitledLineAndRearrangeChildren()
} else if OPTION {
return gSelecting.currentMoveable.convertToFromLine()
} else if COMMAND {
updateSize(up: false)
} else {
addDashedLine()
}
return true
}
func addDashedLine(onCompletion: Closure? = nil) {
// three states:
// 1) plain line -> insert and edit stub title
// 2) titled line selected only -> convert back to plain line
// 3) titled line is first of multiple -> convert titled line to plain title, selected, as parent of others
let grabs = gSelecting.currentGrabs
let isMultiple = grabs.count > 1
if let original = gSelecting.currentMoveableLine,
let name = original.zoneName {
let promoteToParent: ClosureClosure = { innerClosure in
original.convertFromLineWithTitle()
self.moveZones(grabs, into: original) {
original.grab()
gRedrawGraph {
innerClosure()
onCompletion?()
}
}
}
if name.contains(kLineOfDashes) {
// //////////
// state 1 //
// //////////
original.assignAndColorize(kLineWithStubTitle) // convert into a stub title
if !isMultiple {
original.editAndSelect(range: NSMakeRange(12, 1)) // edit selecting stub
} else {
promoteToParent {
original.edit()
}
}
return
} else if name.isLineWithTitle {
if !isMultiple {
// //////////
// state 2 //
// //////////
original.assignAndColorize(kLineOfDashes)
} else {
// //////////
// state 3 //
// //////////
promoteToParent {}
}
return
}
}
gSelecting.rootMostMoveable?.addNext(with: kLineOfDashes) { iChild in
iChild.colorized = true
iChild.grab()
onCompletion?()
}
}
func focusOnTrash() {
gTrash?.focusOn() {
gRedrawGraph()
}
}
func refetch(_ COMMAND: Bool = false, _ OPTION: Bool = false) {
// plain is fetch children
// COMMAND alone is fetch all
// OPTION is all progeny
// both is force adoption of selected
if COMMAND && OPTION {
gSelecting.simplifiedGrabs.assureAdoption() // finish what fetch has done
} else if COMMAND && !OPTION { // COMMAND alone
gBatches.refetch { iSame in
gRedrawGraph()
}
} else {
for grab in gSelecting.currentGrabs {
if !OPTION { // plain
grab.reallyNeedChildren()
} else { // OPTION alone or both
grab.reallyNeedProgeny()
}
}
gBatches.children { iSame in
gRedrawGraph()
}
}
}
func commaAndPeriod(_ COMMAND: Bool, _ OPTION: Bool, with COMMA: Bool) {
if !COMMAND || (OPTION && COMMA) {
toggleGrowthAndConfinementModes(changesDirection: COMMA)
if gIsEditIdeaMode && COMMA {
swapAndResumeEdit()
}
gSignal([.sMap, .sMain, .sDetails, .sPreferences])
} else if !COMMA {
gShowDetailsView = true
gMainController?.update()
gDetailsController?.toggleViewsFor(ids: [.Preferences])
} else if gIsEditIdeaMode {
gTextEditor.cancel()
}
}
func toggleColorized() {
for zone in gSelecting.currentGrabs {
zone.toggleColorized()
}
gRedrawGraph()
}
func prefix(with iMark: String) {
let before = "("
let after = ") "
let zones = gSelecting.currentGrabs
var digit = 0
let count = iMark == "#"
for zone in zones {
if var name = zone.zoneName {
var prefix = before + iMark + after
var add = true
digit += 1
if name.starts(with: prefix) {
let nameParts = name.components(separatedBy: prefix)
name = nameParts[1] // remove prefix
} else {
if name.starts(with: before) {
let nameParts = name.components(separatedBy: after)
var index = 0
while nameParts.count > index + 1 {
let mark = nameParts[index] // found: "(x"
let markParts = mark.components(separatedBy: before) // markParts[1] == x
if markParts.count > 1 && markParts[0].count == 0 {
let part = markParts[1]
index += 1
if part.count <= 2 && part.isDigit {
add = false
break
}
}
}
name = nameParts[index] // remove all (x) where x is any character
}
if add {
if count {
prefix = before + "\(digit)" + after // increment prefix
}
name = prefix + name // replace or prepend with prefix
}
}
zone.zoneName = name
gTextEditor.updateText(inZone: zone)?.updateBookmarkAssociates()
}
}
gRedrawGraph()
}
func grabOrEdit(_ COMMAND: Bool, _ OPTION: Bool, _ ESCAPE: Bool = false) {
if !COMMAND { // switch to essay edit mode
gSelecting.currentMoveable.edit()
if OPTION {
gTextEditor.placeCursorAtEnd()
}
} else { // switch to idea edit mode
if !gIsNoteMode {
gCreateCombinedEssay = !OPTION // default is multiple, option drives it to single
if gCurrentEssay == nil || OPTION || !ESCAPE { // restore prior essay or create one fresh (OPTION forces the latter)
gCurrentEssay = gSelecting.firstGrab?.note
}
}
gControllers.swapGraphAndEssay()
}
}
func divideChildren() {
let grabs = gSelecting.currentGrabs
for zone in grabs {
zone.needChildren()
}
for zone in grabs {
zone.divideEvenly()
}
gRedrawGraph()
}
func rotateWritable() {
for zone in gSelecting.currentGrabs {
zone.rotateWritable()
}
gRedrawGraph()
}
func alterCase(up: Bool) {
for grab in gSelecting.currentGrabs {
if let tWidget = grab.widget?.textWidget {
tWidget.alterCase(up: up)
}
}
}
// MARK:- lines
// MARK:-
func convertToTitledLineAndRearrangeChildren() {
delete(preserveChildren: true, convertToTitledLine: true)
}
func swapWithParent() {
if gSelecting.currentGrabs.count == 1 {
gSelecting.firstSortedGrab?.swapWithParent()
}
}
func swapAndResumeEdit() {
let t = gTextEditor
// //////////////////////////////////////////////////////////
// swap currently editing zone with sibling, resuming edit //
// //////////////////////////////////////////////////////////
if let zone = t.currentlyEditingZone, zone.hasSiblings {
let atStart = gListGrowthMode == .up
let offset = t.editingOffset(atStart)
t.stopCurrentEdit(forceCapture: true)
zone.ungrab()
gCurrentBrowseLevel = zone.level // so cousin list will not be empty
moveUp(atStart, [zone], selectionOnly: false, extreme: false, growSelection: false, targeting: nil) { iKind in
gRedrawGraph() {
t.edit(zone)
t.setCursor(at: offset)
}
}
}
}
// MARK:- copy and paste
// MARK:-
func copyToPaste() {
let grabs = gSelecting.simplifiedGrabs
gSelecting.clearPaste()
for grab in grabs {
grab.addToPaste()
}
}
// MARK:- delete
// MARK:-
func delete(permanently: Bool = false, preserveChildren: Bool = false, convertToTitledLine: Bool = false) {
gDeferRedraw {
if preserveChildren && !permanently {
self.preserveChildrenOfGrabbedZones(convertToTitledLine: convertToTitledLine) {
gFavorites.updateFavoritesAndRedraw {
gDeferringRedraw = false
gRedrawGraph()
}
}
} else {
let deleteThis = gSelecting.rootMostMoveable
let grab = deleteThis?.parentZone
prepareUndoForDelete()
gSelecting.simplifiedGrabs.deleteZones(permanently: permanently) {
gDeferringRedraw = false
gRedrawGraph(for: grab)
gFavorites.updateFavoritesAndRedraw { // delete alters the list
gRedrawGraph(for: grab)
}
}
}
}
}
// MARK:- move
// MARK:-
func moveOut(selectionOnly: Bool = true, extreme: Bool = false, force: Bool = false, onCompletion: Closure?) {
if let zone: Zone = gSelecting.firstSortedGrab {
let parentZone = zone.parentZone
if zone.isARoot || parentZone == gFavoritesRoot {
return // cannot move out from a root or move into favorites root
} else if selectionOnly {
// /////////////////
// MOVE SELECTION //
// /////////////////
zone.moveSelectionOut(extreme: extreme, onCompletion: onCompletion)
} else if let p = parentZone, !p.isARoot {
// ////////////
// MOVE ZONE //
// ////////////
let grandParentZone = p.parentZone
if zone == gHere && !force {
let grandParentName = grandParentZone?.zoneName
let parenthetical = grandParentName == nil ? "" : " (\(grandParentName!))"
// /////////////////////////////////////////////////////////////////////
// present an alert asking if user really wants to move here leftward //
// /////////////////////////////////////////////////////////////////////
gAlerts.showAlert("WARNING", "This will relocate \"\(zone.zoneName ?? "")\" to its parent's parent\(parenthetical)", "Relocate", "Cancel") { iStatus in
if iStatus == .eStatusYes {
self.moveOut(selectionOnly: selectionOnly, extreme: extreme, force: true, onCompletion: onCompletion)
}
}
} else {
let moveOutToHere = { (iHere: Zone?) in
if let here = iHere {
gHere = here
self.moveOut(to: gHere, onCompletion: onCompletion)
}
}
if extreme {
if gHere.isARoot {
moveOut(to: gHere, onCompletion: onCompletion)
} else {
zone.revealZonesToRoot() {
moveOutToHere(gRoot)
onCompletion?()
}
}
} else if grandParentZone != nil {
p.revealParentAndSiblings()
if grandParentZone!.spawnedBy(gHere) {
self.moveOut(to: grandParentZone!, onCompletion: onCompletion)
} else {
moveOutToHere(grandParentZone!)
}
}
}
}
}
onCompletion?()
}
func move(out: Bool, selectionOnly: Bool = true, extreme: Bool = false, onCompletion: Closure?) {
if out {
moveOut (selectionOnly: selectionOnly, extreme: extreme, onCompletion: onCompletion)
} else {
moveInto(selectionOnly: selectionOnly, extreme: extreme, onCompletion: onCompletion)
}
}
func moveInto(selectionOnly: Bool = true, extreme: Bool = false, onCompletion: Closure?) {
if let zone = gSelecting.firstSortedGrab {
if !selectionOnly {
actuallyMoveInto(gSelecting.sortedGrabs, onCompletion: onCompletion)
} else if zone.canTravel && zone.fetchableCount == 0 && zone.count == 0 {
zone.invokeTravel(onCompletion: onCompletion)
} else {
zone.moveSelectionInto(extreme: extreme, onCompletion: onCompletion)
}
}
}
func actuallyMoveInto(_ zones: ZoneArray, onCompletion: Closure?) {
if !gIsRecentlyMode || !zones.anyInRecently,
var there = zones[0].parentZone {
let siblings = Array(there.children)
for zone in zones {
if let index = zone.siblingIndex {
var cousinIndex = index == 0 ? 1 : index - 1 // ALWAYS INSERT INTO SIBLING ABOVE, EXCEPT AT TOP
if cousinIndex >= 0 && cousinIndex < siblings.count {
var newThere = siblings[cousinIndex]
if !zones.contains(newThere) {
there = newThere
break
} else {
cousinIndex += 1
newThere = siblings[cousinIndex]
if !zones.contains(newThere) {
there = newThere
break
}
}
}
}
}
moveZones(zones, into: there, onCompletion: onCompletion)
} else {
onCompletion?()
}
}
func moveZones(_ zones: ZoneArray, into: Zone, at iIndex: Int? = nil, orphan: Bool = true, onCompletion: Closure?) {
into.revealChildren()
into.needChildren()
for zone in zones {
if zone != into {
if orphan {
zone.orphan()
}
into.addAndReorderChild(zone, at: iIndex)
}
}
onCompletion?()
}
// MARK:- undoables
// MARK:-
func reverse() {
UNDO(self) { iUndoSelf in
iUndoSelf.reverse()
}
var zones = gSelecting.simplifiedGrabs
let commonParent = zones.commonParent
if commonParent == nil {
return
}
if zones.count == 1 {
zones = commonParent?.children ?? []
}
zones.reverse()
commonParent?.respectOrder()
gRedrawGraph()
}
func undoDelete() {
gSelecting.ungrabAll()
for (child, (parent, index)) in gSelecting.pasteableZones {
child.orphan()
parent?.addAndReorderChild(child, at: index)
child.addToGrabs()
}
gSelecting.clearPaste()
UNDO(self) { iUndoSelf in
iUndoSelf.delete()
}
gRedrawGraph()
}
func paste() { pasteInto(gSelecting.firstSortedGrab) }
func pasteInto(_ iZone: Zone? = nil, honorFormerParents: Bool = false) {
let pastables = gSelecting.pasteableZones
if pastables.count > 0, let zone = iZone {
let isBookmark = zone.isBookmark
let action = {
var forUndo = ZoneArray ()
gSelecting.ungrabAll()
for (pastable, (parent, index)) in pastables {
let pasteMe = pastable.isInTrash ? pastable : pastable.deepCopy // for zones not in trash, paste a deep copy
let insertAt = index != nil ? index : gListsGrowDown ? nil : 0
let into = parent != nil ? honorFormerParents ? parent! : zone : zone
pasteMe.orphan()
into.revealChildren()
into.addAndReorderChild(pasteMe, at: insertAt)
pasteMe.recursivelyApplyDatabaseID(into.databaseID)
forUndo.append(pasteMe)
pasteMe.addToGrabs()
}
self.UNDO(self) { iUndoSelf in
iUndoSelf.prepareUndoForDelete()
forUndo.deleteZones(iShouldGrab: false, onCompletion: nil)
zone.grab()
gRedrawGraph()
}
if isBookmark {
self.undoManager.endUndoGrouping()
}
gFavorites.updateFavoritesAndRedraw()
}
let prepare = {
for child in pastables.keys {
if !child.isInTrash {
child.needProgeny()
}
}
action()
}
if !isBookmark {
prepare()
} else {
undoManager.beginUndoGrouping()
zone.travelThrough() { (iAny, iSignalKind) in
prepare()
}
}
}
}
func preserveChildrenOfGrabbedZones(convertToTitledLine: Bool = false, onCompletion: Closure?) {
let grabs = gSelecting.simplifiedGrabs
let candidate = gSelecting.rootMostMoveable
if grabs.count > 1 && convertToTitledLine {
addDashedLine {
onCompletion?()
}
return
}
for grab in grabs {
grab.needChildren()
grab.revealChildren()
}
if let parent = candidate?.parentZone {
let siblingIndex = candidate?.siblingIndex
var children = ZoneArray ()
gSelecting.clearPaste()
gSelecting.currentGrabs = []
for grab in grabs {
if !convertToTitledLine { // delete, add to paste
grab.addToPaste()
grab.moveZone(to: grab.trashZone)
} else { // convert to titled line and insert above
grab.convertToTitledLine()
children.append(grab)
grab.addToGrabs()
}
for child in grab.children {
children.append(child)
child.addToGrabs()
}
}
children.reverse()
for child in children {
child.orphan()
parent.addAndReorderChild(child, at: siblingIndex)
}
self.UNDO(self) { iUndoSelf in
iUndoSelf.prepareUndoForDelete()
children .deleteZones(iShouldGrab: false) {}
iUndoSelf.pasteInto(parent, honorFormerParents: true)
}
}
onCompletion?()
}
func prepareUndoForDelete() {
gSelecting.clearPaste()
self.UNDO(self) { iUndoSelf in
iUndoSelf.undoDelete()
}
}
func moveOut(to: Zone, onCompletion: Closure?) {
let zones = gSelecting.sortedGrabs.reversed() as ZoneArray
var completedYet = false
zones.recursivelyRevealSiblings(untilReaching: to) { iRevealedZone in
if !completedYet && iRevealedZone == to {
completedYet = true
for zone in zones {
var insert: Int? = zone.parentZone?.siblingIndex
if zone.parentZone?.parentZone == to,
let i = insert {
insert = i + 1
if insert! >= to.count {
insert = nil // append at end
}
}
if let from = zone.parentZone {
let index = zone.siblingIndex
self.UNDO(self) { iUndoSelf in
zone.moveZone(into: from, at: index, orphan: true) { onCompletion?() }
}
}
zone.orphan()
to.addAndReorderChild(zone, at: insert)
}
onCompletion?()
}
}
}
func moveGrabbedZones(into iInto: Zone, at iIndex: Int?, _ SPECIAL: Bool, onCompletion: Closure?) {
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 1. move a normal zone into another normal zone //
// 2. move a normal zone through a bookmark //
// 3. move a normal zone into small map -- create a bookmark pointing at normal zone, then add it to the map //
// 4. move from small map into a normal zone -- convert to a bookmark, then move the bookmark //
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
let toBookmark = iInto.isBookmark // type 2
let toSmallMap = iInto.isInSmallMap && !toBookmark // type 3
let into = iInto.bookmarkTarget ?? iInto // grab bookmark AFTER travel
var grabs = gSelecting.currentGrabs
var restore = [Zone: (Zone, Int?)] ()
var cyclicals = IndexSet()
for (index, zone) in grabs.enumerated() {
if iInto.spawnedBy(zone) {
cyclicals.insert(index)
} else if let parent = zone.parentZone {
let siblingIndex = zone.siblingIndex
restore[zone] = (parent, siblingIndex)
zone.needProgeny()
}
}
while let index = cyclicals.last {
cyclicals.remove(index)
grabs.remove(at: index)
}
if let dragged = gDraggedZone, dragged.isInSmallMap, !toSmallMap {
dragged.maybeNeedSave() // type 4
}
grabs.sort { (a, b) -> Bool in
if a.isInSmallMap {
a.maybeNeedSave() // type 4
}
return a.order < b.order
}
// ///////////////////
// prepare for UNDO //
// ///////////////////
if toBookmark {
undoManager.beginUndoGrouping()
}
UNDO(self) { iUndoSelf in
for (child, (parent, index)) in restore {
child.orphan()
parent.addAndReorderChild(child, at: index)
}
iUndoSelf.UNDO(self) { iUndoUndoSelf in
iUndoUndoSelf.moveGrabbedZones(into: iInto, at: iIndex, SPECIAL, onCompletion: onCompletion)
}
onCompletion?()
}
// /////////////
// move logic //
// /////////////
let finish = {
var done = false
if !SPECIAL {
into.revealChildren()
}
into.maybeNeedChildren()
if !done {
done = true
if let firstGrab = grabs.first,
let fromIndex = firstGrab.siblingIndex,
(firstGrab.parentZone != into || fromIndex > (iIndex ?? 1000)) {
grabs = grabs.reversed()
}
gSelecting.ungrabAll()
for grab in grabs {
var beingMoved = grab
if toSmallMap && beingMoved.isInBigMap && !beingMoved.isBookmark && !beingMoved.isInTrash && !SPECIAL {
if let bookmark = gFavorites.createFavorite(for: beingMoved, action: .aNotABookmark) { // type 3
beingMoved = bookmark
beingMoved.maybeNeedSave()
}
} else {
beingMoved.orphan()
if beingMoved.databaseID != into.databaseID {
beingMoved.traverseAllProgeny { iChild in
iChild.needDestroy()
}
beingMoved = beingMoved.deepCopy
}
}
if !SPECIAL {
beingMoved.addToGrabs()
}
into.addAndReorderChild(beingMoved, at: iIndex)
beingMoved.recursivelyApplyDatabaseID(into.databaseID)
}
if toBookmark && self.undoManager.groupingLevel > 0 {
self.undoManager.endUndoGrouping()
}
onCompletion?()
}
}
// ////////////////////////////////////
// deal with target being a bookmark //
// ////////////////////////////////////
if !toBookmark || SPECIAL {
finish()
} else {
iInto.travelThrough() { (iAny, iSignalKind) in
finish()
}
}
}
fileprivate func findChildMatching(_ grabThis: inout Zone, _ iMoveUp: Bool, _ iOffset: CGFloat?) {
// ///////////////////////////////////////////////////////////
// IF text is being edited by user, grab another zone whose //
// text contains offset //
// else whose //
// level equals gCurrentBrowsingLevel //
// ///////////////////////////////////////////////////////////
while grabThis.showingChildren, grabThis.count > 0,
let length = grabThis.zoneName?.length {
let range = NSRange(location: length, length: 0)
let index = iMoveUp ? grabThis.count - 1 : 0
let child = grabThis.children[index]
if let offset = iOffset,
let anOffset = grabThis.widget?.textWidget.offset(for: range, iMoveUp),
offset > anOffset + 25.0 { // half the distance from end of parent's text field to beginning of child's text field
grabThis = child
} else if let level = gCurrentBrowseLevel,
child.level == level {
grabThis = child
} else {
break // done
}
}
}
func move(up iMoveUp: Bool = true, selectionOnly: Bool = true, extreme: Bool = false, growSelection: Bool = false, targeting iOffset: CGFloat? = nil) {
priorHere = gHere
moveUp(iMoveUp, gSelecting.sortedGrabs, selectionOnly: selectionOnly, extreme: extreme, growSelection: growSelection, targeting: iOffset) { iKind in
gSignal([iKind])
}
}
func moveUp(_ iMoveUp: Bool = true, _ originalGrabs: ZoneArray, selectionOnly: Bool = true, extreme: Bool = false, growSelection: Bool = false, targeting iOffset: CGFloat? = nil, onCompletion: SignalKindClosure? = nil) {
let doCousinJump = !gBrowsingIsConfined
let hereMaybe = gHereMaybe
let isHere = hereMaybe != nil && originalGrabs.contains(hereMaybe!)
guard let rootMost = originalGrabs.rootMost(goingUp: iMoveUp) else {
onCompletion?(.sData)
return
}
let rootMostParent = rootMost.parentZone
if isHere {
if rootMost.isARoot {
onCompletion?(.sData)
} else {
// ////////////////////////
// parent is not visible //
// ////////////////////////
let snapshot = gSelecting.snapshot
let hasSiblings = rootMost.hasSiblings
rootMost.revealParentAndSiblings()
let recurse = hasSiblings && snapshot.isSame && (rootMostParent != nil)
if let parent = rootMostParent {
gHere = parent
if recurse {
gSelecting.updateCousinList()
self.moveUp(iMoveUp, originalGrabs, selectionOnly: selectionOnly, extreme: extreme, growSelection: growSelection, targeting: iOffset, onCompletion: onCompletion)
} else {
gFavorites.updateAllFavorites()
onCompletion?(.sRelayout)
}
}
}
} else if let parent = rootMostParent {
let targetZones = doCousinJump ? gSelecting.cousinList : parent.children
let targetCount = targetZones.count
let targetMax = targetCount - 1
// ////////////////////
// parent is visible //
// ////////////////////
if let index = targetZones.firstIndex(of: rootMost) {
var toIndex = index + (iMoveUp ? -1 : 1)
var allGrabbed = true
var soloGrabbed = false
var hasGrab = false
let moveClosure: ZonesClosure = { iZones in
if extreme {
toIndex = iMoveUp ? 0 : targetMax
}
var moveUp = iMoveUp
if !extreme {
// ///////////////////////
// vertical wrap around //
// ///////////////////////
if toIndex > targetMax {
toIndex = 0
moveUp = !moveUp
} else if toIndex < 0 {
toIndex = targetMax
moveUp = !moveUp
}
}
let indexer = targetZones[toIndex]
if let intoParent = indexer.parentZone {
let newIndex = indexer.siblingIndex
let moveThese = moveUp ? iZones.reversed() : iZones
self.moveZones(moveThese, into: intoParent, at: newIndex, orphan: true) {
gSelecting.grab(moveThese)
intoParent.children.updateOrder()
onCompletion?(.sRelayout)
}
}
}
// //////////////////////////////////
// detect grab for extend behavior //
// //////////////////////////////////
for child in targetZones {
if !child.isGrabbed {
allGrabbed = false
} else if hasGrab {
soloGrabbed = false
} else {
hasGrab = true
soloGrabbed = true
}
}
// ///////////////////////
// vertical wrap around //
// ///////////////////////
if !growSelection {
let aboveTop = toIndex < 0
let belowBottom = toIndex >= targetCount
// ///////////////////////
// vertical wrap around //
// ///////////////////////
if (!iMoveUp && (allGrabbed || extreme || (!allGrabbed && !soloGrabbed && belowBottom))) || ( iMoveUp && soloGrabbed && aboveTop) {
toIndex = targetMax // bottom
} else if ( iMoveUp && (allGrabbed || extreme || (!allGrabbed && !soloGrabbed && aboveTop))) || (!iMoveUp && soloGrabbed && belowBottom) {
toIndex = 0 // top
}
}
if toIndex >= 0 && toIndex < targetCount {
var grabThis = targetZones[toIndex]
// //////////////////////////
// no vertical wrap around //
// //////////////////////////
UNDO(self) { iUndoSelf in
iUndoSelf.move(up: !iMoveUp, selectionOnly: selectionOnly, extreme: extreme, growSelection: growSelection)
}
if !selectionOnly {
moveClosure(originalGrabs)
} else if !growSelection {
findChildMatching(&grabThis, iMoveUp, iOffset) // should look at siblings, not children
grabThis.grab(updateBrowsingLevel: false)
} else if !grabThis.isGrabbed || extreme {
var grabThese = [grabThis]
if extreme {
// ////////////////
// expand to end //
// ////////////////
if iMoveUp {
for i in 0 ..< toIndex {
grabThese.append(targetZones[i])
}
} else {
for i in toIndex ..< targetCount {
grabThese.append(targetZones[i])
}
}
}
gSelecting.addMultipleGrabs(grabThese)
}
} else if doCousinJump,
var index = targetZones.firstIndex(of: rootMost) {
// //////////////
// cousin jump //
// //////////////
index += (iMoveUp ? -1 : 1)
if index >= targetCount {
index = growSelection ? targetMax : 0
} else if index < 0 {
index = growSelection ? 0 : targetMax
}
var grab = targetZones[index]
findChildMatching(&grab, iMoveUp, iOffset)
if !selectionOnly {
moveClosure(originalGrabs)
} else if growSelection {
grab.addToGrabs()
} else {
grab.grab(updateBrowsingLevel: false)
}
}
onCompletion?(.sRelayout)
}
}
}
}
|
//
// Vector3Tests.swift
//
//
// Created by David Green on 10/9/20.
//
import XCTest
@testable import SwiftGame
final class Vector3Tests: XCTestCase {
func testInitializers () {
let expectedResult = Vector3(1, 2, 3)
let expectedResult2 = Vector3(2.2, 2.2, 2.2)
XCTAssertEqual(expectedResult, Vector3(1, 2, 3))
XCTAssertEqual(expectedResult, Vector3(Vector2(1, 2), 3))
XCTAssertEqual(expectedResult2, Vector3(2.2))
}
func testMultiplication() {
let vector = Vector3(1, 2, 3)
// Test 0.0 scale
XCTAssertEqual(Vector3.zero, 0 * vector)
XCTAssertEqual(Vector3.zero, vector * 0)
// Test 1.0 scale
XCTAssertEqual(vector, 1 * vector)
XCTAssertEqual(vector, vector * 1)
var scaledVec = Vector3(vector.x * 2, vector.y * 2, vector.z * 2)
// Test 2.0 scale
XCTAssertEqual(scaledVec, 2 * vector)
XCTAssertEqual(scaledVec, vector * 2)
XCTAssertEqual(vector * 2, scaledVec)
scaledVec = Vector3(vector.x * 0.999, vector.y * 0.999, vector.z * 0.999)
// Test 0.999 scale
XCTAssertEqual(scaledVec, 0.999 * vector)
XCTAssertEqual(scaledVec, vector * 0.999)
XCTAssertEqual(vector * 0.999, scaledVec)
let vector2 = Vector3(2, 2, 2)
// Test vector multiplication
XCTAssertEqual(Vector3(vector.x * vector2.x, vector.y * vector2.y, vector.z * vector2.z), vector * vector2)
XCTAssertEqual(vector2 * vector, Vector3(vector.x * vector2.x, vector.y * vector2.y, vector.z * vector2.z))
XCTAssertEqual(vector * vector2, vector2 * vector)
}
func testCeil() {
// Test positive rounding
var vector = Vector3(1.999)
XCTAssertEqual(vector.ceiling, Vector3(2.0))
// Test .0 non-rounding
vector = Vector3(2.0)
XCTAssertEqual(vector.ceiling, Vector3(2.0))
// Test negative rounding
vector = Vector3(-3.499)
XCTAssertEqual(vector.ceiling, Vector3(-3.0))
}
func testDebugStrings() {
let vector = Vector3(2.2)
XCTAssertEqual(vector.debugDescription, "2.2 2.2 2.2")
}
func testConstants() {
XCTAssertEqual(Vector3.zero, Vector3(0, 0, 0))
XCTAssertEqual(Vector3.one, Vector3(1, 1, 1))
XCTAssertEqual(Vector3.unitX, Vector3(1, 0, 0))
XCTAssertEqual(Vector3.unitY, Vector3(0, 1, 0))
XCTAssertEqual(Vector3.unitZ, Vector3(0, 0, 1))
XCTAssertEqual(Vector3.up, Vector3(0, 1, 0))
XCTAssertEqual(Vector3.down, Vector3(0, -1, 0))
XCTAssertEqual(Vector3.left, Vector3(-1, 0, 0))
XCTAssertEqual(Vector3.right, Vector3(1, 0, 0))
XCTAssertEqual(Vector3.forward, Vector3(0, 0, -1))
XCTAssertEqual(Vector3.backward, Vector3(0, 0, 1))
}
func testClamping() {
let testVector = Vector3(5, 7, 9)
XCTAssertEqual(testVector.clamped(between: Vector3(6, 8, 8), and: Vector3(8, 10, 8.5)), Vector3(6, 8, 8.5))
}
func testCrossProduct() {
XCTAssertEqual(Vector3.cross(Vector3.forward, Vector3.left), Vector3.up)
}
func testDistanceSquared() {
let v1 = Vector3(0.1, 100.0, -5.5)
let v2 = Vector3(1.1, -2.0, 5.5)
let d = Vector3.distanceSquared(v1, v2)
XCTAssertEqual(d, 10526)
}
static var allTests = [
("testDistanceSquared", testDistanceSquared),
("testInitializers", testInitializers),
("testMultiplication", testMultiplication),
("testCeil", testCeil),
("testDebugStrings", testDebugStrings),
("testConstants", testConstants),
("testClamping", testClamping),
("testCrossProduct", testCrossProduct),
]
}
|
//
// Post.swift
// tablle_json
//
// Created by Tonya on 10/11/2018.
// Copyright © 2018 Tonya. All rights reserved.
//
import Foundation
import UIKit
struct Post {
var name = ""
var type = ""
var episodes = ""
var episode_length = ""
var description = ""
var imageforsecond: UIImage?
}
extension Post {
init?(dict: NSDictionary) {
guard
let name = dict["name"] as? String,
let type = dict["type"] as? String,
let episodes = dict["episodes"] as? String,
let episode_length = dict["episode_length"] as? String,
let description = dict["description"] as? String
else { return nil }
self.name = name
self.type = type
self.episodes = episodes
self.episode_length = episode_length
self.description = description
}
}
|
//
// ConversionViewController.swift
// TemperatureConverter
//
// Created by Dilpreet Singh on 20/10/16.
// Copyright © 2016 Dilpreet Singh. All rights reserved.
//
import UIKit
class ConversionViewController: UIViewController, UITextFieldDelegate {
private var fahrenheitValue: Double? {
didSet {
updateCelsiusLabel()
}
}
private var celsiusValue: Double? {
guard let fahrenheitTemp = fahrenheitValue else { return nil }
return (fahrenheitTemp - 32) * (5 / 9)
}
private let numberFormatter: NSNumberFormatter = {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
numberFormatter.minimumFractionDigits = 0
numberFormatter.maximumFractionDigits = 1
return numberFormatter
}()
@IBOutlet weak var celsiusLabel: UILabel!
@IBOutlet weak var fahrenheitTextField: UITextField!
@IBAction func dismissKeyboard(sender: AnyObject) {
fahrenheitTextField.resignFirstResponder()
}
@IBAction func fahrenheitFieldEditingChanged(sender: UITextField) {
if let temperatureString = sender.text, temperature = numberFormatter.numberFromString(temperatureString) {
fahrenheitValue = temperature.doubleValue
} else {
fahrenheitValue = nil
}
}
private func updateCelsiusLabel() {
if let value = celsiusValue {
celsiusLabel.text = numberFormatter.stringFromNumber(value)
celsiusLabel.text = celsiusLabel.text! + "°"
} else {
celsiusLabel.text = "???"
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let numberSet = NSCharacterSet(charactersInString: "123456789.0")
let currentLocale = NSLocale.currentLocale()
let decimalSeparator = currentLocale.objectForKey(NSLocaleDecimalSeparator) as! String
let existingTextHasDecimalSeparator = textField.text?.rangeOfString(decimalSeparator)
let replacementTextHasDecimalSeparator = string.rangeOfString(decimalSeparator)
if (existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil) || !numberSet.isSupersetOfSet(NSCharacterSet(charactersInString: string)) {
return false
} else {
return true
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
var timeOfDay: TimeOfDay
let presentHour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
switch presentHour {
case 7...18:
timeOfDay = .Day
default:
timeOfDay = .Night
}
switch timeOfDay {
case .Day:
view.backgroundColor = UIColor(red: 210/255.0, green: 240/255.0, blue: 255/255.0, alpha: 1.0)
case .Night:
view.backgroundColor = UIColor(red: 84/255.0, green: 96/255.0, blue: 102/255.0, alpha: 1.0)
fahrenheitTextField.textColor = UIColor.whiteColor()
}
}
enum TimeOfDay: String {
case Day
case Night
}
}
|
//
// Triangle.swift
// GameDevConcepts
//
// Created by Gabriel Anderson on 8/7/15.
// Copyright (c) 2015 Gabriel Anderson. All rights reserved.
//
import Cocoa
import SpriteKit
class Triangle: Shape {
var width: CGFloat, height: CGFloat
//var angle: Float
init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, borderColor: SKColor) {
self.width = width
self.height = height
super.init(x: x, y: y, borderColor: borderColor)
}
init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, borderColor: SKColor, fillColor: SKColor){
self.width = width
self.height = height
super.init(x: x, y: y, borderColor: borderColor, fillColor: fillColor)
buildShape(borderColor,fillColor: fillColor)
}
/* convenience init(fillColor: SKColor) {
self.init(x: 0.0, y: 0.0, width: 0.0, height: 0.0, borderColor: SKColor.windowBackgroundColor(), fillColor: fillColor)
}*/
private func buildShape(borderColor: SKColor) {
/*CGPathMoveToPoint(path, nil, x + width, y)
CGPathMoveToPoint(path, nil, x + width / 2, y+height)
CGPathMoveToPoint(path, nil, x, y)*/
let point1 = CGPoint(x: -height/2, y: -width/2)
let point2 = CGPoint(x: -height/2, y: +width/2)
let point3 = CGPoint(x: height/2, y: 0)
let points: [CGPoint] = [point1, point2, point3]//, point4]
let path = CGPathCreateMutable()
CGPathAddLines(path, nil, points, points.count)
shapeNode.path = path
shapeNode.strokeColor = borderColor
shapeNode.lineWidth = 1.0
//shapeNode.position.x = x
//shapeNode.position.y = y
}
private func buildShape(borderColor: SKColor, fillColor: SKColor) {
buildShape(borderColor)
shapeNode.fillColor = fillColor
}
func buildShape(angle: Float) {
let m1: Float = cos(angle)
let m2: Float = -sin(angle)
let m3: Float = sin(angle)
//let rotationMatrix: [Float] = [m1, m2, m3, m1]
var xp = [Float](count: 3, repeatedValue: 0.0)
var yp = [Float](count: 3, repeatedValue: 0.0)
xp[0] = Float(-height)/2 * m1 + Float(-width)/2 * m2
yp[0] = Float(-height)/2 * m3 + Float(-width)/2 * m1
xp[1] = Float(-height)/2 * m1 + Float(width)/2 * m2
yp[1] = Float(-height)/2 * m3 + Float(width)/2 * m1
xp[2] = Float(height)/2 * m1
yp[2] = Float(height)/2 * m3
let point1 = CGPoint(x: CGFloat(xp[0]), y: CGFloat(yp[0]))
let point2 = CGPoint(x: CGFloat(xp[1]), y: CGFloat(yp[1]))
let point3 = CGPoint(x: CGFloat(xp[2]), y: CGFloat(yp[2]))
let points: [CGPoint] = [point1, point2, point3]//, point4]
let path = CGPathCreateMutable()
CGPathAddLines(path, nil, points, points.count)
shapeNode.path = path
shapeNode.strokeColor = borderColor
shapeNode.lineWidth = 1.0
//NSLog("Angle: \(angle), x1,y1: \(xp[0]),\(yp[0]), x2,y2: \(xp[1]),\(yp[1]), x3,y3: \(xp[2]),\(yp[2])")
}
}
|
//
// UIView+Nib.swift
// FinanteqInterview
//
// Created by Patryk Domagala on 12/06/2018.
// Copyright © 2018 Dom-Pat. All rights reserved.
//
import UIKit
extension Bundle {
public static func nibView<V: UIView>(for viewType: V.Type, owner: Any? = nil) -> V? {
let bundle = Bundle(for: viewType)
return UINib(nibName: String(describing: viewType), bundle: bundle).instantiate(withOwner: owner, options: nil).first as? V
}
public static func nib<V: UIView>(for viewType: V.Type, owner: Any? = nil) -> UINib? {
let bundle = Bundle(for: viewType)
return UINib(nibName: String(describing: viewType), bundle: bundle)
}
}
|
//
// File.swift
// Schuylkill-App
//
// Created by Sam Hicks on 3/1/21.
//
import Foundation
import Resolver
#if !os(watchOS)
import OSLog
#endif
public protocol ServiceNaming {
var name: String { get }
init()
}
|
//
// LampType.swift
// cityos-led
//
// Created by Said Sikira on 9/21/15.
// Copyright © 2015 CityOS. All rights reserved.
//
import CoreLocation
import MapKit
/// Structures adopting LampType procotol can be used to represent single LED
/// Lamp
public protocol LampType {
/// Device meta data
var device : DeviceData { get }
/// Lamp name
var name : String? { get set }
/// Lamp location
var location : LampLocation? { get }
/// Lamp creation date
var creationDate: NSDate? { get }
/// LED light level
var lightLevel : Int { get set }
/// All data readings
var dataReadings : LiveDataCollectionType? { get set }
}
extension LampType {
/// Lamp state
var state : Bool {
return self.lightLevel == 0 ? true : false
}
}
extension LampType {
///Returns MKAnnotation with title and subtitle properties set
public func annotation() -> MKAnnotation? {
if let location = location {
let annonation = location
annonation.title = self.name
annonation.subtitle = "Light level : \(self.lightLevel) %"
return annonation
}
return nil
}
}
extension LampType {
public var params : [String: AnyObject] {
return [
"elems": [
"model" : self.device.model!,
"schema" : self.device.schema!,
"lightLevel" : self.lightLevel,
"flowId" : self.device.flowID!
],
"location" : [
"lat" : self.location!.latitude,
"lon" : self.location!.longitude
],
]
}
}
|
//
// PopOver.swift
// SpotMenu
//
// Created by Miklós Kristyán on 2017. 07. 16..
// Copyright © 2017. KM. All rights reserved.
//
import Cocoa
import Spotify
class PopOver: NSView {
var lastArtworkUrl = ""
var rightTimeIsDuration: Bool = true
public var timer: Timer!
public var defaultImage: NSImage!
@IBOutlet var view: NSView!
@IBOutlet weak public var artworkImageView: NSImageView!
@IBOutlet weak var positionSlider: NSSlider!
@IBOutlet weak var rightTime: NSTextField!
@IBOutlet weak var leftTime: NSTextField!
@IBOutlet weak var playerStateButton: NSButton!
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var artistLabel: NSTextField!
@IBOutlet weak var squareButton: NSButton!
@IBOutlet weak var goLeftButton: NSButton!
@IBOutlet weak var goRightButton: NSButton!
required init?(coder: NSCoder) {
super.init(coder: coder)
guard NSNib(nibNamed: "PopOver", bundle: nil)?.instantiate(withOwner: self, topLevelObjects: nil) != false else {
fatalError("shit")
}
addSubview(view)
view.frame = self.bounds
}
public func updateInfo() {
if let artworkUrl = Spotify.currentTrack.artworkUrl , artworkUrl != lastArtworkUrl {
self.artworkImageView.downloadImage(url: URL(string: artworkUrl)!)
lastArtworkUrl = artworkUrl
}
if Spotify.currentTrack.artworkUrl == nil {
artworkImageView.image = defaultImage
}
if let artist = Spotify.currentTrack.albumArtist {
artistLabel.stringValue = artist
artistLabel.textColor = nil
} else {
artistLabel.stringValue = "Artist"
artistLabel.textColor = NSColor.gray
}
if let title = Spotify.currentTrack.title {
titleLabel.stringValue = title
titleLabel.textColor = nil
} else {
titleLabel.stringValue = "Title"
titleLabel.textColor = NSColor.gray
}
let position = Spotify.currentTrack.positionPercentage
positionSlider.doubleValue = floor(position * 100)
updateTime()
updateButton()
}
func updateButton() {
updateButton(Spotify.playerState)
}
func updateButton(_ state: PlayerState){
switch state {
case .paused:
playerStateButton.title = "▶︎"
case .playing:
playerStateButton.title = "❚❚"
}
}
func updateTime() {
let leftTimeTuple = secondsToHoursMinutesSeconds(seconds: Spotify.currentTrack.position)
leftTime.stringValue = getTimeString(tuple: leftTimeTuple)
switch rightTimeIsDuration {
case true:
let rightTimeTuple = secondsToHoursMinutesSeconds(seconds: Spotify.currentTrack.duration)
rightTime.stringValue = getTimeString(tuple: rightTimeTuple)
case false:
let rightTimeTuple = secondsToHoursMinutesSeconds(seconds: Spotify.currentTrack.duration - Spotify.currentTrack.position)
rightTime.stringValue = "-" + getTimeString(tuple: rightTimeTuple)
}
}
private func secondsToHoursMinutesSeconds (seconds : Double) -> (Int, Int, Int) {
return (Int(seconds / 3600),
Int((seconds.truncatingRemainder(dividingBy: 3600)) / 60),
Int((seconds.truncatingRemainder(dividingBy: 3600).truncatingRemainder(dividingBy:
60))))
}
private func getTimeString(tuple: (Int,Int,Int))-> String {
return String(format: "%02d:%02d", tuple.1, tuple.2)
}
}
extension PopOver {
@IBAction func goLeft(_ sender: NSButton) {
Spotify.playPrevious()
}
@IBAction func goRight(_ sender: NSButton) {
Spotify.playNext()
}
@IBAction func quit(_ sender: NSButton) {
NSApplication.shared().terminate(sender)
}
@IBAction func openSpotify(_ sender: Any) {
Spotify.activateSpotify()
}
@IBAction func positionSliderAction(_ sender: AnyObject) {
Spotify.currentTrack.positionPercentage = positionSlider.doubleValue/100.0
}
@IBAction func togglePlay(_ sender: AnyObject) {
switch Spotify.playerState {
case .paused:
Spotify.playerState = .playing
case .playing:
Spotify.playerState = .paused
}
}
@IBAction func toggleRightTime(_ sender: AnyObject) {
Swift.print("wasap")
rightTimeIsDuration = !rightTimeIsDuration
updateTime()
}
}
extension NSImageView {
private func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
func downloadImage(url: URL) {
//Swift.print("Download Started")
getDataFromUrl(url: url) { (data, response, error) in
DispatchQueue.main.sync() { () -> Void in
guard let data = data, error == nil else { return }
// Swift.print(response?.suggestedFilename ?? url.lastPathComponent)
// Swift.print("Download Finished")
self.image = NSImage(data: data)
}
}
}
}
|
//
// PhotoHeaderView.swift
// FlickrSearch
//
// Created by Jeff Norton on 11/20/16.
// Copyright © 2016 JeffCryst. All rights reserved.
//
import UIKit
class PhotoHeaderView: UICollectionReusableView {
//==================================================
// MARK: - _Properties
//==================================================
@IBOutlet weak var sectionLabel: UILabel!
}
|
import Foundation
// dğişkenler
let x = 7
var y = 65
var z = 45
print("z=\(z)")
print("x=\(x)")
y = y + 4
print("y=\(y)")
var c : Double = 0.0
print("c=\(c)")
// diziler
var d : [Int] = [2,232,4,54,56,767,0,6878,8,8]
var dizi : Dictionary <Int, String> = [12: "sed", 123 : "kub", 35 : "dil" , 57: "cal" ]
print("DİZİ...")
for i in d
{
print(i)
}
print("SÖZLÜK..")
for i in dizi
{
print(i)
}
// donguler
var a = 7
let b = 8
if a>b
{
print(" \(a) büyüktür \(b) den")
} else
{
print("\(a) küçüktür \(b) den")
}
/*
Sayı Toplama;
1 den n sayısına kadar sayıların toplamı.
1+2+3 ....+ n = ?
*/
var n=20
var s:Int=0
var i:Int
/*for i=1;i<=n;i =+1
{ s = s + i
}
print("1+2+3+...\(n)=\(s)")
*/
// let öğreniyoruz.
let label = "selam arkadaş "
let with = 78
let labelwith = "ben arkadşınım yeni yıll da \(with) yaşına girdim."
print(labelwith)
// Example 1
let individualScore = [54,869,968,34,5,3,5356,636,56,3,32,43]
var teamScore = 0
for score in individualScore {
if score < 100 {
teamScore += 4
} else{
teamScore += 1
}
}
print(teamScore)
// exam2
let days = ["pazartesi","salı","çarşamaba","perşembe","cuma","cumartesi","pazar"]
let index1 = Int(arc4random()%7)
|
import Foundation
import Bow
public typealias Algebra<F, A> = (Kind<F, A>) -> A
public typealias Coalgebra<F, A> = (A) -> Kind<F, A>
public extension Functor {
static func hylo<A, B>(_ algebra : @escaping Algebra<Self, Eval<B>>,
_ coalgebra : @escaping Coalgebra<Self, A>,
_ a : A) -> B {
func h(_ a : A) -> Eval<B> {
return algebra(map(coalgebra(a), { x in Eval.defer({ h(x) }) }))
}
return h(a).value()
}
}
// MARK: Syntax for F-Algebras
public extension Kind where F: Functor {
static func hylo<B>(_ algebra: @escaping Algebra<F, Eval<B>>,
_ coalgebra: @escaping Coalgebra<F, A>,
_ a: A) -> B {
return F.hylo(algebra, coalgebra, a)
}
}
|
//
// World.swift
// TextAdventrueSwift
//
import Foundation
struct World {
private(set) var areas: [Area]
private(set) var currentArea: Area
mutating func movePlayer(_ player: Player, inDirection direction: Direction) {
updateArea(currentArea)
guard let area = findArea(atPosition: currentArea.position, inDirection: direction) else {
print("There is nothing to the \(direction.getDirection()).")
return
}
currentArea = area
print(currentArea.getDescription())
if currentArea.enemy != nil {
currentArea.battle(player: player)
}
}
func showSurroundingAreas(ofPosition position: Position) -> String {
let surroundingAreas: [Direction:Area?] = [
Direction.north: findArea(atPosition: position, inDirection: .north),
Direction.south: findArea(atPosition: position, inDirection: .south),
Direction.east: findArea(atPosition: position, inDirection: .east),
Direction.west: findArea(atPosition: position, inDirection: .west)
]
let areaMap = surroundingAreas.reduce("- Map -\n") {
(areaMapAccumulator, surroundingArea) in
let (direction, area) = surroundingArea
let noArea = "Nothing."
switch direction {
case .north:
return areaMapAccumulator + "North:\t\(area?.getDescription() ?? noArea)\n"
case .east:
return areaMapAccumulator + "East:\t\(area?.getDescription() ?? noArea)\n"
case .south:
return areaMapAccumulator + "South:\t\(area?.getDescription() ?? noArea)\n"
case .west:
return areaMapAccumulator + "West:\t\(area?.getDescription() ?? noArea)\n"
}
}
return areaMap
}
private func findArea(atPosition position: Position, inDirection direction: Direction?) -> Area? {
func getArea(atPosition position: Position) -> Area? {
for area in areas {
if area.position == position {
return area
}
}
return nil
}
guard let direction = direction else {
return getArea(atPosition: position)
}
switch direction {
case .north:
return getArea(atPosition: Position(x: position.x, y: position.y-1))
case .south:
return getArea(atPosition: Position(x: position.x, y: position.y+1))
case .east:
return getArea(atPosition: Position(x: position.x-1, y: position.y))
case .west:
return getArea(atPosition: Position(x: position.x+1, y: position.y))
}
}
private mutating func updateArea(_ updatedArea: Area) {
for (index, area) in areas.enumerated() {
if area.position == updatedArea.position {
areas[index] = updatedArea
return
}
}
fatalError("Failed to find index of area.")
}
}
extension World {
static let gameWorld = World(areas: [Area.village, Area.forest], currentArea: Area.village)
}
|
import Foundation
public final class URLSessionRequestDispatcher: RequestDispatcher {
// MARK: - Dependencies
private let session: URLSession
private let responseDecoder: ResponseDecoder
// MARK: - Init
init(session: URLSession, responseDecoder: ResponseDecoder) {
self.session = session
self.responseDecoder = responseDecoder
}
// MARK: - RequestDispatcher
@discardableResult
public func send<R: ApiRequest>(
_ request: R,
urlRequest: URLRequest,
completion: @escaping DataResult<R.Result, RequestError<R.ErrorResponse>>.Completion)
-> NetworkDataTask? {
let task = session.dataTask(with: urlRequest) { [weak self] data, response, error in
guard let httpUrlResponse = response as? HTTPURLResponse else {
completion(.error(RequestError.apiClientError(.decodingFailure)))
return
}
let result: GenericResult<Data>
if let data = data {
result = GenericResult<Data>.data(data)
} else if let error = error {
result = GenericResult<Data>.error(error)
} else {
completion(.error(RequestError.apiClientError(.decodingFailure)))
return
}
let responseResult = ResponseResult(
request: urlRequest,
response: httpUrlResponse,
data: data,
result: result
)
self?.responseDecoder.decode(
response: responseResult,
for: request,
completion: completion
)
}
task.resume()
return URLSessionNetworkDataTask(task: task)
}
}
|
//
// WFMeetingViewController.swift
// niinfor
//
// Created by 王孝飞 on 2017/8/23.
// Copyright © 2017年 孝飞. All rights reserved.
//
import UIKit
import SDCycleScrollView
import JavaScriptCore
import WebKit
import ObjectiveC
import MJRefresh
class WFMeetingViewController: BaseViewController,UIWebViewDelegate {
// var wkWebView = WFWkWebView()
var jsContext : JSContext?
var curUrl = ""
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var cyleScrollView: SDCycleScrollView!
/// 底部视图
@IBOutlet weak var scroView: UIScrollView!
/// 滚动视图
@IBOutlet weak var collectionView: UICollectionView!
/// pageControl
@IBOutlet weak var pageControl: WFPageControl!
/// 按钮上方的约束
@IBOutlet weak var threeBtnTopCons: NSLayoutConstraint!
@IBOutlet weak var btnViewTopCons: NSLayoutConstraint!
/// 按钮的contentView
@IBOutlet weak var btnView: UIView!
/// 会议预告按钮
@IBOutlet weak var foreshowMeetingBtn: UIButton!
/// 历史会议按钮
@IBOutlet weak var historyMeetingBtn: UIButton!
/// 滑动线视图
@IBOutlet weak var lineView: UIImageView!
/// 列表视图
@IBOutlet weak var listTableView: UITableView!
/// 列表视图的高度
@IBOutlet weak var listViewHeightConstant: NSLayoutConstraint!
/// 热门会议点击
@IBAction func hotMeetingClick(_ sender: Any) {
navigationController?.pushViewController(WFHotMeetingViewController(), animated: true)
}
/// 本月会议点击
@IBAction func currentMonthMeetingClick(_ sender: Any) {
navigationController?.pushViewController(WFCurrentMothMTingController(), animated: true)
}
/// 会议查询点击
@IBAction func searchMeetingClick(_ sender: Any) {
navigationController?.pushViewController(WFSearchMeetingController(), animated: true)
}
/// 会议预告点击
@IBAction func foreshowMeetingClick(_ sender: Any) {
if foreshowMeetingBtn.isSelected == true {
return
}
foreshowMeetingBtn.isSelected = !foreshowMeetingBtn.isSelected
historyMeetingBtn.isSelected = !historyMeetingBtn.isSelected
//动画
UIView.animate(withDuration: 0.5) {
var viewFrame = self.lineView.frame
viewFrame.origin.x = self.foreshowMeetingBtn.xf_X
self.lineView.frame = viewFrame
}
}
/// 历史会议点击
@IBAction func historyMeetingClick(_ sender: Any) {
///如果是当下选择的按钮的话返回
if historyMeetingBtn.isSelected == true {
return
}
///切换按钮状态
foreshowMeetingBtn.isSelected = !foreshowMeetingBtn.isSelected
historyMeetingBtn.isSelected = !historyMeetingBtn.isSelected
UIView.animate(withDuration: 0.5) {
var viewFrame = self.lineView.frame
viewFrame.origin.x = self.historyMeetingBtn.xf_X
self.lineView.frame = viewFrame
}
}
deinit {
//NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: notifi_login_html_success), object: nil)
NotificationCenter.default.removeObserver(self)
wkWebView.removeObserver(self, forKeyPath: "canGoBack")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = wkWebView.canGoBack
}
}
// MARK: - 加载网络数据
extension WFMeetingViewController{
override func loadData() {
listViewHeightConstant.constant = 10 * 90
view.layoutIfNeeded()
scroView.delegate = self
loadAdNet()
}
private func loadAdNet() {
NetworkerManager.shared.getAppAdSolts { (isSuccess, json) in
if isSuccess == true {
print(json)
var titleArray = [String]()
var imageArray = [String]()
for item in json {
titleArray.append(item.name ?? "")
imageArray.append(item.imageString )
}
self.cyleScrollView.titlesGroup = titleArray
self.cyleScrollView.imageURLStringsGroup = imageArray
self.pageControl.numberOfPages = json.count
self.pageControl.currentPage = 0
}
}
}
}
// MARK: - TableView数据源代理方法
extension WFMeetingViewController{
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: WFMeetingTableViewCell().identfy) as? WFMeetingTableViewCell
return cell!
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90
}
}
// MARK: - UIScrowView代理方法
//extension WFMeetingViewController{
//
// func scrollViewDidScroll(_ scrollView: UIScrollView) {
//
// let lastNumber = Screen_height / 5
// let number = lastNumber + 48 + 10
//
// //189
// if scrollView.contentOffset.y >= lastNumber &&
// scrollView.contentOffset.y < lastNumber + 10 {
//
// threeBtnTopCons.constant = scrollView.contentOffset.y - lastNumber
// print("lastNuber \(threeBtnTopCons.constant)")
//
// } else if scrollView.contentOffset.y < lastNumber{
// threeBtnTopCons.constant = 0
//
// }else{
//
// threeBtnTopCons.constant = 10
// }
//
// if scrollView.contentOffset.y >= number {
//
// let scrowY = scrollView.contentOffset.y
// btnViewTopCons.constant = scrowY - number + 58
// btnView.layoutIfNeeded()
//
// }else{
// btnViewTopCons.constant = 58
// }
//
// var viewFrame = self.lineView.frame
// viewFrame.origin.x = self.historyMeetingBtn.isSelected ? self.historyMeetingBtn.xf_X : self.foreshowMeetingBtn.xf_X
// self.lineView.frame = viewFrame
// btnView.layoutIfNeeded()
//
// }
//
//}
//
// MARK: - 监听的方法
extension WFMeetingViewController{
// MARK: - 手势监听方法
@objc func gesterClick(gesture : UISwipeGestureRecognizer){
if gesture.direction == .right && historyMeetingBtn.isSelected == true {
foreshowMeetingClick(self)
print("往左滑")
}
if gesture.direction == .left && foreshowMeetingBtn.isSelected == true {
historyMeetingClick(self)
print("往又滑")
}
}
}
///设置界面
extension WFMeetingViewController:SDCycleScrollViewDelegate{
func begainFullScreen() {
let appdelegate = UIApplication.shared.delegate as? AppDelegate
appdelegate?.isRotation = true
}
func endFullScreen() {
let appdelegate = UIApplication.shared.delegate as? AppDelegate
appdelegate?.isRotation = false
UIScreen.rotationScreen()
/* //强制归正:
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val =UIInterfaceOrientationPortrait;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
*/
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "canGoBack" {
let change = change?[NSKeyValueChangeKey.newKey] as? Bool
self.tabBarController?.tabBar.isHidden = change!
change! ? (self.leftItem()) : (setTitleCon())
}
}
private func setTitleCon() {
self.navItem.leftBarButtonItems = []
navItem.title = "会议系统"
}
override func setUpUI() {
super.setUpUI()
removeTabelView()
navItem.title = "会议系统"
if #available(iOS 11, *) {
self.scroView.contentInsetAdjustmentBehavior = .never
}
//NotificationCenter.default.addObserver(self, selector: #selector(resendMessageToHtml(_:)), name: NSNotification.Name(rawValue: notifi_login_html_success), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(begainFullScreen), name: NSNotification.Name.UIWindowDidBecomeVisible, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(endFullScreen), name: NSNotification.Name.UIWindowDidBecomeHidden, object: nil)
setUpTableView()
setUpForeshowBtn()
setUpCycleView()
setupWebView()
loadWebview()
setUpWkView()//加载wk
wkWebView.addObserver(self, forKeyPath: "canGoBack", options: .new, context: nil)
setRightItem()
}
///完成按钮
private func setRightItem(){
let btn = UIButton.cz_textButton("分享", fontSize: 15, normalColor: #colorLiteral(red: 0.4, green: 0.4, blue: 0.4, alpha: 1), highlightedColor: UIColor.white)
btn?.addTarget(self, action: #selector(shareViewClick), for: .touchUpInside)
navItem.rightBarButtonItem = UIBarButtonItem(customView: btn!)
}
@objc private func shareViewClick() {
let block : ([String])->() = {[weak self] (array) in
// self?.shareView.isHidden = true
AppDelegate.shareUrl((self?.wkWebView.shareUrl)!,
imageString: array[1],
title: self?.wkWebView.title ?? "",
descriptionString: array[0],
viewController: self!, .wechatSession)
}
wkWebView.requireShareDetail(block: block)
}
///设置左边的 按钮
func leftItem () {
let item = UIBarButtonItem(imageString: "nav_icon_back", target: self, action: #selector(popToParent), isBack: true)
let spaceItem = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spaceItem.width = -10
navItem.leftBarButtonItems = [spaceItem,item]
}
///
func popToParent() {
var item = wkWebView.backForwardList.backItem
var count = 2
while true {
if item?.url.absoluteString.contains("checkpayresult.jspx") == true ||
item?.url.absoluteString.contains("tenpay") == true ||
item?.url.absoluteString.contains("weixin") == true ||
item?.url.absoluteString.contains("wxpay") == true ||
item?.url.absoluteString.contains("alipay") == true{
item = wkWebView.backForwardList.backList[wkWebView.backForwardList.backList.count - count]
count = count + 1
}else{
break
}
}
wkWebView.go(to: item!)
}
///网页视图
func setUpWkView(){
wkWebView = WFWkWebView(CGRect(x: 0, y: navigation_height, width: Screen_width, height: Screen_height - navigation_height))
wkWebView.mainController = self
if #available(iOS 11, *) {
self.wkWebView.scrollView.contentInsetAdjustmentBehavior = .never
}
// wkWebView.scrollView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
//
// self.wkWebView.reload()
//
// })
guard let url = URL(string:Photo_Path + "/meeting/meetingList.jspx") else{
return
}
let request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
// if let rponse = URLCache.shared.cachedResponse(for: request) {
// if #available(iOS 9.0, *) {
// wkWebView.load(rponse.data, mimeType: "text.html", characterEncodingName: "UTF-8", baseURL: request.url!)
// } else {
// _ = wkWebView.load(request)
// }
// }else{
_ = wkWebView.load(request)
// }
// UIViewPropertyAnimator
view.addSubview(wkWebView)
// guard let data = try? Data.init(contentsOf: url) else {
// return
// }
// let respones = URLResponse.init(url: url, mimeType: "text/html", expectedContentLength: 0, textEncodingName: "UTF-8")
// //42363 8009938
//
// let cacheRespones = CachedURLResponse.init(response: respones, data: data)
// URLCache.shared.storeCachedResponse(cacheRespones, for: request)
}
func loadWebViewHid() {
wkWebView.reload()
}
func backForword() {
if wkWebView.canGoBack == true {
wkWebView.go(to: wkWebView.backForwardList.backItem!)
}
}
private func setupWebView() {
// webView.delegate = self入65555555555555555555555555555555555555555555
}
private func loadWebview() {
guard let url = URL(string:Photo_Path + "/meeting/meetingList.jspx") else{
return
}
webView.loadRequest(URLRequest(url: url))
}
///设置轮播图
private func setUpCycleView() {
cyleScrollView.delegate = self
cyleScrollView.autoScrollTimeInterval = 4
cyleScrollView.showPageControl = false
cyleScrollView.itemDidScrollOperationBlock = {(offset) in
self.pageControl.currentPage = offset
}
}
/// 设置预告和历史按钮
private func setUpForeshowBtn() {
foreshowMeetingBtn.isSelected = true
foreshowMeetingBtn.setAttributedTitle(NSMutableAttributedString(
string: "会议预告",
attributes: [NSForegroundColorAttributeName : #colorLiteral(red: 0.2470588235, green: 0.6117647059, blue: 0.7019607843, alpha: 1)]),
for: .selected)
historyMeetingBtn.setAttributedTitle(NSMutableAttributedString(
string: "历史会议",
attributes: [NSForegroundColorAttributeName : #colorLiteral(red: 0.2470588235, green: 0.6117647059, blue: 0.7019607843, alpha: 1)]),
for: .selected)
}
/// 设置列表视图
private func setUpTableView() {
listTableView.delegate = self
listTableView.dataSource = self
listTableView.tableFooterView = UIView()
listTableView.touchesShouldCancel(in: listTableView)
listTableView.register(UINib.init(
nibName: WFMeetingTableViewCell().identfy,
bundle: nil),
forCellReuseIdentifier: WFMeetingTableViewCell().identfy)
/// 添加右滑收拾
let gesture = UISwipeGestureRecognizer(target: self,
action: #selector(gesterClick(gesture:)))
listTableView.addGestureRecognizer(gesture)
/// 添加左滑收拾
let gestureLeft = UISwipeGestureRecognizer(target: self,
action: #selector(gesterClick(gesture:)))
gestureLeft.direction = .left
listTableView.addGestureRecognizer(gestureLeft)
}
}
extension WFMeetingViewController {
// func webViewDidStartLoad(_ webView: UIWebView) {
//
// }
//
// func webViewDidFinishLoad(_ webView: UIWebView) {
//
// let meeting = MeetingClass()
// //meeting.webView = webView
//
// self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as? JSContext
//
// self.jsContext?.setObject(meeting, forKeyedSubscript: "meeting" as NSCopying & NSObjectProtocol)
//
// meeting.jsContext = self.jsContext
// //WebView当前访问页面的链接 可动态注册
// //let curUrl = webView.request?.url?.absoluteString ,
//
// guard let url = URL(string: curUrl) else {
//
// return
// }
//
// //self.jsContext?.evaluateScript(try? String(contentsOf:url , encoding: String.Encoding.utf8), throw {return})
// do{
//
// let jsSourceContents = try? String(contentsOf:url , encoding: String.Encoding.utf8)
// if jsSourceContents != nil {
// _ = self.jsContext?.evaluateScript(jsSourceContents)
// }
//
// } catch let ex {
//
// print("没有成功")
// print(ex.localizedDescription)
// }
//
// self.jsContext?.exceptionHandler = { (context, exception) in
// print("exception:", exception ?? "没找到")
// }
//
// }
//
// func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//
// curUrl = request.url?.absoluteString ?? ""
// print(request.url?.absoluteString ?? "")
//
// print(curUrl + "-----")
//
// let requestString = request.url?.absoluteString
//
// if requestString?.contains(".jspx?") == true && requestString?.contains("from=app") == false {
//
// guard let url = URL(string: (requestString ?? "") + "&from=app") else{
// return false
// }
// webView.loadRequest(URLRequest(url: url))
// return false
// }else if requestString?.contains(".jspx") == true && requestString?.contains("from=app") == false{
//
// guard let url = URL(string: (requestString ?? "") + "?from=app") else{
// return false
// }
// webView.loadRequest(URLRequest(url: url))
// return false
//
// }else{
//
// return curUrl != ""
// }
//
//
// }
//
// func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
//
// }
// func resendMessageToHtml(_ jsx : JSContext) {
//
// let username = UserDefaults.standard.value(forKey: user_username) as? String
// let password = UserDefaults.standard.value(forKey: user_password) as? String
//
// wkWebView.evaluateJavaScript("userInfo('\(username)','\(password )')") { (json, error ) in
// print("错误 ", json ,"这个是啥",error )
// }
//
// }
}
|
//
// StringExtensions.swift
// FindOrOfferAJobApp
//
// Created by Haroldo on 12/02/20.
// Copyright © 2020 HaroldoLeite. All rights reserved.
//
import Foundation
extension String {
static func localize(_ string: String) -> String {
return NSLocalizedString(string, comment: "")
}
}
|
//
// getAbilities.swift
// PocketDex
//
// Created by Thomas Tenzin on 8/10/20.
// Copyright © 2020 Thomas Tenzin. All rights reserved.
//
import Foundation
func getAbilities(pokemonAbilitiesList: [PokemonAbilities], pkmnID: Int) -> [PokemonAbilities] {
var finalList = [PokemonAbilities]()
if let j = pokemonAbilitiesList.firstIndex(where: {$0.pokemon_id == pkmnID}) {
finalList.append(pokemonAbilitiesList[j])
if pokemonAbilitiesList[j+1].pokemon_id == pkmnID {
finalList.append(pokemonAbilitiesList[j+1])
}
if pokemonAbilitiesList[j+2].pokemon_id == pkmnID {
finalList.append(pokemonAbilitiesList[j+2])
}
}
return finalList
}
func findAbilites(pokemonAbilities: [PokemonAbilities], abilityList: [Ability]) -> [Ability] {
var finalAbilitiesList = [Ability]()
for pkmnAbility in pokemonAbilities {
if let i = abilityList.firstIndex(where: {$0.id == pkmnAbility.ability_id }) {
finalAbilitiesList.append(abilityList[i])
}
}
return finalAbilitiesList
}
|
//
// CrewPageViewController.swift
// Reached
//
// Created by John Wu on 2016-08-04.
// Copyright © 2016 ReachedTechnologies. All rights reserved.
//
//
// CrewPage.swift
// Reached
//
// Created by John Wu on 2016-08-04.
// Copyright © 2016 ReachedTechnologies. All rights reserved.
//
class CrewPageViewController: UIViewController, UIScrollViewDelegate, UIPopoverPresentationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupViews()
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
// Return no adaptive presentation style, use default presentation behaviour
return .None
}
func setupNavigationBar() {
//set background colour
UINavigationBar.appearance().barTintColor = UIColor(red: 20.4/225, green: 20.4/225, blue: 20.4/225, alpha: 1)
//set up title
let titleView = UIImageView(frame: CGRect(x: 0, y: 0, width: 17, height: 17))
titleView.contentMode = .ScaleAspectFit
let title = UIImage(named: "Header.png")
titleView.image = title
navigationItem.titleView = titleView
//set up menu button
let menu = UIButton()
menu.frame = CGRectMake(0, 0, 17, 12) //won't work if you don't set frame
menu.setImage(UIImage(named: "Menu.png"), forState: .Normal)
menu.addTarget(self, action: #selector(menuButtonPressed), forControlEvents: .TouchUpInside)
let menuButton = UIBarButtonItem()
menuButton.customView = menu
self.navigationItem.leftBarButtonItem = menuButton
//set up alert button
let alert = UIButton()
alert.frame = CGRectMake(0, 0, 18, 18) //won't work if you don't set frame
alert.setImage(UIImage(named: "Alert.png"), forState: .Normal)
alert.addTarget(self, action: #selector(alertButtonPressed), forControlEvents: .TouchUpInside)
let alertButton = UIBarButtonItem()
alertButton.customView = alert
self.navigationItem.rightBarButtonItem = alertButton
}
func setupViews() {
//add header view
let headerViewFrame: CGRect = CGRectMake(0, (self.navigationController?.navigationBar.frame.size.height)! , view.frame.width, view.frame.width*0.50)
let headerView: CrewHeader = CrewHeader(frame: headerViewFrame)
view.addSubview(headerView)
//add view for friend request button
let friendRequestViewController: FriendRequestViewController = FriendRequestViewController()
addChildViewController(friendRequestViewController)
friendRequestViewController.view.frame = CGRectMake(view.frame.width*0.70,(self.navigationController?.navigationBar.frame.size.height)!+view.frame.width*0.45 , view.frame.width*0.3, view.frame.width*0.05)
view.addSubview(friendRequestViewController.view)
friendRequestViewController.didMoveToParentViewController(self)
//add black line
let blackLineFrame1: CGRect = CGRectMake(0, (self.navigationController?.navigationBar.frame.size.height)! + view.frame.width*0.50 , view.frame.width, 2)
let blackLine1: BlackLine = BlackLine(frame: blackLineFrame1)
view.addSubview(blackLine1)
//add view for scrolling squad list
let crewListViewController: CrewListViewController = CrewListViewController()
addChildViewController(crewListViewController)
crewListViewController.view.frame = CGRectMake(0, (self.navigationController?.navigationBar.frame.size.height)! + view.frame.width*0.50 + 2 , view.frame.width, view.frame.width*0.20)
view.addSubview(crewListViewController.view)
crewListViewController.didMoveToParentViewController(self)
//add black line
let blackLineFrame2: CGRect = CGRectMake(0, (self.navigationController?.navigationBar.frame.size.height)! + view.frame.width*0.50 + 2 + view.frame.width*0.20, view.frame.width, 2)
let blackLine2: BlackLine = BlackLine(frame: blackLineFrame2)
view.addSubview(blackLine2)
//
//add view for description
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Vertical
let newsFeedViewController: NewsFeedViewController = NewsFeedViewController(collectionViewLayout: layout)
addChildViewController(newsFeedViewController)
newsFeedViewController.view.frame = CGRectMake(0, (self.navigationController?.navigationBar.frame.size.height)! + view.frame.width*0.50 + 2 + view.frame.width*0.20 + 2 , view.frame.width, view.frame.height - ( 2*(self.navigationController?.navigationBar.frame.size.height)! + view.frame.width*0.50 + 2 + view.frame.width*0.20 + 2 ) )
view.addSubview(newsFeedViewController.view)
newsFeedViewController.didMoveToParentViewController(self)
}
func alertButtonPressed() {
let vc: AlertButtonViewController = AlertButtonViewController()
vc.modalPresentationStyle = UIModalPresentationStyle.Popover
vc.preferredContentSize = CGSizeMake(view.frame.width*0.95, view.frame.height*0.60)
let popoverMenuViewController = vc.popoverPresentationController
popoverMenuViewController!.delegate = self
popoverMenuViewController!.sourceView = self.view
self.presentViewController(vc, animated: true, completion: nil)
}
let menuButonViewController = MenuButtonViewController()
func menuButtonPressed() {
menuButonViewController.showMenu()
}
}
|
//
// SelectLocationWireframe.swift
// Weather
//
// Created by Milan Shah on 5/27/19.
// Copyright (c) 2019 Milan Shah. All rights reserved.
//
//
import UIKit
final class SelectLocationWireframe: BaseWireframe {
// MARK: - Module setup -
init() {
let moduleViewController = SelectLocationViewController()
super.init(view: moduleViewController)
let interactor = SelectLocationInteractor()
let presenter = SelectLocationPresenter(wireframe: self, view: moduleViewController, interactor: interactor)
moduleViewController.presenter = presenter
interactor.presenter = presenter
}
}
// MARK: - Extensions -
extension SelectLocationWireframe: SelectLocationWireframeInterface {
func navigate(to option: SelectLocationNavigationOption) {
switch option {
case .details(let cityDetails):
navigationController?.pushWireframe(ShowWeatherDetailsWireframe(cityWeatherDetails: cityDetails))
}
}
}
|
//: Playground - noun: a place where people can play
import UIKit
/// "class"和"static"都可以用来声明一个类属性和方法。不同的是利用"class"关键字修饰的类属性或方法,是可以有子类重写的。而用"static"关键字修饰的,就相当于加了final关键字,子类不能重写相关的属性。因为储值属性是不能被子类重写的,故也不能用"class"关键字修饰。
class SomeClass {
static var someValue : String = ""
class var someValue1 : Int{
return 199
}
class func someMethod(){
print("some")
}
}
class SomeClassSubClass: SomeClass {
// override static var someValue : String = "hello"
override class var someValue1:Int{
return 22
}
override class func someMethod(){
}
}
print(SomeClass.someValue1)
print(SomeClassSubClass.someValue1)
|
//
// LoginInteractor.swift
// BoardlyLogin
//
// Created by Mateusz Dziubek on 07/12/2018.
// Copyright © 2018 Mateusz Dziubek. All rights reserved.
//
import Foundation
import RxSwift
class LoginInteractorImpl: LoginInteractor {
private let loginService: LoginService
init(loginService: LoginService) {
self.loginService = loginService
}
func login(email: String, password: String) -> Observable<PartialLoginViewState> {
return loginService.login(email: email, password: password).map({ (success: Bool) -> PartialLoginViewState in
if success {
return .loginSuccess
} else {
return .errorState
}
})
}
}
|
//
// BookmarksViewController.swift
// TreeNote
//
// Created by Evgenii Loshchenko on 11.11.2020.
//
import UIKit
class BookmarksViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ContentionTableViewCellDelegate {
@IBOutlet weak var tableView: UITableView!
var cells: [ContentionTableViewCell] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "ContentionTableViewCell", bundle: nil), forCellReuseIdentifier: "ContentionTableViewCell")
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableView.automaticDimension
reloadData()
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
func reloadData()
{
print("reloadData")
cells = [];
let rootNode = ModelController.shared.rootNode!;
recursiveAddChildTopicsToCellList(rootNode, 10)
self.tableView.reloadData()
}
func recursiveAddChildTopicsToCellList(_ contention:Contention, _ intendantion:Int)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ContentionTableViewCell") as! ContentionTableViewCell
cell.setData(contention, self, intendantion + 20, contention.id)
cells.append(cell)
for subContention in contention.childTopics()
{
recursiveAddChildTopicsToCellList(subContention,intendantion + 20)
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
return cells[indexPath.row]
}
@IBAction func cancel()
{
self.dismiss(animated: true, completion: nil)
}
func moveToContention(_ :Contention)
{
}
func editContention(_ :Contention)
{
}
func selectContention(_ contention:Contention)
{
SceneDelegate.shared.rootViewCotroller.contentionId = contention.id
SceneDelegate.shared.rootViewCotroller.navigationController?.popToRootViewController(animated: false)
SceneDelegate.shared.rootViewCotroller.reloadData(true)
self.cancel()
}
}
|
//
// newsdetialModel.swift
// huicheng
//
// Created by lvxin on 2018/3/19.
// Copyright © 2018年 lvxin. All rights reserved.
//
//"id": 2950,//ID
//"title": "致全体惠诚同仁",//标题
//"content": "<p><br/>全体惠诚同仁明年胜今年!快乐、吉祥、健康、幸
//福永远伴随您! <\/p>",//正文
//"object": "全体职员",//接收对象
//“state”:1//状态 0-未发布;1-已发布;2-已撤回 "stateStr": "已发布",//状态显示文字
//"user": "超级管理员",//发布者
//"createtime": "2017-12-29 08:40:10"//发布时间
import UIKit
import ObjectMapper
class newsdetialModel: Mappable {
var id: Int!
var title: String!
var content:String!
var object:String!
var state:Int!
var objectid:Int!
var attachment : String!
var stateStr:String!
var user:String!
var createtime:String!
init() {}
required init?(map: Map){
mapping(map: map)
}
// Mappable
func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
object <- map["object"]
content <- map["content"]
createtime <- map["createtime"]
state <- map["state"]
stateStr <- map["stateStr"]
user <- map["user"]
objectid <- map["objectid"]
attachment <- map["attachment"]
}
}
|
// Controller for the Home menu section.
class HomeViewController: UIViewController
{
// Menu buttons.
@IBOutlet weak var btnMusicCorner: UIButton!
@IBOutlet weak var btnAbout: UIButton!
@IBOutlet weak var btnContact: UIButton!
override func viewDidLoad() {
// Set background color.
self.view.backgroundColor = Constants.Color.blueDarker
// Set navigation bar logo.
let imageView = UIImageView(image: Constants.Image.logo)
imageView.frame.size.height = 18
imageView.contentMode = .ScaleAspectFit
navigationItem.titleView = imageView
// Set Music Corner Button style.
btnMusicCorner.layer.backgroundColor = Constants.Color.blueDark.CGColor
btnMusicCorner.tintColor = Constants.Color.white
btnMusicCorner.layer.borderWidth = Constants.Graphic.buttonBorderWidth
btnMusicCorner.layer.borderColor = Constants.Color.white.CGColor
btnMusicCorner.contentEdgeInsets = Constants.Graphic.buttonInsets
btnMusicCorner.layer.cornerRadius = Constants.Graphic.buttonCornerRadius
// Set About Button style.
btnAbout.layer.backgroundColor = Constants.Color.blueDark.CGColor
btnAbout.tintColor = Constants.Color.white
btnAbout.layer.borderWidth = Constants.Graphic.buttonBorderWidth
btnAbout.layer.borderColor = Constants.Color.white.CGColor
btnAbout.contentEdgeInsets = Constants.Graphic.buttonInsets
btnAbout.layer.cornerRadius = Constants.Graphic.buttonCornerRadius
// Set Contact Button style.
btnContact.layer.backgroundColor = Constants.Color.blueDark.CGColor
btnContact.tintColor = Constants.Color.white
btnContact.layer.borderWidth = Constants.Graphic.buttonBorderWidth
btnContact.layer.borderColor = Constants.Color.white.CGColor
btnContact.contentEdgeInsets = Constants.Graphic.buttonInsets
btnContact.layer.cornerRadius = Constants.Graphic.buttonCornerRadius
}
// Unwind from Music Corner View.
@IBAction func unwindFromMusicCorner(segue: UIStoryboardSegue) {
}
// Unwind from About View.
@IBAction func unwindFromAbout(segue: UIStoryboardSegue) {
}
// Unwind from Contact View.
@IBAction func unwindFromContact(segue: UIStoryboardSegue) {
}
}
|
//
// ExercisesPage.swift
// Tracker
//
// Created by Nicholas Coffey on 11/6/20.
//
import SwiftUI
struct ExercisesPage: View {
@State var text = ""
var body: some View {
NavigationView {
ScrollView {
ExercisesHeader()
}
.navigationBarTitle("Exercises")
.navigationBarItems(leading: Button(action: {
print("Pressed")
}){
Text("New")
})
}
}
}
struct ExercisesPage_Previews: PreviewProvider {
static var previews: some View {
ExercisesPage()
}
}
|
//
// LoginViewController.swift
// projecttracking
//
// Created by Kong Mono on 12/19/15.
// Copyright © 2015 River Engineering. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var mUsername:UITextField!
@IBOutlet weak var mPassword:UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func signinTapped(sender : UIButton) {
let username = (self.mUsername.text)! as String
let password = (self.mPassword.text)! as String
if ( username.isEmpty || password.isEmpty || (username.isEmpty && password.isEmpty)) {
let alert = UIAlertController(title: "Sign in Failed!", message: "Please enter Username and Password", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
let post = "username: \(username), password: \(password)" as String
NSLog("data: %@",post)
if username == "1234" && password == "1234" {
NSLog("Login SUCCESS");
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
let alert = UIAlertController(title: "Sign in Failed!", message: "wrong username and password", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
}
|
//
// ListDetailsViewController.swift
//
// Created by Dmitry Vorozhbicki on 30/10/2020.
// Copyright © 2020 Dmitry Vorozhbicki. All rights reserved.
//
import UIKit
class ListDetailsViewController: BaseViewController {
private let tableView = UITableView()
private var safeArea: UILayoutGuide!
private(set) var viewModel: ListDetailsViewModel?
class func `init`(list: List) -> ListDetailsViewController {
let vc = ListDetailsViewController()
vc.viewModel = ListDetailsViewModel(list: list, delegate: vc)
return vc
}
override func loadView() {
super.loadView()
view.backgroundColor = .white
safeArea = view.layoutMarginsGuide
setupTableView()
}
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.dataSource = self
tableView.delegate = self
tableView.register(ListTableViewCell.self, forCellReuseIdentifier: ListTableViewCell.identifier)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = viewModel?.list.name
if viewModel?.list.archivedDate == nil {
addRightNavigationButton(selector: #selector(addAction), title: "Add")
}
}
}
extension ListDetailsViewController {
@objc func addAction() {
showAlertWithTextField(title: "New Product", message: "Add a new product") { [weak self] (text) in
self?.viewModel?.addProduct(with: text)
}
}
}
extension ListDetailsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
viewModel?.deleteItem(indexPath: indexPath)
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if viewModel?.list.archivedDate == nil {
return .delete
}
return .none
}
}
extension ListDetailsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel?.products.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let product = viewModel?.products[indexPath.row] else {
return UITableViewCell()
}
let cell = tableView.dequeueReusableCell(ListTableViewCell.self, for: indexPath)
cell.bind(product: product)
return cell
}
}
extension ListDetailsViewController: ListViewModelDelegate {
func showAlert(with error: Error) {
self.showFailWithMessage(error.localizedDescription)
}
func didUpdate() {
self.tableView.reloadData()
}
func didDeleteElement(at indexPath: IndexPath) {
self.tableView.deleteRows(at: [indexPath], with: .fade)
}
func didAppendNewElement(at indexPath: IndexPath) {
self.tableView.insertRows(at: [indexPath], with: .automatic)
}
}
|
//
// AppearanceView.swift
// assignment3-group
//
// Created by Chau Phuoc Tuong on 5/8/19.
// https://stackoverflow.com/questions/27093226/changing-background-color-of-all-views-in-project-from-one-view-controller
import UIKit
import Foundation
class AppearanceView {
class var sharedService : AppearanceView {
struct Singleton {
static let instance = AppearanceView()
}
return Singleton.instance
}
init() { }
var backgroundColor : UIColor {
get {
var data: NSData? = UserDefaults.standard.object(forKey: "backgroundColor") as? NSData
var returnValue: UIColor?
if data != nil {
returnValue = NSKeyedUnarchiver.unarchiveObject(with: data! as Data) as? UIColor
} else {
returnValue = UIColor(white: 1, alpha: 1);
}
return returnValue!
}
set (newValue) {
let data = NSKeyedArchiver.archivedData(withRootObject: newValue)
UserDefaults.standard.set(data, forKey: "backgroundColor")
UserDefaults.standard.synchronize()
}
}
func backgroundColorChanged(color : UIColor) {
AppearanceView.sharedService.backgroundColor = color;
}
class AppearanceViewController: UIViewController {
//
// AppearanceView.swift
// assignment3-group
//
// Created by Chau Phuoc Tuong on 5/8/19.
// https://stackoverflow.com/questions/27093226/changing-background-color-of-all-views-in-project-from-one-view-controller
import UIKit
import Foundation
class AppearanceView {
class var sharedService : AppearanceView {
struct Singleton {
static let instance = AppearanceView()
}
return Singleton.instance
}
init() { }
var backgroundColor : UIColor {
get {
var data: NSData? = UserDefaults.standard.object(forKey: "backgroundColor") as? NSData
var returnValue: UIColor?
if data != nil {
returnValue = NSKeyedUnarchiver.unarchiveObject(with: data! as Data) as? UIColor
} else {
returnValue = UIColor(white: 1, alpha: 1);
}
return returnValue!
}
set (newValue) {
let data = NSKeyedArchiver.archivedData(withRootObject: newValue)
UserDefaults.standard.set(data, forKey: "backgroundColor")
UserDefaults.standard.synchronize()
}
}
func backgroundColorChanged(color : UIColor) {
AppearanceView.sharedService.backgroundColor = color;
}
class AppearanceViewController: UIViewController {
@IBOutlet weak var blackButton: UIButton!
@IBOutlet weak var blackButtonTapped: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = AppearanceView.sharedService.backgroundColor;
// Do any additional setup after loading the view.
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = AppearanceView.sharedService.backgroundColor;
// Do any additional setup after loading the view.
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
// Refuge.swift
// *プロパティを追加した時は、古い.realmファイルを更新するため、simulator内のアプリアイコンを一度削除してから再ビルドを行う。
import RealmSwift
class Refuge: Object {
// 管理用プライマリーキー
dynamic var id = 1
// カテゴリ
dynamic var category: Category?
// 場所
dynamic var place = ""
// 住所
dynamic var address = ""
// 電話番号
dynamic var tel = ""
// 収容人数
dynamic var capacity = ""
// 優先度
dynamic var priority = "1"
// メモ
dynamic var memo = ""
// idをプライマリーキーとして設定
override static func primaryKey() -> String? {
return "id"
}
}
|
//
// AddCardVC.swift
// ClassyDrives
//
// Created by Mindfull Junkies on 18/06/19.
// Copyright © 2019 Mindfull Junkies. All rights reserved.
//
import UIKit
class AddCardVC: BaseVC, UITextFieldDelegate{
@IBOutlet var cardNoView: UIView!
@IBOutlet var expMonthView: UIView!
@IBOutlet var expYearView: UIView!
@IBOutlet var cvvView: UIView!
@IBOutlet var addBtn: UIButton!
@IBOutlet var cardNoTF: UITextField!
@IBOutlet var monthTF: UITextField!
@IBOutlet var yearTF: UITextField!
@IBOutlet var cvvTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
addBtn.setButtonBorder()
cardNoView.setShadow()
expMonthView.setShadow()
expYearView.setShadow()
cvvView.setShadow()
cardNoTF.delegate = self
monthTF.delegate = self
yearTF.delegate = self
cvvTF.delegate = self
}
@IBAction func backbtnAtn(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
@IBAction func addBtnAtn(_ sender: Any) {
addCardData()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength = textField.text!.utf8.count + string.utf8.count - range.length
if(textField == cvvTF){
return newLength <= 19
}else if(textField == monthTF){
return newLength <= 2
}else if(textField == yearTF){
return newLength <= 4
}else if(textField == cvvTF){
return newLength <= 3
}
return true
}
}
//MARK: - API Methods
extension AddCardVC{
func addCardData(){
Indicator.sharedInstance.showIndicator()
UserVM.sheard.addCard(user_id: userID, card_number: cardNoTF.text!, exp_month: monthTF.text!, cvv: cvvTF.text!, exp_year: yearTF.text!, card_type: "") { (success, message, error) in
if error == nil{
Indicator.sharedInstance.hideIndicator()
if success{
// self.showAlert(message: message)
self.navigationController?.popViewController(animated: true)
}else{
self.showAlert(message: message)
}
}else{
self.showAlert(message: error?.domain)
}
}
}
}
|
//
// ShoppingListItemRow.swift
// Juicies
//
// Created by Brianna Lee on 5/7/20.
// Copyright © 2020 Brianna Zamora. All rights reserved.
//
import SwiftUI
struct ShoppingListItemRow: View {
@Environment(\.managedObjectContext) var context
@ObservedObject var shoppingListItem: ShoppingListItem
func mark() {
shoppingListItem.isComplete = !shoppingListItem.isComplete
do {
try context.save()
} catch {
fatalError(error.localizedDescription)
}
}
var body: some View {
HStack {
Button(action: mark) {
Image(systemName: shoppingListItem.isComplete ? "circle.fill" : "circle")
}.padding()
if shoppingListItem.quantity > 1 {
Text("\(shoppingListItem.quantity)")
}
TextField("Name", text: self.$shoppingListItem.name)
}
}
}
struct ShoppingListItemRow_Previews: PreviewProvider {
struct ShowQuantity: View {
var body: some View {
ShoppingListItemRow(shoppingListItem: ShoppingListItem())
}
}
struct HideQuantity: View {
var body: some View {
ShoppingListItemRow(shoppingListItem: ShoppingListItem())
}
}
static var previews: some View {
Group {
ShowQuantity()
HideQuantity()
}
}
}
|
//
// ActivityVC.swift
// losAngelesPlaces
//
// Created by Andrew Foster on 3/31/17.
// Copyright © 2017 Andrii Halabuda. All rights reserved.
//
import UIKit
class ActivityVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = false
}
}
|
//
// ADWebViewController.swift
// bundapp
//
// Created by YinZhang on 1/14/15.
// Copyright (c) 2015 THEBUND. All rights reserved.
//
import UIKit
class ADWebViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
@IBAction func close(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
let showAd = UserData.sharedInstance.showAd!
UserData.sharedInstance.showAd = nil
let req = NSMutableURLRequest(URL: NSURL(string: showAd)!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 10.0)
self.webView.loadRequest(req)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
//
// Leisure.swift
// TermProject
//
// Created by kpugame on 2021/05/18.
//
import Foundation
struct TimeInfo
{
var time: String?
var pop: String?
var t3h: String?
}
var globalMeasurements: [TimeInfo] = []
var measurementsCount: Int = 0
|
//
// PopoverDatePickerViewController.swift
// RentBuddy
//
// Created by Steve Leeke on 5/11/16.
// Copyright © 2016 Steve Leeke. All rights reserved.
//
import UIKit
protocol PopoverPickerControllerDelegate
{
// MARK: PopoverPickerControllerDelegate Protocol
func stringPicked(_ string:String?)
}
extension PopoverPickerViewController : UIAdaptivePresentationControllerDelegate
{
// MARK: UIAdaptivePresentationControllerDelegate
// Specifically for Plus size iPhones.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle
{
return UIModalPresentationStyle.none
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
extension PopoverPickerViewController : UIPickerViewDataSource
{
// MARK: UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
if stringTree != nil {
var depth = 0
if let depthBelow = stringTree?.root?.depthBelow(0) {
depth = depthBelow
}
// print("Depth: ",depth)
return depth
} else {
return 1
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
guard stringTree != nil else {
return strings?.count ?? 0
}
var stringNode = stringTree?.root
switch component {
case 0:
break
default:
for i in 0..<component {
if let stringNodes = stringNode?.stringNodes?.sorted(by: { $0.string < $1.string }) {
pickerSelections[i] = pickerSelections[i] != nil ? pickerSelections[i] : 0
if let selection = pickerSelections[i] {
if selection < stringNodes.count {
stringNode = stringNodes[selection]
}
}
}
}
break
}
if let count = stringNode?.stringNodes?.count {
return count
} else {
return 0
}
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
{
let label = view as? UILabel ?? UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
if stringTree != nil {
if let title = title(forRow: row, forComponent: component) {
label.attributedText = NSAttributedString(string: title,attributes: Constants.Fonts.Attributes.normal)
}
label.textAlignment = .left
} else {
guard component == 0 else {
label.text = "ERROR"
return label
}
if let string = strings?[row] {
label.attributedText = NSAttributedString(string: string,attributes: Constants.Fonts.Attributes.normal)
}
label.textAlignment = .center
}
label.sizeToFit()
return label
}
func title(forRow row:Int, forComponent component:Int) -> String?
{
var stringNode = stringTree?.root
switch component {
case 0:
break
default:
for i in 0..<component {
if let stringNodes = stringNode?.stringNodes?.sorted(by: { $0.string < $1.string }) {
pickerSelections[i] = pickerSelections[i] != nil ? pickerSelections[i] : 0
if let selection = pickerSelections[i] {
if selection < stringNodes.count {
stringNode = stringNodes[selection]
}
}
}
}
break
}
if let count = stringNode?.stringNodes?.count, row >= 0, row < count {
// print("Component: ",component," Row: ",row," String: ",string)
switch count {
default:
if let string = stringNode?.stringNodes?.sorted(by: { $0.string < $1.string })[row].string {
return string
}
break
}
}
return nil
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
if stringTree != nil {
return title(forRow: row,forComponent: component)
} else {
return strings?[row]
}
}
}
extension PopoverPickerViewController : UIPickerViewDelegate
{
// MARK: UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat
{
if stringTree != nil {
var stringNode = stringTree?.root
switch component {
case 0:
break
default:
for i in 0..<component {
if let stringNodes = stringNode?.stringNodes?.sorted(by: { $0.string < $1.string }) {
pickerSelections[i] = pickerSelections[i] != nil ? pickerSelections[i] : 0
if let selection = pickerSelections[i] {
if selection < stringNodes.count {
stringNode = stringNodes[selection]
}
}
}
}
break
}
var width:CGFloat = 0.0
let widthSize: CGSize = CGSize(width: .greatestFiniteMagnitude, height: Constants.Fonts.body.lineHeight)
if let stringNodes = stringNode?.stringNodes {
switch stringNodes.count {
default:
for stringNode in stringNodes {
if let stringWidth = stringNode.string?.boundingRect(with: widthSize, options: .usesLineFragmentOrigin, attributes: Constants.Fonts.Attributes.normal, context: nil).width {
if stringWidth > width {
width = stringWidth
}
}
}
break
}
} else {
return 0
}
if component < pickerSelections.count, let index = pickerSelections[component], index < stringNode?.stringNodes?.count,
let string = stringNode?.stringNodes?[index].string, string == Constants.WORD_ENDING {
return width + 20
} else {
return width + 10
}
} else {
var width:CGFloat = 0.0
let widthSize: CGSize = CGSize(width: .greatestFiniteMagnitude, height: Constants.Fonts.body.lineHeight)
if let strings = strings {
for string in strings {
let stringWidth = string.boundingRect(with: widthSize, options: .usesLineFragmentOrigin, attributes: Constants.Fonts.Attributes.normal, context: nil).width
if stringWidth > width {
width = stringWidth
}
}
} else {
return 0
}
return width + 16
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
guard Thread.isMainThread else {
alert(viewController:self,title: "Not Main Thread", message: "PopoverPickerViewController:pickerView", completion: nil)
return
}
if stringTree != nil {
pickerSelections[component] = row
spinner.startAnimating()
DispatchQueue.global(qos: .userInteractive).async { [weak self] in
self?.updatePickerSelections()
self?.updatePicker()
}
} else {
guard component == 0 else {
return
}
string = strings?[row]
print(row, string as Any)
}
}
}
extension PopoverPickerViewController : UIPopoverPresentationControllerDelegate
{
func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool
{
return popoverPresentationController.presentedViewController.modalPresentationStyle == .popover
}
}
extension PopoverPickerViewController : PopoverTableViewControllerDelegate
{
func rowClickedAtIndex(_ index: Int, strings: [String]?, purpose: PopoverPurpose, mediaItem: MediaItem?)
{
guard Thread.isMainThread else {
alert(viewController:self,title: "Not Main Thread", message: "PopoverPickerViewController:rowClickedAtIndex",completion:nil)
return
}
guard let string = strings?[index] else {
return
}
switch purpose {
case .selectingAction:
switch string {
case Constants.Strings.Expanded_View:
process(viewController: self, work: { [weak self] () -> (Any?) in
var bodyHTML = "<!DOCTYPE html>"
bodyHTML = bodyHTML + "<html><body>"
bodyHTML = bodyHTML + "<center>"
if let roots = self?.stringTree?.root?.stringNodes {
bodyHTML = bodyHTML + "<table><tr>"
for root in roots {
if let string = root.string {
bodyHTML = bodyHTML + "<td>" + "<a id=\"index\(string)\" name=\"index\(string)\" href=#\(string)>" + string + "</a>" + "</td>"
}
}
bodyHTML = bodyHTML + "</tr></table>"
bodyHTML = bodyHTML + "<table>"
for root in roots {
if let rows = root.htmlWords(nil) {
if let string = root.string {
bodyHTML = bodyHTML + "<tr><td>" + "<a id=\"\(string)\" name=\"\(string)\" href=#index\(string)>" + string + "</a>" + " (\(rows.count))</td></tr>"
}
for row in rows {
bodyHTML = bodyHTML + "<tr>" + row + "</tr>"
}
}
}
bodyHTML = bodyHTML + "</table>"
}
bodyHTML = bodyHTML + "</center>"
bodyHTML = bodyHTML + "</body></html>"
return bodyHTML
}, completion: { [weak self] (data:Any?) in
if let vc = self {
presentHTMLModal(viewController: vc, mediaItem: nil, style: .fullScreen, title: Constants.Strings.Expanded_View, htmlString: data as? String)
}
})
break
default:
break
}
break
default:
break
}
}
}
class PopoverPickerViewController : UIViewController
{
var popover : PopoverTableViewController?
var delegate : PopoverPickerControllerDelegate?
var stringTree : StringTree?
var incremental = false
// var mediaListGroupSort:MediaListGroupSort?
var pickerSelections = [Int:Int]()
// var root:StringNode?
// {
// get {
// return lexicon?.stringTree.root
// }
// }
// var lexicon:Lexicon?
// {
// get {
// return mediaListGroupSort?.lexicon
// }
// }
var strings:[String]?
var string:String?
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var picker: UIPickerView!
@IBOutlet weak var selectButton: UIButton!
@IBOutlet weak var expandedViewButton: UIButton!
// @IBOutlet weak var wordListButton: UIButton!
@IBAction func expandedViewAction(_ sender: UIButton)
{
process(viewController: self, work: { [weak self] () -> (Any?) in
var bodyHTML = "<!DOCTYPE html>"
var wordsHTML = ""
var indexHTML = ""
bodyHTML = bodyHTML + "<html><body>"
if let roots = self?.stringTree?.root?.stringNodes?.sorted(by: { (lhs:StringNode, rhs:StringNode) -> Bool in
return lhs.string < rhs.string
}) {
var total = 0
wordsHTML = "<table>"
for root in roots {
if let rows = root.htmlWords(nil) {
total += rows.count
if let string = root.string {
wordsHTML = wordsHTML + "<tr><td><br/></td></tr>"
wordsHTML = wordsHTML + "<tr><td>" + "<a id=\"\(string)\" name=\"\(string)\" href=#index>" + string + "</a>" + " (\(rows.count))</td></tr>" //#index\(string)
}
for row in rows {
wordsHTML = wordsHTML + "<tr>" + row + "</tr>"
}
}
}
wordsHTML = wordsHTML + "</table>"
indexHTML = "<table>"
indexHTML = indexHTML + "<tr><td><br/></td></tr>" // \(string)
indexHTML = indexHTML + "<tr><td>Index to \(total) Words</td>"
for root in roots {
if let string = root.string {
indexHTML = indexHTML + "<td>" + "<a id=\"index\" name=\"index\" href=#\(string)>" + string + "</a>" + "</td>"
}
}
indexHTML = indexHTML + "</tr></table>"
}
bodyHTML = bodyHTML + indexHTML + wordsHTML + "</body></html>"
return bodyHTML
}, completion: { [weak self] (data:Any?) in
if let vc = self {
presentHTMLModal(viewController: vc, dismiss:false, mediaItem: nil, style: .fullScreen, title: Constants.Strings.Expanded_View, htmlString: data as? String)
}
})
}
// @IBAction func wordListAction(_ sender: UIButton)
// {
// process(viewController: self, work: { () -> (Any?) in
// var bodyHTML = "<!DOCTYPE html>"
//
// var wordsHTML = ""
// var indexHTML = ""
//
// bodyHTML = bodyHTML + "<html><body>"
//
// if let roots = self.stringTree?.root?.stringNodes?.sorted(by: { (lhs:StringNode, rhs:StringNode) -> Bool in
// return lhs.string < rhs.string
// }) {
// var total = 0
//
// wordsHTML = "<table>"
//
// for root in roots {
// if let rows = root.words(nil) {
// total += rows.count
//
// if let string = root.string {
// wordsHTML = wordsHTML + "<tr><td><br/></td></tr>"
//
// wordsHTML = wordsHTML + "<tr><td>" + "<a id=\"\(string)\" name=\"\(string)\" href=#index>" + string + "</a>" + " (\(rows.count))</td></tr>" //#index\(string)
// }
//
// for row in rows {
// // This is where we would add columns.
// wordsHTML = wordsHTML + "<tr><td>" + row + "</td></tr>"
// }
// }
// }
//
// wordsHTML = wordsHTML + "</table>"
//
// indexHTML = "<table>"
//
// indexHTML = indexHTML + "<tr><td><br/></td></tr>" // \(string)
//
// indexHTML = indexHTML + "<tr><td>Index to \(total) Words</td>"
//
// for root in roots {
// if let string = root.string {
// indexHTML = indexHTML + "<td>" + "<a id=\"index\" name=\"index\" href=#\(string)>" + string + "</a>" + "</td>"
// }
// }
//
// indexHTML = indexHTML + "</tr></table>"
// }
//
// bodyHTML = bodyHTML + indexHTML + wordsHTML + "</body></html>"
//
// return bodyHTML
// }, completion: { (data:Any?) in
// presentHTMLModal(viewController: self, dismiss:false, mediaItem: nil, style: .fullScreen, title: Constants.Strings.Expanded_View, htmlString: data as? String)
// })
// }
@IBAction func selectButtonAction(sender: UIButton)
{
string = wordFromPicker()
// print("\(string)")
delegate?.stringPicked(string)
}
func actionMenu() -> [String]?
{
var actionMenu = [String]()
// actionMenu.append(Constants.Strings.Expanded_View)
return actionMenu.count > 0 ? actionMenu : nil
}
@objc func actions()
{
if let navigationController = self.storyboard?.instantiateViewController(withIdentifier: Constants.IDENTIFIER.POPOVER_TABLEVIEW) as? UINavigationController,
let popover = navigationController.viewControllers[0] as? PopoverTableViewController {
popover.navigationItem.title = "Select"
navigationController.isNavigationBarHidden = false
navigationController.modalPresentationStyle = .popover // MUST OCCUR BEFORE PPC DELEGATE IS SET.
navigationController.popoverPresentationController?.delegate = self
navigationController.popoverPresentationController?.permittedArrowDirections = .up
navigationController.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
// popover.navigationController?.isNavigationBarHidden = true
popover.delegate = self
popover.purpose = .selectingAction
popover.section.strings = actionMenu()
//
// popover.section.showIndex = false
// popover.section.showHeaders = false
popover.vc = self
ptvc = popover
present(navigationController, animated: true, completion: nil)
}
}
func updateActionButton()
{
navigationItem.rightBarButtonItem?.isEnabled = stringTree?.root.depthBelow(0) > 0
}
func setupActionButton()
{
guard stringTree != nil else {
return
}
if actionMenu()?.count > 0 {
let actionButton = UIBarButtonItem(title: Constants.FA.ACTION, style: UIBarButtonItemStyle.plain, target: self, action: #selector(actions))
actionButton.setTitleTextAttributes(Constants.FA.Fonts.Attributes.show)
navigationItem.setRightBarButton(actionButton, animated: false)
}
}
@objc func done()
{
dismiss(animated: true, completion: nil)
}
var doneButton : UIBarButtonItem!
override func viewDidLoad()
{
super.viewDidLoad()
doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(done))
if let presentationStyle = navigationController?.modalPresentationStyle {
switch presentationStyle {
case .overCurrentContext:
fallthrough
case .fullScreen:
fallthrough
case .overFullScreen:
if navigationItem.leftBarButtonItems != nil {
navigationItem.leftBarButtonItems?.append(doneButton)
} else {
navigationItem.leftBarButtonItem = doneButton
}
default:
break
}
}
setupActionButton()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
super.viewWillTransition(to: size, with: coordinator)
if (self.view.window == nil) {
return
}
// print("Size: \(size)")
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
}) { (UIViewControllerTransitionCoordinatorContext) -> Void in
}
}
var ptvc:PopoverTableViewController?
var orientation : UIDeviceOrientation?
@objc func deviceOrientationDidChange()
{
// Dismiss any popover
func action()
{
ptvc?.dismiss(animated: false, completion: nil)
}
guard let orientation = orientation else {
return
}
switch orientation {
case .faceUp:
switch UIDevice.current.orientation {
case .faceUp:
break
case .faceDown:
break
case .landscapeLeft:
action()
break
case .landscapeRight:
action()
break
case .portrait:
break
case .portraitUpsideDown:
break
case .unknown:
action()
break
}
break
case .faceDown:
switch UIDevice.current.orientation {
case .faceUp:
break
case .faceDown:
break
case .landscapeLeft:
action()
break
case .landscapeRight:
action()
break
case .portrait:
action()
break
case .portraitUpsideDown:
action()
break
case .unknown:
action()
break
}
break
case .landscapeLeft:
switch UIDevice.current.orientation {
case .faceUp:
break
case .faceDown:
break
case .landscapeLeft:
break
case .landscapeRight:
action()
break
case .portrait:
action()
break
case .portraitUpsideDown:
action()
break
case .unknown:
action()
break
}
break
case .landscapeRight:
switch UIDevice.current.orientation {
case .faceUp:
break
case .faceDown:
break
case .landscapeLeft:
break
case .landscapeRight:
break
case .portrait:
action()
break
case .portraitUpsideDown:
action()
break
case .unknown:
action()
break
}
break
case .portrait:
switch UIDevice.current.orientation {
case .faceUp:
break
case .faceDown:
break
case .landscapeLeft:
action()
break
case .landscapeRight:
action()
break
case .portrait:
break
case .portraitUpsideDown:
break
case .unknown:
action()
break
}
break
case .portraitUpsideDown:
switch UIDevice.current.orientation {
case .faceUp:
break
case .faceDown:
break
case .landscapeLeft:
action()
break
case .landscapeRight:
action()
break
case .portrait:
break
case .portraitUpsideDown:
break
case .unknown:
action()
break
}
break
case .unknown:
break
}
switch UIDevice.current.orientation {
case .faceUp:
break
case .faceDown:
break
case .landscapeLeft:
self.orientation = UIDevice.current.orientation
break
case .landscapeRight:
self.orientation = UIDevice.current.orientation
break
case .portrait:
self.orientation = UIDevice.current.orientation
break
case .portraitUpsideDown:
self.orientation = UIDevice.current.orientation
break
case .unknown:
break
}
}
func addNotifications()
{
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
orientation = UIDevice.current.orientation
addNotifications()
updateActionButton()
if stringTree?.incremental == true {
if stringTree?.completed == false {
spinner.isHidden = false
spinner.startAnimating()
}
globals.queue.async(execute: { () -> Void in
NotificationCenter.default.addObserver(self, selector: #selector(self.updated), name: NSNotification.Name(rawValue: Constants.NOTIFICATION.STRING_TREE_UPDATED), object: self.stringTree)
})
}
if let string = string, let index = strings?.index(of:string) {
picker.selectRow(index, inComponent: 0, animated: false)
} else
if (stringTree != nil) && (strings != nil) {
if stringTree?.incremental == true {
self.stringTree?.build(strings: self.strings)
} else {
process(viewController: self, work: { [weak self] () -> (Any?) in
self?.stringTree?.build(strings: self?.strings)
return nil
}, completion: { [weak self] (data:Any?) in
self?.updateActionButton()
self?.updatePickerSelections()
self?.updatePicker()
})
}
}
preferredContentSize = CGSize(width: 300, height: 300)
}
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)
}
func setPreferredContentSize()
{
guard Thread.isMainThread else {
alert(viewController:self,title: "Not Main Thread", message: "PopoverPickerViewController:setPreferredContentSize",completion:nil)
return
}
var width:CGFloat = 0
var count:CGFloat = 0
for component in 0..<picker.numberOfComponents {
let componentWidth = pickerView(picker, widthForComponent: component)
if componentWidth > 0 {
count += 1
}
width += componentWidth
}
preferredContentSize = CGSize(width: max(200,width + 70 + count*2), height: 300)
}
func updatePickerSelections()
{
guard stringTree?.root?.stringNodes != nil else {
return
}
var stringNode = stringTree?.root
var i = 0
while stringNode != nil {
if stringNode?.stringNodes == nil {
pickerSelections[i] = nil
stringNode = nil
} else
if let count = stringNode?.stringNodes?.count, pickerSelections[i] >= count {
pickerSelections[i] = 0
stringNode = stringNode?.stringNodes?[0]
} else {
if let index = pickerSelections[i] {
stringNode = stringNode?.stringNodes?[index]
} else {
stringNode = nil
}
}
i += 1
}
var index = i
Thread.onMainThread {
while index < self.picker.numberOfComponents {
self.pickerSelections[index] = nil
index += 1
}
self.picker.setNeedsLayout()
}
}
func wordFromPicker() -> String?
{
var word:String?
var stringNode = stringTree?.root
var i = 0
while i < pickerSelections.count, pickerSelections[i] != nil {
if i < pickerSelections.count, let selection = pickerSelections[i] {
if let stringNodes = stringNode?.stringNodes {
if selection < stringNodes.count {
let node = stringNodes.sorted(by: { $0.string < $1.string })[selection]
if node.string != Constants.WORD_ENDING {
stringNode = node
if let string = stringNode?.string {
word = (word ?? "") + string
}
}
}
}
}
i += 1
}
if let wordEnding = stringNode?.wordEnding, wordEnding {
return word
} else {
return nil
}
}
func updatePicker()
{
Thread.onMainThread {
self.picker.reloadAllComponents()
var i = 0
while i < self.picker.numberOfComponents, i < self.pickerSelections.count, self.pickerSelections[i] != nil {
if let row = self.pickerSelections[i] {
self.picker.selectRow(row,inComponent: i, animated: true)
}
i += 1
}
self.setPreferredContentSize()
self.string = self.wordFromPicker()
if self.stringTree?.completed == true {
self.spinner.stopAnimating()
}
}
}
func started()
{
self.updatePickerSelections()
self.updatePicker()
Thread.onMainThread {
self.updateActionButton()
}
}
@objc func updated()
{
self.updatePickerSelections()
self.updatePicker()
Thread.onMainThread {
self.updateActionButton()
if self.stringTree?.completed == true {
self.spinner.stopAnimating()
}
}
}
func completed()
{
self.updatePickerSelections()
self.updatePicker()
Thread.onMainThread {
self.updateActionButton()
}
}
}
|
//
// CompositionTests.swift
//
// Created by Chuck Krutsinger on 2/15/19.
// Copyright © 2019 Countermind, LLC. All rights reserved.
//
import XCTest
@testable import CMUtilities
class CompositionTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testPipeForward() {
XCTAssertEqual(1 |> incr, incr(1))
}
func testForwardComposeArrows() {
XCTAssertEqual("\(square(incr(1)))", 1 |> incr >>> square >>> { "\($0)" })
}
func testForwardComposeDiamondSameType() {
XCTAssertEqual(square(incr(1)), 1 |> incr <> square)
}
func testForwardComposeDiamondObjectMutation() {
let setBackgroundBlue = setBackgroundColor(UIColor.blue)
let button = UIButton()
button |> setBackgroundBlue <> makeViewRound
XCTAssertEqual(UIColor.blue, button.backgroundColor)
XCTAssertTrue(button.layer.masksToBounds)
XCTAssertEqual(button.layer.cornerRadius, button.frame.height / 2.0)
XCTAssertTrue(button.clipsToBounds)
}
func testForwardComposeDiamonStructMutation() {
let string = "string"
var objectUnderTest = StructWithString(string: string)
objectUnderTest |> toUpper <> exclaim
XCTAssertEqual(objectUnderTest.string, "STRING!")
}
func testFishCompositionWithArrayToCaptureHiddenOuputSideEffects() {
let result = 1 |> incrWithLog >=> squareWithLog
let expectedCalc = ((1+1) * (1+1))
let expectedLog = ["1 + 1 = 2", "2 * 2 = 4"]
XCTAssertEqual(result.0, expectedCalc)
XCTAssertEqual(result.1, expectedLog)
}
func testFishCompositionForChainingOptionals() {
let fNil: (Int) -> Int? = { _ in nil }
let gNil: (Int) -> Int? = { _ in nil }
let fIdentity = { (x: Int) in x }
let gIdentity = { (x: Int) in x }
XCTAssertNil(1 |> fNil >=> gIdentity)
XCTAssertNil(1 |> fIdentity >=> gNil)
XCTAssertNil(1 |> fNil >=> gNil)
XCTAssertEqual(1, 1 |> fIdentity >=> gIdentity)
}
}
//Fixtures
fileprivate func incr<A: Numeric>(_ x: A) -> A {
return x + 1
}
fileprivate func square<A: Numeric>(_ x: A) -> A {
return x * x
}
fileprivate struct StructWithString {
var string: String
}
fileprivate func toUpper(_ item: inout StructWithString) {
item.string = item.string.uppercased()
}
fileprivate func exclaim(_ item: inout StructWithString) {
item.string = item.string + "!"
}
fileprivate func incrWithLog<A: Numeric>(_ x: A)
-> (A, [String])
{
return (x + 1, ["\(x) + 1 = \(x + 1)"])
}
fileprivate func squareWithLog<A: Numeric>(_ x: A)
-> (A, [String])
{
return (x * x, ["\(x) * \(x) = \(x * x)"])
}
|
import Flutter
import UIKit
func getMyPerson() -> Person {
let p = Person.with {
$0.name = "TruongSinh"
$0.supervisorOf = [
Person.with {
$0.name = "Jane Dane"
$0.addresses = [
UsaAddress.with{
$0.streetNameAndNumber = "1 Infinity Loop"
$0.city = "Cupertino"
$0.state = UsaState.ca
$0.postCode = 95014
},
UsaAddress.with {
$0.streetNameAndNumber = "1 Microsoft Way"
$0.city = "Redmond"
$0.state = UsaState.wa
$0.postCode = 98052
},
]
},
Person.with {
$0.name = "Joe Doe"
$0.addresses = [
UsaAddress.with{
$0.streetNameAndNumber = "1 Infinity Loop"
$0.city = "Cupertino"
$0.state = UsaState.ca
$0.postCode = 95014
},
UsaAddress.with {
$0.streetNameAndNumber = "1 Microsoft Way"
$0.city = "Redmond"
$0.state = UsaState.wa
$0.postCode = 98052
},
]
}
]
}
return p;
}
public class SwiftPluginWithProtobufPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "plugin_with_protobuf", binaryMessenger: registrar.messenger())
let instance = SwiftPluginWithProtobufPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
do {
result(try getMyPerson().serializedData())
} catch {
result(FlutterError(code: "Cannot serialize data", message: nil, details: nil))
}
}
}
|
//
// tsuutiCustomCell.swift
// しゅくまる
//
// Created by miyu.s on 2017/11/14.
// Copyright © 2017年 miyu.s. All rights reserved.
//
import UIKit
import NCMB
class setTsuutiCell {
var iconView: String
var title: String
init(icon: String, title: String) {
self.iconView = icon
self.title = title
}
}
protocol CustomTableViewTsuutiCellDelegate: class {
func updateCellObject(object: setTsuutiCell)
}
class tsuutiCustomCell: UITableViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
weak var delegate: CustomTableViewTsuutiCellDelegate!
var indexPath = IndexPath()
var cellObject: setTsuutiCell! {
didSet {
iconView.image = UIImage(named: cellObject.iconView)
titleLabel.text = String(describing: cellObject.title)
// 行間の変更(正確には行自体の高さを変更している。)
let LineSpaceStyle = NSMutableParagraphStyle()
LineSpaceStyle.lineSpacing = 10.0
let lineSpaceAttr = [NSParagraphStyleAttributeName: LineSpaceStyle]
titleLabel.attributedText = NSMutableAttributedString(string: titleLabel.text!, attributes: lineSpaceAttr)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// CommentCell.swift
// TemplateSwiftAPP
//
// Created by wenhua on 2018/9/2.
// Copyright © 2018年 wenhua yu. All rights reserved.
//
import Foundation
import UIKit
class CommentCell: BaseTCell {
/// 懒加载
lazy var iconView: UIImageView = {
let view = UIImageView()
return view
}()
lazy var titleLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 16)
return view
}()
lazy var lineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.init(white: 0.7, alpha: 0.3)
return view
}()
lazy var contentLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 16)
view.numberOfLines = 2
return view
}()
lazy var timeLabel: UILabel = {
let view = UILabel()
view.textColor = UIColor.lightGray
view.font = UIFont.systemFont(ofSize: 14)
view.textAlignment = NSTextAlignment.left
return view
}()
override func setupSubViews() {
self.addSubview(iconView)
self.addSubview(titleLabel)
self.addSubview(lineView)
self.addSubview(timeLabel)
self.addSubview(contentLabel)
self.setupLayouts()
}
override func setupLayouts() {
iconView.snp.makeConstraints({ (make) -> Void in
make.width.height.equalTo(20)
make.left.equalTo(20)
make.top.equalTo(5)
})
titleLabel.snp.makeConstraints({ (make) -> Void in
make.left.equalTo(iconView.snp.right).offset(10)
make.width.equalTo(80)
make.height.equalTo(20)
make.top.equalTo(5)
})
timeLabel.snp.makeConstraints({ (make) -> Void in
make.left.equalTo(titleLabel.snp.right).offset(10)
make.right.equalTo(-20)
make.height.equalTo(20)
make.top.equalTo(5)
})
lineView.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.right.equalTo(-20)
make.top.equalTo(iconView.snp.bottom).offset(5)
make.height.equalTo(1)
}
contentLabel.snp.makeConstraints({ (make) -> Void in
make.left.equalTo(10)
make.right.equalTo(-10)
make.top.equalTo(iconView.snp.bottom).offset(5)
make.bottom.equalTo(5)
})
}
func updateComment(comment: Comment) -> Void {
iconView.image = UIImage.init(named: "app_placeholder")
titleLabel.text = comment.author
timeLabel.text = "发布于:" + DateUtil.timeStampToString(timeStamp: comment.createTime)
contentLabel.text = comment.content
}
override class func classCellHeight() -> CGFloat {
return 80.0
}
}
|
//
// Author+CoreDataProperties.swift
// ChallengeApp
//
// Created by Jayr Atamosa on 21/08/2019.
// Copyright © 2019 Jayr Atamosa. All rights reserved.
//
//
import Foundation
import CoreData
extension Author {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Author> {
return NSFetchRequest<Author>(entityName: "Author")
}
@NSManaged public var address: String?
@NSManaged public var author_id: String?
@NSManaged public var avatar_link: String?
@NSManaged public var dob: String?
@NSManaged public var edit_link: String?
@NSManaged public var email: String?
@NSManaged public var first_name: String?
@NSManaged public var gender: String?
@NSManaged public var last_name: String?
@NSManaged public var original_link: String?
@NSManaged public var phone: String?
@NSManaged public var status: String?
@NSManaged public var website: String?
enum CodingKeys: String, CodingKey {
case address
case author_id = "id"
case avatar_link
case dob
case edit_link
case email
case first_name
case gender
case last_name
case original_link
case phone
case status
case website
case links = "_links"
case result
}
enum LinkKeys: String, CodingKey {
case original = "self"
case edit
case avatar
case href
}
}
extension Author {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(address, forKey: .address)
try container.encode(author_id, forKey: .author_id)
try container.encode(dob, forKey: .dob)
try container.encode(email, forKey: .email)
try container.encode(first_name, forKey: .first_name)
try container.encode(gender, forKey: .gender)
try container.encode(last_name, forKey: .last_name)
try container.encode(phone, forKey: .phone)
try container.encode(status, forKey: .status)
try container.encode(website, forKey: .website)
var links = container.nestedContainer(keyedBy: LinkKeys.self, forKey: .links)
var origLink = links.nestedContainer(keyedBy: LinkKeys.self, forKey: .original)
var editLink = links.nestedContainer(keyedBy: LinkKeys.self, forKey: .edit)
var avatarLink = links.nestedContainer(keyedBy: LinkKeys.self, forKey: .avatar)
try origLink.encode(original_link, forKey: .href)
try editLink.encode(edit_link, forKey: .href)
try avatarLink.encode(avatar_link, forKey: .href)
}
}
|
//
// VAsset.swift
// TG
//
// Created by Andrii Narinian on 9/23/17.
// Copyright © 2017 ROLIQUE. All rights reserved.
//
import Foundation
import SwiftyJSON
import Alamofire
typealias TelemetryCompletion = ([ActionModel]) -> Void
class VAsset: VModel {
var url: String?
var contentType: String?
var createdAt: Date?
var description: String?
var filename: String?
var name: String?
init (model: VModel) {
super.init(id: model.id, type: model.type, attributes: model.attributes, relationships: model.relationships)
decode()
}
required init(json: JSON, included: [VModel]? = nil) {
super.init(json: json, included: included)
}
override var encoded: [String : Any?] {
let dict: [String: Any?] = [
"id": id,
"type": type,
"url": url,
"contentType": contentType,
"createdAt": TGDateFormats.iso8601WithoutTimeZone.string(from: createdAt ?? Date()),
"description": description,
"filename": filename,
"name": name
]
return dict
}
private func decode() {
guard let att = self.attributes as? JSON else { return }
self.url = att["URL"].string
self.contentType = att["contentType"].string
self.createdAt = att["createdAt"].stringValue.dateFromISO8601WithoutTimeZone
self.description = att["description"].string
self.filename = att["filename"].string
self.name = att["name"].string
}
}
extension VAsset {
func loadTelemetry(withOwner owner: TGOwner? = nil,
loaderMessage: String? = nil,
control: Control? = nil,
onSuccess: @escaping TelemetryCompletion,
onError: Completion? = nil) {
let router = Router.telemetry(urlString: url ?? "", contentType: contentType ?? "")
Alamofire.request(try! router.asURLRequest())
.responseJSON { response in
debugPrint(response)
if let object = response.result.value {
let jsonArray = JSON(object).arrayValue
onSuccess(jsonArray.map({ ActionModel(json: $0) }))
}
}
}
}
extension Asset {
func loadTelemetry(withOwner owner: TGOwner? = nil,
loaderMessage: String? = nil,
control: Control? = nil,
onSuccess: @escaping ([Action]) -> Void,
onError: Completion? = nil) {
let router = Router.telemetry(urlString: url ?? "", contentType: contentType ?? "")
Alamofire.request(try! router.asURLRequest())
.responseJSON { response in
owner?.navigationController?.showLoader(message: "building graph")
DispatchQueue.global(qos: .userInitiated).async {
debugPrint(response)
if let object = response.result.value {
let jsonArray = JSON(object).arrayValue
let actions = jsonArray.map({ Action(dict: ActionModel(json: $0).encoded) })
onSuccess(actions)
}
}
}
}
}
|
//
// AddTwoNumbersViewController.swift
// LeetCode-Swift-master
//
// Created by lengain on 2019/1/14.
// Copyright © 2019 Lengain. All rights reserved.
//
import UIKit
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
public func traverseNode() {
print(self.val)
if self.next != nil {
self.next?.traverseNode()
}
}
}
class AddTwoNumbersViewController: LNBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let node1 = ListNode.init(2)
let node2 = ListNode.init(4)
node1.next = node2
let node3 = ListNode.init(3)
node2.next = node3
let node4 = ListNode.init(5)
let node5 = ListNode.init(6)
node4.next = node5
let node6 = ListNode.init(4)
node5.next = node6
let result1 = Solution.addTwoNumbers(node1, node4)
if result1 != nil {
result1?.traverseNode()
}
let node7 = ListNode.init(5)
let node8 = ListNode.init(5)
let result2 = Solution.addTwoNumbers(node7, node8)
if result2 != nil {
result2?.traverseNode()
}
}
/*
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) +
(5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
*/
class Solution {
class func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var leftNode = l1
var rightNode = l2
var resultNode : ListNode?
var tempResultNode : ListNode?
var moreThanTen = false
while leftNode != nil || rightNode != nil {
var sum = 0;
if leftNode != nil {
sum += leftNode!.val
leftNode = leftNode?.next
}
if rightNode != nil {
sum += rightNode!.val
rightNode = rightNode?.next
}
if moreThanTen {
sum += 1
}
if sum > 9 {
moreThanTen = true
sum = sum % 10
}else {
moreThanTen = false
}
if tempResultNode == nil {
resultNode = ListNode.init(sum)
tempResultNode = resultNode
}else {
tempResultNode?.next = ListNode.init(sum);
tempResultNode = tempResultNode?.next;
}
}
if moreThanTen {
tempResultNode?.next = ListNode.init(1)
}
return resultNode;
}
}
/// 当数很长时,此方法不正确,会超出数据类型长度,会错误
class Solution1 {
class func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var sum = Solution1.convertMath(l1) + Solution1.convertMath(l2)
let listNode = ListNode.init(Int(Int64(sum)%10))
var tempNode = listNode;
while sum > 0 {
sum /= 10
if sum < 1 {break}
let node = ListNode.init(Int(Int64(sum)%10))
tempNode.next = node
tempNode = node
}
return listNode;
}
class func convertMath(_ node: ListNode?) -> Double {
var tempNode :ListNode? = node;
var index = 0
var sum : Double = 0
while tempNode != nil {
sum += Double(powf(10, Float(index))) * Double(tempNode!.val)
index += 1
tempNode = tempNode!.next
}
return sum
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
// Youtube.swift
// Youtube ( https://github.com/xmartlabs/XLActionController )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
#if IMPORT_BASE_XLACTIONCONTROLLER
import XLActionController
#endif
open class YoutubeCell: ActionCell {
open lazy var animatableBackgroundView: UIView = { [weak self] in
let view = UIView(frame: self?.frame ?? CGRect.zero)
view.backgroundColor = UIColor.red.withAlphaComponent(0.40)
return view
}()
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
func initialize() {
actionTitleLabel?.textColor = UIColor(white: 0.098, alpha: 1.0)
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.0)
backgroundView.addSubview(animatableBackgroundView)
selectedBackgroundView = backgroundView
}
open override var isHighlighted: Bool {
didSet {
if isHighlighted {
animatableBackgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.0)
animatableBackgroundView.frame = CGRect(x: 0, y: 0, width: 30, height: frame.height)
animatableBackgroundView.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
UIView.animate(withDuration: 0.5) { [weak self] in
guard let me = self else {
return
}
me.animatableBackgroundView.frame = CGRect(x: 0, y: 0, width: me.frame.width, height: me.frame.height)
me.animatableBackgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.08)
}
} else {
animatableBackgroundView.backgroundColor = animatableBackgroundView.backgroundColor?.withAlphaComponent(0.0)
}
}
}
}
open class YoutubeActionController: ActionController<YoutubeCell, ActionData, UICollectionReusableView, Void, UICollectionReusableView, Void> {
public override init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
collectionViewLayout.minimumLineSpacing = -0.5
settings.behavior.hideOnScrollDown = false
settings.animation.scale = nil
settings.animation.present.duration = 0.6
settings.animation.dismiss.duration = 0.6
settings.animation.dismiss.offset = 30
settings.animation.dismiss.options = .curveLinear
cellSpec = .nibFile(nibName: "YoutubeCell", bundle: Bundle(for: YoutubeCell.self), height: { _ in 46 })
onConfigureCellForAction = { cell, action, indexPath in
cell.setup(action.data?.title, detail: action.data?.subtitle, image: action.data?.image)
cell.alpha = action.enabled ? 1.0 : 0.5
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
import UIKit
// Declaring static variables
// price for the tax, based on this table https://www.theitaliantimes.it/economia/calcolo-bollo-auto-online-quando-pagamento_060619/
let euroStandardPrice = [3.00,2.90,2.80,2.70,2.58,2.58,2.58]
let euroElevatedPrice = [4.50,4.35,4.20,4.05,3.87,3.87,3.87]
let overPrice185kw = [12.0,6.0,3.0,0.0]
func calculatePrice(kw: Double, euro: Int, productionYear: Int) -> Double{
// declaring dynamic variables
var tempUnder100kw = 0.0
var tempOver100kw = 0.0
var priceUnder100kw = 0.0
var priceOver100kw = 0.0
var superPriceOver185kw = 0.0
if(kw - 100 <= 0.0){
// standard tax for kw under 100
tempUnder100kw = kw
priceUnder100kw = tempUnder100kw * euroStandardPrice[euro]
}else{
// adding extra-tax for kw over 100
tempUnder100kw = 100
tempOver100kw = kw - 100
priceUnder100kw = tempUnder100kw * euroStandardPrice[euro]
priceOver100kw = tempOver100kw * euroElevatedPrice[euro]
}
if(kw >= 185){
// adding the extra-tax for kw over 185
let date = Date()
let calendar = Calendar.current
let over185kw = kw - 185
let year = calendar.component(.year, from: date)
let yearPassed = year - productionYear
switch yearPassed {
case 0 ... 5:
superPriceOver185kw = overPrice185kw[0] * over185kw
case 5 ... 10:
superPriceOver185kw = overPrice185kw[0] * over185kw
case 10 ... 15:
superPriceOver185kw = overPrice185kw[0] * over185kw
default:
superPriceOver185kw = 0.0
}
}
// adding all the taxes
return priceOver100kw + priceUnder100kw + superPriceOver185kw
}
let price = calculatePrice(kw: 63.0, euro: 6, productionYear: 2011)
print ("Il bollo per la tua auto è di \(price) €")
|
//
// GenericProtocol.swift
// Driveo
//
// Created by Admin on 6/3/18.
// Copyright © 2018 ITI. All rights reserved.
//
import Foundation
protocol GenericProtocol {
func showAlert(ofError error:ErrorType)->Void
func presentToNextScreen()
}
|
import Foundation
import JavaScriptCore
@objc protocol MusicMakerJSExports: JSExport {
static func playSound(_ file: String)
}
/**
Class exposed to a JS context.
*/
@objc class MusicMaker: NSObject, MusicMakerJSExports {
/// Keeps track of all sounds currently being played.
private static var audioPlayers = Set<AudioPlayer>()
private static var conditionLocks = [String: NSConditionLock]()
/**
Play a specific sound.
This method is exposed to a JS context as `MusicMaker.playSound(_)`.
- parameter file: The sound file to play.
*/
// Create a protocol that inherits JSExport, marking methods/variables
// that should be exposed to a JavaScript VM.
// NOTE: This protocol must be attributed with @objc.
static func playSound(_ file: String) {
guard let player = AudioPlayer(file: file) else {
return
}
// Create a condition lock for this player so we don't return back to JS code until
// the player has finished playing.
let uuid = NSUUID().uuidString
self.conditionLocks[uuid] = NSConditionLock(condition: 0)
player.completion = { player, successfully in
// Now that playback has completed, dispose of the player and change the lock condition to
// "1" to the code below `player.play()`.
self.conditionLocks[uuid]?.lock()
self.audioPlayers.remove(player)
self.conditionLocks[uuid]?.unlock(withCondition: 1)
}
if player.play() {
// Hold a reference to the audio player so it doesn't go out of memory.
self.audioPlayers.insert(player)
// Block this thread by waiting for the condition lock to change to "1", which happens when
// playback is complete.
// Once this happens, dispose of the lock and let control return back to the JS code (which
// was the original caller of `MusicMaker.playSound(...)`).
self.conditionLocks[uuid]?.lock(whenCondition: 1)
self.conditionLocks[uuid]?.unlock()
self.conditionLocks[uuid] = nil
}
}
}
|
//
// AppTheme.swift
// Nightscouter
//
// Created by Peter Ina on 8/4/15.
// Copyright (c) 2015 Peter Ina. All rights reserved.
//
import UIKit
public struct Theme {
public struct Color {
public static let windowTintColor = NSAssetKit.predefinedNeutralColor
public static let headerTextColor = UIColor(white: 1.0, alpha: 0.5)
public static let labelTextColor = UIColor.whiteColor()
public static let navBarColor: UIColor = NSAssetKit.darkNavColor
public static let navBarTextColor: UIColor = UIColor.whiteColor()
}
public struct Font {
static let navBarTitleFont = UIFont(name: "HelveticaNeue-Thin", size: 20.0)
}
}
public class AppThemeManager: NSObject {
public class var themeApp: AppThemeManager {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: AppThemeManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = AppThemeManager()
}
return Static.instance!
}
override init() {
UINavigationBar.appearance().tintColor = Theme.Color.windowTintColor
// Change the font and size of nav bar text.
if let navBarFont = Theme.Font.navBarTitleFont {
let navBarColor: UIColor = Theme.Color.navBarColor
UINavigationBar.appearance().barTintColor = navBarColor
let navBarAttributesDictionary: [String: AnyObject]? = [
NSForegroundColorAttributeName: Theme.Color.navBarTextColor,
NSFontAttributeName: navBarFont
]
UINavigationBar.appearance().titleTextAttributes = navBarAttributesDictionary
}
super.init()
}
}
|
/* Copyright Airship and Contributors */
import Foundation
/// The Config object provides an interface for passing common configurable values to `UAirship`.
/// The simplest way to use this class is to add an AirshipConfig.plist file in your app's bundle and set
/// the desired options.
@objc(UAConfig)
public class Config: NSObject, NSCopying {
/// The development app key. This should match the application on go.urbanairship.com that is
/// configured with your development push certificate.
@objc
public var developmentAppKey: String?
/// The development app secret. This should match the application on go.urbanairship.com that is
/// configured with your development push certificate.
@objc
public var developmentAppSecret: String?
/// The production app key. This should match the application on go.urbanairship.com that is
/// configured with your production push certificate. This is used for App Store, Ad-Hoc and Enterprise
/// app configurations.
@objc
public var productionAppKey: String?
/// The production app secret. This should match the application on go.urbanairship.com that is
/// configured with your production push certificate. This is used for App Store, Ad-Hoc and Enterprise
/// app configurations.
@objc
public var productionAppSecret: String?
/// The log level used for development apps. Defaults to `debug`.
@objc
public var developmentLogLevel: LogLevel = .debug
/// The log level used for production apps. Defaults to `error`.
@objc
public var productionLogLevel: LogLevel = .error
/// The airship cloud site. Defaults to `us`.
@objc
public var site: CloudSite = .us
/// Default enabled Airship features for the app. For more details, see `PrivacyManager`.
/// Defaults to `all`.
@objc
public var enabledFeatures: Features = .all
/// The default app key. Depending on the `inProduction` status,
/// `developmentAppKey` or `productionAppKey` will take priority.
@objc
public var defaultAppKey: String = ""
/// The default app secret. Depending on the `inProduction` status,
/// `developmentAppSecret` or `productionAppSecret` will take priority.
@objc
public var defaultAppSecret: String = ""
/// The production status of this application. This may be set directly, or it may be determined
/// automatically if the `detectProvisioningMode` flag is set to `true`.
/// If neither `inProduction` nor `detectProvisioningMode` is set,
/// `detectProvisioningMode` will be enabled.
@objc
public var inProduction: Bool {
get {
return detectProvisioningMode ? usesProductionPushServer : _inProduction
}
set {
_defaultProvisioningMode = false
_inProduction = newValue
_usesProductionPushServer = nil
}
}
/// Apps may be set to self-configure based on the APS-environment set in the
/// embedded.mobileprovision file by using `detectProvisioningMode`. If
/// `detectProvisioningMode` is set to `true`, the `inProduction` value will
/// be determined at runtime by reading the provisioning profile. If it is set to
/// `false` (the default), the inProduction flag may be set directly or by using the
/// AirshipConfig.plist file.
///
/// When this flag is enabled, the `inProduction` will fallback to `true` for safety
/// so that the production keys will always be used if the profile cannot be read
/// in a released app. Simulator builds do not include the profile, and the
/// `detectProvisioningMode` flag does not have any effect in cases where a profile
/// is not present. When a provisioning file is not present, the app will fall
/// back to the `inProduction` property as set in code or the AirshipConfig.plist
/// file.
@objc
public var detectProvisioningMode: Bool {
get {
return _detectProvisioningMode ?? _defaultProvisioningMode
} set {
_detectProvisioningMode = newValue
}
}
/// NOTE: For internal use only. :nodoc:
@objc
public var profilePath: String? {
didSet {
_usesProductionPushServer = nil
}
}
private var _usesProductionPushServer: Bool?
private var usesProductionPushServer: Bool {
get {
if (_usesProductionPushServer == nil) {
if let profilePath = self.profilePath, profilePath.count > 0, FileManager.default.fileExists(atPath: profilePath) {
_usesProductionPushServer = Config.isProductionProvisioningProfile(profilePath)
} else {
if (self.isSimulator) {
AirshipLogger.error("No profile found for the simulator. Defaulting to inProduction flag: \(self._inProduction)")
_usesProductionPushServer = self._inProduction
} else {
AirshipLogger.error("No profile found, but not a simulator. Defaulting to inProduction = true")
_usesProductionPushServer = true
}
}
}
return _usesProductionPushServer ?? false
}
}
private var _inProduction = false
private var _defaultProvisioningMode = true
private var _detectProvisioningMode: Bool?
/// If enabled, the Airship library automatically registers for remote notifications when push is enabled
/// and intercepts incoming notifications in both the foreground and upon launch.
///
/// Defaults to `true`. If this is disabled, you will need to register for remote notifications
/// in application:didFinishLaunchingWithOptions: and forward all notification-related app delegate
/// calls to UAPush and UAInbox.
@objc
public var isAutomaticSetupEnabled = true
/// An array of `UAURLAllowList` entry strings.
/// This url allow list is used for validating which URLs can be opened or load the JavaScript native bridge.
/// It affects landing pages, the open external URL and wallet actions,
/// deep link actions (if a delegate is not set), and HTML in-app messages.
///
/// - NOTE: See `UAURLAllowList` for pattern entry syntax.
@objc(URLAllowList)
public var urlAllowList: [String] = []
/// An array of` UAURLAllowList` entry strings.
/// This url allow list is used for validating which URLs can load the JavaScript native bridge,
/// It affects Landing Pages, Message Center and HTML In-App Messages.
///
/// - NOTE: See `UAURLAllowList` for pattern entry syntax.
@objc(URLAllowListScopeJavaScriptInterface)
public var urlAllowListScopeJavaScriptInterface: [String] = []
/// An array of UAURLAllowList entry strings.
/// This url allow list is used for validating which URLs can be opened.
/// It affects landing pages, the open external URL and wallet actions,
/// deep link actions (if a delegate is not set), and HTML in-app messages.
///
/// - NOTE: See `UAURLAllowList` for pattern entry syntax.
@objc(URLAllowListScopeOpenURL)
public var urlAllowListScopeOpenURL: [String] = []
/// Whether to suppress console error messages about missing allow list entries during takeOff.
///
/// Defaults to `false`.
@objc
public var suppressAllowListError = false
/// The iTunes ID used for Rate App Actions.
@objc
public var itunesID: String?
/// Toggles Airship analytics. Defaults to `true`. If set to `false`, many Airship features will not be
/// available to this application.
@objc
public var isAnalyticsEnabled = true
/// The Airship default message center style configuration file.
@objc
public var messageCenterStyleConfig: String?
/// If set to `true`, the Airship user will be cleared if the application is
/// restored on a different device from an encrypted backup.
///
/// Defaults to `false`.
@objc
public var clearUserOnAppRestore = false
/// If set to `true`, the application will clear the previous named user ID on a
/// re-install. Defaults to `false`.
@objc
public var clearNamedUserOnAppRestore = false
/// Flag indicating whether channel capture feature is enabled or not.
///
/// Defaults to `true`.
@objc
public var isChannelCaptureEnabled = true
/// Flag indicating whether delayed channel creation is enabled. If set to `true` channel
/// creation will not occur until channel creation is manually enabled.
///
/// Defaults to `false`.
@objc
public var isChannelCreationDelayEnabled = false
/// Flag indicating whether extended broadcasts are enabled. If set to `true` the AirshipReady NSNotification
/// will contain additional data: the channel identifier and the app key.
///
/// Defaults to `false`.
@objc
public var isExtendedBroadcastsEnabled = false
/// Dictionary of custom config values.
@objc
public var customConfig: [AnyHashable : Any] = [:]
/// If set to 'YES', the Airship SDK will request authorization to use
/// notifications from the user. Apps that set this flag to `false` are
/// required to request authorization themselves.
///
/// Defaults to `true`.
@objc
public var requestAuthorizationToUseNotifications = true
/// If set to `true`, the SDK will wait for an initial remote config instead of falling back on default API URLs.
///
/// Defaults to `true`.
@objc
public var requireInitialRemoteConfigEnabled = true
/// The Airship URL used to pull the initial config. This should only be set
/// if you are using custom domains that forward to Airship.
///
@objc
public var initialConfigURL: String?
/// The Airship device API url.
///
/// - Note: This option is reserved for internal debugging. :nodoc:
@objc
public var deviceAPIURL: String?
/// The Airship analytics API url.
///
/// - Note: This option is reserved for internal debugging. :nodoc:
@objc
public var analyticsURL: String?
/// The Airship remote data API url.
///
/// - Note: This option is reserved for internal debugging. :nodoc:
@objc
public var remoteDataAPIURL: String?
/// The Airship chat API URL.
@objc
public var chatURL: String?
/// The Airship web socket URL.
@objc
public var chatWebSocketURL: String?
/// Returns the resolved app key.
/// - Returns: The resolved app key or an empty string.
@objc
public var appKey: String {
get {
let key = inProduction ? productionAppKey : developmentAppKey
return key ?? defaultAppKey
}
}
/// Returns the resolved app secret.
/// - Returns: The resolved app key or an empty string.
@objc
public var appSecret: String {
get {
let secret = inProduction ? productionAppSecret : developmentAppSecret
return secret ?? defaultAppSecret
}
}
/// Returns the resolved log level.
/// - Returns: The resolved log level.
@objc
public var logLevel: LogLevel {
get {
return inProduction ? productionLogLevel : developmentLogLevel
}
}
private var isSimulator: Bool {
get {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}
}
/// Creates an instance using the values set in the `AirshipConfig.plist` file.
/// - Returns: A config with values from `AirshipConfig.plist` file.
@objc(defaultConfig)
public class func `default`() -> Config {
return Config(contentsOfFile: Bundle.main.path(forResource: "AirshipConfig", ofType: "plist"))
}
/**
* Creates an instance using the values found in the specified `.plist` file.
* - Parameter path: The path of the specified file.
* - Returns: A config with values from the specified file.
*/
@objc
public class func config(contentsOfFile path: String?) -> Config {
return Config(contentsOfFile: path)
}
/// Creates an instance with empty values.
/// - Returns: A config with empty values.
@objc
public class func config() -> Config {
return Config()
}
/**
* Creates an instance using the values found in the specified `.plist` file.
* - Parameter path: The path of the specified file.
* - Returns: A config with values from the specified file.
*/
@objc
public convenience init(contentsOfFile path: String?) {
self.init()
if let path = path {
//copy from dictionary plist
if let configDict = NSDictionary(contentsOfFile: path) as? [AnyHashable : Any] {
self.applyConfig(configDict)
}
}
}
/// Creates an instance with empty values.
/// - Returns: A Config with empty values.
@objc
public override init() {
#if !targetEnvironment(macCatalyst)
self.profilePath = Bundle.main.path(forResource: "embedded", ofType: "mobileprovision")
#else
self.profilePath = URL(fileURLWithPath: URL(fileURLWithPath: Bundle.main.resourcePath ?? "").deletingLastPathComponent().path).appendingPathComponent("embedded.provisionprofile").path
#endif
}
init(_ config: Config) {
developmentAppKey = config.developmentAppKey
developmentAppSecret = config.developmentAppSecret
productionAppKey = config.productionAppKey
productionAppSecret = config.productionAppSecret
defaultAppKey = config.defaultAppKey
defaultAppSecret = config.defaultAppSecret
deviceAPIURL = config.deviceAPIURL
remoteDataAPIURL = config.remoteDataAPIURL
initialConfigURL = config.initialConfigURL
chatWebSocketURL = config.chatWebSocketURL
chatURL = config.chatURL
analyticsURL = config.analyticsURL
site = config.site
developmentLogLevel = config.developmentLogLevel
productionLogLevel = config.productionLogLevel
enabledFeatures = config.enabledFeatures
requestAuthorizationToUseNotifications = config.requestAuthorizationToUseNotifications
suppressAllowListError = config.suppressAllowListError
requireInitialRemoteConfigEnabled = config.requireInitialRemoteConfigEnabled
isAutomaticSetupEnabled = config.isAutomaticSetupEnabled
isAnalyticsEnabled = config.isAnalyticsEnabled
clearUserOnAppRestore = config.clearUserOnAppRestore
urlAllowList = config.urlAllowList
urlAllowListScopeJavaScriptInterface = config.urlAllowListScopeJavaScriptInterface
urlAllowListScopeOpenURL = config.urlAllowListScopeOpenURL
clearNamedUserOnAppRestore = config.clearNamedUserOnAppRestore
isChannelCaptureEnabled = config.isChannelCaptureEnabled
customConfig = config.customConfig
isChannelCreationDelayEnabled = config.isChannelCreationDelayEnabled
isExtendedBroadcastsEnabled = config.isExtendedBroadcastsEnabled
messageCenterStyleConfig = config.messageCenterStyleConfig
itunesID = config.itunesID
profilePath = config.profilePath
_detectProvisioningMode = config.detectProvisioningMode
_defaultProvisioningMode = config._defaultProvisioningMode
_inProduction = config._inProduction
}
public func copy(with zone: NSZone? = nil) -> Any {
return Config(self)
}
public override var description: String {
get {
return String(format: """
In Production (resolved): %d\n\
In Production (as set): %d\n\
Resolved App Key: %@\n\
Resolved App Secret: %@\n\
Resolved Log Level: %ld\n\
Default App Key: %@\n\
Default App Secret: %@\n\
Development App Key: %@\n\
Development App Secret: %@\n\
Development Log Level: %ld\n\
Production App Key: %@\n\
Production App Secret: %@\n\
Production Log Level: %ld\n\
Detect Provisioning Mode: %d\n\
Request Authorization To Use Notifications: %@\n\
Suppress Allow List Error: %@\n\
Require initial remote config: %@\n\
Analytics Enabled: %d\n\
Analytics URL: %@\n\
Device API URL: %@\n\
Remote Data API URL: %@\n\
Initial config URL: %@\n\
Automatic Setup Enabled: %d\n\
Clear user on Application Restore: %d\n\
URL Accepts List: %@\n\
URL Accepts List Scope JavaScript Bridge : %@\n\
URL Accepts List Scope Open : %@\n\
Clear named user on App Restore: %d\n\
Channel Capture Enabled: %d\n\
Custom Config: %@\n\
Delay Channel Creation: %d\n\
Extended broadcasts: %d\n\
Default Message Center Style Config File: %@\n\
Use iTunes ID: %@\n\
Site: %ld\n\
Enabled features %ld\n
""", inProduction, inProduction, appKey, appSecret, logLevel.rawValue, defaultAppKey, defaultAppSecret, developmentAppKey ?? "", developmentAppSecret ?? "", developmentLogLevel.rawValue, productionAppKey ?? "", productionAppSecret ?? "", productionLogLevel.rawValue, detectProvisioningMode, requestAuthorizationToUseNotifications ? "YES" : "NO", suppressAllowListError ? "YES" : "NO", requireInitialRemoteConfigEnabled ? "YES" : "NO", isAnalyticsEnabled, analyticsURL ?? "", deviceAPIURL ?? "", remoteDataAPIURL ?? "", initialConfigURL ?? "", isAutomaticSetupEnabled, clearUserOnAppRestore, urlAllowList , urlAllowListScopeJavaScriptInterface, urlAllowListScopeOpenURL, clearNamedUserOnAppRestore, isChannelCaptureEnabled, customConfig, isChannelCreationDelayEnabled, isExtendedBroadcastsEnabled, messageCenterStyleConfig ?? "", itunesID ?? "", site.rawValue, enabledFeatures.rawValue)
}
}
/// Validates the current configuration. In addition to performing a strict validation, this method
/// will log warnings and common configuration errors.
/// - Parameters:
/// - logIssues: `true` to log issues with the config, otherwise `false`
/// - Returns: `true` if the current configuration is valid, otherwise `false`.
@objc
public func validate(logIssues: Bool) -> Bool {
var valid = true
//Check the format of the app key and password.
//If they're missing or malformed, stop takeoff
//and prevent the app from connecting to UA.
let matchPred = NSPredicate(format: "SELF MATCHES %@", "^\\S{22}+$")
if !matchPred.evaluate(with: developmentAppKey), logIssues {
AirshipLogger.warn("Development App Key is not valid.")
}
if !matchPred.evaluate(with: developmentAppSecret), logIssues {
AirshipLogger.warn("Development App Secret is not valid.")
}
if !matchPred.evaluate(with: productionAppKey), logIssues {
AirshipLogger.warn("Production App Key is not valid.")
}
if !matchPred.evaluate(with: productionAppSecret), logIssues {
AirshipLogger.warn("Production App Secret is not valid.")
}
if !matchPred.evaluate(with: appKey) {
if (logIssues) {
AirshipLogger.error("Current App Key \(appKey) is not valid.")
}
valid = false
}
if !matchPred.evaluate(with: appSecret) {
if (logIssues) {
AirshipLogger.error("Current App Secret \(appSecret) is not valid.")
}
valid = false
}
if developmentAppKey == productionAppKey, logIssues {
AirshipLogger.warn("Production App Key matches Development App Key.")
}
if developmentAppSecret == productionAppSecret, logIssues {
AirshipLogger.warn("Production App Secret matches Development App Secret.")
}
if (!self.suppressAllowListError && self.urlAllowList.isEmpty && self.urlAllowListScopeOpenURL.isEmpty), logIssues {
AirshipLogger.impError("The airship config options is missing URL allow list rules for SCOPE_OPEN. By default only Airship, YouTube, mailto, sms, and tel URLs will be allowed. To suppress this error, specify allow list rules by providing rules for URLAllowListScopeOpenURL or URLAllowList. Alternatively you can suppress this error and keep the default rules by using the flag suppressAllowListError. For more information, see https://docs.airship.com/platform/ios/getting-started/#url-allow-list.");
}
return valid
}
/// Validates the current configuration. In addition to performing a strict validation, this method
/// will log warnings and common configuration errors.
/// - Returns: `true` if the current configuration is valid, otherwise `false`.
@objc
public func validate() -> Bool {
return validate(logIssues: true)
}
private func applyConfig(_ keyedValues: [AnyHashable : Any]) {
let oldKeyMap = [
"LOG_LEVEL": "developmentLogLevel",
"PRODUCTION_APP_KEY": "productionAppKey",
"PRODUCTION_APP_SECRET": "productionAppSecret",
"DEVELOPMENT_APP_KEY": "developmentAppKey",
"DEVELOPMENT_APP_SECRET": "developmentAppSecret",
"APP_STORE_OR_AD_HOC_BUILD": "inProduction",
"AIRSHIP_SERVER": "deviceAPIURL",
"ANALYTICS_SERVER": "analyticsURL",
"whitelist": "urlAllowList",
"analyticsEnabled": "isAnalyticsEnabled",
"extendedBroadcastsEnabled": "isExtendedBroadcastsEnabled",
"channelCaptureEnabled": "isChannelCaptureEnabled",
"channelCreationDelayEnabled": "isChannelCreationDelayEnabled",
"automaticSetupEnabled": "isAutomaticSetupEnabled",
"isInProduction": "inProduction",
]
let swiftToObjcMap = [
"urlAllowList": "URLAllowList",
"urlAllowListScopeOpenURL": "URLAllowListScopeOpenURL",
"urlAllowListScopeJavaScriptInterface": "URLAllowListScopeJavaScriptInterface",
]
let mirror = Mirror(reflecting: self)
var propertyInfo: [String : (String, Any.Type)] = [:]
mirror.children.forEach { child in
if let label = child.label {
var normalizedLabel = label
if (normalizedLabel.hasPrefix("_")) {
normalizedLabel.removeFirst()
}
if let objcName = swiftToObjcMap[normalizedLabel] {
normalizedLabel = objcName
}
propertyInfo[normalizedLabel.lowercased()] = (normalizedLabel, type(of: child.value))
}
}
for key in keyedValues.keys {
guard var key = (key as? String) else {
continue
}
guard var value = keyedValues[key] else {
continue
}
if let newKey = oldKeyMap[key] {
AirshipLogger.warn("\(key) is a legacy config key, use \(newKey) instead")
key = newKey
}
// Trim any strings
if let stringValue = value as? String {
value = stringValue.trimmingCharacters(in: CharacterSet.whitespaces)
}
if let propertyInfo = propertyInfo[key.lowercased()] {
let propertyKey = propertyInfo.0
let propertyType = propertyInfo.1
var normalizedValue: Any?
if (propertyType == CloudSite.self || propertyType == CloudSite?.self) {
// we do all the work to parse it to a log level, but setValue(forKey:) does not work for enums
normalizedValue = Config.coerceSite(value)?.rawValue
} else if (propertyType == LogLevel.self || propertyType == LogLevel?.self) {
// we do all the work to parse it to a log level, but setValue(forKey:) does not work for enums
normalizedValue = Config.coerceLogLevel(value)?.rawValue
} else if (propertyType == Features.self || propertyType == Features?.self) {
normalizedValue = Config.coerceFeatures(value)?.rawValue
} else if (propertyType == String.self || propertyType == String?.self) {
normalizedValue = Config.coerceString(value)
} else if (propertyType == Bool.self || propertyType == Bool?.self) {
normalizedValue = Config.coerceBool(value)
} else {
normalizedValue = value
}
if let normalizedValue = normalizedValue {
self.setValue(normalizedValue, forKey: propertyKey)
} else {
AirshipLogger.error("Invalid config \(propertyKey)(\(key)) \(value)")
}
} else {
AirshipLogger.error("Unknown config \(key)")
}
}
}
private class func coerceString(_ value: Any) -> String? {
if let value = value as? String {
return value
}
if let value = value as? Character {
return String(value)
}
return nil
}
private class func coerceBool(_ value: Any) -> Bool? {
if let value = value as? Bool {
return value
}
if let value = value as? NSNumber {
return value.boolValue
}
if let value = value as? String {
let lowerCased = value.lowercased()
if (lowerCased == "true" || lowerCased == "yes") {
return true
} else if (lowerCased == "false" || lowerCased == "no") {
return false
}
}
return nil
}
private class func coerceSite(_ value: Any) -> CloudSite? {
if let site = value as? CloudSite {
return site
}
if let rawValue = value as? Int {
return CloudSite(rawValue: rawValue)
}
if let rawValue = value as? UInt {
return CloudSite(rawValue: Int(rawValue))
}
if let number = value as? NSNumber {
return CloudSite(rawValue: number.intValue)
}
if let string = value as? String {
return CloudSiteNames(rawValue: string.lowercased())?.toSite()
}
return nil
}
private class func coerceLogLevel(_ value: Any) -> LogLevel? {
if let logLevel = value as? LogLevel {
return logLevel
}
if let rawValue = value as? Int {
return LogLevel(rawValue: rawValue)
}
if let rawValue = value as? UInt {
return LogLevel(rawValue: Int(rawValue))
}
if let number = value as? NSNumber {
return LogLevel(rawValue: number.intValue)
}
if let string = value as? String {
if let int = Int(string) {
return LogLevel(rawValue: int)
} else {
return LogLevelNames(rawValue: string.lowercased())?.toLogLevel()
}
}
return nil
}
private class func coerceFeatures(_ value: Any) -> Features? {
if let features = value as? Features {
return features
}
var names: [String]?
if let string = value as? String {
names = string.components(separatedBy: ",")
}
if let array = value as? [String] {
names = array
}
if let names = names {
var features : Features = []
for name in names {
guard let parsedFeatures = FeatureNames(rawValue: name.lowercased())?.toFeatures() else {
return nil
}
features.insert(parsedFeatures)
}
return features
} else {
return nil
}
}
// NOTE: For internal use only. :nodoc:
@objc
public class func isProductionProvisioningProfile(_ profilePath: String) -> Bool {
AirshipLogger.trace("Profile path: \(profilePath)")
// Attempt to read this file as ASCII (rather than UTF-8) due to the binary blocks before and after the plist data
guard let embeddedProfile: String = try? String(contentsOfFile: profilePath, encoding: .ascii) else {
AirshipLogger.info("No mobile provision profile found or the profile could not be read. Defaulting to production mode.")
return true
}
let scanner = Scanner(string: embeddedProfile)
var extractedPlist: NSString?
guard scanner.scanUpTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", into: nil),
scanner.scanUpTo("</plist>", into: &extractedPlist),
let plistData = extractedPlist?.appending("</plist>").data(using: .utf8),
let plistDict = try? PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as? [AnyHashable : Any] else {
AirshipLogger.error("Unable to read provision profile. Defaulting to production mode.")
return true
}
guard let entitlements = plistDict["Entitlements"] as? [AnyHashable : Any] else {
AirshipLogger.error("Unable to read provision profile. Defaulting to production mode.")
return true
}
// Tell the logs a little about the app
if (plistDict["ProvisionedDevices"] != nil) {
if ((entitlements["get-task-allow"] as? Bool) == true) {
AirshipLogger.debug("Debug provisioning profile. Uses the APNS Sandbox Servers.")
} else {
AirshipLogger.debug("Ad-Hoc provisioning profile. Uses the APNS Production Servers.")
}
} else if ((plistDict["ProvisionsAllDevices"] as? Bool) == true) {
AirshipLogger.debug("Enterprise provisioning profile. Uses the APNS Production Servers.")
} else {
AirshipLogger.debug("App Store provisioning profile. Uses the APNS Production Servers.")
}
let apsEnvironment = entitlements["aps-environment"] as? String
if (apsEnvironment == nil) {
AirshipLogger.warn("aps-environment value is not set. If this is not a simulator, ensure that the app is properly provisioned for push")
}
AirshipLogger.debug("APS Environment set to \(apsEnvironment ?? "")")
return "development" != apsEnvironment
}
public override func setValue(_ value: Any?, forUndefinedKey key: String) {
switch(key) {
case "openURLWhitelistingEnabled":
AirshipLogger.warn("The config key openURLWhitelistingEnabled has been removed. Use URLAllowListScopeJavaScriptInterface or URLAllowListScopeOpenURL instead")
case "dataCollectionOptInEnabled":
AirshipLogger.warn("The config key dataCollectionOptInEnabled has been removed. Use enabledFeatures instead.")
default:
break
}
AirshipLogger.debug("Ignoring invalid Config key: \(key)")
}
}
private enum LogLevelNames : String {
case undefined
case none
case error
case warn
case info
case debug
case trace
func toLogLevel() -> LogLevel {
switch(self) {
case .undefined:
return LogLevel.undefined
case .debug:
return LogLevel.debug
case .none:
return LogLevel.none
case .error:
return LogLevel.error
case .warn:
return LogLevel.warn
case .info:
return LogLevel.info
case .trace:
return LogLevel.trace
}
}
}
private enum FeatureNames : String {
case push
case chat
case contacts
case location
case messageCenter = "message_center"
case analytics
case tagsAndAttributes = "tags_and_attributes"
case inAppAutomation = "in_app_automation"
case none
case all
func toFeatures() -> Features {
switch self {
case .push:
return Features.push
case .chat:
return Features.chat
case .contacts:
return Features.contacts
case .location:
return Features.location
case .messageCenter:
return Features.messageCenter
case .analytics:
return Features.analytics
case .tagsAndAttributes:
return Features.tagsAndAttributes
case .inAppAutomation:
return Features.inAppAutomation
case .none:
return []
case .all:
return Features.all
}
}
}
private enum CloudSiteNames : String {
case eu
case us
func toSite() -> CloudSite {
switch (self) {
case .eu:
return CloudSite.eu
case .us:
return CloudSite.us
}
}
}
|
//
// LocationService.swift
// DailyLifeV2
//
// Created by Lý Gia Liêm on 8/20/19.
// Copyright © 2019 LGL. All rights reserved.
//
import Foundation
import CoreLocation
import AlamofireObjectMapper
import Alamofire
class WeatherApiService {
let weatherTitles = ["time", "summary", "latitude", "longitude", "temperature", "humidity", "pressure", "nearest Storm Distance", "precip Intensity", "precip Type", "precip Probability", "dew point", "wind Bearing", "ozone", "cloud Cover", "visibility", "UV Index"]
func getWeatherApi(latitude: Double, longitude: Double, completion: @escaping (DarkSkyApi) -> Void) {
let totalUrl = URL(string: "\(URL_API.DarkSkyAPI.keyAndPath.path)\(URL_API.DarkSkyAPI.keyAndPath.key)/\(latitude),\(longitude)/?exclude=hourly,minutely,alerts,flags&units=ca")
guard let url = totalUrl else {return}
Alamofire.request(url).validate().responseObject { (response: DataResponse<DarkSkyApi>) in
if response.result.error == nil {
guard let weatherResponse = response.result.value else {return}
completion(weatherResponse)
} else {
debugPrint(response.result.error!.localizedDescription)
}
}
}
func getHourlyDarkSkyApi(latitude: Double, longitude: Double, completion: @escaping (HourlyDarkSkyApi) -> Void) {
guard let url = URL(string: "\(URL_API.DarkSkyAPI.keyAndPath.path)\(URL_API.DarkSkyAPI.keyAndPath.key)/\(latitude),\(longitude)/?exclude=daily,currently,minutely,alerts,flags&units=si") else {return}
Alamofire.request(url).validate().responseObject {(response: DataResponse<HourlyDarkSkyApi>) in
if response.result.error == nil {
guard let hourlyData = response.result.value else {return}
completion(hourlyData)
} else {
debugPrint(response.result.error!.localizedDescription)
}
}
}
func getCountryForecastApi(nameOfCountry: String, completion: @escaping (ForecastApi) -> Void) {
let url = "\(URL_API.ApixuAPI.keyAndPath.path).json?key=\(URL_API.ApixuAPI.keyAndPath.key)&q=\(nameOfCountry.replacingOccurrences(of: " ", with: "%20"))&days=7"
guard let urlRequest = URL(string: url) else {return}
URLSession.shared.dataTask(with: urlRequest) {(data, _, error) in
if error == nil {
guard let data = data else {return}
do {
let dataDecoded = try JSONDecoder().decode(ForecastApi.self, from: data)
completion(dataDecoded)
} catch let jsonError {
debugPrint("JSON ERROR: ", jsonError, "Error: ", error ?? Error())
}
}
}.resume()
}
func getIconJson(completion: @escaping ([IconApi]) -> Void) {
let urlRequest = URL(string: "http://www.apixu.com/doc/Apixu_weather_conditions.json")
guard let url = urlRequest else {return}
URLSession.shared.dataTask(with: url) { (data, _, error) in
guard let data = data else {return}
do {
let dataDecoded = try JSONDecoder().decode([IconApi].self, from: data)
completion(dataDecoded)
} catch {
debugPrint("ErrorCallAPi: \(String(describing: error))")
}
}.resume()
}
}
|
import Foundation
class PipelineDataDeserializer {
func deserialize(_ data: Data) -> (pipelines: [Pipeline]?, error: DeserializationError?) {
var pipelinesJSONObject: Any?
do {
pipelinesJSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch { }
guard let pipelinesJSON = pipelinesJSONObject as? Array<NSDictionary> else {
return (nil, DeserializationError(details: "Could not interpret data as JSON dictionary", type: .invalidInputFormat))
}
var pipelines = [Pipeline]()
for pipelineDictionary in pipelinesJSON {
guard let pipelineName = pipelineDictionary["name"] as? String else { continue }
pipelines.append(Pipeline(name: pipelineName))
}
return (pipelines, nil)
}
}
|
//
// TimelineViewController.swift
// J.YoutubeWatcher
//
// Created by JinYoung Lee on 21/02/2019.
// Copyright © 2019 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
class TimelineVideoController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var timelineTableView: UITableView!
@IBOutlet weak var backgroundView: UIView!
private let videoFetcher:YoutubeVideoFetcher = YoutubeVideoFetcher()
private final let PreLoadCount = 1
private var whileLoadMore:Bool = false
override var prefersStatusBarHidden: Bool {
return false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
timelineTableView.delegate = self
timelineTableView.dataSource = self
timelineTableView.rowHeight = UITableView.automaticDimension
timelineTableView.estimatedRowHeight = UIScreen.main.bounds.height
searchBar.delegate = self
loadData()
backgroundView.isHidden = true
backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onClickBackground)))
}
@objc private func onClickBackground() {
if searchBar.canResignFirstResponder {
searchBar.resignFirstResponder()
}
backgroundView.isHidden = true
}
private func startSearch(_ searchWord:String) {
}
override func viewWillAppear(_ animated: Bool) {
}
override func viewWillDisappear(_ animated: Bool) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let cell = sender as? UITableViewCell {
if let videoPlayer = segue.destination as? VideoPlayerViewController {
if let indexPath = timelineTableView.indexPath(for: cell) {
videoPlayer.setData(videoFetcher.getModelAt(indexPath.row) as! YoutubeVideoData)
}
}
}
}
}
extension TimelineVideoController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoFetcher.getDataCount() + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == videoFetcher.getDataCount() {
if let refreshCell: TimelineRefreshCell = tableView.dequeueReusableCell(withIdentifier: "id_refreshCell", for: indexPath) as? TimelineRefreshCell {
refreshCell.startAnimate()
return refreshCell
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: "id_timelineVideoCell", for: indexPath) as! TimelineVideoCell
if let data = videoFetcher.getModelAt(indexPath.row) as? YoutubeVideoData {
cell.setData(data)
}
if indexPath.row == videoFetcher.getDataCount() - 1 {
loadModelIfNeed()
}
return cell
}
private func loadModelIfNeed() {
guard !whileLoadMore else {
return
}
whileLoadMore = true
loadData()
}
private func loadData() {
videoFetcher.loadModel { [weak self](contentList) in
guard let strongSelf = self else {
return
}
strongSelf.timelineTableView.reloadData()
strongSelf.whileLoadMore = false
}
}
}
extension TimelineVideoController: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//
// let currentOffset = scrollView.contentOffset.y
// let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
//
// if maximumOffset - currentOffset <= 10 {
// self.loadModelIfNeed()
// }
}
}
extension TimelineVideoController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
backgroundView.isHidden = false
searchBar.becomeFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
backgroundView.isHidden = true
searchBar.resignFirstResponder()
if let searchKeyword = searchBar.text {
guard !searchKeyword.isEmpty else {
return
}
videoFetcher.SearchKeyWord = searchKeyword
videoFetcher.clearData()
timelineTableView.reloadData()
loadData()
}
}
}
extension UINavigationController {
open override var prefersStatusBarHidden: Bool {
return topViewController?.prefersStatusBarHidden ?? true
}
}
|
//
// ArtistaDashboardController.swift
// IVO
//
// Created by user on 12/30/16.
// Copyright © 2016 3dlink. All rights reserved.
//
import Foundation
import UIKit
class ArtistaDashboardController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var talents = ["1", "2", "3"]
var provider = ["1", "2", "3"]
var followers = ["1", "2"]
var following = ["1", "2"]
@IBOutlet weak var TitleCastingHeight: NSLayoutConstraint!
@IBOutlet weak var TitleCastingWidth: NSLayoutConstraint!
@IBOutlet weak var TitleProviderHeight: NSLayoutConstraint!
@IBOutlet weak var TitleProviderWidth: NSLayoutConstraint!
@IBOutlet weak var VArtist: UIView!
@IBOutlet weak var VArtistHeight: NSLayoutConstraint!
@IBOutlet weak var CVArtist: UICollectionView!
@IBOutlet weak var VProvider: UIView!
@IBOutlet weak var CVProvider: UICollectionView!
@IBOutlet weak var VProviderHeight: NSLayoutConstraint!
@IBOutlet weak var VFollowers: UIView!
@IBOutlet weak var CVFollowers: UICollectionView!
@IBOutlet weak var VFollowersHeight: NSLayoutConstraint!
@IBOutlet weak var VFollowing: UIView!
@IBOutlet weak var CVFollowing: UICollectionView!
@IBOutlet weak var VFollowingHeight: NSLayoutConstraint!
override func viewDidLoad() {
if ( UIDevice.current.userInterfaceIdiom == .pad ) {
self.TitleCastingHeight.constant = 45
self.TitleCastingWidth.constant = 160
self.TitleProviderHeight.constant = 45
self.TitleProviderWidth.constant = 260
self.VArtist.layoutIfNeeded()
self.VArtistHeight.constant = 220 * 3
self.VProvider.layoutIfNeeded()
self.VProviderHeight.constant = VProvider.frame.size.width / 3 + ( 100 )
self.VFollowers.layoutIfNeeded()
self.VFollowersHeight.constant = VFollowers.frame.size.width / 2 + ( 102 )
self.VFollowing.layoutIfNeeded()
self.VFollowingHeight.constant = VFollowing.frame.size.width / 2 + ( 102 )
}
else{
self.VArtist.layoutIfNeeded()
self.VArtistHeight.constant = 110 * 3
self.VProvider.layoutIfNeeded()
self.VProviderHeight.constant = VProvider.frame.size.width / 3 + ( 90 )
self.VFollowers.layoutIfNeeded()
self.VFollowersHeight.constant = VFollowers.frame.size.width / 2 + ( 51 )
self.VFollowing.layoutIfNeeded()
self.VFollowingHeight.constant = VFollowing.frame.size.width / 2 + ( 51 )
}
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if ( UIDevice.current.userInterfaceIdiom == .pad ) {
if collectionView.tag == 1 {
return CGSize(width: VArtist.frame.size.width, height: 220)
}
else if collectionView.tag == 2{
return CGSize(width: VProvider.frame.size.width / 3, height: (VProvider.frame.size.width / 3) + 100 )
}
else{
return CGSize(width: VFollowers.frame.size.width / 2, height: (VFollowers.frame.size.width / 2) + 102 )
}
}
else{
if collectionView.tag == 1 {
return CGSize(width: VArtist.frame.size.width, height: 110)
}
else if collectionView.tag == 2{
return CGSize(width: VProvider.frame.size.width / 3, height: (VProvider.frame.size.width / 3) + 71 )
}
else{
return CGSize(width: VFollowers.frame.size.width / 2, height: (VFollowers.frame.size.width / 2) + 51 )
}
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(-0.05,-0.05,-0.05,-0.05)
}
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView.tag == 1{
return self.talents.count
}
else if collectionView.tag == 2{
return self.provider.count
}
else if collectionView.tag == 3{
return self.followers.count
}
else{
return self.following.count
}
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView.tag == 1{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "talent", for: indexPath as IndexPath) as! ArtistGridList
if ( UIDevice.current.userInterfaceIdiom == .pad ) {
cell.LTagHeight.constant = 30
cell.BReadMoreHeight.constant = 25
cell.BReadMoreWidth.constant = 150
}
cell.content.text = "MÚSICA"
return cell
}
else if collectionView.tag == 2{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "provider", for: indexPath as IndexPath) as! TalentsGrid
cell.talentName.text = "Catherine Lewis"
if ( UIDevice.current.userInterfaceIdiom == .pad ) {
cell.LTalentTagHeight.constant = 24
cell.LTalentNameHeight.constant = 34
cell.LTalentOtherHeight.constant = 34
}
return cell
}
else if collectionView.tag == 3{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "follower", for: indexPath as IndexPath) as! FollowGrid
if ( UIDevice.current.userInterfaceIdiom == .pad ) {
cell.LFollowTagHeight.constant = 35
cell.LFollowNameHeight.constant = 35
cell.LFollowOtherHeight.constant = 35
}
cell.followName.text = "Music Records"
return cell
}
else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "following", for: indexPath as IndexPath) as! FollowGrid
if ( UIDevice.current.userInterfaceIdiom == .pad ) {
cell.LFollowTagHeight.constant = 35
cell.LFollowNameHeight.constant = 35
cell.LFollowOtherHeight.constant = 35
}
cell.followName.text = "Music Records"
return cell
}
//
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController!.navigationBar.isHidden = false
self.navigationItem.setHidesBackButton(true, animated:false);
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
let image = UIImage(named: "LogoTop.png")
imageView.image = image
imageView.contentMode = UIViewContentMode.scaleAspectFit
navigationItem.titleView = imageView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// MainView.swift
// MedDesktop
//
// Created by Igor Ogai on 05.07.2021.
//
import UIKit
class MainView: UIView {
//MARK:- Private Properties
private lazy var fullNameHeaderLabel: UILabel = {
let label = UILabel()
label.text = "ФИО пациента"
label.textColor = .black
label.textAlignment = .left
label.font = UIFont(name: "HelveticaNeue-Medium", size: 30)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var dateOfBirthHeaderLabel: UILabel = {
let label = UILabel()
label.text = "Дата рождения"
label.textColor = .black
label.textAlignment = .right
label.font = UIFont(name: "HelveticaNeue-Medium", size: 30)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var ageHeaderLabel: UILabel = {
let label = UILabel()
label.text = "Возраст"
label.textColor = .black
label.textAlignment = .right
label.font = UIFont(name: "HelveticaNeue-Medium", size: 30)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var cardNumberHeaderLabel: UILabel = {
let label = UILabel()
label.text = "№"
label.textColor = .black
label.textAlignment = .left
label.font = UIFont(name: "HelveticaNeue-Medium", size: 30)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private(set) lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.register(PatientCell.self, forCellReuseIdentifier: PatientCell.reuseIdentifier)
tableView.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)
return tableView
}()
//MARK:- Initializers
init() {
super.init(frame: .zero)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- Private Methods
private func setup() {
backgroundColor = .white
tableView.keyboardDismissMode = .onDrag
addSubview(fullNameHeaderLabel)
addSubview(dateOfBirthHeaderLabel)
addSubview(ageHeaderLabel)
addSubview(cardNumberHeaderLabel)
addSubview(tableView)
fullNameHeaderLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
dateOfBirthHeaderLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
NSLayoutConstraint.activate([
cardNumberHeaderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 16),
cardNumberHeaderLabel.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
cardNumberHeaderLabel.widthAnchor.constraint(equalToConstant: 70),
fullNameHeaderLabel.leftAnchor.constraint(equalTo: cardNumberHeaderLabel.rightAnchor, constant: 8),
fullNameHeaderLabel.centerYAnchor.constraint(equalTo: cardNumberHeaderLabel.centerYAnchor),
dateOfBirthHeaderLabel.centerYAnchor.constraint(equalTo: fullNameHeaderLabel.centerYAnchor),
dateOfBirthHeaderLabel.leftAnchor.constraint(equalTo: fullNameHeaderLabel.rightAnchor, constant: 8),
ageHeaderLabel.centerYAnchor.constraint(equalTo: dateOfBirthHeaderLabel.centerYAnchor),
ageHeaderLabel.leftAnchor.constraint(equalTo: dateOfBirthHeaderLabel.rightAnchor, constant: 8),
ageHeaderLabel.widthAnchor.constraint(equalToConstant: 150),
ageHeaderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -16),
tableView.leftAnchor.constraint(equalTo: leftAnchor),
tableView.rightAnchor.constraint(equalTo: rightAnchor),
tableView.topAnchor.constraint(equalTo: fullNameHeaderLabel.bottomAnchor, constant: 8),
tableView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
|
//
// CategoriesViewController.swift
// NasiShadchanHelper
//
// Created by user on 4/24/20.
// Copyright © 2020 user. All rights reserved.
//
import UIKit
import Firebase
import ObjectMapper
class CategoriesViewController: UIViewController {
var ref: DatabaseReference!
var messages = [[String: Any]]()
//var arrGirlsList = [NasiGirlsList]()
var arrayOfNasiGirls = [NasiGirl]()
override func viewDidLoad() {
super.viewDidLoad()
fetchAndCreateNasiGirlsArray()
}
func fetchAndCreateNasiGirlsArray() {
self.view.showLoadingIndicator()
let allNasiGirlsRef = Database.database().reference().child("NasiGirlsList")
allNasiGirlsRef.observe(.value, with: { snapshot in
var nasiGirlsArray: [NasiGirl] = []
for child in snapshot.children {
let snapshot = child as? DataSnapshot
//print("the state of snapshot is \(snapshot?.description)")
let nasiGirl = NasiGirl(snapshot: snapshot!)
nasiGirlsArray.append(nasiGirl)
}
self.arrayOfNasiGirls = nasiGirlsArray
self.view.hideLoadingIndicator()
self.setBadgeCount()
})
}
/*
func fetchList() {
self.view.showLoadingIndicator()
ref = Database.database().reference()
ref.child("NasiGirlsList").observeSingleEvent(of: .value, with: { (snapshot) in
self.view.hideLoadingIndicator()
if ( snapshot.value is NSNull ) {
print("– – – Data was not found – – –")
} else {
var message = [String: Any]()
for nasigirls_child in (snapshot.children) {
let user_snap = nasigirls_child as! DataSnapshot
let dict = user_snap.value as! [String: String?]
// extract the value for key dateOfBirth
if let strDOB = dict["dateOfBirth"] {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "MM-dd-yyyy"
let someDate = strDOB
if dateFormatterGet.date(from: someDate!) != nil {
// valid format
// pass the s
let age = calculateAgeFrom(dobString: dict["dateOfBirth"]! ?? "")
// add age to dict using key dateOfBirthh
message["dateOfBirth"] = age
} else {
// invalid format
message["dateOfBirth"] = 0.0
}
} else {
message["dateOfBirth"] = 0
// print("here is not exist")
}
message["briefDescriptionOfWhatGirlIsLike"] = dict["briefDescriptionOfWhatGirlIsLike"] as? String
message["briefDescriptionOfWhatGirlIsLookingFor"] = dict["briefDescriptionOfWhatGirlIsLookingFor"] as? String
message["category"] = dict["category"] as? String
message["cellNumberOfContactToReddShidduch"] = dict["cellNumberOfContactToReddShidduch"] as? String
message["cellNumberOfContactWhoKNowsGirl"] = dict["cellNumberOfContactWhoKNowsGirl"] as? String
message["cityOfResidence"] = dict["cityOfResidence"] as? String
message["currentGirlUID"] = dict["currentGirlUID"] as? String
message["documentDownloadURLString"] = dict["documentDownloadURLString"] as? String
message["emailOfContactToReddShidduch"] = dict["emailOfContactToReddShidduch"] as? String
message["emailOfContactWhoKnowsGirl"] = dict["emailOfContactWhoKnowsGirl"] as? String
message["firstNameOfGirl"] = dict["firstNameOfGirl"] as? String
message["firstNameOfPersonToContactToReddShidduch"] = dict["firstNameOfPersonToContactToReddShidduch"] as? String
message["fullhebrewNameOfGirlAndMothersHebrewName"] = dict["fullhebrewNameOfGirlAndMothersHebrewName"] as? String
message["girlsCellNumber"] = dict["girlsCellNumber"] as? String
message["girlsEmailAddress"] = dict["girlsEmailAddress"] as? String
message["heightInFeet"] = dict["heightInFeet"] as? String
message["heightInInches"] = dict["heightInInches"] as? String
message["imageDownloadURLString"] = dict["imageDownloadURLString"] as? String
message["lastNameOfGirl"] = dict["lastNameOfGirl"] as? String
message["lastNameOfPersonToContactToReddShidduch"] = dict["lastNameOfPersonToContactToReddShidduch"] as? String
message["middleNameOfGirl"] = dict["middleNameOfGirl"] as? String
message["nameSheIsCalledOrKnownBy"] = dict["nameSheIsCalledOrKnownBy"] as? String
message["plan"] = dict["plan"] as? String
message["relationshipOfThisContactToGirl"] = dict["relationshipOfThisContactToGirl"] as? String
message["seminaryName"] = dict["seminaryName"] as? String
message["stateOfResidence"] = dict["stateOfResidence"] as? String
message["yearsOfLearning"] = dict["yearsOfLearning"] as? String
message["zipCode"] = dict["zipCode"] as? String
message["firstNameOfAContactWhoKnowsGirl"] = dict["firstNameOfAContactWhoKnowsGirl"] as? String
message["girlFamilyBackground"] = dict["girlFamilyBackground"] as? String
message["girlFamilySituation"] = dict["girlFamilySituation"] as? String
message["koveahIttim"] = dict["koveahIttim"] as? String
message["lastNameOfAContactWhoKnowsGirl"] = dict["lastNameOfAContactWhoKnowsGirl"] as? String
message["livingInIsrael"] = dict["livingInIsrael"] as? String
message["professionalTrack"] = dict["professionalTrack"] as? String
// add message dict to
// array of messages dict
self.messages.append(message)
}
if self.messages.count > 0 {
let model = Mapper<NasiGirlsList>().mapArray(JSONArray: self.messages as [[String : AnyObject]])
// assign the array of dict to
// arrGirlsList
self.arrGirlsList = model
Variables.sharedVariables.arrList = self.arrGirlsList
self.setBadgeCount()
}
}
}) { (error) in
print(error.localizedDescription)
}
}
*/
// MARK: -Status Bar Style
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
func setBadgeCount() {
if let tabItems = self.tabBarController?.tabBar.items {
if arrayOfNasiGirls.count > 0 {
let tabItem = tabItems[0]
tabItem.badgeValue = "\(arrayOfNasiGirls.count)" // set Badge count you need
}
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AllNasiGirls" {
let controller = segue.destination as! AllNasiGirlsViewController
controller.allNasiGirlsList = arrayOfNasiGirls
}
if segue.identifier == "ShowFullTimeYeshiva" {
/*
Analytics.logEvent("categories_action", parameters: [
"item_name": "Full Time Yeshiva",
])
*/
let controller = segue.destination as! FullTimeYeshivaViewController
controller.arrGirlsList = arrayOfNasiGirls
} else if segue.identifier == "ShowFullTimeCollege/Working" {
/*
Analytics.logEvent("categories_action", parameters: [
"item_name": "Full Time College/Working",
])
*/
let controller = segue.destination as! FullTimeCollegeWorkingViewController
controller.arrGirlsList = arrayOfNasiGirls
} else if segue.identifier == "ShowYeshivaAndCollege/Working" {
/*
Analytics.logEvent("categories_action", parameters: [
"item_name": "Yeshiva And College/Working",
])
*/
let controller = segue.destination as! YeshivaAndCollegeWorkingViewController
controller.arrGirlsList = arrayOfNasiGirls
}
}
}
// MARK:- IBActions
extension CategoriesViewController {
@IBAction func btnlogoutAction(_ sender: Any) {
let alertControler = UIAlertController.init(title:"Logout", message: Constant.ValidationMessages.msgLogout, preferredStyle:.alert)
alertControler.addAction(UIAlertAction.init(title:"Yes", style:.default, handler: { (action) in
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
// removes it from user defaults
UserInfo.resetCurrentUser()
// make the authVC the rootVC
AppDelegate.instance().makingRootFlow(Constant.AppRootFlow.kAuthVc)
}))
alertControler.addAction(UIAlertAction.init(title:"No", style:.destructive, handler: { (action) in
}))
self.present(alertControler,animated:true, completion:nil)
}
}
|
//
// GitHubSearchViewReactor.swift
// RxMVVMDemo
//
// Created by mengxiangjian on 2018/11/2.
// Copyright © 2018 mengxiangjian. All rights reserved.
//
import Foundation
import ReactorKit
import RxCocoa
import RxSwift
class GitHubSearchViewReactor: Reactor {
var initialState = State()
enum Action {
case update(String?)
case loadMore
}
enum Mutation {
case setRepos([String], Int)
case setMoreRepos([String], Int)
case setIsLoading(Bool)
case setQuery(String?)
}
struct State {
var repos : [String] = []
var nextPage = 1
var query : String?
var isLoading = false
}
func mutate(action: Action) -> Observable<Mutation> {
switch action {
case let .update(query) :
guard query?.lengthOfBytes(using: .utf8) ?? 0 > 0 else {return Observable.empty()}
return Observable.concat([
Observable.just(Mutation.setQuery(query)),
self.search(query: query, page: 1).map {
return Mutation.setRepos($0, $1)
}])
case .loadMore :
guard !self.currentState.isLoading else {return Observable.empty()}
guard let query = self.currentState.query else {return Observable.empty()}
guard self.currentState.nextPage > 0 else {return Observable.empty()}
return Observable.concat([
Observable.just(Mutation.setIsLoading(true)),
self.search(query: query, page: self.currentState.nextPage).map {
return Mutation.setMoreRepos($0, $1)
},
Observable.just(Mutation.setIsLoading(false))
])}
}
func reduce(state: State, mutation: Mutation) -> State {
switch mutation {
case let .setRepos(repos, nextPage):
var newState = state
newState.repos = repos
newState.nextPage = nextPage
return newState
case let .setMoreRepos(repos, nextPage):
var newState = state
newState.repos.append(contentsOf: repos)
newState.nextPage = nextPage
newState.isLoading = false
return newState
case let .setIsLoading(isLoading):
var newState = state
newState.isLoading = isLoading
return newState
case let .setQuery(query):
var newState = state
newState.query = query
return newState
}
}
func search(query: String?, page: Int) -> Observable<(repos:[String], nextPage:Int)> {
let emptyResult : ([String], Int) = ([], 1)
guard let query = query else {
return .just(emptyResult)
}
guard let url = Endpoint.search(query: query, page: page).url else {
return .just(emptyResult)
}
return URLSession.shared.rx.json(url: url).map {
json in
guard let dict = json as? [String:Any] else { return emptyResult }
guard let items = dict["items"] as? [[String:Any]] else { return emptyResult }
let repos = items.compactMap { $0["full_name"] as? String}
let nextPage = repos.isEmpty ? 0 : page + 1
return (repos, nextPage)
}.catchErrorJustReturn(([], page))
}
}
struct Endpoint {
let path : String
let queryItems: [URLQueryItem]
var url : URL? {
var component = URLComponents()
component.scheme = "https"
component.host = "api.github.com"
component.path = path
component.queryItems = queryItems
return component.url
}
}
extension Endpoint {
static func search(query:String, page:Int) -> Endpoint {
return Endpoint(path: "/search/repositories",
queryItems: [URLQueryItem(name: "q", value: query),
URLQueryItem(name: "page", value: "\(page)")])
}
}
|
import Bow
import SwiftCheck
// MARK: Generator for Property-based Testing
extension Zipper: Arbitrary where A: Arbitrary {
public static var arbitrary: Gen<Zipper<A>> {
Gen.zip([A].arbitrary, A.arbitrary, [A].arbitrary)
.map(Zipper.init(left:focus:right:))
}
}
// MARK: Instance of ArbitraryK for ArrayK
extension ZipperPartial: ArbitraryK {
public static func generate<A: Arbitrary>() -> ZipperOf<A> {
Zipper<A>.arbitrary.generate
}
}
|
//
// HomeViewController.swift
// BeforAfter
//
// Created by 石井晃 on 2015/05/23.
// Copyright (c) 2015年 Mobile Interaction Researcher. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
private var timelines: [Timeline] = []
@IBOutlet weak var tableView: UITableView!
// MARK: - View cycle
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
BAAPIManager.getTimelineWithSuccess({ (timelines: [AnyObject]!) -> Void in
var timelinesBuf: [Timeline] = []
for timeline in timelines {
if let timelineDictionary = timeline as? NSDictionary {
timelinesBuf += [Timeline(dictionary: timelineDictionary)]
}
}
self.timelines = timelinesBuf
self.tableView.reloadData()
}, failure: { (error: NSError?) -> Void in
println("ERROR: \(error)")
return
})
}
// MARK: - TableView data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return timelines.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MainCell", forIndexPath: indexPath) as! HomeViewTableCell
cell.timeline = timelines[indexPath.row]
return cell
}
// MARK: - TableView delegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return tableView.frame.size.width + 37 + 60
}
}
class HomeViewTableCell: UITableViewCell {
var timeline: Timeline? {
didSet {
if let unwrappedTimeline = timeline {
self.animatedImageView.animatedImage = nil
animatedImageURL = unwrappedTimeline.gifURL
nameLabel.text = unwrappedTimeline.userName
}
}
}
private var animatedImageURL: NSURL? {
didSet {
if let unwrappedURL = animatedImageURL {
SDWebImageDownloader.sharedDownloader().downloadImageWithURL(unwrappedURL, options: SDWebImageDownloaderOptions.UseNSURLCache, progress: { (expectedSize: Int, receivedSize: Int) -> Void in
//println("\()")
}, completed: { (image: UIImage!, data: NSData!, error: NSError!, finished: Bool) -> Void in
self.animatedImageView.animatedImage = FLAnimatedImage(GIFData: data)
})
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// let animatedImage = FLAnimatedImage(GIFData: NSData(contentsOfURL: unwrappedURL))
//
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.animatedImageView.animatedImage = animatedImage
// return
// })
// })
}
}
}
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var commentButton: UIButton!
@IBOutlet weak var animatedImageView: FLAnimatedImageView!
override func awakeFromNib() {
likeButton.setTitle(ion_ios_heart_outline, forState: .Normal)
commentButton.setTitle(ion_ios_chatbubble_outline, forState: .Normal)
animatedImageView.contentMode = .ScaleAspectFill
}
@IBAction func didTouchLikeButton(sender: AnyObject) {
println("like")
}
@IBAction func didTouchCommentButton(sender: AnyObject) {
println("comment")
}
}
class Timeline {
var gifURL: NSURL
var likeNum: Int
var title: String?
var description: String?
var userName: String?
init(dictionary: NSDictionary) {
gifURL = NSURL(string: dictionary["pic"]! as! String)!
likeNum = dictionary["like_num"]!.integerValue
title = dictionary["title"] as? String
description = dictionary["description"] as? String
userName = dictionary["user_name"] as? String
}
}
|
//
// UsefulLinkCell.swift
// companion
//
// Created by Uchenna Aguocha on 11/14/18.
// Copyright © 2018 Yves Songolo. All rights reserved.
//
import Foundation
import UIKit
class UsefulLinkSectionCell: UITableViewCell {
// MARK: Properties
static let cellId = "UsefulLinkCellId"
// MARK: UI Element
let userLinkButton: UIButton = {
let button = UIButton()
button.setTitle("Useful Links", for: .normal)
button.setTitleColor(MakeSchoolDesignColor.faintBlue, for: .normal)
button.layer.cornerRadius = 6
button.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 23)
button.backgroundColor = MakeSchoolDesignColor.lightBlue
return button
}()
// MARK: Initializers
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Layout Methods
override func layoutSubviews() {
backgroundColor = MakeSchoolDesignColor.faintBlue
setupAutoLayout()
}
// MARK: Methods
fileprivate func setupAutoLayout() {
contentView.addSubview(userLinkButton)
userLinkButton.anchor(top: contentView.topAnchor, right: contentView.rightAnchor, bottom: contentView.bottomAnchor, left: contentView.leftAnchor, topPadding: 20, rightPadding: 52, bottomPadding: 20, leftPadding: 52, height: 60, width: 0)
}
}
|
import UIKit
import FriendTabFramework
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let bundle = Bundle(for: MainViewController.self)
let storyboard = UIStoryboard(name: "Main", bundle: bundle)
let vc = storyboard.instantiateInitialViewController()!
PlaygroundPage.current.liveView = vc
|
/**
Copyright Alexander Oldroyd 2020
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
extension DataFrame {
public static func == (lhs: DataFrame, rhs: DataFrame) -> Bool {
guard lhs.columns == rhs.columns,
lhs.data == rhs.data,
lhs.totalRows == rhs.totalRows else{
return false
}
return true
}
}
|
//
// InvocationCounterSinceEver.swift
// Invoke
//
// Created by Gruppioni Michele on 14/08/16.
//
//
import Foundation
final class InvocationCounterSinceEver {
fileprivate let kInvocationsLabels = "kInvocationsLabels"
fileprivate let kInvocationsCountPrefix = "kInvocationsLabelsCount."
fileprivate var keychain: KeychainSwift
init(keychainPrefix: String? = nil) {
keychain = KeychainSwift(keyPrefix: keychainPrefix ?? "invoke")
}
}
// MARK: InvocationCounter
extension InvocationCounterSinceEver: InvocationCounter {
var allInvocationsLabels: [String] {
get {
return keychain.getStringArray(kInvocationsLabels) ?? []
}
set {
keychain.set(newValue, forKey: kInvocationsLabels)
}
}
func numberOfInvocations(of label: String) -> Int {
let invocationCountLabel = createInvocationCountLabel(with: label)
return Int(keychain.getString(invocationCountLabel) ?? "0") ?? 0
}
func invoked(label: String) {
if !allInvocationsLabels.contains(label) {
allInvocationsLabels.append(label)
}
let invocationCountLabel = createInvocationCountLabel(with: label)
keychain.set(String(numberOfInvocations(of: label) + 1), forKey: invocationCountLabel)
}
func reset(label: String) {
if allInvocationsLabels.contains(label) {
allInvocationsLabels = allInvocationsLabels.filter({$0 != label})
let invocationCountLabel = createInvocationCountLabel(with: label)
keychain.delete(invocationCountLabel)
}
}
private func createInvocationCountLabel(with label: String) -> String {
return kInvocationsCountPrefix + label
}
}
|
//
// ChatViewController.swift
// FlowTest
//
// Created by Šimun on 09.05.2015..
// Copyright (c) 2015. Manifest Media ltd. All rights reserved.
//
import UIKit
import Starscream
import SwiftyJSON
import AVFoundation
import AVKit
class ChatViewController: UIViewController, UITextViewDelegate, WebSocketDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
var inputContainerView: UIView!
var enterMsgTextView: UITextField!
var outcomingMsgContiner: UIView!
var incomingMsgContainer: UIView!
var sendButton: UIButton!
var userImageView: UIImageView!
var sendMediaButton: UIButton!
var outcomingMsgView: UITextView!
var friendImageView: UIImageView!
var incomingMediaButton: UIButton!
var incomingMsgView: UITextView!
var statusView: UIImageView!
var progressView: UIProgressView!
var accountId: Int?
var friendId: Int?
var channelId: Int?
var socket: WebSocket?
let apiRequest: ApiRequest! = ApiRequest()
let imagePicker: UIImagePickerController = UIImagePickerController()
var photoMsgView: UIImageView!
var photo: UIImage!
var videoUrl: URL!
let playerController = AVPlayerViewController()
var displayingMediaMode: Bool = false
var counter:Int = 0 {
didSet {
let fractionalProgress = Float(counter) / 100.0
let animated = counter != 0
progressView.setProgress(fractionalProgress, animated: animated)
}
}
override func viewDidLoad() {
super.viewDidLoad()
dismissPoke()
configureNavigationBarView()
configureView()
getChannelId()
socket = WebSocket(url: (NSURL(scheme: "http", host:ConfigManager.sharedInstance.WebSocketUrl!, path: "/chat/\(channelId!)/\(accountId!)") as? URL)!)
socket!.delegate = self
socket!.connect()
progressView.isHidden = true
progressView.setProgress(0, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillDisappear(_ animated: Bool) {
if (!displayingMediaMode) {
self.socket!.disconnect()
} else {
print("displaying media")
}
}
func dismissPoke() {
let friend: Friend = Friend.get(friendId!)!
let requestBody : [String:String] = [
"id" : "\(accountId!)",
"buddy_id" : "\(friend.friend_account_id)"]
apiRequest.dismissPoke(requestBody, completionHandler: {(success, poked, responseBody, error) -> Void in
if (success) {
print("poke dismissed succesfully")
}
else {
print("problem with dismissing poke")
}
})
}
func getChannelId() {
let friend: Friend = Friend.get(friendId!)!
if Int(friend.friend_account_id) > accountId! {
let id: String = "\(accountId!)\(Int(friend.friend_account_id))"
channelId = Int(id)
} else {
let id: String = "\(Int(friend.friend_account_id))\(accountId!)"
channelId = Int(id)
}
print(channelId)
}
//MARK: UITextView delegate methods
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let maxHeight: CGFloat = 180.0
let lineHeight = textView.font!.lineHeight
let contentHeight = textView.contentSize.height
var newViewHeight = contentHeight + lineHeight
if text == "\n" {
if newViewHeight > maxHeight {
newViewHeight = maxHeight
}
}
return true
}
func textViewDidChangeSelection(_ textView: UITextView) {
let maxHeight: CGFloat = 180.0
let lineHeight = textView.font!.lineHeight
let contentHeight = textView.contentSize.height
let newViewHeight = contentHeight + lineHeight
if newViewHeight > maxHeight {
}
}
//MARK: websocket delegate methods
func websocketDidConnect(_ socket: WebSocket) {
print("Chat connected \(socket)")
}
func websocketDidDisconnect(_ socket: WebSocket, error: NSError?) {
print("Chat disconnected \(error?.localizedDescription)")
}
func websocketDidReceiveData(_ socket: WebSocket, data: Data) {
print("Chat data transfer")
}
func websocketDidReceiveMessage(_ socket: WebSocket, text: String) {
if let dataFromString = text.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
print("\(json["type"]) received")
if json["type"].stringValue == "status" {
print("Update user status: \(json)")
if json["online"].stringValue == "true" {
statusView.isHidden = false
sendButton.setImage(UIImage(named: "SEND"), for: UIControlState())
sendButton.tag = 1
sendMediaButton.setImage(UIImage(named: "SEND-MEDIA"), for: UIControlState())
sendMediaButton.isEnabled = true
} else {
statusView.isHidden = true
sendButton.setImage(UIImage(named: "POKE-BUTTON"), for: UIControlState())
sendButton.tag = 0
sendMediaButton.setImage(UIImage(named: "SEND-MEDIA-GRAY"), for: UIControlState())
sendMediaButton.isEnabled = false
incomingMediaButton.isEnabled = false
}
} else if json["type"].stringValue == "text" {
incomingMsgView.text = json["content"].stringValue
incomingMediaButton.setImage(UIImage(named: "NEW-PHOTO-GRAY"), for: UIControlState())
incomingMediaButton.isEnabled = false
}
else if json["type"].stringValue == "image" {
if let image: String = json["content"].string {
let imgData: Data = Data(base64Encoded: image, options:NSData.Base64DecodingOptions(rawValue: 0))!
self.photo = UIImage(data: imgData)!
}
incomingMediaButton.setImage(UIImage(named: "NEW-PHOTO"), for: UIControlState())
incomingMediaButton.tag = 0
incomingMediaButton.isEnabled = true
}
else if json["type"].stringValue == "video" {
if let video: String = json["content"].string {
let videoData: Data = Data(base64Encoded: video, options:NSData.Base64DecodingOptions(rawValue: 0))!
let writePath: URL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("receivedMovie.mov")
try? videoData.write(to: writePath, options: [.atomic])
self.videoUrl = writePath
}
incomingMediaButton.setImage(UIImage(named: "NEW-PHOTO"), for: UIControlState())
incomingMediaButton.tag = 1
incomingMediaButton.isEnabled = true
}
}
}
//MARK: buttons actions
func cleanButtonPressed(_ sender: UIButton) {
print("cleanButtonPressed")
outcomingMsgView.text! = ""
incomingMsgView.text! = ""
enterMsgTextView.text! = ""
}
func sendButtonPressed(_ sender: UIButton) {
print("send/poke ButtonPressed")
if sender.tag == 1 {
let dict = [ "content": "\(enterMsgTextView.text!)", "type" : "text" ]
let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
socket!.writeString(string as! String)
outcomingMsgView.text = enterMsgTextView.text!
incomingMsgView.text = ""
enterMsgTextView.text = ""
} else {
let friend: Friend = Friend.get(friendId!)!
let requestBody : [String:String] = [
"id" : "\(accountId!)",
"buddy_id" : "\(friend.friend_account_id)"]
apiRequest.poke(requestBody, completionHandler: {(success, poked, responseBody, error) -> Void in
if (success) {
print("poke sent successfully")
}
else {
print("problem with poke")
}
})
}
}
func incomingMediaButtonPressed(_ sender: UIButton) {
displayingMediaMode = true
print("incomingMediaButtonPressed")
if sender.tag == 0 {
self.showPhotoMsg()
let dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(4 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
self.hidePhotoMsg()
})
} else if sender.tag == 1 {
self.showVideoMsg()
}
}
func sendMediaButtonPressed(_ sender: UIButton) {
displayingMediaMode = true
print("sendMediaButtonPressed")
presentActionSheet()
}
func presentActionSheet() {
let actionSheet: UIAlertController = UIAlertController(title:nil, message:nil, preferredStyle:UIAlertControllerStyle.actionSheet)
actionSheet.addAction(UIAlertAction(title:"Choose photo from library".localized, style:UIAlertActionStyle.default, handler:{ action in
self.choosePhotoFromLibrery()
}))
actionSheet.addAction(UIAlertAction(title:"Take photo".localized, style:UIAlertActionStyle.default, handler:{ action in
self.takePhoto()
}))
actionSheet.addAction(UIAlertAction(title:"Cancel".localized, style:UIAlertActionStyle.cancel, handler:nil))
present(actionSheet, animated:true, completion:nil)
}
func choosePhotoFromLibrery() {
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
imagePicker.navigationBar.barTintColor = UIColor.TurntPink()
imagePicker.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
imagePicker.navigationBar.tintColor = UIColor.white
imagePicker.navigationBar.barStyle = .black
imagePicker.navigationBar.isTranslucent = false
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum){
self.present(imagePicker, animated: true, completion: nil)
}
}
func takePhoto() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
imagePicker.delegate = self
imagePicker.sourceType = .camera
let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .camera)
imagePicker.mediaTypes = availableMediaTypes!
imagePicker.videoMaximumDuration = 10.0
self.present(imagePicker, animated: true, completion: nil)
} else {
print("camera not avaliable")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info["UIImagePickerControllerMediaType"]!
var dict: [String: String] = [:]
if ((mediaType as AnyObject).isEqual("public.movie")) {
//writing video to socket as string
let videoUrl = info["UIImagePickerControllerMediaURL"] as! URL
let video: Data = try! Data(contentsOf: videoUrl)
let videoAsString: String = video.base64EncodedString(options: [])
dict = ["content": "\(videoAsString)", "type" : "video"]
}
else if ((mediaType as AnyObject).isEqual("public.image")) {
//writing image to socket as string
let image: UIImage = info["UIImagePickerControllerOriginalImage"] as! UIImage
let imageAsString: String = UIImageJPEGRepresentation(image, 0.1)!.base64EncodedString(options: [])
dict = ["content": "\(imageAsString)", "type" : "image"]
}
let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
self.socket!.writeString(string as! String)
//progress bar of sending (now fake)
self.progressView.isHidden = false
self.counter = 0
for _ in 0..<100 {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background).async(execute: {
sleep(2)
DispatchQueue.main.async(execute: {
if self.counter == 99 {
self.progressView.isHidden = true
} else {
self.counter += 1
}
return
})
})
}
self.sendMediaButton.isEnabled = true
self.dismiss(animated: true, completion: nil)
self.enterMsgTextView.becomeFirstResponder()
displayingMediaMode = false
}
//MARK: view configuration
func configureNavigationBarView() {
let friend = Friend.get(friendId!)
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
let cleanButton = UIBarButtonItem(title: "Clear".localized, style: UIBarButtonItemStyle.plain, target: self, action:#selector(ChatViewController.cleanButtonPressed(_:)))
cleanButton.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 15)], for: UIControlState())
self.navigationItem.rightBarButtonItem = cleanButton
let friendUsername: NSString = "\(friend!.username)"
let friendUsernameSize = friendUsername.size(attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)])
let navBarTitleView = UIView.init(frame: CGRect(x: 0, y: 0, width: friendUsernameSize.width + 15, height: friendUsernameSize.height))
let usernameLabel = UILabel.init(frame: CGRect(x: 10, y: 0, width: friendUsernameSize.width, height: friendUsernameSize.height))
usernameLabel.text = "\(friend!.username)"
usernameLabel.textColor = UIColor.TurntWhite()
usernameLabel.font = UIFont.boldSystemFont(ofSize: 18)
statusView = UIImageView.init(frame: CGRect(x: 0, y: friendUsernameSize.height/2 - 4, width: 8, height: 8))
statusView.backgroundColor = UIColor.TurntGreenLumo()
statusView.layer.cornerRadius = 4
statusView.clipsToBounds = true
navBarTitleView.addSubview(usernameLabel)
navBarTitleView.addSubview(statusView)
self.navigationItem.titleView = navBarTitleView
}
func configureView() {
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let statusBarHeight: CGFloat = 20.0 //UIApplication.sharedApplication().statusBarFrame.size.height
let navigationBarHeight: CGFloat = 44.0 //self.navigationController!.navigationBar.frame.size.height
let keyboardHeight: CGFloat = 216.0
let margin: CGFloat = 10.0
var smallMargin: CGFloat = 8.0
let inputContainerViewHeight: CGFloat = 40.0
let inputContainerViewY = screenHeight - keyboardHeight - inputContainerViewHeight - statusBarHeight - navigationBarHeight
let enterMsgTextViewHeight = inputContainerViewHeight/2
let pokeButtonWidth: CGFloat = 60.0
let pokeButtonHeight: CGFloat = 30.0
let halfFreeScreenHeight = (screenHeight - keyboardHeight - inputContainerViewHeight - statusBarHeight - navigationBarHeight)/2
var squareElementSide: CGFloat = 37.0
if (halfFreeScreenHeight - 2*margin < 2*squareElementSide + smallMargin) { //adjust view to iPhone 4s
squareElementSide = 27.0
smallMargin = 5.0
}
//progressView
progressView = UIProgressView.init(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 10))
progressView.progressTintColor = UIColor.TurntGreenLumo()
progressView.backgroundColor = UIColor.clear
self.view.addSubview(progressView)
//input Container
inputContainerView = UIView.init(frame: CGRect(x: 0, y: inputContainerViewY, width: screenWidth, height: inputContainerViewHeight))
inputContainerView.backgroundColor = UIColor.TurntWhite()
self.view.addSubview(inputContainerView)
//enterMsg
enterMsgTextView = UITextField.init(frame: CGRect(x: margin, y: enterMsgTextViewHeight/2, width: screenWidth - pokeButtonWidth - 3*margin, height: enterMsgTextViewHeight))
enterMsgTextView.backgroundColor = UIColor.TurntWhite()
enterMsgTextView.font = UIFont.systemFont(ofSize: 15)
enterMsgTextView.placeholder = "Enter message"
enterMsgTextView.becomeFirstResponder()
inputContainerView.addSubview(enterMsgTextView)
//pokeButton
sendButton = UIButton.init(frame: CGRect(x: enterMsgTextView.frame.size.width + 2*margin, y: (inputContainerViewHeight - pokeButtonHeight)/2, width: pokeButtonWidth, height: pokeButtonHeight))
sendButton.setBackgroundImage(UIImage(named: "POKE-BUTTON"), for: UIControlState())
sendButton.addTarget(self, action: #selector(ChatViewController.sendButtonPressed(_:)), for: UIControlEvents.touchUpInside)
inputContainerView.addSubview(sendButton)
//msg Containers
//outcoming container
outcomingMsgContiner = UIView.init(frame: CGRect(x: margin, y: halfFreeScreenHeight + margin, width: screenWidth - 2*margin, height: halfFreeScreenHeight - 2*margin))
self.view.addSubview(outcomingMsgContiner)
//user image view
userImageView = UIImageView.init(frame: CGRect(x: outcomingMsgContiner.frame.size.width - squareElementSide, y: 0, width: squareElementSide, height: squareElementSide))
userImageView.image = Account.get(accountId!)?.getChatImage()
userImageView.layer.cornerRadius = 4.0
userImageView.clipsToBounds = true
outcomingMsgContiner.addSubview(userImageView)
//send media button
sendMediaButton = UIButton.init(frame: CGRect(x: outcomingMsgContiner.frame.size.width - squareElementSide, y: squareElementSide + smallMargin, width: squareElementSide, height: squareElementSide))
sendMediaButton.setBackgroundImage(UIImage(named: "SEND-MEDIA-GRAY"), for: UIControlState())
sendMediaButton.addTarget(self, action: #selector(ChatViewController.sendMediaButtonPressed(_:)), for: UIControlEvents.touchUpInside)
outcomingMsgContiner.addSubview(sendMediaButton)
//outcoming msg view
outcomingMsgView = UITextView.init(frame: CGRect(x: 0, y: 0, width: outcomingMsgContiner.frame.size.width - squareElementSide - smallMargin, height: halfFreeScreenHeight - 2*margin))
outcomingMsgView.backgroundColor = UIColor.TurntWhite()
outcomingMsgView.font = UIFont.systemFont(ofSize: 15.0)
outcomingMsgView.textColor = UIColor.TurntChatTextColor()
outcomingMsgView.isUserInteractionEnabled = false
outcomingMsgView.layer.cornerRadius = 4.0
outcomingMsgView.clipsToBounds = true
outcomingMsgContiner.addSubview(outcomingMsgView)
//incoming container
incomingMsgContainer = UIView.init(frame: CGRect(x: margin, y: margin, width: screenWidth - 2*margin, height: halfFreeScreenHeight - 2*margin))
self.view.addSubview(incomingMsgContainer)
//friend image view
friendImageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: squareElementSide, height: squareElementSide))
friendImageView.image = Friend.get(friendId!)?.getImage()
friendImageView.layer.cornerRadius = 4.0
friendImageView.clipsToBounds = true
incomingMsgContainer.addSubview(friendImageView)
//incoming media button
incomingMediaButton = UIButton.init(frame: CGRect(x: 0, y: squareElementSide + smallMargin, width: squareElementSide, height: squareElementSide))
incomingMediaButton.setBackgroundImage(UIImage(named: "NEW-PHOTO-GRAY"), for: UIControlState())
incomingMediaButton.addTarget(self, action: #selector(ChatViewController.incomingMediaButtonPressed(_:)), for: UIControlEvents.touchUpInside)
// incomingMediaButton.userInteractionEnabled = false
incomingMsgContainer.addSubview(incomingMediaButton)
//incomin msg view
incomingMsgView = UITextView.init(frame: CGRect(x: squareElementSide + smallMargin, y: 0, width: incomingMsgContainer.frame.size.width - squareElementSide - smallMargin, height: halfFreeScreenHeight - 2*margin))
incomingMsgView.backgroundColor = UIColor.TurntWhite()
incomingMsgView.isUserInteractionEnabled = false
incomingMsgView.layer.cornerRadius = 4.0
incomingMsgView.clipsToBounds = true
incomingMsgContainer.addSubview(incomingMsgView)
//separating line
let separatorView = UIImageView.init(frame: CGRect(x: margin, y: halfFreeScreenHeight, width: screenWidth - 2*margin, height: 1))
separatorView.image = UIImage(named: "SEPARATOR")
self.view.addSubview(separatorView)
}
func adjustViewToHideMediaMsg() {
self.navigationController!.navigationBar.isHidden = false
self.view.frame.origin.y += 64
self.view.frame.size.height -= 64.0
enterMsgTextView.becomeFirstResponder()
}
func adjustViewToShowMediaMsg() {
self.navigationController!.navigationBar.isHidden = true
self.view.frame.origin.y -= 64
self.view.frame.size.height += 64.0
enterMsgTextView.resignFirstResponder()
}
//MARK: media message display
func showVideoMsg() {
displayingMediaMode = true
self.adjustViewToShowMediaMsg()
// let tap = UITapGestureRecognizer.init(target: self, action: Selector("msgViewTapped:"))
// tap.delegate = self
let player = AVPlayer(url: self.videoUrl)
playerController.player = player
playerController.showsPlaybackControls = false
self.addChildViewController(playerController)
// playerController.view.addGestureRecognizer(tap)
playerController.view.isUserInteractionEnabled = true
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
player.play()
NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.hideVideoMsg(_:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
}
func hideVideoMsg(_ note: Notification) {
displayingMediaMode = false
if (self.view.subviews.contains(playerController.view)) {
playerController.view.removeFromSuperview()
self.adjustViewToHideMediaMsg()
incomingMediaButton.setImage(UIImage(named: "NEW-PHOTO-GRAY"), for: UIControlState())
incomingMediaButton.isEnabled = false
}
}
func showPhotoMsg() {
displayingMediaMode = true
self.adjustViewToShowMediaMsg()
let tap = UITapGestureRecognizer.init(target: self, action:#selector(ChatViewController.tapPhotoMsg(_:)))
tap.delegate = self
photoMsgView = UIImageView(frame: self.view.frame)
photoMsgView.image = photo
photoMsgView.isUserInteractionEnabled = true
photoMsgView.addGestureRecognizer(tap)
self.view.addSubview(photoMsgView)
}
func hidePhotoMsg() {
print("hidePhotoMsg")
displayingMediaMode = false
if (self.view.subviews.contains(photoMsgView)) {
photoMsgView.removeFromSuperview()
self.adjustViewToHideMediaMsg()
incomingMediaButton.setImage(UIImage(named: "NEW-PHOTO-GRAY"), for: UIControlState())
incomingMediaButton.isEnabled = false
}
}
func tapPhotoMsg(_ recognizer: UITapGestureRecognizer) {
self.hidePhotoMsg();
}
}
|
//
// TSDiscoverViewController.swift
// TVShow
//
// Created by lkx on 16/4/28.
// Copyright © 2016年 imeng. All rights reserved.
//
import UIKit
import AlamofireObjectMapper
import Alamofire
import SwiftyJSON
private let reuseIdentifier = "Cell"
//let DiscoverSectionURL = "http://api.douban.com/v2/movie/top250"
let DiscoverSectionURL = "http://api.douban.com/v2/movie/in_theaters"
//let DiscoverSectionURL = "https://m.douban.com/rexxar/api/v2/subject_collection/movie_showing/items?os=ios"
class TSDiscoverViewController: UICollectionViewController {
var responseObjectData:JSON? {
didSet {
let sectionModel = TSDiscoverSectionController(json: (responseObjectData!["subjects"]))
self.collectionView?.register(UINib.init(nibName: "TSDiscoverShelfCollectionViewCell", bundle: Bundle.main), forCellWithReuseIdentifier:sectionModel.sectionReuseIdentifier())
print(sectionModel.sectionReuseIdentifier())
contentObjects.append(sectionModel)
self.collectionView?.reloadData()
// if let listArray = responseObjectData?["subjects"].array {
// for sectionItem in listArray {
// let sectionModel = TSDiscoverSectionController(json: sectionItem)
// self.collectionView?.register(UINib.init(nibName: "TSDiscoverShelfCollectionViewCell", bundle: Bundle.main), forCellWithReuseIdentifier:sectionModel.sectionReuseIdentifier())
// print(sectionModel.sectionReuseIdentifier())
// contentObjects.append(sectionModel)
// }
// self.collectionView?.reloadData()
// }
// if let listArray = responseObjectData?["album"].array {
// bannerObjects += listArray
// }
}
}
var contentObjects = [TSDiscoverSectionController]()
var bannerObjects = [JSON]()
// MARK: - Left Cycle
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
let headerNib = UINib(nibName: "TSDiscoverBannerHeader", bundle: Bundle.main)
self.collectionView!.register(headerNib, forSupplementaryViewOfKind: IOStickyHeaderParallaxHeader, withReuseIdentifier: "header")
let screenBounds = UIScreen.main.bounds
// setup layout
if let layout: IOStickyHeaderFlowLayout = self.collectionView?.collectionViewLayout as? IOStickyHeaderFlowLayout {
layout.parallaxHeaderReferenceSize = CGSize(width: screenBounds.width, height:0.54 * screenBounds.width)
layout.parallaxHeaderMinimumReferenceSize = CGSize(width: screenBounds.width, height: 0)
layout.itemSize = CGSize(width: UIScreen.main.bounds.size.width, height: layout.itemSize.height)
layout.parallaxHeaderAlwaysOnTop = true
layout.disableStickyHeaders = true
}
TSNetRequestManager.sharedInstance.request(DiscoverSectionURL).validate().responseJSON { response in
switch response.result {
case .success(let value):
self.responseObjectData = JSON(value)
case .failure(let error):
print(error)
}
}
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return contentObjects.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model = contentObjects[indexPath.section]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: model.sectionReuseIdentifier(), for: indexPath) as! TSDiscoverShelfCollectionViewCell
model.collectionViewController = self
cell.collectionView.dataSource = model
cell.collectionView.delegate = model
print(cell)
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if UICollectionElementKindSectionHeader == kind {
let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! TSDiscoverSectionHeader
if let string = responseObjectData?["index"][indexPath.section]["title"].string {
sectionHeader.textLabel.text = string
}
return sectionHeader
} else {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: IOStickyHeaderParallaxHeader, withReuseIdentifier: "header", for: indexPath) as! TSDiscoverBannerHeader
header.objects = self.bannerObjects
return header
}
}
/*
// 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.
}
*/
}
|
//
// ScoreBoardCellView.swift
// Blueprint
//
// Created by Samuel Proulx on 2020-01-26.
// Copyright © 2020 SP. All rights reserved.
//
import SwiftUI
struct ScoreBoardCellView: View {
@State var team: String = ""
var body: some View {
TextField("Red1", text: $team)
}
}
struct ScoreBoardCellView_Previews: PreviewProvider {
static var previews: some View {
ScoreBoardCellView()
}
}
|
//
// SavedPasswordTableViewCell.swift
// PasswordSaver
//
// Created by Victor Martins Rabelo on 03/02/18.
// Copyright © 2018 Victor Martins Rabelo. All rights reserved.
//
import UIKit
class SavedPasswordTableViewCell: UITableViewCell {
@IBOutlet weak var logo: UIImageView!
@IBOutlet weak var url: UILabel!
@IBOutlet weak var email: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
logo.image = #imageLiteral(resourceName: "defaultSiteImageSmall")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func prepareForReuse() {
super.prepareForReuse()
logo.image = #imageLiteral(resourceName: "defaultSiteImageSmall")
url.text = ""
email.text = ""
}
}
|
//
// ContentView.swift
// VolumeConversion
//
// Created by Mike Pattee on 6/9/20.
// Copyright © 2020 Mike Pattee. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var fromVolumeTypeIndex = 0
@State private var toVolumeTypeIndex = 0
@State private var valueString = ""
private var value: Double {
Double(valueString) ?? 0.0
}
private var valueInMililiters: Double {
let conversionValue = volumeConversions[fromVolumeTypeIndex]
return value * conversionValue
}
private var convertedValue: Double {
let conversionValue = volumeConversions[toVolumeTypeIndex]
return valueInMililiters / conversionValue
}
private var volumeTypes = ["mililiters", "liters", "cups", "pints", "gallons"]
private var volumeConversions = [1.0, 1000.0, 236.588, 473.176, 3785.40800010238]
var body: some View {
Form {
Section(header: Text("Starting Value")) {
Picker(selection: $fromVolumeTypeIndex, label: Text("from unit")) {
ForEach(0 ..< volumeTypes.count) {
Text(self.volumeTypes[$0])
}
}
.pickerStyle(SegmentedPickerStyle())
TextField("Starting Amount", text: $valueString).keyboardType(.decimalPad)
}
Section(header: Text("Resulting Value")) {
Picker(selection: $toVolumeTypeIndex, label: Text("to unit")) {
ForEach(0 ..< volumeTypes.count) {
Text(self.volumeTypes[$0])
}
}
.pickerStyle(SegmentedPickerStyle())
Text("Resulting Value: \(convertedValue, specifier: "%.2f")")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// GameView.swift
// bowtie2
//
// Created by Jake Runzer on 2020-11-21.
//
import SwiftUI
fileprivate class GameViewSheetState: Identifiable {
var addingScore: PlayerScore?
var playerHistory: PlayerScore?
init(adding addingScore: PlayerScore?,
history playerHistory: PlayerScore?) {
self.addingScore = addingScore
self.playerHistory = playerHistory
}
static func addingScore(for player: PlayerScore) -> GameViewSheetState {
return GameViewSheetState.init(adding: player, history: nil)
}
static func viewHistory(for player: PlayerScore) -> GameViewSheetState {
return GameViewSheetState.init(adding: nil, history: player)
}
}
struct GameView: View {
@Environment(\.managedObjectContext) private var viewContext
@EnvironmentObject var settings: UserSettings
@ObservedObject var game: Game
@State private var addingScore: PlayerScore? = nil
@State private var sheetState: GameViewSheetState? = nil
var body: some View {
ScrollView {
ForEach(game.scoresArray, id: \.self) { score in
Button(action: {
sheetState = GameViewSheetState.addingScore(for: score)
}) {
PlayerScoreCard(name: score.player!.wrappedName,
colour: score.player!.wrappedColor,
score: score.currentScore,
numTurns: score.history!.count,
maxScoresGame: game.maxNumberOfEntries)
}
.contextMenu {
Button(action: {
sheetState = GameViewSheetState.viewHistory(for: score)
}) {
HStack {
Text("View History")
Image(systemName: "archivebox")
}
}
}
}
.padding(.horizontal)
if settings.showGraph && game.maxNumberOfEntries >= 2 {
GameGraph(game: game)
.frame(maxWidth: .infinity, idealHeight: 200)
.padding(.horizontal)
} else {
EmptyView()
}
}
.navigationBarTitle(game.wrappedName, displayMode: .large)
.toolbar {
NavigationLink(
destination: GameSettings(game: game),
label: {
Label("Game settings", systemImage: "gearshape")
})
}
.sheet(item: $sheetState, content: presentSheet)
}
@ViewBuilder
private func presentSheet(for sheet: GameViewSheetState) -> some View {
if let addingScore = sheet.addingScore {
EnterScoreView(playerScore: addingScore, addScore: addScore)
.environmentObject(settings)
} else if let playerHistory = sheet.playerHistory {
ScoreHistoryView(playerScore: playerHistory)
}
}
private func addScore(playerScore: PlayerScore, score: Int) {
do {
let currentPlayerScore = viewContext.object(with: playerScore.objectID) as! PlayerScore
if currentPlayerScore.history == nil {
currentPlayerScore.history = []
}
currentPlayerScore.history?.append(score)
viewContext.refresh(currentPlayerScore, mergeChanges: true)
viewContext.refresh(currentPlayerScore.game!, mergeChanges: true)
viewContext.refresh(currentPlayerScore.player!, mergeChanges: true)
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
struct GameView_Previews: PreviewProvider {
static var previews: some View {
NavigationView{
GameView(game: Game.gameByName(context: PersistenceController.preview.container.viewContext, name: "Blitz")!)
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
.environmentObject(UserSettings())
}
}
}
|
//
// SourceViewController.swift
// News Today
import UIKit
import NVActivityIndicatorView
import DropDown
class SourceViewController: UIViewController,NVActivityIndicatorViewable {
@IBOutlet weak var languageButton: UIButton!
@IBOutlet weak var countryCode: UIButton!
@IBOutlet weak var categoryType: UIButton!
@IBOutlet weak var sourceTableView: UITableView!
var sourceViewModel: SourceViewModel?
var countryDropDown = DropDown()
var categoryDropDown = DropDown()
var languageDropDown = DropDown()
// MARK:- View life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.sourceViewModel?.setUpCountryList()
self.sourceViewModel?.setUplanguageArray()
self.sourceViewModel?.setUpCategoryArray()
self.sourceViewModel?.loadingClosure = { [weak self] in
DispatchQueue.main.async {
guard let self = self else {return}
let isLoading = self.sourceViewModel?.isLoading ?? false
if isLoading {
let size = CGSize(width: 50, height: 50)
self.startAnimating(size, message: "Loading", messageFont: .none, type: .ballScaleRippleMultiple, color: .white, fadeInAnimation: .none)
} else {
self.stopAnimating()
}
}
}
self.sourceViewModel?.showAlert = { [weak self] in
DispatchQueue.main.async {
guard let self = self else {return}
let alert = UIAlertController(title: self.sourceViewModel?.articlesModel?.code ?? "", message: self.sourceViewModel?.articlesModel?.message ?? "", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
self.sourceViewModel?.navigationClosure = { [weak self] in
DispatchQueue.main.async {
guard let self = self else {return}
guard let vc = self.storyboard?.instantiateViewController(identifier: "ArticlesListViewController") as? ArticlesListViewController else {
return
}
vc.articlesListViewModel = self.sourceViewModel?.viewModelForArtilceList()
self.navigationController?.pushViewController(vc, animated: true)
}
}
self.sourceViewModel?.reloadClosure = { [weak self] in
DispatchQueue.main.async {
guard let self = self else {return}
self.sourceTableView.reloadData()
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Set up country name
countryDropDown.dataSource = self.sourceViewModel?.countryNameArray ?? [String]()
self.countryCode.setTitle(self.sourceViewModel?.selectedCountry?.countryName, for: .normal)
//Set up category button values
categoryDropDown.dataSource = self.sourceViewModel?.categoryArray ?? [String]()
self.categoryType.setTitle(self.sourceViewModel?.selectedCategory, for: .normal)
//Language Button
languageDropDown.dataSource = self.sourceViewModel?.languageNameList ?? [String]()
self.languageButton.setTitle(self.sourceViewModel?.selectedLanguage?.languageName, for: .normal)
//Set border radius curve
self.countryCode.layer.borderWidth = 1
self.categoryType.layer.borderWidth = 1
self.languageButton.layer.borderWidth = 1
self.countryCode.layer.cornerRadius = 10
self.categoryType.layer.cornerRadius = 10
self.languageButton.layer.cornerRadius = 10
self.countryCode.layer.borderColor = UIColor.gray.cgColor
self.categoryType.layer.borderColor = UIColor.gray.cgColor
self.languageButton.layer.borderColor = UIColor.gray.cgColor
}
// MARK:- Action for buttons
@IBAction func languageSelected(_ sender: UIButton) {
languageDropDown.anchorView = sender
languageDropDown.bottomOffset = CGPoint(x: 0, y: sender.frame.size.height)
languageDropDown.show()
languageDropDown.backgroundColor = .white
languageDropDown.selectionAction = { [weak self] (index: Int, item: String) in //8
guard let _ = self else { return }
sender.setTitle(item, for: .normal)
self?.sourceViewModel?.updateSelectedLanguage(language: item)
}
}
@IBAction func categorySelected(_ sender: UIButton) {
categoryDropDown.anchorView = sender
categoryDropDown.bottomOffset = CGPoint(x: 0, y: sender.frame.size.height)
categoryDropDown.show()
categoryDropDown.backgroundColor = .white
categoryDropDown.selectionAction = { [weak self] (index: Int, item: String) in //8
guard let _ = self else { return }
sender.setTitle(item, for: .normal)
self?.sourceViewModel?.updateSelectedCategory(category: item)
}
}
@IBAction func countrySelected(_ sender: UIButton) {
countryDropDown.anchorView = sender
countryDropDown.bottomOffset = CGPoint(x: 0, y: sender.frame.size.height)
countryDropDown.show()
countryDropDown.backgroundColor = .white
countryDropDown.selectionAction = { [weak self] (index: Int, item: String) in //8
guard let _ = self else { return }
sender.setTitle(item, for: .normal)
self?.sourceViewModel?.updateSelectedCountry(country: item)
}
}
}
// MARK:- Table view delegates
extension SourceViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sourceViewModel?.numberOfRows() ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = sourceTableView.dequeueReusableCell(withIdentifier: "SourceListTableViewCell") as! SourceListTableViewCell
cell.textLabel?.textColor = .white
if self.sourceViewModel?.sourceModel?.sources?.count == 0 {
cell.textLabel?.text = "No result found"
} else {
cell.textLabel?.text = sourceViewModel?.getSourceList(index: indexPath.row)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.sourceViewModel?.updateSourceValue(index: indexPath.row)
self.sourceViewModel?.makeApiCall()
}
}
|
//
// AppColors.swift
// HSAPP-iOS
//
// Created by Tony Cioara on 6/7/18.
// Copyright © 2018 Tony Cioara. All rights reserved.
//
import UIKit
extension UIColor {
struct AppColors {
static var lightBlue: UIColor { return UIColor(red: 0 / 255, green: 122 / 255, blue: 255 / 255, alpha: 1.0) }
static var backgroundRed: UIColor {
return UIColor(red: 233/255, green: 202/255, blue: 208/255, alpha: 1)
}
static var backgroundGray: UIColor {
return UIColor(red: 226/255, green: 228/255, blue: 233/255, alpha: 1)
}
static var backgroundGrayBlue: UIColor {
return UIColor(red: 194/255, green: 205/255, blue: 233/255, alpha: 1)
}
static var backgroundWhite: UIColor {
return UIColor(red: 252/255, green: 250/255, blue: 250/255, alpha: 1)
}
static var viewWhite: UIColor {
return UIColor(red: 253/255, green: 252/255, blue: 252/255, alpha: 1)
}
}
}
|
// Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you 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 UIKit
class DynamicTableViewImageCardCell: UITableViewCell {
// MARK: - View elements.
lazy var title = ENALabel(frame: .zero)
lazy var body = ENALabel(frame: .zero)
lazy var cellImage = UIImageView(frame: .zero)
lazy var chevron = UIImageView(image: UIImage(systemName: "chevron.right"))
lazy var insetView = UIView(frame: .zero)
// MARK: - Constraints for resizing.
var heightConstraint: NSLayoutConstraint?
var insetViewHeightConstraint: NSLayoutConstraint?
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
self.autoresizingMask = .flexibleHeight
}
private func setup() {
// MARK: - General cell setup.
selectionStyle = .none
backgroundColor = .preferredColor(for: .backgroundPrimary)
// MARK: - Add inset view
insetView.backgroundColor = .preferredColor(for: .backgroundSecondary)
insetView.layer.cornerRadius = 16.0
insetView.clipsToBounds = true
// MARK: - Title adjustment.
title.style = .title2
title.textColor = .preferredColor(for: .textPrimary1)
title.lineBreakMode = .byWordWrapping
title.numberOfLines = 0
// MARK: - Body adjustment.
body.style = .body
body.textColor = .preferredColor(for: .textPrimary1)
body.lineBreakMode = .byWordWrapping
body.numberOfLines = 0
// MARK: - Chevron adjustment.
chevron = UIImageView(image: UIImage(systemName: "chevron.right"))
chevron.tintColor = UIColor.preferredColor(for: .textPrimary2)
// MARK: - Image adjustment.
cellImage.contentMode = .scaleAspectFit
}
private func setupConstraints() {
UIView.translatesAutoresizingMaskIntoConstraints(for: [
title,
body,
cellImage,
chevron,
insetView
], to: false)
contentView.addSubview(insetView)
insetView.addSubviews([
title,
body,
cellImage,
chevron
])
let marginGuide = contentView.layoutMarginsGuide
insetView.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true
insetView.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true
insetView.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true
insetView.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor).isActive = true
title.leadingAnchor.constraint(equalTo: insetView.leadingAnchor, constant: 16).isActive = true
title.topAnchor.constraint(equalTo: insetView.topAnchor, constant: 16).isActive = true
chevron.widthAnchor.constraint(equalToConstant: 15).isActive = true
chevron.heightAnchor.constraint(equalToConstant: 20).isActive = true
chevron.leadingAnchor.constraint(equalTo: title.trailingAnchor).isActive = true
chevron.trailingAnchor.constraint(equalTo: insetView.trailingAnchor, constant: -16).isActive = true
chevron.centerYAnchor.constraint(equalTo: title.centerYAnchor).isActive = true
body.leadingAnchor.constraint(equalTo: insetView.leadingAnchor, constant: 16).isActive = true
body.trailingAnchor.constraint(equalTo: cellImage.leadingAnchor, constant: -16).isActive = true
body.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 21).isActive = true
insetView.bottomAnchor.constraint(greaterThanOrEqualTo: body.bottomAnchor, constant: 16).isActive = true
cellImage.topAnchor.constraint(greaterThanOrEqualTo: chevron.bottomAnchor).isActive = true
cellImage.trailingAnchor.constraint(equalTo: insetView.trailingAnchor).isActive = true
cellImage.bottomAnchor.constraint(equalTo: insetView.bottomAnchor).isActive = true
cellImage.widthAnchor.constraint(equalToConstant: 150).isActive = true
cellImage.heightAnchor.constraint(equalToConstant: 130).isActive = true
}
func configure(title: String, image: UIImage?, body: String) {
setup()
setupConstraints()
self.title.text = title
self.body.text = body
if let image = image {
cellImage.image = image
}
}
/// This method builds a NSMutableAttributedString for the cell.
/// - Parameters:
/// - title: The title of the cell.
/// - image: The image to be displayed on the right hand of the cell.
/// - body: The text shown below the title, which should NOT be formatted in any way.
/// - attributedStrings: The text that is injected into `body` with applied attributes, e.g.
/// bold text, with color.
func configure(title: String, image: UIImage?, body: String, attributedStrings: [NSAttributedString]) {
setup()
setupConstraints()
self.title.text = title
self.body.attributedText = NSMutableAttributedString.generateAttributedString(
normalText: body,
attributedText: attributedStrings
)
if let image = image {
cellImage.image = image
}
}
}
|
//
// GZEMenuMain.swift
// Gooze
//
// Created by Yussel Paredes Perez on 5/19/18.
// Copyright © 2018 Gooze. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
import enum Result.NoError
class GZEMenuMain {
static let shared = GZEMenuMain()
let menuItemTitleProfile = "menu.item.title.profile".localized().uppercased()
let menuItemTitleBeGooze = "menu.item.title.beGooze".localized().uppercased()
let menuItemTitleSearchGooze = "menu.item.title.searchGooze".localized().uppercased()
let menuItemTitleChats = "menu.item.title.chats".localized().uppercased()
let menuItemTitleHistory = "menu.item.title.history".localized().uppercased()
let menuItemTitlePayment = "menu.item.title.payment".localized().uppercased()
let menuItemTitleregisterPayPal = "menu.item.title.registerPayPal".localized().uppercased()
let menuItemTitleCoupons = "menu.item.title.coupons".localized().uppercased()
let menuItemTitleTransactions = "menu.item.title.transactions".localized().uppercased()
let menuItemTitleInvite = "menu.item.title.invite".localized().uppercased()
let menuItemTitleTips = "menu.item.title.tips".localized().uppercased()
let menuItemTitleHelp = "menu.item.title.help".localized().uppercased()
let menuItemTitleConfiguration = "menu.item.title.configuration".localized().uppercased()
let menuItemTitleLogout = "menu.item.title.logout".localized().uppercased()
let menu = GZEMenu()
var navButton: GZEMenuButton {
get {
return self.menu.buttonView
}
}
var containerView: UIView {
set {
self.menu.menuContainer = newValue
}
get {
return self.menu.menuContainer
}
}
var chatButton: GZEButton!
var switchModeGoozeButton: GZEButton!
weak var controller: GZEActivateGoozeViewController?
lazy var logoutCocoaAction = {
return self.createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
//controller.navigationController?.popToRootViewController(animated: false)
//GZEAuthService.shared.logout(presenter: controller)
GZEExitAppButton.shared.button.sendActions(for: .touchUpInside)
}).1
}()
lazy var logoutButton = {
return self.createMenuItemButton(title: self.menuItemTitleLogout, action: self.logoutCocoaAction)
}()
let switchModeEnabled = MutableProperty(true)
let (disposeSignal, disposeObs) = Signal<Void, NoError>.pipe()
init() {
//let profileCocoaAction = CocoaAction<GZEButton>(Action<Void, Void, NoError>{SignalProducer.empty})
let (_, profileCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToMyProfile, sender: nil)
})
GZEAuthService.shared
.authUserProperty
.producer
.take(until: self.disposeSignal)
.startWithValues {[weak self] authUser in
guard let this = self else {return}
if let request = authUser?.activeDateRequest {
log.debug("request id: \(request.id)")
this.switchModeEnabled.value = false
} else {
this.switchModeEnabled.value = true
}
}
let (_, switchModeCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
if controller.scene == .activate {
controller.scene = .search
} else {
controller.scene = .activate
}
}, enabledIf: switchModeEnabled)
self.switchModeGoozeButton = createMenuItemButton(title: menuItemTitleSearchGooze, action: switchModeCocoaAction, image: #imageLiteral(resourceName: "switch-mode"))
let (_, chatCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToChats, sender: nil)
})
let (_, historyCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToHistory, sender: nil)
})
let (_, paymentCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToPayment, sender: nil)
})
let (_, registerPayPalCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToRegisterPayPal, sender: nil)
})
let (_, transactionsCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToBalance, sender: nil)
})
let (_, tipsCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToTips, sender: nil)
})
let (_, helpCocoaAction) = createMenuAction(producer: SignalProducer{[weak self] in
guard let controller = self?.controller else {return}
controller.performSegue(withIdentifier: controller.segueToHelp, sender: GZEHelpViewModelGooze())
})
chatButton = createMenuItemButton(title: menuItemTitleChats, action: chatCocoaAction, hasBadge: true)
let menuItems: [UIView] = [
createMenuItemButton(title: menuItemTitleProfile, action: profileCocoaAction),
createMenuSeparator(),
self.switchModeGoozeButton,
createMenuSeparator(),
chatButton,
createMenuSeparator(),
createMenuItemButton(title: menuItemTitleHistory, action: historyCocoaAction),
createMenuSeparator(),
//createMenuItemButton(title: menuItemTitlePayment, action: paymentCocoaAction),
//createMenuSeparator(),
createMenuItemButton(title: menuItemTitleregisterPayPal, action: registerPayPalCocoaAction),
createMenuSeparator(),
//createMenuItemButton(title: menuItemTitleCoupons, action: profileCocoaAction),
//createMenuSeparator(),
createMenuItemButton(title: menuItemTitleTransactions, action: transactionsCocoaAction),
createMenuSeparator(),
//createMenuItemButton(title: menuItemTitleInvite, action: profileCocoaAction),
//createMenuSeparator(),
createMenuItemButton(title: menuItemTitleTips, action: tipsCocoaAction),
createMenuSeparator(),
createMenuItemButton(title: menuItemTitleHelp, action: helpCocoaAction),
createMenuSeparator(),
//createMenuItemButton(title: menuItemTitleConfiguration, action: profileCocoaAction),
//createMenuSeparator(),
logoutButton
]
menuItems.forEach{
menu.view.menuList.addArrangedSubview($0)
}
}
func createMenuAction(producer: SignalProducer<Void, NoError> = SignalProducer.empty, enabledIf: MutableProperty<Bool> = MutableProperty(true), onCloseMenu: CompletionBlock? = nil) -> (Action<(), Void, NoError>, CocoaAction<GZEButton>) {
let action = Action(enabledIf: enabledIf){ () -> SignalProducer<Void, NoError> in
log.debug("Menu action pressed")
return producer
}
let cocoaAction = CocoaAction<GZEButton>(action) {[weak self] _ in
self?.menu.close(animated: true) {
onCloseMenu?()
}
}
return (action, cocoaAction)
}
func createMenuItemButton(title: String, action: CocoaAction<GZEButton>, hasBadge: Bool = false, image: UIImage? = nil) -> GZEButton {
let button = GZEButton()
button.setTitle(title, for: .normal)
button.reactive.pressed = action
button.backgroundColor = .clear
button.widthConstraint.isActive = false
button.heightConstraint.constant = 45
if let image = image {
button.setImage(image, for: .normal)
button.alignImageLeft = true
}
if hasBadge {
button.pp_addBadge(withNumber: 1)
button.pp_moveBadgeWith(x: UIScreen.main.bounds.width / 2 + 30, y: 11)
button.pp_setBadgeLabelAttributes{label in
label?.backgroundColor = GZEConstants.Color.mainGreen
label?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
}
}
return button
}
func createMenuSeparator() -> UIView {
let line = UIView()
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = .white
let separator = UIView()
separator.translatesAutoresizingMaskIntoConstraints = false
separator.backgroundColor = .clear
separator.addSubview(line)
separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
separator.centerYAnchor.constraint(equalTo: line.centerYAnchor).isActive = true
separator.centerXAnchor.constraint(equalTo: line.centerXAnchor).isActive = true
separator.heightAnchor.constraint(equalTo: line.heightAnchor).isActive = true
separator.widthAnchor.constraint(equalTo: line.widthAnchor, multiplier: 1.5).isActive = true
return separator
}
deinit {
disposeObs.send(value: ())
}
}
|
//
// SellerEmptyProfileViewC.swift
// MyLoqta
//
// Created by Shivansh Jaitly on 7/4/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
class SellerEmptyProfileViewC: BaseViewC {
// MARK: - IBOutlets
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var lblStartEarning: UILabel!
@IBOutlet weak var lblWayDescription: UILabel!
@IBOutlet weak var lblAddImageDesc: UILabel!
@IBOutlet weak var lblGetPaidDesc: UILabel!
@IBOutlet weak var lblWeDeliverDesc: UILabel!
@IBOutlet weak var btnBecomeSeller: AVButton!
//MARK: - Variables
internal var viewModel: SellerEmptyProfileVModeling?
// MARK: - LifeCycle Methods
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Private Methods
private func setup() {
self.view.bringSubview(toFront: self.containerView)
if let viewBg = self.view as? ColorBgView {
viewBg.updateBackgroudForSeller()
}
self.recheckVM()
}
private func recheckVM() {
if self.viewModel == nil {
self.viewModel = SellerEmptyProfileVM()
}
}
// MARK: - IBActions
@IBAction func tapCross(_ sender: UIButton) {
AppDelegate.delegate.showHome()
}
@IBAction func tapBecomeSeller(_ sender: UIButton) {
if let sellerTypeVC = DIConfigurator.sharedInst().getSellerTypeVC() {
self.navigationController?.pushViewController(sellerTypeVC, animated: true)
}
}
}
|
//
// GalleryViewController.swift
// App
//
// Created by developer on 05.05.16.
// Copyright © 2016 developer. All rights reserved.
//
import UIKit
import SnapKit
class GalleryViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet var viewC: UIView!
@IBOutlet weak var scrollView: UIScrollView!
var nextButton: UIBarButtonItem!
var previousButton: UIBarButtonItem!
var indexOfPage = 0
var scrollWidth: CGFloat = 0
var move = true
var manager: ImageViewManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = ImageViewManager(cacheCount: 3, imagesPath: "/Images", view: view)
configureNavigationBar()
addImageViewsToScrollView()
}
override func viewDidLayoutSubviews() {
if scrollWidth != self.scrollView.frame.width {
move = false
configureScrollView()
if !manager.isEmpty {
manager.updateViews(self.scrollView.frame.width, height: self.scrollView.frame.height)
}
scrollWidth = self.scrollView.frame.width
self.scrollView.contentOffset.x = CGFloat(indexOfPage) * scrollView.frame.width
}
move = true
switchNavigationButtons()
}
func configureNavigationBar() {
title = "Gallery"
self.edgesForExtendedLayout = UIRectEdge.None
nextButton = UIBarButtonItem(title: "Next", style: .Plain, target: self, action: #selector(GalleryViewController.moveToNextPage))
previousButton = UIBarButtonItem(title: "Previous", style: .Plain, target: self, action: #selector(GalleryViewController.moveToPreviousPage))
navigationItem.rightBarButtonItem = nextButton
navigationItem.leftBarButtonItem = previousButton
}
func configureScrollView() {
self.scrollView.frame = CGRect.init(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
self.scrollView.contentSize = CGSize.init(width: self.scrollView.frame.width * CGFloat(manager.count), height: self.scrollView.frame.height)
self.scrollView.delegate = self
}
func switchNavigationButtons() {
if let _ = manager.views.getElement(indexOfPage + 1) {
nextButton.enabled = true
} else {
nextButton.enabled = false
}
if let _ = manager.views.getElement(indexOfPage - 1) {
previousButton.enabled = true
} else {
previousButton.enabled = false
}
move = true
}
func addImageViewsToScrollView() {
if !manager.isEmpty {
for view in manager.views {
self.scrollView.addSubview(view)
}
}
}
// MARK: ScrollView Actions
func moveToNextPage() {
if let nextView = manager.views.getElement(indexOfPage + 1) {
move = false
manager.resetRightImage(indexOfPage + 1)
indexOfPage += 1
nextView.resetScale()
switchNavigationButtons()
UIView.animateWithDuration(0.2) {
self.scrollView.scrollRectToVisible(nextView.frame, animated: false)
}
}
}
func moveToPreviousPage() {
if let previousView = manager.views.getElement(indexOfPage - 1) {
move = false
manager.resetLeftImage(indexOfPage - 1)
indexOfPage -= 1
previousView.resetScale()
UIView.animateWithDuration(0.2) {
self.scrollView.scrollRectToVisible(previousView.frame, animated: false)
}
switchNavigationButtons()
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
getIndex(scrollView.contentOffset.x)
}
func getIndex(content: CGFloat) {
if move && view.frame.width == scrollWidth {
let content = content + scrollView.frame.size.width / 2
let newindex = Int(content / scrollView.frame.size.width)
if indexOfPage - newindex > 0 {
manager.resetLeftImage(newindex)
} else if indexOfPage - newindex < 0 {
manager.resetRightImage(newindex)
}
indexOfPage = Int((content) / scrollView.frame.size.width)
switchNavigationButtons()
}
}
}
|
//
// NextHandsOverViewController.swift
// Your Projects
//
// Created by Carlos Modinez on 04/06/19.
// Copyright © 2019 Carlos Modinez. All rights reserved.
//
import UIKit
class NextHandsOverViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tbvActivities: UITableView!
var sections : [String]?
override func viewWillAppear(_ animated: Bool) {
tbvActivities.delegate = self
tbvActivities.dataSource = self
self.sections = assignSections()
tbvActivities.reloadData()
}
//Atribui a quantidade de linhas para cada secao
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section < sections!.count && Model.shared.projects[section].activities.count > 0{
return Model.shared.projects[section].activities.count
}
else {
return 1
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < sections!.count {
return sections?[section]
}
else {
return nil
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections!.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section < sections!.count {
let cell = tableView.dequeueReusableCell(withIdentifier: "activityCell", for: indexPath) as! ActivityViewCell
if Model.shared.projects[indexPath.section].activities.count > 0 {
cell.lblActivityName.text = Model.shared.projects[indexPath.section].activities[indexPath.row].name
cell.lblDate.text = Model.shared.projects[indexPath.section].activities[indexPath.row].date
if self.view.frame.width/self.view.frame.height < 0.55 {
tbvActivities.rowHeight = self.view.frame.height * 0.1
}else {
tbvActivities.rowHeight = self.view.frame.height * 0.15
}
}else {
cell.lblActivityName.text = ""
cell.lblDate.text = ""
tbvActivities.rowHeight = self.view.frame.height * 0.1
}
return cell
}else {
let cell1 = tableView.dequeueReusableCell(withIdentifier: "addActivityCell", for: indexPath) as! AddActivityViewCell
tbvActivities.rowHeight = self.view.frame.height * 0.07
return cell1
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section < sections!.count && Model.shared.projects[indexPath.section].activities.count > 0 {
if let vc = storyboard?.instantiateViewController(withIdentifier: "activityDetails") as? PresentationActivityViewController {
vc.project = Model.shared.projects[indexPath.section]
vc.activity = Model.shared.projects[indexPath.section].activities[indexPath.row]
self.navigationController?.show(vc, sender: self)
}
}
else {
if Model.shared.projects.count > 0 {
if let vc = storyboard?.instantiateViewController(withIdentifier: "addActivity") as? AddNewActivityViewController {
self.navigationController?.show(vc, sender: self)
}
}
else{
//Mensagem de erro que indica que não há projetos Criados
}
}
}
func assignSections() -> [String] {
var sectionsName : [String] = []
for i in 0..<Model.shared.projects.count {
sectionsName.append(Model.shared.projects[i].Name)
}
return sectionsName
}
}
|
//
// Collection+Extensions.swift
// Just Do It
//
// Created by Pavel Shadrin on 21/06/2017.
// Copyright © 2017 Pavel Shadrin. All rights reserved.
//
import Foundation
extension Collection where Index == Int {
func randomElement() -> Iterator.Element? {
return isEmpty ? nil : self[Int(arc4random_uniform(UInt32(endIndex)))]
}
}
|
//
// SecondChapter.swift
// TDD
//
// Created by tangyuhua on 2017/4/10.
// Copyright © 2017年 tangyuhua. All rights reserved.
//
import UIKit
class ItemListViewController: UIViewController {
@IBOutlet var dataProvider: protocol<UITableViewDataSource,
UITableViewDelegate,ItemManagerSettable>!
@IBOutlet var tableView: UITableView!
let itemManager = ItemManager()
@IBAction func addItem(_ sender: Any) {
if let nextViewController = storyboard?.instantiateViewController(withIdentifier: "InputViewController")
as? InputViewController {
nextViewController.itemManager = self.itemManager
present(nextViewController, animated: true,
completion: nil)
}
}
override func viewDidLoad() {
tableView.dataSource = dataProvider
tableView.delegate = dataProvider
dataProvider.itemManager = itemManager
NotificationCenter.default.addObserver(self,
selector: Selector(("showDetails:")),
name: NSNotification.Name(rawValue: "ItemSelectedNotification"),
object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
func showDetials(sender:NSNotification) {
guard let index = sender.userInfo?["index"] as? Int else {
fatalError()
}
if let nextViewController = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as?
DetailViewController {
nextViewController.itemInfo = (itemManager, index)
navigationController?.pushViewController(nextViewController, animated: true)
}
}
}
|
//
// SlideMenuTableViewController.swift
// SlideOutMenus
//
// Created by Jagadish Uppala on 3/15/16.
// Copyright © 2016 Jagadish Uppala. All rights reserved.
//
import UIKit
class SlideMenuTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
private let menuItems = ["Home", "Settings", "Help"]
private var tabViewController: UITabBarController!
@IBOutlet weak var tableView: UITableView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tabViewController = parentViewController!.childViewControllers[1] as! UITabBarController
let firstIndexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.delegate = self
tableView.dataSource = self
if tableView.indexPathForSelectedRow == nil {
tableView.selectRowAtIndexPath(firstIndexPath, animated: true, scrollPosition: .Top)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:")
tapGestureRecognizer.delegate = self
tapGestureRecognizer.cancelsTouchesInView = false
tableView.addGestureRecognizer(tapGestureRecognizer)
//tableView.allowsSelection = true
//tableView.canCancelContentTouches = false
}
// UIGestureRecognizerDelegate method
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if touch.view != nil && touch.view!.isDescendantOfView(self.tableView) {
return false
}
return true
}
func handleTapGesture(recognizer: UITapGestureRecognizer) {
UIView.animateWithDuration(0.4){
self.view.frame.origin.x = 0
//self.view.layoutIfNeeded()
}
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return menuItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SlideMenuCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = menuItems[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tabViewController.selectedIndex = indexPath.row
parentViewController?.navigationItem.title = menuItems[indexPath.row]
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.