repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
citysite102/kapi-kaffeine
|
refs/heads/master
|
kapi-kaffeine/NetworkRequest.swift
|
mit
|
1
|
//
// NetworkRequest.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/5/1.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
import SwiftyJSON
public struct errorInformation {
let error: Error
let statusCode: Int?
let responseBody: KPErrorResponseModel?
let errorCode: String?
init(error: Error, data: Data?, urlResponse: HTTPURLResponse?) {
self.error = error
let json = String(data: data ?? Data(), encoding: String.Encoding.utf8)
responseBody = KPErrorResponseModel(JSONString:json!)
statusCode = urlResponse?.statusCode
errorCode = responseBody?.errorCode
}
}
public enum NetworkRequestError: Error {
case invalidData
case apiError(errorInformation: errorInformation)
case unknownError
case noNetworkConnection
case resultUnavailable
}
public typealias RawJsonResult = JSON
// MARK: Request
public protocol NetworkRequest {
associatedtype ResponseType
// Required
/// End Point.
/// e.g. /cards/:id/dislike
var endpoint: String { get }
/// Will transform given data to requested type of response.
var responseHandler: (Data) throws -> ResponseType { get }
// Optional
var baseURL: String { get }
/// Method to make the request. E.g. get, post.
var method: Alamofire.HTTPMethod { get }
/// Parameter encoding. E.g. JSON, URLEncoding.default.
var encoding: Alamofire.ParameterEncoding { get }
var parameters: [String : Any]? { get }
var headers: [String : String] { get }
/// Client that helps you to make reqeust.
var networkClient: NetworkClientType { get }
}
extension NetworkRequest {
public var url: String { return baseURL + endpoint}
// public var baseURL: String { return "https://kapi-v2-test.herokuapp.com/api/v2" }
public var baseURL: String { return "https://api.kapi.tw/api/v2" }
// public var baseURL: String { return "http://35.201.206.7/api/v2" }
public var method: Alamofire.HTTPMethod { return .get }
public var encoding: Alamofire.ParameterEncoding { return method == .get ?
URLEncoding.default :
JSONEncoding.default }
public var parameters: [String : AnyObject] { return [:] }
public var headers: [String : String] {
return ["token": (KPUserManager.sharedManager.currentUser?.accessToken) ?? ""]
}
public var networkClient: NetworkClientType { return NetworkClient() }
}
extension NetworkRequest where ResponseType: Mappable {
// 輸入 Data 型別,回傳 ResponseType
public var responseHandler: (Data) throws -> ResponseType { return jsonResponseHandler }
public var arrayResponseHandler: (Data) throws -> [ResponseType] { return jsonArrayResponseHandler }
private func jsonResponseHandler(_ data: Data) throws -> ResponseType {
let json = String(data: data, encoding: String.Encoding.utf8)
if let response = Mapper<ResponseType>().map(JSONString: json!) {
return response
} else {
throw NetworkRequestError.invalidData
}
}
private func jsonArrayResponseHandler(_ data: Data) throws -> [ResponseType] {
let json = String(data: data , encoding: String.Encoding.utf8)
if let responses = Mapper<ResponseType>().mapArray(JSONString: json!) {
return responses
} else {
throw NetworkRequestError.invalidData
}
}
}
extension NetworkRequest where ResponseType == RawJsonResult {
public var responseHandler: (Data) throws -> ResponseType {
return rawJsonResponseHandler
}
private func rawJsonResponseHandler(_ data: Data) throws -> ResponseType {
if let responseResult = JSON(data: data).dictionary?["result"] {
if responseResult.boolValue {
return JSON(data: data)
} else {
throw NetworkRequestError.resultUnavailable
}
}
return JSON(data: data)
}
}
// MARK: Upload Request
public protocol NetworkUploadRequest {
associatedtype ResponseType
var endpoint: String { get }
var responseHandler: (Data) throws -> ResponseType { get }
// Optional
var baseURL: String { get }
var method: Alamofire.HTTPMethod { get }
var threshold: UInt64 { get }
var parameters: [String : Any]? { get }
var headers: [String : String] { get }
var fileData: Data? { get }
var fileKey: String? { get }
var fileName: String? { get }
var mimeType: String? { get }
/// Client that helps you to make reqeust.
var networkClient: NetworkClientType { get }
}
extension NetworkUploadRequest {
public var url: String { return baseURL + endpoint}
// public var baseURL: String {return "https://kapi-v2-test.herokuapp.com/api/v2"}
public var baseURL: String { return "https://api.kapi.tw/api/v2" }
// public var baseURL: String { return "http://35.201.206.7/api/v2" }
public var method: Alamofire.HTTPMethod { return .post }
public var threshold: UInt64 { return 100_000_000 }
public var parameters: [String : AnyObject] { return [:] }
public var headers: [String : String] { return ["Content-Type":"multipart/form-data",
"User-Agent":"iReMW4K4fyWos"] }
public var networkClient: NetworkClientType { return NetworkClient() }
}
extension NetworkUploadRequest where ResponseType: Mappable {
// 輸入 Data 型別,回傳 ResponseType
public var responseHandler: (Data) throws -> ResponseType { return jsonResponseHandler }
public var arrayResponseHandler: (Data) throws -> [ResponseType] { return jsonArrayResponseHandler }
private func jsonResponseHandler(_ data: Data) throws -> ResponseType {
let json = String(data: data, encoding: String.Encoding.utf8)
if let response = Mapper<ResponseType>().map(JSONString: json!) {
return response
} else {
throw NetworkRequestError.invalidData
}
}
private func jsonArrayResponseHandler(_ data: Data) throws -> [ResponseType] {
let json = String(data: data , encoding: String.Encoding.utf8)
if let responses = Mapper<ResponseType>().mapArray(JSONString: json!) {
return responses
} else {
throw NetworkRequestError.invalidData
}
}
}
extension NetworkUploadRequest where ResponseType == RawJsonResult {
public var responseHandler: (Data) throws -> ResponseType { return rawJsonResponseHandler }
private func rawJsonResponseHandler(_ data: Data) throws -> ResponseType {
return JSON(data: data)
}
}
|
8693866f71b9a1548d2c156339629598
| 30.509174 | 104 | 0.647838 | false | false | false | false |
howwayla/taipeiAttractions
|
refs/heads/master
|
taipeiAttractions/Networking/Model/TAAttraction.swift
|
mit
|
1
|
//
// TAAttraction.swift
// taipeiAttractions
//
// Created by Hardy on 2016/6/27.
// Copyright © 2016年 Hardy. All rights reserved.
//
import Foundation
import ObjectMapper
import CoreLocation
struct TAAttraction: Mappable {
var ID: String?
var category: String?
var title: String?
var location: CLLocation?
var description: String?
var photoURL: [URL]?
init(JSON: JSONDictionary) {
let restructJSON = restructLocation(JSON: JSON)
if let object = Mapper<TAAttraction>().map(JSON: restructJSON) {
self = object
}
}
fileprivate func restructLocation(JSON: JSONDictionary) -> JSONDictionary {
var restructJSON = JSON
guard restructJSON["location"] == nil else {
return JSON
}
guard let longitude = JSON["longitude"] as? String,
let latitude = JSON["latitude"] as? String else {
return JSON
}
restructJSON["location"] = [ "longitude" : longitude,
"latitude" : latitude ]
return restructJSON
}
//MARK:- Mappable
init?(map: Map) {
}
mutating func mapping(map: Map) {
ID <- map["_id"]
category <- map["CAT2"]
title <- map["stitle"]
location <- (map["location"], LocationTransform())
description <- map["xbody"]
photoURL <- (map["file"], PhotoURLTransform())
}
}
|
b1460e6d45b7ecba7af075e34cd5e6c4
| 23.693548 | 79 | 0.546048 | false | false | false | false |
liuweicode/LinkimFoundation
|
refs/heads/master
|
Example/LinkimFoundation/Foundation/System/Network/NetworkClient.swift
|
mit
|
1
|
//
// NetworkClient.swift
// Pods
//
// Created by 刘伟 on 16/6/30.
//
//
import UIKit
import Alamofire
typealias NetworkSuccessBlock = (message:NetworkMessage) -> Void
typealias NetworkFailBlock = (message:NetworkMessage) -> Void
enum NetworkRequestMethod : Int {
case POST, GET
}
var clientNO:UInt = 1
class NetworkClient : NSObject {
// 网络数据封装
lazy var message = NetworkMessage()
// 回调者
private var target:NSObject
// 超时时间
let networkTimeout:NSTimeInterval = 30
// 请求任务
var task:Request?
// 当前任务标识
var clientId:NSNumber?
// 回调
var successBlock:NetworkSuccessBlock?
var failBlock:NetworkFailBlock?
init(target obj:NSObject) {
target = obj
super.init()
clientNO = clientNO + 1
clientId = NSNumber(unsignedInteger: clientNO)
NetworkClientManager.sharedInstance.addClient(client: self, forClientId: clientId!)
}
func send(method method:NetworkRequestMethod, params:[String:AnyObject], url:String, successBlock:NetworkSuccessBlock, failBlock:NetworkFailBlock ) -> NSNumber? {
self.message.request.url = url
self.message.request.params = params
self.message.request.method = method
self.successBlock = successBlock
self.failBlock = failBlock
return self.send()
}
private func send() -> NSNumber?
{
switch self.message.request.method {
case .POST:
self.task = self.POST()
case .GET:
self.task = self.GET()
}
return self.clientId
}
private func POST() -> Request? {
return Alamofire.request(.POST, self.message.request.url!,
parameters:[:],
encoding: Alamofire.ParameterEncoding.Custom({ (convertible, params) -> (NSMutableURLRequest, NSError?) in
var data:NSData?
do{
data = try NSJSONSerialization.dataWithJSONObject(self.message.request.params!, options: NSJSONWritingOptions.init(rawValue: 0))
}catch{
print("--------请求参数报错-------")
}
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = data
mutableRequest.addValue("abcdefg", forHTTPHeaderField: "id")
return (mutableRequest, nil)
}),
headers: nil ).validate().response(completionHandler: {[weak self] (request, response, data, error) in
// 设置请求头信息
self?.message.request.headers = request?.allHTTPHeaderFields
// 设置响应信息
self?.message.response.data = data
self?.message.response.headers = response?.allHeaderFields
// 是否有错误
if let responseError = error{
self?.message.networkError = .httpError(responseError.code, responseError.description)
self?.failure()
}else{
self?.success()
}
NetworkClientManager.sharedInstance.removeClientWithId((self?.clientId!)!)
})
}
private func GET() -> Request? {
return Alamofire.request(.GET, self.message.request.url!,
parameters:self.message.request.params,
encoding: Alamofire.ParameterEncoding.JSON,
headers: nil ).validate().response(completionHandler: {[weak self] (request, response, data, error) in
// 设置请求头信息
self?.message.request.headers = request?.allHTTPHeaderFields
// 设置响应信息
self?.message.response.data = data
self?.message.response.headers = response?.allHeaderFields
// 是否有错误
if let responseError = error{
self?.message.networkError = .httpError(responseError.code, responseError.description)
self?.failure()
}else{
self?.success()
}
NetworkClientManager.sharedInstance.removeClientWithId((self?.clientId!)!)
})
}
private func success()
{
self.successBlock?(message:self.message)
}
private func failure()
{
self.failBlock?(message:self.message)
}
// 取消请求
func cancel() {
self.task?.cancel()
}
// 获取调用者
func requestReceive() -> NSObject {
return self.target
}
}
|
d95e52b121b1d27cf9d133d5271f806c
| 30.623288 | 166 | 0.566385 | false | false | false | false |
xiongxiong/TagList
|
refs/heads/master
|
Example/TagList/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TagList
//
// Created by 王继荣 on 13/12/2016.
// Copyright © 2016 wonderbear. All rights reserved.
//
import UIKit
import SwiftTagList
class ViewController: UIViewController {
var addBtn: UIButton = {
let view = UIButton()
view.setTitle("Add Tag", for: .normal)
view.layer.borderWidth = 1
view.layer.borderColor = UIColor.blue.cgColor
view.layer.cornerRadius = 10
view.setTitleColor(UIColor.blue, for: .normal)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var typeLabel: UILabel = {
let view = UILabel()
view.text = "tag type"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var typeSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["text", "icon", "icon & text"])
view.selectedSegmentIndex = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var selectLabel: UILabel = {
let view = UILabel()
view.text = "multi selection"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var selectSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["none", "single", "multi"])
view.selectedSegmentIndex = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignHorizontalLabel: UILabel = {
let view = UILabel()
view.text = "horizontal alignment"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignHorizontalSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["left", "center", "right"])
view.selectedSegmentIndex = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignVerticalLabel: UILabel = {
let view = UILabel()
view.text = "vertical alignment"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignVerticalSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["top", "center", "bottom"])
view.selectedSegmentIndex = 1
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchSeparateLabel: UILabel = {
let view = UILabel()
view.text = "tag is separated"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchSeparateBtn: UISwitch = {
let view = UISwitch()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchDeleteLabel: UILabel = {
let view = UILabel()
view.text = "tag is deletable"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchDeleteBtn: UISwitch = {
let view = UISwitch()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var areaSelected: UIScrollView = {
let view = UIScrollView()
view.backgroundColor = UIColor.lightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var selectedTagList: TagList = {
let view = TagList()
view.isAutowrap = false
view.backgroundColor = UIColor.yellow
view.tagMargin = UIEdgeInsets(top: 3, left: 5, bottom: 3, right: 5)
view.separator.image = #imageLiteral(resourceName: "icon_arrow_right")
view.separator.size = CGSize(width: 16, height: 16)
view.separator.margin = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return view
}()
var areaList: UIScrollView = {
let view = UIScrollView()
view.backgroundColor = UIColor.cyan
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var tagList: TagList = {
let view = TagList()
view.backgroundColor = UIColor.green
view.tagMargin = UIEdgeInsets(top: 3, left: 5, bottom: 3, right: 5)
view.separator.image = #imageLiteral(resourceName: "icon_arrow_right")
view.separator.size = CGSize(width: 16, height: 16)
view.separator.margin = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return view
}()
var areaListMask = UIView()
var swiDelete: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(addBtn)
view.addSubview(typeLabel)
view.addSubview(typeSegment)
view.addSubview(selectLabel)
view.addSubview(selectSegment)
view.addSubview(alignHorizontalLabel)
view.addSubview(alignHorizontalSegment)
view.addSubview(alignVerticalLabel)
view.addSubview(alignVerticalSegment)
view.addSubview(switchSeparateLabel)
view.addSubview(switchSeparateBtn)
view.addSubview(switchDeleteLabel)
view.addSubview(switchDeleteBtn)
view.addSubview(areaSelected)
areaSelected.addSubview(selectedTagList)
view.addSubview(areaList)
areaList.addSubview(tagList)
addBtn.addTarget(self, action: #selector(addTag), for: .touchUpInside)
typeSegment.addTarget(self, action: #selector(switchType), for: .valueChanged)
selectSegment.addTarget(self, action: #selector(switchSelect), for: .valueChanged)
alignHorizontalSegment.addTarget(self, action: #selector(switchHorizontalAlign), for: .valueChanged)
alignVerticalSegment.addTarget(self, action: #selector(switchVerticalAlign), for: .valueChanged)
switchSeparateBtn.addTarget(self, action: #selector(switchSeparate), for: .valueChanged)
switchDeleteBtn.addTarget(self, action: #selector(switchDelete), for: .valueChanged)
selectedTagList.delegate = self
tagList.delegate = self
// ==================================
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 40))
// ==================================
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .trailing, relatedBy: .equal, toItem: selectSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .top, relatedBy: .equal, toItem: addBtn, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: typeSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: typeSegment, attribute: .centerY, relatedBy: .equal, toItem: typeLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .trailing, relatedBy: .equal, toItem: selectSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .top, relatedBy: .equal, toItem: typeLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: selectSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: selectSegment, attribute: .centerY, relatedBy: .equal, toItem: selectLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .trailing, relatedBy: .equal, toItem: alignHorizontalSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .top, relatedBy: .equal, toItem: selectLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalSegment, attribute: .centerY, relatedBy: .equal, toItem: alignHorizontalLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .trailing, relatedBy: .equal, toItem: alignHorizontalSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .top, relatedBy: .equal, toItem: alignHorizontalLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: alignVerticalSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: alignVerticalSegment, attribute: .centerY, relatedBy: .equal, toItem: alignVerticalLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .trailing, relatedBy: .equal, toItem: switchSeparateBtn, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .top, relatedBy: .equal, toItem: alignVerticalLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: switchSeparateBtn, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateBtn, attribute: .centerY, relatedBy: .equal, toItem: switchSeparateLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .trailing, relatedBy: .equal, toItem: switchDeleteBtn, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .top, relatedBy: .equal, toItem: switchSeparateLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: switchDeleteBtn, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteBtn, attribute: .centerY, relatedBy: .equal, toItem: switchDeleteLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .top, relatedBy: .equal, toItem: switchDeleteLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 80))
// ==================================
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .top, relatedBy: .equal, toItem: areaSelected, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectedTagList.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: areaSelected.frame.height))
tagList.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: areaList.frame.width, height: 0))
}
func addTag() {
let str = "In 1886 he moved to Paris where he met members of the avant-garde"
let icons = ["tag_0","tag_1","tag_2","tag_3","tag_4","tag_5","tag_6","tag_7","tag_8","tag_9"]
let tagArr = str.components(separatedBy: .whitespaces)
let tagStr = tagArr[Int(arc4random_uniform(UInt32(tagArr.count)))]
var newPresent: TagPresentable!
switch typeSegment.selectedSegmentIndex {
case 1:
newPresent = TagPresentableIcon(tag: tagStr, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))], height: 30)
case 2:
newPresent = TagPresentableIconText(tag: tagStr, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))]) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
default:
newPresent = TagPresentableText(tag: tagStr) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
}
let tag = Tag(content: newPresent, onInit: {
$0.padding = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10)
$0.layer.borderColor = UIColor.cyan.cgColor
$0.layer.borderWidth = 2
$0.layer.cornerRadius = 5
$0.backgroundColor = UIColor.white
}, onSelect: {
$0.backgroundColor = $0.isSelected ? UIColor.orange : UIColor.white
})
if swiDelete {
tag.wrappers = [TagWrapperRemover(onInit: {
$0.space = 8
$0.deleteButton.tintColor = UIColor.black
}) {
$0.deleteButton.tintColor = $1 ? UIColor.white : UIColor.black
}]
}
tagList.tags.append(tag)
}
func switchType() {
let icons = ["tag_0","tag_1","tag_2","tag_3","tag_4","tag_5","tag_6","tag_7","tag_8","tag_9"]
tagList.tags = tagList.tagPresentables().map({ (present) -> Tag in
var newPresent: TagPresentable!
switch typeSegment.selectedSegmentIndex {
case 1:
newPresent = TagPresentableIcon(tag: present.tag, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))], height: 30)
case 2:
newPresent = TagPresentableIconText(tag: present.tag, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))]) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
default:
newPresent = TagPresentableText(tag: present.tag) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
}
let tag = Tag(content: newPresent, onInit: {
$0.padding = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10)
$0.layer.borderColor = UIColor.cyan.cgColor
$0.layer.borderWidth = 2
$0.layer.cornerRadius = 5
$0.backgroundColor = UIColor.white
}, onSelect: {
$0.backgroundColor = $0.isSelected ? UIColor.orange : UIColor.white
})
if swiDelete {
tag.wrappers = [TagWrapperRemover(onInit: {
$0.space = 8
$0.deleteButton.tintColor = UIColor.black
}) {
$0.deleteButton.tintColor = $1 ? UIColor.white : UIColor.black
}]
}
return tag
})
}
func switchSelect() {
tagList.selectionMode = [TagSelectionMode.none, TagSelectionMode.single, TagSelectionMode.multiple][selectSegment.selectedSegmentIndex]
if tagList.selectionMode == TagSelectionMode.none {
tagList.clearSelected()
}
}
func switchSeparate() {
tagList.isSeparatorEnabled = switchSeparateBtn.isOn
}
func switchDelete() {
swiDelete = switchDeleteBtn.isOn
if switchDeleteBtn.isOn {
tagList.tags.forEach { (tag) in
tag.wrappers = [TagWrapperRemover(onInit: {
$0.space = 8
$0.deleteButton.tintColor = UIColor.black
}) {
$0.deleteButton.tintColor = $1 ? UIColor.white : UIColor.black
}]
}
} else {
tagList.tags.forEach { (tag) in
tag.wrappers = []
}
}
}
func switchHorizontalAlign() {
tagList.horizontalAlignment = [TagHorizontalAlignment.left, TagHorizontalAlignment.center, TagHorizontalAlignment.right][alignHorizontalSegment.selectedSegmentIndex]
}
func switchVerticalAlign() {
tagList.verticalAlignment = [TagVerticalAlignment.top, TagVerticalAlignment.center, TagVerticalAlignment.bottom][alignHorizontalSegment.selectedSegmentIndex]
}
func updateSelectedTagList() {
selectedTagList.tags = tagList.selectedTagPresentables().map({ (tag) -> Tag in
Tag(content: TagPresentableText(tag: tag.tag) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}, onInit: {
$0.padding = UIEdgeInsets(top: 3, left: 5, bottom: 3, right: 5)
$0.layer.borderColor = UIColor.cyan.cgColor
$0.layer.borderWidth = 2
$0.layer.cornerRadius = 5
})
})
}
}
extension ViewController: TagListDelegate {
func tagListUpdated(tagList: TagList) {
if tagList == selectedTagList {
areaSelected.contentSize = tagList.intrinsicContentSize
} else {
areaList.contentSize = tagList.intrinsicContentSize
updateSelectedTagList()
}
}
func tagActionTriggered(tagList: TagList, action: TagAction, content: TagPresentable, index: Int) {
print("========= action -- \(action), content -- \(content.tag), index -- \(index)")
}
}
|
ae24b4935be2c0b5b5a84f30dae2a5cf
| 57.06366 | 196 | 0.656053 | false | false | false | false |
leuski/Coiffeur
|
refs/heads/github
|
Coiffeur/src/view/OptionsRowView.swift
|
apache-2.0
|
1
|
//
// OptionsRowView.swift
// Coiffeur
//
// Created by Anton Leuski on 4/16/15.
// Copyright (c) 2015 Anton Leuski. All rights reserved.
//
// 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 Cocoa
class ConfigCellView: NSTableCellView {
// prevent the state restoration mechanism to save/restore this view properties
override class var restorableStateKeyPaths: [String] { return [] }
}
class ConfigOptionCellView: ConfigCellView {
// will use this to shift the content of the cell appropriately
@IBOutlet weak var leftMargin: NSLayoutConstraint!
}
class ConfigChoiceCellView: ConfigOptionCellView {
@IBOutlet weak var segmented: NSSegmentedControl!
}
extension ConfigNodeLocation {
var color: NSColor {
// section color
return NSColor(calibratedHue: CGFloat(index)/CGFloat(12),
saturation: 0.7, brightness: 0.7, alpha: 1)
}
}
class ConfigRowView: NSTableRowView {
// prevent the state restoration mechanism to save/restore this view properties
override class var restorableStateKeyPaths: [String] { return [] }
@IBOutlet weak var leftMargin: NSLayoutConstraint!
@IBOutlet weak var textField: NSTextField!
var drawSeparator = false
typealias Location = ConfigNode.Location
var locations = [Location]()
override func drawBackground(in dirtyRect: NSRect)
{
if self.isGroupRowStyle {
// start with the background color
var backgroundColor = self.backgroundColor
if self.locations.count > 1 {
// if this is a subsection, add a splash of supersection color
backgroundColor = backgroundColor.blended(
withFraction: 0.1, of: locations[0].color)
?? backgroundColor
}
// make it a bit darker
backgroundColor = backgroundColor.shadow(withLevel: 0.025)
?? backgroundColor
if self.isFloating {
// if the row is floating, add a bit of transparency
backgroundColor = backgroundColor.withAlphaComponent(0.75)
}
backgroundColor.setFill()
} else {
_adjustTextFieldFont()
self.backgroundColor.setFill()
}
NSRect(x: CGFloat(0), y: CGFloat(0),
width: self.bounds.size.width, height: self.bounds.size.height).fill()
if drawSeparator {
_separatorPath().stroke()
}
// draw the colored lines using the section colors
for index in 0 ..< min(1, locations.count - 1) {
locations[index].color.setFill()
NSRect(x: CGFloat(3 + index*5), y: CGFloat(0),
width: CGFloat(3), height: self.bounds.size.height-1).fill()
}
// if we are a group, underline the title with the appropriate color
if self.isGroupRowStyle && locations.count == 1 {
locations.last?.color.set()
let path = NSBezierPath()
let lineLength = 200
let hOffset = 3 + 5*(locations.count-1)
path.lineWidth = CGFloat(1)
path.move(to: NSPoint(x: CGFloat(hOffset),
y: self.bounds.size.height-path.lineWidth+0.5))
path.line(to: NSPoint(x: CGFloat(lineLength - hOffset),
y: self.bounds.size.height-path.lineWidth+0.5))
path.stroke()
}
}
private func _adjustTextFieldFont() {
guard
let textField = textField,
let textFieldFont = textField.font
else { return }
if self.interiorBackgroundStyle == .dark {
textField.textColor = .selectedTextColor
if self.window?.backingScaleFactor == 1 {
// light on dark looks bad on regular resolution screen,
// so we make the font bold to improve readability
textField.font = NSFontManager.shared.convert(
textFieldFont, toHaveTrait: .boldFontMask)
} else {
// on a retina screen the same text looks fine. no need to do bold.
textField.font = NSFontManager.shared.convert(
textFieldFont, toNotHaveTrait: .boldFontMask)
}
} else {
textField.textColor = NSColor.textColor
textField.font = NSFontManager.shared.convert(
textFieldFont, toNotHaveTrait: .boldFontMask)
}
}
private func _separatorPath() -> NSBezierPath {
// draw the top border
let path = NSBezierPath()
path.lineWidth = CGFloat(1)
path.move(to: NSPoint(x: CGFloat(0),
y: self.bounds.size.height-path.lineWidth+0.5))
path.line(to: NSPoint(x: self.bounds.size.width,
y: self.bounds.size.height-path.lineWidth+0.5))
NSColor.gridColor.set()
return path
}
override func drawSelection(in dirtyRect: NSRect)
{
let margin = CGFloat(7)
// start with the regular selection color
var color = NSColor.selectedMenuItemColor
// add a hint of the current section color
if locations.count > 0 {
color = color.blended(
withFraction: 0.25, of: locations[0].color) ?? color
}
if self.interiorBackgroundStyle == .light {
// if we are out of focus, lighten the color
color = color.blended(
withFraction: 0.9, of: NSColor(calibratedWhite: 0.9, alpha: 1))
?? color
}
// make sure it is not transparent
color = color.withAlphaComponent(1)
// paint
color.setFill()
NSRect(
x: margin, y: CGFloat(0),
width: bounds.size.width-margin,
height: bounds.size.height-1)
.fill()
}
}
|
d7a673e493cdbcb0a8be4eda39bab2e5
| 31.831461 | 81 | 0.660849 | false | false | false | false |
BalestraPatrick/Tweetometer
|
refs/heads/develop
|
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/Views/SpinnerCell.swift
|
apache-2.0
|
4
|
/**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import UIKit
func spinnerSectionController() -> ListSingleSectionController {
let configureBlock = { (item: Any, cell: UICollectionViewCell) in
guard let cell = cell as? SpinnerCell else { return }
cell.activityIndicator.startAnimating()
}
let sizeBlock = { (item: Any, context: ListCollectionContext?) -> CGSize in
guard let context = context else { return .zero }
return CGSize(width: context.containerSize.width, height: 100)
}
return ListSingleSectionController(cellClass: SpinnerCell.self,
configureBlock: configureBlock,
sizeBlock: sizeBlock)
}
final class SpinnerCell: UICollectionViewCell {
lazy var activityIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
let bounds = contentView.bounds
activityIndicator.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
}
|
e5201107606987c493a145cdc0147528
| 36.875 | 80 | 0.70462 | false | true | false | false |
cemolcay/Fretboard
|
refs/heads/master
|
Source/FretboardView.swift
|
mit
|
1
|
//
// FretboardView.swift
// Fretboard
//
// Created by Cem Olcay on 20/04/2017.
//
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
import MusicTheorySwift
import CenterTextLayer
// MARK: - FretLabel
@IBDesignable
public class FretLabel: FRView {
public var textLayer = CenterTextLayer()
// MARK: Init
#if os(iOS) || os(tvOS)
public override init(frame: CGRect) {
super.init(frame: frame)
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.contentsScale = UIScreen.main.scale
layer.addSublayer(textLayer)
}
#elseif os(OSX)
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.contentsScale = NSScreen.main?.backingScaleFactor ?? 1
layer?.addSublayer(textLayer)
}
#endif
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Lifecycle
#if os(iOS) || os(tvOS)
public override func layoutSubviews() {
super.layoutSubviews()
textLayer.frame = layer.bounds
}
#elseif os(OSX)
public override func layout() {
super.layout()
guard let layer = layer else { return }
textLayer.frame = layer.bounds
}
#endif
}
// MARK: - FretView
public enum FretNoteType {
case `default`
case capoStart
case capo
case capoEnd
case none
}
@IBDesignable
public class FretView: FRView {
/// `FretboardNote` on fretboard.
public var note: FretboardNote
/// Direction of fretboard.
public var direction: FretboardDirection = .horizontal
/// Note drawing style if it is pressed.
public var noteType: FretNoteType = .none
/// Note drawing offset from edges.
public var noteOffset: CGFloat = 5
/// If its 0th fret, than it is an open string, which is not a fret technically but represented as a FretView.
public var isOpenString: Bool = false
/// Draws the selected note on its text layer.
public var isDrawSelectedNoteText: Bool = true
/// When we are on chordMode, we check the if capo on the fret to detect chords.
public var isCapoOn: Bool = false
/// Shape layer that strings draws on.
public var stringLayer = CAShapeLayer()
/// Shape layer that frets draws on.
public var fretLayer = CAShapeLayer()
/// Shape layer that notes draws on.
public var noteLayer = CAShapeLayer()
/// Text layer that notes writes on.
public var textLayer = CenterTextLayer()
/// `textLayer` color that note text draws on.
public var textColor = FRColor.white.cgColor
// MARK: Init
public init(note: FretboardNote) {
self.note = note
super.init(frame: .zero)
setup()
}
required public init?(coder: NSCoder) {
note = FretboardNote(note: Pitch(midiNote: 0), fretIndex: 0, stringIndex: 0)
super.init(coder: coder)
setup()
}
// MARK: Lifecycle
#if os(iOS) || os(tvOS)
public override func layoutSubviews() {
super.layoutSubviews()
draw()
}
#elseif os(OSX)
public override func layout() {
super.layout()
draw()
}
#endif
// MARK: Setup
private func setup() {
#if os(OSX)
wantsLayer = true
guard let layer = layer else { return }
#endif
layer.addSublayer(stringLayer)
layer.addSublayer(fretLayer)
layer.addSublayer(noteLayer)
layer.addSublayer(textLayer)
#if os(iOS) || os(tvOS)
textLayer.contentsScale = UIScreen.main.scale
#elseif os(OSX)
textLayer.contentsScale = NSScreen.main?.backingScaleFactor ?? 1
#endif
}
// MARK: Draw
private func draw() {
#if os(OSX)
guard let layer = layer else { return }
#endif
CATransaction.setDisableActions(true)
// FretLayer
fretLayer.frame = layer.bounds
let fretPath = FRBezierPath()
switch direction {
case .horizontal:
fretPath.move(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.minY))
fretPath.addLine(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.maxY))
case .vertical:
#if os(iOS) || os(tvOS)
fretPath.move(to: CGPoint(x: fretLayer.frame.minX, y: fretLayer.frame.maxY))
fretPath.addLine(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.maxY))
#elseif os(OSX)
fretPath.move(to: CGPoint(x: fretLayer.frame.minX, y: fretLayer.frame.minY))
fretPath.addLine(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.minY))
#endif
}
fretLayer.path = fretPath.cgPath
// StringLayer
stringLayer.frame = layer.bounds
let stringPath = FRBezierPath()
if !isOpenString { // Don't draw strings on fret 0 because it is open string.
switch direction {
case .horizontal:
stringPath.move(to: CGPoint(x: stringLayer.frame.minX, y: stringLayer.frame.midY))
stringPath.addLine(to: CGPoint(x: stringLayer.frame.maxX, y: stringLayer.frame.midY))
case .vertical:
stringPath.move(to: CGPoint(x: stringLayer.frame.midX, y: stringLayer.frame.minY))
stringPath.addLine(to: CGPoint(x: stringLayer.frame.midX, y: stringLayer.frame.maxY))
}
}
stringLayer.path = stringPath.cgPath
// NoteLayer
noteLayer.frame = layer.bounds
let noteSize = max(min(noteLayer.frame.size.width, noteLayer.frame.size.height) - noteOffset, 0)
var notePath = FRBezierPath()
switch noteType {
case .none:
break
case .capo:
switch direction {
case .horizontal:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height))
#elseif os(OSX)
notePath.appendRect(CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width,
height: noteSize))
#elseif os(OSX)
notePath.appendRect(CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width,
height: noteSize))
#endif
}
case .capoStart:
switch direction {
case .horizontal:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.midX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
#endif
}
case .capoEnd:
switch direction {
case .horizontal:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
#endif
}
default:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
#endif
}
noteLayer.path = notePath.cgPath
// TextLayer
let noteText = NSAttributedString(
string: "\(note.note.key)",
attributes: [
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.font: FRFont.systemFont(ofSize: noteSize / 2)
])
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.string = isDrawSelectedNoteText && note.isSelected ? noteText : nil
textLayer.frame = layer.bounds
}
}
// MARK: - FretboardView
@IBDesignable
public class FretboardView: FRView, FretboardDelegate {
public var fretboard = Fretboard()
@IBInspectable public var fretStartIndex: Int = 0 { didSet { fretboard.startIndex = fretStartIndex }}
@IBInspectable public var fretCount: Int = 5 { didSet { fretboard.count = fretCount }}
@IBInspectable public var direction: String = "horizontal" { didSet { directionDidChange() }}
@IBInspectable public var isDrawNoteName: Bool = true { didSet { redraw() }}
@IBInspectable public var isDrawStringName: Bool = true { didSet { redraw() }}
@IBInspectable public var isDrawFretNumber: Bool = true { didSet { redraw() }}
@IBInspectable public var isDrawCapo: Bool = true { didSet { redraw() }}
@IBInspectable public var isChordModeOn: Bool = false { didSet { redraw() }}
@IBInspectable public var fretWidth: CGFloat = 5 { didSet { redraw() }}
@IBInspectable public var stringWidth: CGFloat = 0.5 { didSet { redraw() }}
#if os(iOS) || os(tvOS)
@IBInspectable public var stringColor: UIColor = .black { didSet { redraw() }}
@IBInspectable public var fretColor: UIColor = .darkGray { didSet { redraw() }}
@IBInspectable public var noteColor: UIColor = .black { didSet { redraw() }}
@IBInspectable public var noteTextColor: UIColor = .white { didSet { redraw() }}
@IBInspectable public var stringLabelColor: UIColor = .black { didSet { redraw() }}
@IBInspectable public var fretLabelColor: UIColor = .black { didSet { redraw() }}
#elseif os(OSX)
@IBInspectable public var stringColor: NSColor = .black { didSet { redraw() }}
@IBInspectable public var fretColor: NSColor = .darkGray { didSet { redraw() }}
@IBInspectable public var noteColor: NSColor = .black { didSet { redraw() }}
@IBInspectable public var noteTextColor: NSColor = .white { didSet { redraw() }}
@IBInspectable public var stringLabelColor: NSColor = .black { didSet { redraw() }}
@IBInspectable public var fretLabelColor: NSColor = .black { didSet { redraw() }}
#endif
private var fretViews: [FretView] = []
private var fretLabels: [FretLabel] = []
private var stringLabels: [FretLabel] = []
// MARK: Init
#if os(iOS) || os(tvOS)
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
#elseif os(OSX)
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
#endif
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: Lifecycle
#if os(iOS) || os(tvOS)
public override func layoutSubviews() {
super.layoutSubviews()
draw()
drawNotes()
}
#elseif os(OSX)
public override func layout() {
super.layout()
draw()
drawNotes()
}
#endif
// MARK: Setup
private func setup() {
// Create fret views
fretViews.forEach({ $0.removeFromSuperview() })
fretViews = []
fretboard.notes.forEach{ fretViews.append(FretView(note: $0)) }
fretViews.forEach({ addSubview($0) })
// Create fret numbers
fretLabels.forEach({ $0.removeFromSuperview() })
fretLabels = []
(0..<fretboard.count).forEach({ _ in fretLabels.append(FretLabel(frame: .zero)) })
fretLabels.forEach({ addSubview($0) })
// Create string names
stringLabels.forEach({ $0.removeFromSuperview() })
stringLabels = []
fretboard.tuning.strings.forEach({ _ in stringLabels.append(FretLabel(frame: .zero)) })
stringLabels.forEach({ addSubview($0) })
// Set FretboardDelegate
fretboard.delegate = self
}
private func directionDidChange() {
switch direction {
case "vertical", "Vertical":
fretboard.direction = .vertical
default:
fretboard.direction = .horizontal
}
}
// MARK: Draw
private func draw() {
let gridWidth = frame.size.width / (CGFloat(fretboard.direction == .horizontal ? fretboard.count : fretboard.tuning.strings.count) + 0.5)
let gridHeight = frame.size.height / (CGFloat(fretboard.direction == .horizontal ? fretboard.tuning.strings.count: fretboard.count) + 0.5)
// String label size
var stringLabelSize = CGSize()
if isDrawStringName {
let horizontalSize = CGSize(
width: gridWidth / 2,
height: gridHeight)
let verticalSize = CGSize(
width: gridWidth,
height: gridHeight / 2)
stringLabelSize = fretboard.direction == .horizontal ? horizontalSize : verticalSize
}
// Fret label size
var fretLabelSize = CGSize()
if isDrawFretNumber {
let horizontalSize = CGSize(
width: (frame.size.width - stringLabelSize.width) / CGFloat(fretboard.direction == .horizontal ? fretboard.count : fretboard.tuning.strings.count),
height: gridHeight / 2)
let verticalSize = CGSize(
width: gridWidth / 2,
height: (frame.size.height - stringLabelSize.height) / CGFloat(fretboard.direction == .horizontal ? fretboard.tuning.strings.count : fretboard.count))
fretLabelSize = fretboard.direction == .horizontal ? horizontalSize : verticalSize
}
// Fret view size
let horizontalSize = CGSize(
width: (frame.size.width - stringLabelSize.width) / CGFloat(fretboard.count),
height: (frame.size.height - fretLabelSize.height) / CGFloat(fretboard.tuning.strings.count))
let verticalSize = CGSize(
width: (frame.size.width - fretLabelSize.width) / CGFloat(fretboard.tuning.strings.count),
height: (frame.size.height - stringLabelSize.height) / CGFloat(fretboard.count))
var fretSize = fretboard.direction == .horizontal ? horizontalSize : verticalSize
// Layout string labels
for (index, label) in stringLabels.enumerated() {
var position = CGPoint()
switch fretboard.direction {
case .horizontal:
#if os(iOS) || os(tvOS)
position.y = stringLabelSize.height * CGFloat(index)
#elseif os(OSX)
position.y = frame.size.height - stringLabelSize.height - (stringLabelSize.height * CGFloat(index))
#endif
case .vertical:
position.x = stringLabelSize.width * CGFloat(index) + fretLabelSize.width
}
label.textLayer.string = NSAttributedString(
string: "\(fretboard.strings[index].key)",
attributes: [
NSAttributedString.Key.foregroundColor: stringLabelColor,
NSAttributedString.Key.font: FRFont.systemFont(ofSize: (min(stringLabelSize.width, stringLabelSize.height) * 2) / 3)
])
label.frame = CGRect(origin: position, size: stringLabelSize)
}
// Layout fret labels
for (index, label) in fretLabels.enumerated() {
var position = CGPoint()
switch fretboard.direction {
case .horizontal:
position.x = (fretLabelSize.width * CGFloat(index)) + stringLabelSize.width
#if os(iOS) || os(tvOS)
position.y = frame.size.height - fretLabelSize.height
#endif
case .vertical:
#if os(iOS) || os(tvOS)
position.y = fretLabelSize.height * CGFloat(index) + stringLabelSize.height
#elseif os(OSX)
position.y = frame.size.height - fretLabelSize.height - (fretLabelSize.height * CGFloat(index)) - stringLabelSize.height
#endif
}
if fretboard.startIndex == 0, index == 0 {
label.textLayer.string = nil
} else {
label.textLayer.string = NSAttributedString(
string: "\(fretboard.startIndex + index)",
attributes: [
NSAttributedString.Key.foregroundColor: fretLabelColor,
NSAttributedString.Key.font: FRFont.systemFont(ofSize: (min(fretLabelSize.width, fretLabelSize.height) * 2) / 3)
])
}
label.frame = CGRect(origin: position, size: fretLabelSize)
}
// Layout fret views
for (index, fret) in fretViews.enumerated() {
let fretIndex = fret.note.fretIndex
let stringIndex = fret.note.stringIndex
// Position
var position = CGPoint()
switch fretboard.direction {
case .horizontal:
#if os(iOS) || os(tvOS)
position.x = fretSize.width * CGFloat(fretIndex) + stringLabelSize.width
position.y = fretSize.height * CGFloat(stringIndex)
#elseif os(OSX)
position.x = fretSize.width * CGFloat(fretIndex) + stringLabelSize.width
position.y = frame.size.height - fretSize.height - (fretSize.height * CGFloat(stringIndex))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
position.x = fretSize.width * CGFloat(stringIndex) + fretLabelSize.width
position.y = fretSize.height * CGFloat(fretIndex) + stringLabelSize.height
#elseif os(OSX)
position.x = fretSize.width * CGFloat(stringIndex) + fretLabelSize.width
position.y = frame.size.height - fretSize.height - (fretSize.height * CGFloat(fretIndex)) - stringLabelSize.height
#endif
}
// Fret options
fret.note = fretboard.notes[index]
fret.direction = fretboard.direction
fret.isOpenString = fretboard.startIndex == 0 && fretIndex == 0
fret.isDrawSelectedNoteText = isDrawNoteName
fret.textColor = noteTextColor.cgColor
fret.stringLayer.strokeColor = stringColor.cgColor
fret.stringLayer.lineWidth = stringWidth
fret.fretLayer.strokeColor = fretColor.cgColor
fret.fretLayer.lineWidth = fretWidth * (fretboard.startIndex == 0 && fretIndex == 0 ? 2 : 1)
fret.noteLayer.fillColor = noteColor.cgColor
fret.frame = CGRect(origin: position, size: fretSize)
}
}
private func drawNotes() {
for (index, fret) in fretViews.enumerated() {
let fretIndex = fret.note.fretIndex
let stringIndex = fret.note.stringIndex
let note = fretboard.notes[index]
fret.note = note
if note.isSelected, isDrawCapo {
// Set note types
let notesOnFret = fretboard.notes.filter({ $0.fretIndex == fretIndex }).sorted(by: { $0.stringIndex < $1.stringIndex })
if (notesOnFret[safe: stringIndex-1] == nil || notesOnFret[safe: stringIndex-1]?.isSelected == false),
notesOnFret[safe: stringIndex+1]?.isSelected == true,
notesOnFret[safe: stringIndex+2]?.isSelected == true {
fret.noteType = .capoStart
} else if (notesOnFret[safe: stringIndex+1] == nil || notesOnFret[safe: stringIndex+1]?.isSelected == false),
notesOnFret[safe: stringIndex-1]?.isSelected == true,
notesOnFret[safe: stringIndex-2]?.isSelected == true {
fret.noteType = .capoEnd
} else if notesOnFret[safe: stringIndex-1]?.isSelected == true,
notesOnFret[safe: stringIndex+1]?.isSelected == true {
fret.noteType = .capo
} else {
fret.noteType = .default
}
// Do not draw higher notes on the same string
if isChordModeOn {
let selectedNotesOnString = fretboard.notes
.filter({ $0.stringIndex == stringIndex && $0.isSelected })
.sorted(by: { $0.fretIndex < $1.fretIndex })
if selectedNotesOnString.count > 1,
selectedNotesOnString
.suffix(from: 1)
.contains(where: { $0.fretIndex == fretIndex }) {
fret.noteType = .none
}
}
} else if note.isSelected, !isDrawCapo {
fret.noteType = .default
} else {
fret.noteType = .none
}
#if os(iOS) || os(tvOS)
fret.setNeedsLayout()
#elseif os(OSX)
fret.needsLayout = true
#endif
}
}
private func redraw() {
#if os(iOS) || os(tvOS)
setNeedsLayout()
#elseif os(OSX)
needsLayout = true
#endif
}
// MARK: FretboardDelegate
public func fretboard(_ fretboard: Fretboard, didChange: [FretboardNote]) {
setup()
drawNotes()
}
public func fretboard(_ fretboard: Fretboard, didDirectionChange: FretboardDirection) {
redraw()
}
public func fretboad(_ fretboard: Fretboard, didSelectedNotesChange: [FretboardNote]) {
drawNotes()
}
}
|
40b21bc8e84461df243dd45949c3908f
| 32.372521 | 158 | 0.628199 | false | false | false | false |
skedgo/tripkit-ios
|
refs/heads/main
|
Sources/TripKitUI/views/trip overview/TKSegment+AccessoryViews.swift
|
apache-2.0
|
1
|
//
// TKSegment+AccessoryViews.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 06.03.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
import TripKit
extension TKSegment {
/// Builds recommended accessory views to show for this segment in a detail
/// view.
///
/// These accessory views can include the following:
/// - `TKUITrainOccupancyView`
/// - `TKUIOccupancyView`
/// - `TKUIPathFriendlinessView`
///
/// - Returns: List of accessory view instances; can be empty
func buildAccessoryViews() -> [UIView] {
var accessoryViews: [UIView] = []
let occupancies = realTimeVehicle?.components?.map { $0.map { $0.occupancy ?? .unknown } }
if let occupancies = occupancies, occupancies.count > 1 {
let trainView = TKUITrainOccupancyView()
trainView.occupancies = occupancies
accessoryViews.append(trainView)
}
if let occupancy = realTimeVehicle?.averageOccupancy {
let occupancyView = TKUIOccupancyView(with: .occupancy(occupancy.0, title: occupancy.title))
accessoryViews.append(occupancyView)
}
if let accessibility = wheelchairAccessibility, accessibility.showInUI() {
let wheelchairView = TKUIOccupancyView(with: .wheelchair(accessibility))
accessoryViews.append(wheelchairView)
}
if canShowPathFriendliness {
let pathFriendlinessView = TKUIPathFriendlinessView.newInstance()
pathFriendlinessView.segment = self
accessoryViews.append(pathFriendlinessView)
}
return accessoryViews
}
}
|
daba7f920fa9f69a8446879d06d48af8
| 28.462963 | 98 | 0.693903 | false | false | false | false |
mparrish91/gifRecipes
|
refs/heads/master
|
application/UIViewController+reddift.swift
|
mit
|
2
|
//
// UIViewController+reddift.swift
// reddift
//
// Created by sonson on 2016/09/11.
// Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
extension UIViewController {
func createImageViewPageControllerWith(_ thumbnails: [Thumbnail], openThumbnail: Thumbnail, isOpenedBy3DTouch: Bool = false) -> ImageViewPageController {
for i in 0 ..< thumbnails.count {
if thumbnails[i].thumbnailURL == openThumbnail.thumbnailURL && thumbnails[i].parentID == openThumbnail.parentID {
return ImageViewPageController.controller(thumbnails: thumbnails, index: i, isOpenedBy3DTouch: isOpenedBy3DTouch)
}
}
return ImageViewPageController.controller(thumbnails: thumbnails, index: 0, isOpenedBy3DTouch: isOpenedBy3DTouch)
}
}
|
530c4cce61dc0e5a8d6ac6b36c365316
| 39.15 | 157 | 0.716065 | false | false | false | false |
samsao/DataProvider
|
refs/heads/master
|
Example/DataProvider/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// DataProvider
//
// Created by Guilherme Lisboa on 12/22/2015.
// Copyright (c) 2015 Guilherme Lisboa. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
let tabbarController = UITabBarController()
let tableVC = TableViewExampleController()
tableVC.tabBarItem = UITabBarItem(title: "TableView Example", image: UIImage(named: "TableIcon"), tag: 0)
let collectionVC = CollectionViewExampleController()
collectionVC.tabBarItem = UITabBarItem(title: "CollectionView Example", image: UIImage(named: "CollectionIcon"), tag: 1)
tabbarController.viewControllers = [UINavigationController(rootViewController: tableVC),UINavigationController(rootViewController: collectionVC)]
self.window!.rootViewController = tabbarController
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
c4a1f7291d553254e224276b43dda319
| 50.140351 | 285 | 0.748885 | false | false | false | false |
LTMana/LTPageView
|
refs/heads/master
|
LTPageVIew/LTPageVIew/LTPageView/LTPageStyle.swift
|
mit
|
1
|
//
// LTPageStyle.swift
// LTPageVIew
//
// Created by liubotong on 2017/5/8.
// Copyright © 2017年 LTMana. All rights reserved.
//
import UIKit
struct LTPageStyle{
var titleHeight:CGFloat = 44
var normalColor:UIColor = UIColor.white
var selectColor:UIColor = UIColor.orange
var titleFont : UIFont = UIFont.systemFont(ofSize: 14.0)
var isScrollEnable:Bool = false
var titleMargin:CGFloat = 20
}
|
3ebb2b9bc3209f244a4f4f5a3aeac796
| 22.555556 | 60 | 0.705189 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/Serialization/inherited-initializer.swift
|
apache-2.0
|
32
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t -module-name InheritedInitializerBase %S/Inputs/inherited-initializer-base.swift
// RUN: %target-swift-frontend -emit-silgen -I %t %s | %FileCheck %s
import InheritedInitializerBase
class InheritsInit : Base {}
// CHECK-LABEL: sil hidden [ossa] @$s4main10testSimpleyyF
func testSimple() {
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase0C0CyACSicfcfA_
// CHECK: [[ARG:%.+]] = apply [[DEFAULT]]()
// CHECK: [[INIT:%.+]] = function_ref @$s4main12InheritsInitCyACSicfC
// CHECK: apply [[INIT]]([[ARG]], {{%.+}})
_ = InheritsInit()
// CHECK: [[VALUE:%.+]] = integer_literal $Builtin.IntLiteral, 5
// CHECK: [[ARG:%.+]] = apply {{%.+}}([[VALUE]], {{%.+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[INIT:%.+]] = function_ref @$s4main12InheritsInitCyACSicfC
// CHECK: apply [[INIT]]([[ARG]], {{%.+}})
_ = InheritsInit(5)
} // CHECK: end sil function '$s4main10testSimpleyyF'
struct Reinitializable<T>: Initializable {
init() {}
}
class GenericSub<T: Initializable> : GenericBase<T> {}
class ModifiedGenericSub<U> : GenericBase<Reinitializable<U>> {}
class NonGenericSub : GenericBase<Reinitializable<Int>> {}
// CHECK-LABEL: sil hidden [ossa] @$s4main11testGenericyyF
func testGeneric() {
// CHECK: [[TYPE:%.+]] = metatype $@thick GenericSub<Reinitializable<Int8>>.Type
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
// CHECK: apply [[DEFAULT]]<Reinitializable<Int8>>({{%.+}})
// CHECK: [[INIT:%.+]] = function_ref @$s4main10GenericSubCyACyxGxcfC
// CHECK: apply [[INIT]]<Reinitializable<Int8>>({{%.+}}, [[TYPE]])
_ = GenericSub<Reinitializable<Int8>>.init() // works around SR-3806
// CHECK: [[TYPE:%.+]] = metatype $@thick ModifiedGenericSub<Int16>.Type
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
// CHECK: apply [[DEFAULT]]<Reinitializable<Int16>>({{%.+}})
// CHECK: [[INIT:%.+]] = function_ref @$s4main18ModifiedGenericSubCyACyxGAA15ReinitializableVyxGcfC
// CHECK: apply [[INIT]]<Int16>({{%.+}}, [[TYPE]])
_ = ModifiedGenericSub<Int16>()
// CHECK: [[TYPE:%.+]] = metatype $@thick NonGenericSub.Type
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
// CHECK: apply [[DEFAULT]]<Reinitializable<Int>>({{%.+}})
// CHECK: [[INIT:%.+]] = function_ref @$s4main13NonGenericSubCyAcA15ReinitializableVySiGcfC
// CHECK: apply [[INIT]]({{%.+}}, [[TYPE]])
_ = NonGenericSub()
} // CHECK: end sil function '$s4main11testGenericyyF'
|
38318071870f5313cc7d9afd7fea0bb9
| 48.462963 | 130 | 0.666043 | false | true | false | false |
iAugux/Weboot
|
refs/heads/master
|
Weboot/PanDirectionGestureRecognizer+Addtions.swift
|
mit
|
1
|
//
// PanDirectionGestureRecognizer+Addtions.swift
// TinderSwipeCellSwift
//
// Created by Augus on 8/23/15.
// Copyright © 2015 iAugus. All rights reserved.
// http://stackoverflow.com/a/30607392/4656574
import UIKit
import UIKit.UIGestureRecognizerSubclass
enum PanDirection {
case Vertical
case Horizontal
}
class PanDirectionGestureRecognizer: UIPanGestureRecognizer {
let direction : PanDirection
init(direction: PanDirection, target: AnyObject, action: Selector) {
self.direction = direction
super.init(target: target, action: action)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
if state == .Began {
let velocity = velocityInView(self.view!)
switch direction {
// disable local gesture when locationInView < 44 to ensure UIScreenEdgePanGestureRecognizer is only avalible
// The comfortable minimum size of tappable UI elements is 44 x 44 points.
case .Horizontal where fabs(velocity.y) > fabs(velocity.x) || locationInView(self.view).x <= 44:
state = .Cancelled
case .Vertical where fabs(velocity.x) > fabs(velocity.y):
state = .Cancelled
default:
break
}
}
}
}
|
6c9d91ca9daebf4a02a8abb81126d5a5
| 31.045455 | 125 | 0.638041 | false | false | false | false |
nzaghini/b-viper
|
refs/heads/master
|
WeatherTests/Modules/WeatherLocation/WeatherLocationDefaultPresenterMapperSpec.swift
|
mit
|
2
|
import Nimble
import Quick
@testable import Weather
class WeatherLocationDefaultPresenterMapperSpec: QuickSpec {
var viewModelBuilder: SelectableLocationListViewModelBuilder!
override func spec() {
beforeEach {
self.viewModelBuilder = SelectableLocationListViewModelBuilder()
}
context("When building with a list of locations") {
it("Should return one view model") {
let location = Location.locationWithIndex(1)
let viewModel = self.viewModelBuilder.buildViewModel([location])
expect(viewModel.locations[0].locationId).to(equal(location.locationId))
expect(viewModel.locations[0].name).to(equal(location.name))
expect(viewModel.locations[0].detail).to(equal("Region1, Country1"))
}
}
context("When mapping a map location without region") {
it("Should return a view model with a detail that contains only the country") {
let location = Location(locationId: "id", name: "name", region: "", country: "country", latitude: nil, longitude: nil)
let viewModel = self.viewModelBuilder.buildViewModel([location])
expect(viewModel.locations[0].detail).to(equal("country"))
}
}
}
}
|
4affaae1693d42888509949461cc4df9
| 38.222222 | 134 | 0.596317 | false | false | false | false |
PangPangPangPangPang/MXPlayer
|
refs/heads/master
|
Source/MXPlayerViewController.swift
|
mit
|
1
|
//
// MXPlayerViewController.swift
// MXPlayer
//
// Created by Max Wang on 16/5/20.
// Copyright © 2016年 Max Wang. All rights reserved.
//
import UIKit
import AVFoundation
typealias MXPlayerViewSubClazzImp = MXPlayerViewController
class MXPlayerViewController: UIViewController,MXPlayerCallBack, MXPlayerProtocol,MXPlayerSubClazzProtocol {
var url: NSURL?
var player: MXPlayer!
var playerView: MXPlayerView!
var currentTime: NSTimeInterval! = 0
var duration: NSTimeInterval! = 0
var playableDuration: NSTimeInterval! = 0
var loadState: MXPlayerLoadState! = .unknown
var originFrame: CGRect! {
didSet {
playerView.frame = originFrame
}
}
var scalingMode: MXPlayerScaleMode! {
didSet {
let layer = playerView.layer as! AVPlayerLayer
switch scalingMode as MXPlayerScaleMode {
case .none, .aspectFit:
layer.videoGravity = AVLayerVideoGravityResizeAspect
break
case .aspectFill:
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
break
case .Fill:
layer.videoGravity = AVLayerVideoGravityResize
break
}
}
}
var shouldAutoPlay: Bool! = false
var allowsMediaAirPlay :Bool! = false
var isDanmakuMediaAirPlay: Bool! = false
var airPlayMediaActive: Bool! = false
var playbackRate: Float! = 0
var bufferState: MXPlayerBufferState! {
didSet {
switch bufferState as MXPlayerBufferState {
case .unknown:
break
case .empty:
self.playableBufferBecomeEmpty()
break
case .keepUp:
self.playableBufferBecomeKeepUp()
break
case .full:
break
}
print("bufferState:\(bufferState)")
}
}
var orientationLandScapeRight: Bool! {
didSet {
let value: Int!
if orientationLandScapeRight == true {
value = UIInterfaceOrientation.LandscapeRight.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
playerView.frame = UIScreen.mainScreen().bounds
} else {
value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
playerView.frame = originFrame
}
}
}
var movieState: MXPlayerMovieState! {
didSet {
print(movieState)
}
}
var canPlayFastForward: Bool? {
get {
return self.player.currentItem?.canPlayFastForward
}
}
var canPlaySlowForward: Bool? {
get {
return self.player.currentItem?.canPlaySlowForward
}
}
var canPlayFastReverse: Bool? {
get {
return self.player.currentItem?.canPlayFastReverse
}
}
var canPlaySlowReverse: Bool? {
get {
return self.player.currentItem?.canPlaySlowReverse
}
}
init(url: NSURL?) {
super.init(nibName: nil, bundle: nil)
self.url = url
orientationLandScapeRight = false
scalingMode = .Fill
bufferState = .unknown
movieState = .stopped
AudioSessionManager.shareInstance.audioSession()
self.prepareToplay(self.url)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension MXPlayerViewController {
func playerObserver(item: AVPlayerItem?, keyPath: String?, change: [String : AnyObject]?) {
switch keyPath! {
case "status":
do {
let status = change![NSKeyValueChangeNewKey] as! Int
switch status {
case AVPlayerItemStatus.ReadyToPlay.rawValue:
loadState = .playable
duration = player.duration
break
case AVPlayerItemStatus.Failed.rawValue:
loadState = .failed
break
default:
break
}
}
break
case "loadedTimeRanges":
do {
playableDuration = player.availableDuration()
self.playableDurationDidChange()
}
break
case "playbackBufferFull":
do {
bufferState = .full
}
break
case "playbackLikelyToKeepUp":
do {
bufferState = .keepUp
loadState = .playable
}
break
case "playbackBufferEmpty":
do {
bufferState = .empty
}
break;
default:
break
}
}
func playerPlayWithTime(time: CMTime) {
guard duration != 0 else {return}
currentTime = CMTimeGetSeconds(time)
playbackRate = Float(currentTime) / Float(duration)
self.playDurationDidChange(playbackRate, second: currentTime)
}
}
extension MXPlayerViewController {
func prepareToplay(url: NSURL?) -> Void {
let item = AVPlayerItem.init(URL: url ?? self.url!);
if player == nil {
player = MXPlayer.init(item: item, delegate: self)
playerView = MXPlayerView.init(player: player, frame: self.view.bounds);
originFrame = playerView.frame
playerView.userInteractionEnabled = false
self.view.addSubview(playerView)
self.view.insertSubview(playerView, atIndex: 0)
} else {
self.pause()
player.changePlayerItem(item)
self.play()
}
}
func play() -> Void {
if loadState == MXPlayerLoadState.playable
&& movieState != MXPlayerMovieState.playing {
player.play()
movieState = .playing
}
}
func pause() -> Void {
player.pause()
movieState = .paused
}
func stop() -> Void {
player.setRate(0, time: kCMTimeInvalid, atHostTime: kCMTimeInvalid)
movieState = .stopped
}
func isPlayer() -> Bool {
return movieState == MXPlayerMovieState.playing
}
func shutDown() -> Void {
}
func switchScaleMode(mode: MXPlayerScaleMode!) -> Void {
scalingMode = mode
}
func flashImage() -> UIImage {
return UIImage()
}
func seekToTime(time: NSTimeInterval) -> Void {
player.seekToTime(CMTimeMakeWithSeconds(time, Int32(kCMTimeMaxTimescale)),
toleranceBefore: CMTimeMakeWithSeconds(0.2, Int32(kCMTimeMaxTimescale)),
toleranceAfter: CMTimeMakeWithSeconds(0.2, Int32(kCMTimeMaxTimescale))) {
(result) in
print(result)
}
}
}
extension MXPlayerViewSubClazzImp {
func playableDurationDidChange() {}
func playDurationDidChange(rate: Float, second: NSTimeInterval) {}
func playableBufferBecomeEmpty() {}
func playableBufferBecomeKeepUp() {}
}
|
fee4e2d5e4a98842f9cd8db06edff5c5
| 28.785425 | 108 | 0.558923 | false | false | false | false |
jasnig/ScrollPageView
|
refs/heads/master
|
ScrollViewController/other/TestController.swift
|
mit
|
1
|
//
// TestController.swift
// ScrollViewController
//
// Created by jasnig on 16/4/13.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// 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
class TestController: UIViewController {
// storyBoard中的controller初始化会调用这个初始化方法, 在这里面注册通知监听者
// 如果在viewDidLoad()里面注册第一次出现的时候接受不到通知, 这个在oc里面是没有问题的, 很无奈
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.didSelectIndex(_:)), name: ScrollPageViewDidShowThePageNotification, object: nil)
}
func didSelectIndex(noti: NSNotification) {
let userInfo = noti.userInfo!
//注意键名是currentIndex
print(userInfo["currentIndex"])
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
print("\(self.debugDescription) --- 销毁")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func btnOnClick(sender: UIButton) {
let testSelectedVc = TestSelectedIndexController()
testSelectedVc.backClosure = {[weak self] in
guard let strongSelf = self else { return }
// 或者通过navigationController 的stack 来获取到指定的控制器
if let vc9Controller = strongSelf.parentViewController as? Vc9Controller {
// 返回的时候设置其他页为选中页
vc9Controller.scrollPageView.selectedIndex(3, animated: true)
}
if let vc6Controller = strongSelf.parentViewController as? Vc6Controller {
// 返回的时候设置其他页为选中页
vc6Controller.reloadChildVcs()
}
let rootNav = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController
rootNav?.popViewControllerAnimated(true)
}
showViewController(testSelectedVc, sender: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class Test1Controller: PageTableViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承1-----------------\(indexPath.row)"
return cell
}
}
class Test2Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承2--------------\(indexPath.row)"
return cell
}
}
class Test3Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承3--------------\(indexPath.row)"
return cell
}
}
class Test4Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承4--------------\(indexPath.row)"
return cell
}
}
class Test5Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承5--------------\(indexPath.row)"
return cell
}
}
class Test6Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承6--------------\(indexPath.row)"
return cell
}
}
class Test7Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承7--------------\(indexPath.row)"
return cell
}
}
class Test8Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承8--------------\(indexPath.row)"
return cell
}
}
class Test9Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承9--------------\(indexPath.row)"
return cell
}
}
class Test10Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承10--------------"
return cell
}
}
|
7413b5cc1aaa5cbf84e86ad15d4b2a71
| 31.577963 | 169 | 0.665475 | false | false | false | false |
DashiDashCam/iOS-App
|
refs/heads/master
|
Dashi/Dashi/Controllers/VideosTableViewController.swift
|
mit
|
1
|
//
// VideosTableViewController.swift
// Dashi
//
// Created by Arslan Memon on 10/31/17.
// Copyright © 2017 Senior Design. All rights reserved.
//
import UIKit
import Photos
import CoreMedia
import CoreData
import PromiseKit
import SwiftyJSON
import MapKit
import SVGKit
class VideosTableViewController: UITableViewController {
var videos: [Video] = []
var timer: Timer?
let appDelegate =
UIApplication.shared.delegate as? AppDelegate
// get's video metadata from local db and cloud
override func viewDidLoad() {
super.viewDidLoad()
getMetaData()
// navigation bar and back button
navigationController?.isNavigationBarHidden = false
// override back button to ensure it always returns to the home screen
if let rootVC = navigationController?.viewControllers.first {
navigationController?.viewControllers = [rootVC, self]
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func viewWillAppear(_: Bool) {
self.tableView.reloadData()
// set orientation
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
// lock orientation
AppUtility.lockOrientation(.portrait)
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true){_ in
let cells = self.tableView.visibleCells as! Array<VideoTableViewCell>
self.tableView.beginUpdates()
var indexToRemove : IndexPath? = nil
for cell in cells{
let indexPath = self.tableView.indexPath(for: cell)
let row = indexPath?.row
//prevent code from firing if video was deleted in videoDetail
if(!self.videos[row!].wasDeleted()){
cell.storageIcon.image = UIImage(named: self.videos[row!].getStorageStat()) // idk why, but don't delete this
// set storage image based off stat
var storageImage: SVGKImage
let storageStat = self.videos[row!].getStorageStat()
cell.location.text = self.videos[row!].getLocation()
// video hasn't been uploaded
if storageStat == "local" {
storageImage = SVGKImage(named: "local")
} else {
storageImage = SVGKImage(named: "cloud")
}
cell.storageIcon.image = storageImage.uiImage
if self.videos[row!].getDownloadInProgress() {
var namSvgImgVar: SVGKImage = SVGKImage(named: "download")
cell.uploadDownloadIcon.image = namSvgImgVar.uiImage
cell.uploadDownloadIcon.isHidden = false
} else if self.videos[row!].getUploadInProgress() {
var namSvgImgVar: SVGKImage = SVGKImage(named: "upload")
cell.uploadDownloadIcon.image = namSvgImgVar.uiImage
cell.uploadDownloadIcon.isHidden = false
} else {
cell.uploadDownloadIcon.isHidden = true
}
}
else{
indexToRemove = indexPath
}
}
//I am assuming it is impossible for a user to be able to delete more than one video
//in under 0.5 seconds, so only 1 cell will ever need to be removed at a time
if(indexToRemove != nil){
self.videos.remove(at: (indexToRemove?.row)!)
self.tableView.deleteRows(at: [indexToRemove!], with: .automatic)
}
self.tableView.endUpdates()
}
timer?.fire()
}
override func viewWillDisappear(_ animated: Bool) {
timer?.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
// returns the number of sections(types of cells) that are going to be in the table to the table view controller
override func numberOfSections(in _: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
// returns how many of each type of cell the table has
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return videos.count
}
// allows a row to be deleted
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func getMetaData() {
var fetchedmeta: [NSManagedObject] = []
let managedContext =
appDelegate?.persistentContainer.viewContext
// 2
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Videos")
fetchRequest.predicate = NSPredicate(format: "accountID == %d", (sharedAccount?.getId())!)
fetchRequest.propertiesToFetch = ["startDate", "length", "size", "thumbnail", "id", "startLat", "startLong", "endLat", "endLong", "locationName"]
// 3
do {
fetchedmeta = (try managedContext?.fetch(fetchRequest))!
} catch let error as Error {
print("Could not fetch. \(error), \(error.localizedDescription)")
}
for meta in fetchedmeta {
var video: Video
let id = meta.value(forKey: "id") as! String
let date = meta.value(forKey: "startDate") as! Date
let thumbnailData = meta.value(forKey: "thumbnail") as! Data
let size = meta.value(forKey: "size") as! Int
let length = meta.value(forKey: "length") as! Int
let startLat = meta.value(forKey: "startLat") as! CLLocationDegrees?
let startLong = meta.value(forKey: "startLong") as! CLLocationDegrees?
let endLat = meta.value(forKey: "endLat") as! CLLocationDegrees?
let endLong = meta.value(forKey: "endLong") as! CLLocationDegrees?
let locationName = meta.value(forKey: "locationName") as! String?
if let lat1 = startLat, let lat2 = endLat, let long1 = startLong, let long2 = endLong{
// dates.append(video.value(forKeyPath: "startDate") as! Date)
video = Video(started: date, imageData: thumbnailData, id: id, length: length, size: size, startLoc: CLLocationCoordinate2D(latitude: lat1, longitude: long1), endLoc: CLLocationCoordinate2D(latitude: lat2, longitude: long2), locationName: locationName )
}
else{
video = Video(started: date, imageData: thumbnailData, id: id, length: length, size: size, startLoc: nil, endLoc: nil, locationName: locationName )
}
videos.append(video)
}
videos.sort(by: { $0.getStarted() > $1.getStarted() })
}
// sets cell data for each video
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
let cell = tableView.dequeueReusableCell(withIdentifier: "vidCell2", for: indexPath) as! VideoTableViewCell
let dateFormatter = DateFormatter()
// US English Locale (en_US)
dateFormatter.dateFormat = "MMMM dd"
// dateFormatter.timeStyle = .short
cell.thumbnail.image = videos[row].getThumbnail()
cell.date.text = dateFormatter.string(from: videos[row].getStarted())
cell.location.text = videos[row].getLocation()
// set time
dateFormatter.dateFormat = "hh:mm a"
cell.time.text = dateFormatter.string(from: videos[row].getStarted())
cell.id = videos[row].getId()
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
let preview = segue.destination as! VideoDetailViewController
let row = (tableView.indexPath(for: (sender as! UITableViewCell))?.row)!
let selectedVideo = videos[row]
preview.selectedVideo = selectedVideo
}
// pass the id of a desired video to delete it from core data
func deleteLocal(id: String) {
var content: [NSManagedObject]
let managedContext =
appDelegate?.persistentContainer.viewContext
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Videos")
fetchRequest.propertiesToFetch = ["videoContent"]
fetchRequest.predicate = NSPredicate(format: "id == %@ && accountID == %d", id, (sharedAccount?.getId())!)
do {
content = (try managedContext?.fetch(fetchRequest))!
managedContext?.delete(content[0])
do {
// commit changes to context
try managedContext!.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
} catch let error as NSError {
print("Could not fetch. \(error), \(error.localizedDescription)")
return
}
}
}
|
6f29d614fa05e29b42c757ad810c6f2e
| 40.106227 | 270 | 0.611567 | false | false | false | false |
vauxhall/worldcities
|
refs/heads/master
|
worldcities/Model/ModelListSearch.swift
|
mit
|
1
|
import Foundation
extension ModelList
{
private static let kStringEmpty:String = ""
private static let kStringSpace:String = " "
private static let kStringNewLine:String = "\n"
private static let kStringTab:String = "\t"
private static let kStringReturn:String = "\r"
private class func cleanInput(input:String) -> String
{
var cleaned:String = input.lowercased()
cleaned = cleaned.replacingOccurrences(
of:kStringSpace,
with:kStringEmpty)
cleaned = cleaned.replacingOccurrences(
of:kStringNewLine,
with:kStringEmpty)
cleaned = cleaned.replacingOccurrences(
of:kStringTab,
with:kStringEmpty)
cleaned = cleaned.replacingOccurrences(
of:kStringReturn,
with:kStringEmpty)
return cleaned
}
//MARK: internal
func searchItems(forInput:String) -> [ModelListItem]
{
let cleanedInput:String = ModelList.cleanInput(
input:forInput)
let countCharacters:Int = cleanedInput.characters.count
let items:[ModelListItem]
if countCharacters > 0
{
items = mappedItems(withString:cleanedInput)
}
else
{
items = self.items
}
return items
}
//MARK: private
private func mappedItems(withString:String) -> [ModelListItem]
{
guard
let items:[ModelListItem] = itemsMap[withString]
else
{
return []
}
return items
}
}
|
3e30cf0d5916897e11cac67bdf90f0d7
| 24.136364 | 66 | 0.566606 | false | false | false | false |
itechline/bonodom_new
|
refs/heads/master
|
SlideMenuControllerSwift/MyEstatesCell.swift
|
mit
|
1
|
//
// MyEstatesCell.swift
// Bonodom
//
// Created by Attila Dán on 2016. 07. 20..
// Copyright © 2016. Itechline. All rights reserved.
//
import UIKit
import SwiftyJSON
import SDWebImage
struct MyEstatesCellData {
init(id: Int, imageUrl: String, adress: String, description: String, row: Int) {
self.id = id
self.imageUrl = imageUrl
self.adress = adress
self.description = description
self.row = row
}
var id: Int
var imageUrl: String
var adress: String
var description: String
var row: Int
}
class MyEstatesCell : BaseTableViewCell {
var id : Int!
var row : Int!
let screensize = UIScreen.mainScreen().bounds
@IBOutlet weak var cellWidth: NSLayoutConstraint!
@IBOutlet weak var modifyHeight: NSLayoutConstraint!
@IBOutlet weak var modifyWidth: NSLayoutConstraint!
@IBOutlet weak var deleteHeight: NSLayoutConstraint!
@IBOutlet weak var deleteWidth: NSLayoutConstraint!
@IBOutlet weak var upWidth: NSLayoutConstraint!
@IBOutlet weak var upHeight: NSLayoutConstraint!
@IBOutlet weak var adress_text: UILabel!
@IBOutlet weak var description_text: UILabel!
@IBOutlet weak var estate_image: UIImageView!
@IBOutlet weak var up_text: UIButton!
@IBAction func up_button(sender: AnyObject) {
}
@IBOutlet weak var modify_text: UIButton!
@IBAction func modify_button(sender: AnyObject) {
let mod: [String:AnyObject] = [ "mod": "1", "row": String(row!)]
NSNotificationCenter.defaultCenter().postNotificationName("estate_adding", object: mod)
}
@IBOutlet weak var delete_text: UIButton!
@IBAction func delete_button(sender: AnyObject) {
let del_id: [String:AnyObject] = [ "del_id":String(id!), "row":String(row!)]
NSNotificationCenter.defaultCenter().postNotificationName("delete_estate", object: del_id)
/*EstateUtil.sharedInstance.delete_estate(String(self.id), onCompletion: { (json: JSON) in
print ("DELETE ESTATE")
print (json)
dispatch_async(dispatch_get_main_queue(),{
if (!json["error"].boolValue) {
} else {
}
})
})*/
}
override func awakeFromNib() {
//self.dataText?.font = UIFont.boldSystemFontOfSize(16)
//self.dataText?.textColor = UIColor(hex: "000000")
let iconsize = (((screensize.width)-estate_image.frame.width)-20)/5
let iconwidth = (((screensize.width)-estate_image.frame.width)-20)/4
cellWidth.constant = screensize.width
modifyWidth.constant = iconwidth
modifyHeight.constant = iconsize
deleteWidth.constant = iconwidth
deleteHeight.constant = iconsize
upWidth.constant = iconwidth
upHeight.constant = iconsize
print("iconsize: ", iconsize)
}
override class func height() -> CGFloat {
return 170
}
override func setData(data: Any?) {
if let data = data as? MyEstatesCellData {
if (data.imageUrl != "") {
let url: NSURL = NSURL(string: data.imageUrl)!
self.estate_image.sd_setImageWithURL(url)
} else {
self.estate_image.image = UIImage(named: "noimage")
}
self.estate_image.sizeThatFits(CGSize.init(width: 116.0, height: 169.0))
self.adress_text.text = data.adress
self.description_text.text = data.description
self.row = data.row
self.id = data.id
self.delete_text.layer.cornerRadius = 3
self.delete_text.layer.borderColor = UIColor.redColor().CGColor
self.delete_text.layer.borderWidth = 1
self.modify_text.layer.cornerRadius = 3
self.modify_text.layer.borderColor = UIColor.blueColor().CGColor
self.modify_text.layer.borderWidth = 1
//00D548 -> UP BUTTON COLOR
self.up_text.layer.cornerRadius = 3
self.up_text.layer.borderColor = UIColor(hex: "00D548").CGColor
self.up_text.layer.borderWidth = 1
}
}
}
|
175202f5c763502323cdaf3ac02918cb
| 30.264286 | 98 | 0.594243 | false | false | false | false |
Antondomashnev/Sourcery
|
refs/heads/master
|
Pods/Yams/Sources/Yams/Tag.swift
|
mit
|
3
|
//
// Tag.swift
// Yams
//
// Created by Norio Nomura on 12/15/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
#if SWIFT_PACKAGE
import CYaml
#endif
import Foundation
public final class Tag {
public struct Name: RawRepresentable {
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
}
public static var implicit: Tag {
return Tag(.implicit)
}
// internal
let constructor: Constructor
var name: Name
public init(_ name: Name,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) {
self.resolver = resolver
self.constructor = constructor
self.name = name
}
func resolved<T>(with value: T) -> Tag where T: TagResolvable {
if name == .implicit {
name = resolver.resolveTag(of: value)
} else if name == .nonSpecific {
name = T.defaultTagName
}
return self
}
// fileprivate
fileprivate let resolver: Resolver
}
extension Tag: CustomStringConvertible {
public var description: String {
return name.rawValue
}
}
extension Tag: Hashable {
public var hashValue: Int {
return name.hashValue
}
public static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.name == rhs.name
}
}
extension Tag.Name: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.rawValue = value
}
public init(unicodeScalarLiteral value: String) {
self.rawValue = value
}
public init(extendedGraphemeClusterLiteral value: String) {
self.rawValue = value
}
}
extension Tag.Name: Hashable {
public var hashValue: Int {
return rawValue.hashValue
}
public static func == (lhs: Tag.Name, rhs: Tag.Name) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
// http://www.yaml.org/spec/1.2/spec.html#Schema
extension Tag.Name {
// Special
/// Tag should be resolved by value.
public static let implicit: Tag.Name = ""
/// Tag should not be resolved by value, and be resolved as .str, .seq or .map.
public static let nonSpecific: Tag.Name = "!"
// Failsafe Schema
/// "tag:yaml.org,2002:str" <http://yaml.org/type/str.html>
public static let str: Tag.Name = "tag:yaml.org,2002:str"
/// "tag:yaml.org,2002:seq" <http://yaml.org/type/seq.html>
public static let seq: Tag.Name = "tag:yaml.org,2002:seq"
/// "tag:yaml.org,2002:map" <http://yaml.org/type/map.html>
public static let map: Tag.Name = "tag:yaml.org,2002:map"
// JSON Schema
/// "tag:yaml.org,2002:bool" <http://yaml.org/type/bool.html>
public static let bool: Tag.Name = "tag:yaml.org,2002:bool"
/// "tag:yaml.org,2002:float" <http://yaml.org/type/float.html>
public static let float: Tag.Name = "tag:yaml.org,2002:float"
/// "tag:yaml.org,2002:null" <http://yaml.org/type/null.html>
public static let null: Tag.Name = "tag:yaml.org,2002:null"
/// "tag:yaml.org,2002:int" <http://yaml.org/type/int.html>
public static let int: Tag.Name = "tag:yaml.org,2002:int"
// http://yaml.org/type/index.html
/// "tag:yaml.org,2002:binary" <http://yaml.org/type/binary.html>
public static let binary: Tag.Name = "tag:yaml.org,2002:binary"
/// "tag:yaml.org,2002:merge" <http://yaml.org/type/merge.html>
public static let merge: Tag.Name = "tag:yaml.org,2002:merge"
/// "tag:yaml.org,2002:omap" <http://yaml.org/type/omap.html>
public static let omap: Tag.Name = "tag:yaml.org,2002:omap"
/// "tag:yaml.org,2002:pairs" <http://yaml.org/type/pairs.html>
public static let pairs: Tag.Name = "tag:yaml.org,2002:pairs"
/// "tag:yaml.org,2002:set". <http://yaml.org/type/set.html>
public static let set: Tag.Name = "tag:yaml.org,2002:set"
/// "tag:yaml.org,2002:timestamp" <http://yaml.org/type/timestamp.html>
public static let timestamp: Tag.Name = "tag:yaml.org,2002:timestamp"
/// "tag:yaml.org,2002:value" <http://yaml.org/type/value.html>
public static let value: Tag.Name = "tag:yaml.org,2002:value"
/// "tag:yaml.org,2002:yaml" <http://yaml.org/type/yaml.html> We don't support this.
public static let yaml: Tag.Name = "tag:yaml.org,2002:yaml"
}
protocol TagResolvable {
var tag: Tag { get }
static var defaultTagName: Tag.Name { get }
func resolveTag(using resolver: Resolver) -> Tag.Name
}
extension TagResolvable {
var resolvedTag: Tag {
return tag.resolved(with: self)
}
func resolveTag(using resolver: Resolver) -> Tag.Name {
return tag.name == .implicit ? Self.defaultTagName : tag.name
}
}
|
9731ee881b78a50d2d3a7384e534924c
| 31.135135 | 88 | 0.631623 | false | false | false | false |
oarrabi/Guaka-Generator
|
refs/heads/master
|
Tests/GuakaClILibTests/MockTypes.swift
|
mit
|
1
|
//
// MockDirectoryType.swift
// guaka-cli
//
// Created by Omar Abdelhafith on 27/11/2016.
//
//
@testable import GuakaClILib
struct MockDirectoryType: DirectoryType {
static var currentDirectory: String = ""
static var pathsCreated: [String] = []
static var pathsEmptyValue: [String: Bool] = [:]
static var pathsCreationValue: [String: Bool] = [:]
static var pathsValidationValue: [String: Bool] = [:]
static var pathsExistanceValue: [String: Bool] = [:]
static func clear() {
currentDirectory = ""
pathsCreated = []
pathsEmptyValue = [:]
pathsCreationValue = [:]
pathsValidationValue = [:]
pathsExistanceValue = [:]
}
static func isEmpty(directoryPath: String) -> Bool {
return pathsEmptyValue[directoryPath] ?? false
}
static func create(atPath path: String) -> Bool {
pathsCreated.append(path)
return pathsCreationValue[path] ?? false
}
static func isValidDirectory(atPath path: String) -> Bool {
return pathsValidationValue[path] ?? false
}
static func exists(atPath path: String) -> Bool {
return pathsExistanceValue[path] ?? false
}
}
struct MockFileType: FileType {
static var fileExistanceValue: [String: Bool] = [:]
static var fileReadValue: [String: String] = [:]
static var fileWriteValue: [String: Bool] = [:]
static var writtenFiles: [String: String] = [:]
static func clear() {
fileExistanceValue = [:]
fileReadValue = [:]
fileWriteValue = [:]
writtenFiles = [:]
}
static func write(string: String, toFile file: String) -> Bool {
writtenFiles[file] = string
return fileWriteValue[file] ?? false
}
static func read(fromFile file: String) -> String? {
return fileReadValue[file]
}
static func exists(atPath path: String) -> Bool {
return fileExistanceValue[path] ?? false
}
}
|
a045a13a27ceecf0727550540c13e0d0
| 23.573333 | 66 | 0.66739 | false | false | false | false |
yaslab/ZeroFormatter.swift
|
refs/heads/master
|
Sources/TimeSpan.swift
|
mit
|
1
|
//
// TimeSpan.swift
// ZeroFormatter
//
// Created by Yasuhiro Hatta on 2016/12/15.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
public struct TimeSpan: Serializable {
public let totalSeconds: TimeInterval
public init(totalSeconds: TimeInterval) {
self.totalSeconds = totalSeconds
}
// MARK: - ZeroFormattable
public static var length: Int? {
return 12
}
// MARK: - Serializable
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: TimeSpan) -> Int {
let unixTime = value.totalSeconds
let seconds = Int64(unixTime)
let nanos = Int32((abs(unixTime) - floor(abs(unixTime))) * 1_000_000_000)
var byteSize = 0
byteSize += BinaryUtility.serialize(bytes, seconds)
byteSize += BinaryUtility.serialize(bytes, nanos)
return byteSize
}
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: TimeSpan?) -> Int {
var byteSize = 0
if let value = value {
byteSize += BinaryUtility.serialize(bytes, true)
byteSize += serialize(bytes, -1, value)
} else {
byteSize += BinaryUtility.serialize(bytes, false)
byteSize += BinaryUtility.serialize(bytes, Int64(0)) // seconds
byteSize += BinaryUtility.serialize(bytes, Int32(0)) // nanos
}
return byteSize
}
// MARK: - Deserializable
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> TimeSpan {
let start = byteSize
let seconds: Int64 = BinaryUtility.deserialize(bytes, offset + (byteSize - start), &byteSize)
let nanos: Int32 = BinaryUtility.deserialize(bytes, offset + (byteSize - start), &byteSize)
var unixTime = TimeInterval(seconds)
unixTime += TimeInterval(nanos) / 1_000_000_000.0
return TimeSpan(totalSeconds: unixTime)
}
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> TimeSpan? {
let start = byteSize
let hasValue: Bool = BinaryUtility.deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: TimeSpan = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
}
|
5da8b716405eafe4363de01fdff705e0
| 32.833333 | 104 | 0.612069 | false | false | false | false |
wuleijun/Zeus
|
refs/heads/master
|
Zeus/Views/BorderButton.swift
|
mit
|
1
|
//
// BorderButton.swift
// Zeus
//
// Created by 吴蕾君 on 16/4/12.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
@IBDesignable
class BorderButton: UIButton {
lazy var topLineLayer:CAShapeLayer = {
let topLayer = CAShapeLayer()
topLayer.lineWidth = 1
topLayer.strokeColor = UIColor.zeusBorderColor().CGColor
return topLayer
}()
override func didMoveToSuperview() {
super.didMoveToSuperview()
layer.addSublayer(topLineLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
let topPath = UIBezierPath()
topPath.moveToPoint(CGPoint(x: 0, y: 0.5))
topPath.addLineToPoint(CGPoint(x: CGRectGetWidth(bounds), y: 0.5))
topLineLayer.path = topPath.CGPath
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
679c8f263856ea2e9d6520efcee731d7
| 23.55814 | 78 | 0.63447 | false | false | false | false |
soapyigu/Swift30Projects
|
refs/heads/master
|
Project 07 - PokedexGo/PokedexGo/MasterTableViewCell.swift
|
apache-2.0
|
1
|
//
// MasterTableViewCell.swift
// PokedexGo
//
// Created by Yi Gu on 7/10/16.
// Copyright © 2016 yigu. All rights reserved.
//
import UIKit
class MasterTableViewCell: UITableViewCell {
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var pokeImageView: UIImageView!
fileprivate var indicator: UIActivityIndicatorView!
func awakeFromNib(_ id: Int, name: String, pokeImageUrl: String) {
super.awakeFromNib()
setupUI(id, name: name)
setupNotification(pokeImageUrl)
}
deinit {
pokeImageView.removeObserver(self, forKeyPath: "image")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
fileprivate func setupUI(_ id: Int, name: String) {
idLabel.text = NSString(format: "#%03d", id) as String
nameLabel.text = name
pokeImageView.image = UIImage(named: "default_img")
indicator = UIActivityIndicatorView()
indicator.center = CGPoint(x: pokeImageView.bounds.midX, y: pokeImageView.bounds.midY)
indicator.activityIndicatorViewStyle = .whiteLarge
indicator.startAnimating()
pokeImageView.addSubview(indicator)
pokeImageView.addObserver(self, forKeyPath: "image", options: [], context: nil)
}
fileprivate func setupNotification(_ pokeImageUrl: String) {
NotificationCenter.default.post(name: Notification.Name(rawValue: downloadImageNotification), object: self, userInfo: ["pokeImageView":pokeImageView, "pokeImageUrl" : pokeImageUrl])
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "image" {
indicator.stopAnimating()
}
}
}
|
748fe5bfea3bf96aece9cf018c9f57e1
| 31.363636 | 185 | 0.718539 | false | false | false | false |
chamander/Sampling-Reactive
|
refs/heads/master
|
Source/Models/Weather.swift
|
mit
|
2
|
// Copyright © 2016 Gavan Chan. All rights reserved.
import Argo
import Curry
import Runes
typealias Temperature = Double
typealias Percentage = Double
struct Weather {
let city: City
let current: Temperature
let cloudiness: Percentage
}
extension Weather: Decodable {
static func decode(_ json: JSON) -> Decoded<Weather> {
let city: Decoded<City> = City.decode(json)
let current: Decoded<Temperature> = json <| ["main", "temp"]
let cloudiness: Decoded<Percentage> = json <| ["clouds", "all"]
let initialiser: ((City) -> (Temperature) -> (Percentage) -> Weather) = curry(Weather.init)
return initialiser <^> city <*> current <*> cloudiness
}
}
|
a7603ba1aa4b88edc8bf5b8138d17118
| 25.192308 | 95 | 0.687225 | false | false | false | false |
kuruvilla6970/Zoot
|
refs/heads/master
|
Source/Web View/WebViewController.swift
|
mit
|
1
|
//
// WebViewController.swift
// THGHybridWeb
//
// Created by Angelo Di Paolo on 4/16/15.
// Copyright (c) 2015 TheHolyGrail. All rights reserved.
//
import Foundation
import JavaScriptCore
import UIKit
#if NOFRAMEWORKS
#else
import THGBridge
#endif
/**
Defines methods that a delegate of a WebViewController object can optionally
implement to interact with the web view's loading cycle.
*/
@objc public protocol WebViewControllerDelegate {
/**
Sent before the web view begins loading a frame.
:param: webViewController The web view controller loading the web view frame.
:param: request The request that will load the frame.
:param: navigationType The type of user action that started the load.
:returns: Return true to
*/
optional func webViewController(webViewController: WebViewController, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
/**
Sent before the web view begins loading a frame.
:param: webViewController The web view controller that has begun loading the frame.
*/
optional func webViewControllerDidStartLoad(webViewController: WebViewController)
/**
Sent after the web view as finished loading a frame.
:param: webViewController The web view controller that has completed loading the frame.
*/
optional func webViewControllerDidFinishLoad(webViewController: WebViewController)
/**
Sent if the web view fails to load a frame.
:param: webViewController The web view controller that failed to load the frame.
:param: error The error that occured during loading.
*/
optional func webViewController(webViewController: WebViewController, didFailLoadWithError error: NSError)
/**
Sent when the web view creates the JS context for the frame.
:param: webViewController The web view controller that failed to load the frame.
:param: context The newly created JavaScript context.
*/
optional func webViewControllerDidCreateJavaScriptContext(webViewController: WebViewController, context: JSContext)
}
/**
A view controller that integrates a web view with the hybrid JavaScript API.
# Usage
Initialize a web view controller and call `loadURL()` to asynchronously load
the web view with a URL.
```
let webController = WebViewController()
webController.loadURL(NSURL(string: "foo")!)
window?.rootViewController = webController
```
Call `addHybridAPI()` to add the bridged JavaScript API to the web view.
The JavaScript API will be accessible to any web pages that are loaded in the
web view controller.
```
let webController = WebViewController()
webController.addHybridAPI()
webController.loadURL(NSURL(string: "foo")!)
window?.rootViewController = webController
```
To utilize the navigation JavaScript API you must provide a navigation
controller for the web view controller.
```
let webController = WebViewController()
webController.addHybridAPI()
webController.loadURL(NSURL(string: "foo")!)
let navigationController = UINavigationController(rootViewController: webController)
window?.rootViewController = navigationController
```
*/
public class WebViewController: UIViewController {
enum AppearenceCause {
case Unknown, WebPush, WebPop, WebModal, WebDismiss
}
/// The URL that was loaded with `loadURL()`
private(set) public var url: NSURL?
/// The web view used to load and render the web content.
private(set) public lazy var webView: UIWebView = {
let webView = UIWebView(frame: CGRectZero)
webView.delegate = self
webViews.addObject(webView)
return webView
}()
/// JavaScript bridge for the web view's JSContext
private(set) public var bridge = Bridge()
private var storedScreenshotGUID: String? = nil
private var goBackInWebViewOnAppear = false
private var firstLoadCycleCompleted = true
private var disappearedBy = AppearenceCause.Unknown
private var storedAppearence = AppearenceCause.WebPush
private var appearedFrom: AppearenceCause {
get {
switch disappearedBy {
case .WebPush: return .WebPop
case .WebModal: return .WebDismiss
default: return storedAppearence
}
}
set {
storedAppearence = newValue
}
}
private lazy var placeholderImageView: UIImageView = {
return UIImageView(frame: self.view.bounds)
}()
private var errorView: UIView?
private var errorLabel: UILabel?
private var reloadButton: UIButton?
public weak var hybridAPI: HybridAPI?
public var navigationCallback: JSValue?
/// Handles web view controller events.
public weak var delegate: WebViewControllerDelegate?
/// Set `false` to disable error message UI.
public var showErrorDisplay = true
/**
Initialize a web view controller instance with a web view and JavaScript
bridge. The newly initialized web view controller becomes the delegate of
the web view.
:param: webView The web view to use in the web view controller.
:param: bridge The bridge instance to integrate int
*/
public required init(webView: UIWebView, bridge: Bridge) {
super.init(nibName: nil, bundle: nil)
self.bridge = bridge
self.webView = webView
self.webView.delegate = self
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
if webView.delegate === self {
webView.delegate = nil
}
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
edgesForExtendedLayout = .None
view.addSubview(placeholderImageView)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
hybridAPI?.parentViewController = self
switch appearedFrom {
case .WebPush, .WebModal, .WebPop, .WebDismiss:
if goBackInWebViewOnAppear {
goBackInWebViewOnAppear = false
webView.goBack() // go back before remove/adding web view
}
webView.delegate = self
webView.removeFromSuperview()
webView.frame = view.bounds
view.addSubview(webView)
view.removeDoubleTapGestures()
// if we have a screenshot stored, load it.
if let guid = storedScreenshotGUID {
placeholderImageView.image = UIImage.loadImageFromGUID(guid)
placeholderImageView.frame = view.bounds
view.bringSubviewToFront(placeholderImageView)
}
if appearedFrom == .WebModal || appearedFrom == .WebPush {
navigationCallback?.asValidValue?.callWithArguments(nil)
}
case .Unknown: break
}
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
hybridAPI?.view.appeared()
switch appearedFrom {
case .WebPop, .WebDismiss:
showWebView()
addBridgeAPIObject()
case .WebPush, .WebModal, .Unknown: break
}
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
switch disappearedBy {
case .WebPop, .WebDismiss, .WebPush, .WebModal:
// only store screen shot when disappearing by web transition
placeholderImageView.frame = webView.frame // must align frames for image capture
let image = webView.captureImage()
placeholderImageView.image = image
storedScreenshotGUID = image.saveImageToGUID()
view.bringSubviewToFront(placeholderImageView)
webView.hidden = true
case .Unknown: break
}
hybridAPI?.view.disappeared() // needs to be called in viewWillDisappear not Did
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
switch disappearedBy {
case .WebPop, .WebDismiss, .WebPush, .WebModal:
// we're gone. dump the screenshot, we'll load it later if we need to.
placeholderImageView.image = nil
case .Unknown:
// we don't know how it will appear if we don't know how it disappeared
appearedFrom = .Unknown
}
}
public final func showWebView() {
webView.hidden = false
placeholderImageView.image = nil
view.sendSubviewToBack(placeholderImageView)
}
}
// MARK: - Request Loading
extension WebViewController {
/**
Load the web view with the provided URL.
:param: url The URL used to load the web view.
*/
final public func loadURL(url: NSURL) {
webView.stopLoading()
hybridAPI = nil
firstLoadCycleCompleted = false
self.url = url
webView.loadRequest(requestWithURL(url))
}
/**
Create a request with the provided URL.
:param: url The URL for the request.
*/
public func requestWithURL(url: NSURL) -> NSURLRequest {
return NSURLRequest(URL: url)
}
}
// MARK: - UIWebViewDelegate
extension WebViewController: UIWebViewDelegate {
final public func webViewDidStartLoad(webView: UIWebView) {
delegate?.webViewControllerDidStartLoad?(self)
}
public func webViewDidFinishLoad(webView: UIWebView) {
delegate?.webViewControllerDidFinishLoad?(self)
if self.errorView != nil {
self.removeErrorDisplay()
}
}
final public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if pushesWebViewControllerForNavigationType(navigationType) {
pushWebViewController()
}
return delegate?.webViewController?(self, shouldStartLoadWithRequest: request, navigationType: navigationType) ?? true
}
final public func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
if error.code != NSURLErrorCancelled {
if showErrorDisplay {
renderFeatureErrorDisplayWithError(error, featureName: featureNameForError(error))
}
}
delegate?.webViewController?(self, didFailLoadWithError: error)
}
}
// MARK: - JavaScript Context
extension WebViewController {
/**
Update the bridge's JavaScript context by attempting to retrieve a context
from the web view.
*/
final public func updateBridgeContext() {
if let context = webView.javaScriptContext {
configureBridgeContext(context)
} else {
println("Failed to retrieve JavaScript context from web view.")
}
}
private func didCreateJavaScriptContext(context: JSContext) {
configureBridgeContext(context)
delegate?.webViewControllerDidCreateJavaScriptContext?(self, context: context)
configureContext(context)
if let hybridAPI = hybridAPI {
var readyCallback = bridge.contextValueForName("nativeBridgeReady")
if !readyCallback.isUndefined() {
readyCallback.callWithData(hybridAPI)
}
}
}
/**
Explictly set the bridge's JavaScript context.
*/
final public func configureBridgeContext(context: JSContext) {
bridge.context = context
}
public func configureContext(context: JSContext) {
addBridgeAPIObject()
}
}
// MARK: - Web Controller Navigation
extension WebViewController {
/**
Push a new web view controller on the navigation stack using the existing
web view instance. Does not affect web view history. Uses animation.
*/
public func pushWebViewController() {
pushWebViewController(hideBottomBar: false, callback: nil)
}
/**
Push a new web view controller on the navigation stack using the existing
web view instance. Does not affect web view history. Uses animation.
:param: hideBottomBar Hides the bottom bar of the view controller when true.
*/
public func pushWebViewController(#hideBottomBar: Bool, callback: JSValue?) {
goBackInWebViewOnAppear = true
disappearedBy = .WebPush
let webViewController = newWebViewController()
webViewController.appearedFrom = .WebPush
webViewController.navigationCallback = callback
webViewController.hidesBottomBarWhenPushed = hideBottomBar
navigationController?.pushViewController(webViewController, animated: true)
}
/**
Pop a web view controller off of the navigation. Does not affect
web view history. Uses animation.
*/
public func popWebViewController() {
if let navController = self.navigationController
where navController.viewControllers.count > 1 {
(navController.viewControllers[navController.viewControllers.count - 1] as? WebViewController)?.goBackInWebViewOnAppear = false
navController.popViewControllerAnimated(true)
}
}
/**
Present a navigation controller containing a new web view controller as the
root view controller. The existing web view instance is reused.
*/
public func presentModalWebViewController(callback: JSValue?) {
goBackInWebViewOnAppear = false
disappearedBy = .WebModal
let webViewController = newWebViewController()
webViewController.appearedFrom = .WebModal
webViewController.navigationCallback = callback
let navigationController = UINavigationController(rootViewController: webViewController)
if let tabBarController = tabBarController {
tabBarController.presentViewController(navigationController, animated: true, completion: nil)
} else {
presentViewController(navigationController, animated: true, completion: nil)
}
}
/// Pops until there's only a single view controller left on the navigation stack.
public func popToRootWebViewController() {
navigationController?.popToRootViewControllerAnimated(true)
}
/**
Return `true` to have the web view controller push a new web view controller
on the stack for a given navigation type of a request.
*/
public func pushesWebViewControllerForNavigationType(navigationType: UIWebViewNavigationType) -> Bool {
return false
}
public func newWebViewController() -> WebViewController {
let webViewController = self.dynamicType(webView: webView, bridge: bridge)
webViewController.addBridgeAPIObject()
return webViewController
}
}
// MARK: - Error UI
extension WebViewController {
private func createErrorLabel() -> UILabel? {
let height = CGFloat(50)
let y = CGRectGetMidY(view.bounds) - (height / 2) - 100
var label = UILabel(frame: CGRectMake(0, y, CGRectGetWidth(view.bounds), height))
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = view.backgroundColor
label.font = UIFont.systemFontOfSize(12, weight: 2)
return label
}
private func createReloadButton() -> UIButton? {
if let button = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton {
let size = CGSizeMake(170, 38)
let x = CGRectGetMidX(view.bounds) - (size.width / 2)
var y = CGRectGetMidY(view.bounds) - (size.height / 2)
if let label = errorLabel {
y = CGRectGetMaxY(label.frame) + 20
}
button.setTitle(NSLocalizedString("Try again", comment: "Try again"), forState: UIControlState.Normal)
button.frame = CGRectMake(x, y, size.width, size.height)
button.backgroundColor = UIColor.lightGrayColor()
button.titleLabel?.backgroundColor = UIColor.lightGrayColor()
button.titleLabel?.textColor = UIColor.whiteColor()
return button
}
return nil
}
}
// MARK: - Error Display Events
extension WebViewController {
/// Override to completely customize error display. Must also override `removeErrorDisplay`
public func renderErrorDisplayWithError(error: NSError, message: String) {
let errorView = UIView(frame: view.bounds)
view.addSubview(errorView)
self.errorView = errorView
self.errorLabel = createErrorLabel()
self.reloadButton = createReloadButton()
if let errorLabel = errorLabel {
errorLabel.text = NSLocalizedString(message, comment: "Web View Load Error")
errorView.addSubview(errorLabel)
}
if let button = reloadButton {
button.addTarget(self, action: "reloadButtonTapped:", forControlEvents: .TouchUpInside)
errorView.addSubview(button)
}
}
/// Override to handle custom error display removal.
public func removeErrorDisplay() {
errorView?.removeFromSuperview()
errorView = nil
}
/// Override to customize the feature name that appears in the error display.
public func featureNameForError(error: NSError) -> String {
return "This feature"
}
/// Override to customize the error message text.
public func renderFeatureErrorDisplayWithError(error: NSError, featureName: String) {
let message = "Sorry!\n \(featureName) isn't working right now."
renderErrorDisplayWithError(error, message: message)
}
/// Removes the error display and attempts to reload the web view.
public func reloadButtonTapped(sender: AnyObject) {
map(url) {self.loadURL($0)}
}
}
// MARK: - Bridge API
extension WebViewController {
public func addBridgeAPIObject() {
if let bridgeObject = hybridAPI {
bridge.context.setObject(bridgeObject, forKeyedSubscript: HybridAPI.exportName)
} else {
let platform = HybridAPI(parentViewController: self)
bridge.context.setObject(platform, forKeyedSubscript: HybridAPI.exportName)
hybridAPI = platform
}
}
}
// MARK: - UIView Utils
extension UIView {
func captureImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0)
layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func removeDoubleTapGestures() {
for view in self.subviews {
view.removeDoubleTapGestures()
}
if let gestureRecognizers = gestureRecognizers {
for gesture in gestureRecognizers {
if let gesture = gesture as? UITapGestureRecognizer
where gesture.numberOfTapsRequired == 2 {
removeGestureRecognizer(gesture)
}
}
}
}
}
// MARK: - UIImage utils
extension UIImage {
// saves image to temp directory and returns a GUID so you can fetch it later.
func saveImageToGUID() -> String? {
let guid = String.GUID()
// do this shit in the background.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
let data = UIImageJPEGRepresentation(self, 1.0)
if let data = data {
let fileManager = NSFileManager.defaultManager()
let fullPath = NSTemporaryDirectory().stringByAppendingPathComponent(guid)
fileManager.createFileAtPath(fullPath, contents: data, attributes: nil)
}
}
return guid
}
class func loadImageFromGUID(guid: String?) -> UIImage? {
if let guid = guid {
let fileManager = NSFileManager.defaultManager()
let fullPath = NSTemporaryDirectory().stringByAppendingPathComponent(guid)
let image = UIImage(contentsOfFile: fullPath)
return image
}
return nil
}
}
// MARK: - JSContext Event
private var webViews = NSHashTable.weakObjectsHashTable()
private struct Statics {
static var webViewOnceToken: dispatch_once_t = 0
}
extension NSObject {
func webView(webView: AnyObject, didCreateJavaScriptContext context: JSContext, forFrame frame: AnyObject) {
if let webFrameClass: AnyClass = NSClassFromString("WebFrame")
where !(frame.dynamicType === webFrameClass) {
return
}
if let allWebViews = webViews.allObjects as? [UIWebView] {
for webView in allWebViews {
webView.didCreateJavaScriptContext(context)
}
}
}
}
extension UIWebView {
func didCreateJavaScriptContext(context: JSContext) {
(delegate as? WebViewController)?.didCreateJavaScriptContext(context)
}
}
|
a37ecc13f27e349d2bab021b26cc2e33
| 32.519142 | 172 | 0.651818 | false | false | false | false |
qianyu09/AppLove
|
refs/heads/master
|
App Love/WHC_Lib/Swift_Lib/WHC_MoreMenuItemVC.swift
|
mit
|
1
|
//
// WHC_MoreMenuItemVC.swift
// WHC_MenuViewDemo
//
// Created by 吴海超 on 15/10/20.
// Copyright © 2015年 吴海超. All rights reserved.
//
/*
* qq:712641411
* gitHub:https://github.com/netyouli
* csdn:http://blog.csdn.net/windwhc/article/category/3117381
*/
import UIKit
protocol WHC_MoreMenuItemVCDelegate{
func WHCMoreMenuItemVC(moreVC: WHC_MoreMenuItemVC , addTitles: [String]! , addImageNames: [String]!);
}
class WHC_MoreMenuItemVC: UIViewController{
/// 缓存菜单key
var cacheWHCMenuKey: String!;
var AppCategoryList:[AppCategoryItem]!
/// 菜单项标题集合
var menuItemTitles: [String]!;
/// 菜单项图片名称集合
var menuItemImageNames: [String]!;
/// 代理
var delegate: WHC_MoreMenuItemVCDelegate!;
/// 边距
var pading: CGFloat = 0;
/// 菜单对象
private var menuView: WHC_MenuView!;
override func viewDidLoad() {
super.viewDidLoad()
self.initData();
self.layoutUI();
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func initData(){
}
private func layoutUI(){
self.navigationItem.title = "更多";
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor();
self.view.backgroundColor = UIColor.themeBackgroundColor();
let cancelBarItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(WHC_MoreMenuItemVC.clickCancelItem(_:)));
self.navigationItem.leftBarButtonItem = cancelBarItem;
let menuViewParam = WHC_MenuViewParam.getWHCMenuViewDefaultParam(titles: self.menuItemTitles, imageNames: self.menuItemImageNames, cacheWHCMenuKey: self.cacheWHCMenuKey);
//by louis
// let menuViewParam = WHC_MenuViewParam.getWHCMenuViewDefaultParam(self.AppCategoryList, cacheWHCMenuKey: self.cacheWHCMenuKey);
menuViewParam.canDelete = false;
menuViewParam.canAdd = true;
menuViewParam.canSort = true;
menuViewParam.cacheWHCMenuKey = self.cacheWHCMenuKey;
menuViewParam.isMoreMenuItem = true;
self.menuView = WHC_MenuView(frame: UIScreen.mainScreen().bounds, menuViewParam: menuViewParam);
self.view.addSubview(self.menuView);
}
func clickCancelItem(sender: UIBarButtonItem){
self.delegate?.WHCMoreMenuItemVC(self,
addTitles: self.menuView.getInsertTitles(),
addImageNames: self.menuView.getInsertImageNames());
self.dismissViewControllerAnimated(true, completion: nil);
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
f6bb808d43600b415e82048ecf71f0ab
| 33.431818 | 178 | 0.686799 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
refs/heads/master
|
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/SpeedTesting/NxMSeriesSpeedTestSciChart.swift
|
mit
|
1
|
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// NxMSeriesSpeedTestSciChart.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class NxMSeriesSpeedTestSciChart: SingleChartLayout {
let PointsCount: Int32 = 100
let SeriesCount: Int32 = 100
var _timer: Timer!
let _yAxis = SCINumericAxis()
var _updateNumber = 0
var _rangeMin = Double.nan
var _rangeMax = Double.nan
override func initExample() {
let xAxis = SCINumericAxis()
let randomWalk = RandomWalkGenerator()!
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(self._yAxis)
var color: Int64 = 0xFF0F0505
for _ in 0..<self.SeriesCount {
randomWalk.reset()
let doubleSeries = randomWalk.getRandomWalkSeries(self.PointsCount)
let dataSeries = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries.appendRangeX(doubleSeries!.xValues, y: doubleSeries!.yValues, count: doubleSeries!.size)
color = color + 0x00000101
let rSeries = SCIFastLineRenderableSeries()
rSeries.dataSeries = dataSeries
rSeries.strokeStyle = SCISolidPenStyle(colorCode: UInt32(color), withThickness: 0.5)
self.surface.renderableSeries.add(rSeries)
}
}
_timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(updateData), userInfo: nil, repeats: true)
}
@objc fileprivate func updateData(_ timer: Timer) {
if (_rangeMin.isNaN) {
_rangeMin = _yAxis.visibleRange.minAsDouble()
_rangeMax = _yAxis.visibleRange.maxAsDouble()
}
let scaleFactor = fabs(sin(Double(_updateNumber) * 0.1)) + 0.5;
_yAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(_rangeMin * scaleFactor), max: SCIGeneric(_rangeMax * scaleFactor))
_updateNumber += 1
}
override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if (newWindow == nil) {
_timer.invalidate()
_timer = nil
}
}
}
|
82f2ae09c22db4c22f057232b898bd65
| 38.306667 | 134 | 0.591927 | false | false | false | false |
robpeach/test
|
refs/heads/master
|
SwiftPages/AboutVC.swift
|
mit
|
1
|
//
// AboutVC.swift
// Britannia v2
//
// Created by Rob Mellor on 10/08/2016.
// Copyright © 2016 Robert Mellor. All rights reserved.
//
import UIKit
import Foundation
import MessageUI
class AboutVC: UIViewController, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func findusButton(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/?address=198,HighStreet,Scunthorpe.DN156EA")!)
}
@IBAction func sendEmailButtonTapped(sender: AnyObject) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.view.window!.rootViewController?.presentViewController(mailComposeViewController, animated: true, completion: nil)
})
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("")
mailComposerVC.setMessageBody("Sent from The Britannia App - We aim to reply within 24 hours.", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func movetoChatBtn(sender: AnyObject) {
print("button pressed")
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : ChatVC = storyboard.instantiateViewControllerWithIdentifier("ChatView") as! ChatVC
// vc.teststring = "hello"
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
7a77630c8dbfefc34728554464215797
| 33.183673 | 213 | 0.676119 | false | false | false | false |
Bargetor/beak
|
refs/heads/master
|
Beak/Beak/extension/BBStringExtension.swift
|
mit
|
1
|
//
// BBStringExtension.swift
// Beak
//
// Created by 马进 on 2016/12/6.
// Copyright © 2016年 马进. All rights reserved.
//
import Foundation
extension String {
public func substringWithRange(_ range: NSRange) -> String! {
let r = (self.index(self.startIndex, offsetBy: range.location) ..< self.index(self.startIndex, offsetBy: range.location + range.length))
return String(self[r])
}
public func urlencode() -> String {
let urlEncoded = self.replacingOccurrences(of: " ", with: "+")
let chartset = NSMutableCharacterSet(bitmapRepresentation: (CharacterSet.urlQueryAllowed as NSCharacterSet).bitmapRepresentation)
chartset.removeCharacters(in: "!*'();:@&=$,/?%#[]")
return urlEncoded.addingPercentEncoding(withAllowedCharacters: chartset as CharacterSet)!
}
public func length() -> Int{
return self.count
}
public func format(arguments: CVarArg...) -> String{
return String(format: self, arguments: arguments)
}
public mutating func replaceSubrange(_ range: NSRange, with replacementString: String) -> String {
if(range.location >= self.count){
self.append(replacementString)
return self
}
if let newRange: Range<String.Index> = self.range(for: range){
self.replaceSubrange(newRange, with: replacementString)
}
return self
}
func range(for range: NSRange) -> Range<String.Index>? {
guard range.location != NSNotFound else { return nil }
guard let fromUTFIndex = self.utf16.index(self.utf16.startIndex, offsetBy: range.location, limitedBy: self.utf16.endIndex) else { return nil }
guard let toUTFIndex = self.utf16.index(fromUTFIndex, offsetBy: range.length, limitedBy: self.utf16.endIndex) else { return nil }
guard let fromIndex = String.Index(fromUTFIndex, within: self) else { return nil }
guard let toIndex = String.Index(toUTFIndex, within: self) else { return nil }
return fromIndex ..< toIndex
}
}
|
16c1085034327c641097b968575b3c75
| 35.016949 | 150 | 0.64 | false | false | false | false |
tensorflow/examples
|
refs/heads/master
|
lite/examples/gesture_classification/ios/GestureClassification/ModelDataHandler/ModelDataHandler.swift
|
apache-2.0
|
1
|
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// 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 Accelerate
import CoreImage
import TensorFlowLite
import UIKit
// MARK: Structures That hold results
/**
Stores inference results for a particular frame that was successfully run through the
TensorFlow Lite Interpreter.
*/
struct Result{
let inferenceTime: Double
let inferences: [Inference]
}
/**
Stores one formatted inference.
*/
struct Inference {
let confidence: Float
let label: String
}
/// Information about a model file or labels file.
typealias FileInfo = (name: String, extension: String)
// Information about the model to be loaded.
enum Model {
static let modelInfo: FileInfo = (name: "model", extension: "tflite")
static let labelsInfo: FileInfo = (name: "labels", extension: "txt")
}
/**
This class handles all data preprocessing and makes calls to run inference on
a given frame through the TensorFlow Lite Interpreter. It then formats the
inferences obtained and returns the top N results for a successful inference.
*/
class ModelDataHandler {
// MARK: Paremeters on which model was trained
let batchSize = 1
let wantedInputChannels = 3
let wantedInputWidth = 224
let wantedInputHeight = 224
let stdDeviation: Float = 127.0
let mean: Float = 1.0
// MARK: Constants
let threadCountLimit: Int32 = 10
// MARK: Instance Variables
/// The current thread count used by the TensorFlow Lite Interpreter.
let threadCount: Int
var labels: [String] = []
private let resultCount = 1
private let threshold = 0.5
/// TensorFlow Lite `Interpreter` object for performing inference on a given model.
private var interpreter: Interpreter
private let bgraPixel = (channels: 4, alphaComponent: 3, lastBgrComponent: 2)
private let rgbPixelChannels = 3
private let colorStrideValue = 10
/// Information about the alpha component in RGBA data.
private let alphaComponent = (baseOffset: 4, moduloRemainder: 3)
// MARK: Initializer
/**
This is a failable initializer for ModelDataHandler. It successfully initializes an object of the class if the model file and labels file is found, labels can be loaded and the interpreter of TensorflowLite can be initialized successfully.
*/
init?(modelFileInfo: FileInfo, labelsFileInfo: FileInfo, threadCount: Int = 1) {
// Construct the path to the model file.
guard let modelPath = Bundle.main.path(
forResource: modelFileInfo.name,
ofType: modelFileInfo.extension
) else {
print("Failed to load the model file with name: \(modelFileInfo.name).")
return nil
}
// Specify the options for the `Interpreter`.
self.threadCount = threadCount
var options = InterpreterOptions()
options.threadCount = threadCount
do {
// Create the `Interpreter`.
interpreter = try Interpreter(modelPath: modelPath, options: options)
// Allocate memory for the model's input `Tensor`s.
try interpreter.allocateTensors()
} catch let error {
print("Failed to create the interpreter with error: \(error.localizedDescription)")
return nil
}
// Opens and loads the classes listed in labels file
loadLabels(fromFileName: Model.labelsInfo.name, fileExtension: Model.labelsInfo.extension)
}
// MARK: Methods for data preprocessing and post processing.
/**
Performs image preprocessing, calls the TensorFlow Lite Interpreter methods
to feed the pixel buffer into the input tensor and run inference
on the pixel buffer.
*/
func runModel(onFrame pixelBuffer: CVPixelBuffer) -> Result? {
let sourcePixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer)
assert(sourcePixelFormat == kCVPixelFormatType_32ARGB ||
sourcePixelFormat == kCVPixelFormatType_32BGRA || sourcePixelFormat == kCVPixelFormatType_32RGBA)
let imageChannels = 4
assert(imageChannels >= wantedInputChannels)
// Crops the image to the biggest square in the center and scales it down to model dimensions.
guard let thumbnailPixelBuffer = centerThumbnail(from: pixelBuffer, size: CGSize(width: wantedInputWidth, height: wantedInputHeight)) else {
return nil
}
CVPixelBufferLockBaseAddress(thumbnailPixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
let interval: TimeInterval
let outputTensor: Tensor
do {
let inputTensor = try interpreter.input(at: 0)
// Remove the alpha component from the image buffer to get the RGB data.
guard let rgbData = rgbDataFromBuffer(
thumbnailPixelBuffer,
byteCount: batchSize * wantedInputWidth * wantedInputHeight * wantedInputChannels,
isModelQuantized: inputTensor.dataType == .uInt8
) else {
print("Failed to convert the image buffer to RGB data.")
return nil
}
// Copy the RGB data to the input `Tensor`.
try interpreter.copy(rgbData, toInputAt: 0)
// Run inference by invoking the `Interpreter`.
let startDate = Date()
try interpreter.invoke()
interval = Date().timeIntervalSince(startDate) * 1000
// Get the output `Tensor` to process the inference results.
outputTensor = try interpreter.output(at: 0)
} catch let error {
print("Failed to invoke the interpreter with error: \(error.localizedDescription)")
return nil
}
let results: [Float]
switch outputTensor.dataType {
case .uInt8:
guard let quantization = outputTensor.quantizationParameters else {
print("No results returned because the quantization values for the output tensor are nil.")
return nil
}
let quantizedResults = [UInt8](outputTensor.data)
results = quantizedResults.map {
quantization.scale * Float(Int($0) - quantization.zeroPoint)
}
case .float32:
results = [Float32](unsafeData: outputTensor.data) ?? []
default:
print("Output tensor data type \(outputTensor.dataType) is unsupported for this example app.")
return nil
}
// Process the results.
let topNInferences = getTopN(results: results)
// Return the inference time and inference results.
return Result(inferenceTime: interval, inferences: topNInferences)
}
/// Returns the RGB data representation of the given image buffer with the specified `byteCount`.
///
/// - Parameters
/// - buffer: The BGRA pixel buffer to convert to RGB data.
/// - byteCount: The expected byte count for the RGB data calculated using the values that the
/// model was trained on: `batchSize * imageWidth * imageHeight * componentsCount`.
/// - isModelQuantized: Whether the model is quantized (i.e. fixed point values rather than
/// floating point values).
/// - Returns: The RGB data representation of the image buffer or `nil` if the buffer could not be
/// converted.
private func rgbDataFromBuffer(
_ buffer: CVPixelBuffer,
byteCount: Int,
isModelQuantized: Bool
) -> Data? {
CVPixelBufferLockBaseAddress(buffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(buffer, .readOnly) }
let pixelBufferFormat = CVPixelBufferGetPixelFormatType(buffer)
assert(pixelBufferFormat == kCVPixelFormatType_32BGRA)
guard let sourceData = CVPixelBufferGetBaseAddress(buffer) else {
return nil
}
let width = CVPixelBufferGetWidth(buffer)
let height = CVPixelBufferGetHeight(buffer)
let sourceBytesPerRow = CVPixelBufferGetBytesPerRow(buffer)
let destinationChannelCount = 3
let destinationBytesPerRow = destinationChannelCount * width
var sourceBuffer = vImage_Buffer(data: sourceData,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: sourceBytesPerRow)
guard let destinationData = malloc(height * destinationBytesPerRow) else {
print("Error: out of memory")
return nil
}
defer {
free(destinationData)
}
var destinationBuffer = vImage_Buffer(data: destinationData,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: destinationBytesPerRow)
vImageConvert_BGRA8888toRGB888(&sourceBuffer, &destinationBuffer, UInt32(kvImageNoFlags))
let byteData = Data(bytes: destinationBuffer.data, count: destinationBuffer.rowBytes * height)
if isModelQuantized {
return byteData
}
// Not quantized, convert to floats
let bytes = Array<UInt8>(unsafeData: byteData)!
var floats = [Float]()
for i in 0..<bytes.count {
floats.append(Float(bytes[i]) / 255.0)
}
return Data(copyingBufferOf: floats)
}
/// Returns the top N inference results sorted in descending order.
private func getTopN(results: [Float]) -> [Inference] {
// Create a zipped array of tuples [(labelIndex: Int, confidence: Float)].
let zippedResults = zip(labels.indices, results)
// Sort the zipped results by confidence value in descending order.
let sortedResults = zippedResults.sorted { $0.1 > $1.1 }.prefix(resultCount)
// Return the `Inference` results.
return sortedResults.map { result in Inference(confidence: result.1, label: labels[result.0]) }
}
/**
Returns thumbnail by cropping pixel buffer to biggest square and scaling the cropped image to model dimensions.
*/
private func centerThumbnail(from pixelBuffer: CVPixelBuffer, size: CGSize ) -> CVPixelBuffer? {
let imageWidth = CVPixelBufferGetWidth(pixelBuffer)
let imageHeight = CVPixelBufferGetHeight(pixelBuffer)
let pixelBufferType = CVPixelBufferGetPixelFormatType(pixelBuffer)
assert(pixelBufferType == kCVPixelFormatType_32BGRA)
let inputImageRowBytes = CVPixelBufferGetBytesPerRow(pixelBuffer)
let imageChannels = 4
let thumbnailSize = min(imageWidth, imageHeight)
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
var originX = 0
var originY = 0
if imageWidth > imageHeight {
originX = (imageWidth - imageHeight) / 2
}
else {
originY = (imageHeight - imageWidth) / 2
}
// Finds the biggest square in the pixel buffer and advances rows based on it.
guard let inputBaseAddress = CVPixelBufferGetBaseAddress(pixelBuffer)?.advanced(by: originY * inputImageRowBytes + originX * imageChannels) else {
return nil
}
// Gets vImage Buffer from input image
var inputVImageBuffer = vImage_Buffer(data: inputBaseAddress, height: UInt(thumbnailSize), width: UInt(thumbnailSize), rowBytes: inputImageRowBytes)
let thumbnailRowBytes = Int(size.width) * imageChannels
guard let thumbnailBytes = malloc(Int(size.height) * thumbnailRowBytes) else {
return nil
}
// Allocates a vImage buffer for thumbnail image.
var thumbnailVImageBuffer = vImage_Buffer(data: thumbnailBytes, height: UInt(size.height), width: UInt(size.width), rowBytes: thumbnailRowBytes)
// Performs the scale operation on input image buffer and stores it in thumbnail image buffer.
let scaleError = vImageScale_ARGB8888(&inputVImageBuffer, &thumbnailVImageBuffer, nil, vImage_Flags(0))
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
guard scaleError == kvImageNoError else {
return nil
}
let releaseCallBack: CVPixelBufferReleaseBytesCallback = {mutablePointer, pointer in
if let pointer = pointer {
free(UnsafeMutableRawPointer(mutating: pointer))
}
}
var thumbnailPixelBuffer: CVPixelBuffer?
// Converts the thumbnail vImage buffer to CVPixelBuffer
let conversionStatus = CVPixelBufferCreateWithBytes(nil, Int(size.width), Int(size.height), pixelBufferType, thumbnailBytes, thumbnailRowBytes, releaseCallBack, nil, nil, &thumbnailPixelBuffer)
guard conversionStatus == kCVReturnSuccess else {
free(thumbnailBytes)
return nil
}
return thumbnailPixelBuffer
}
/**
Loads the labels from the labels file and stores it in an instance variable
*/
func loadLabels(fromFileName fileName: String, fileExtension: String) {
guard let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) else {
fatalError("Labels file not found in bundle. Please add a labels file with name \(fileName).\(fileExtension) and try again")
}
do {
let contents = try String(contentsOf: fileURL, encoding: .utf8)
self.labels = contents.components(separatedBy: ",")
self.labels.removeAll { (label) -> Bool in
return label == ""
}
}
catch {
fatalError("Labels file named \(fileName).\(fileExtension) cannot be read. Please add a valid labels file and try again.")
}
}
}
// MARK: - Extensions
extension Data {
/// Creates a new buffer by copying the buffer pointer of the given array.
///
/// - Warning: The given array's element type `T` must be trivial in that it can be copied bit
/// for bit with no indirection or reference-counting operations; otherwise, reinterpreting
/// data from the resulting buffer has undefined behavior.
/// - Parameter array: An array with elements of type `T`.
init<T>(copyingBufferOf array: [T]) {
self = array.withUnsafeBufferPointer(Data.init)
}
}
extension Array {
/// Creates a new array from the bytes of the given unsafe data.
///
/// - Warning: The array's `Element` type must be trivial in that it can be copied bit for bit
/// with no indirection or reference-counting operations; otherwise, copying the raw bytes in
/// the `unsafeData`'s buffer to a new array returns an unsafe copy.
/// - Note: Returns `nil` if `unsafeData.count` is not a multiple of
/// `MemoryLayout<Element>.stride`.
/// - Parameter unsafeData: The data containing the bytes to turn into an array.
init?(unsafeData: Data) {
guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil }
#if swift(>=5.0)
self = unsafeData.withUnsafeBytes { .init($0.bindMemory(to: Element.self)) }
#else
self = unsafeData.withUnsafeBytes {
.init(UnsafeBufferPointer<Element>(
start: $0,
count: unsafeData.count / MemoryLayout<Element>.stride
))
}
#endif // swift(>=5.0)
}
}
|
678c7e010272b855ab4baf77f4a8b0fe
| 36.293532 | 242 | 0.702708 | false | false | false | false |
JonMercer/burritoVSWHackathon
|
refs/heads/master
|
Burrito/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Burrito
//
// Created by Odin on 2016-09-23.
// Copyright © 2016 TeamAlpaka. All rights reserved.
//
import UIKit
import STZPopupView
class ViewController: UIViewController, CardViewDelegate {
var cardView: CardView!
@IBOutlet weak var minutesLabel: UILabel!
@IBOutlet weak var secondsLabel: UILabel!
var timer = NSTimer()
var secondsLeft = 60*40 // 40min
let CHANGE_MODE_DELAY = 2.0
let LOADING_DELAY = 2.5
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.tabBar.tintColor = UIColor.whiteColor()
self.tabBarController?.tabBar.backgroundImage = UIImage.fromColor(DARK_BLUR_COLOR)
//self.tabBarController?.tabBar.backgroundColor = UIColor.redColor()
//self.tabBarController?.tabBar.translucent = false
updateTimerLabel()
let one:NSTimeInterval = 1.0
timer = NSTimer.scheduledTimerWithTimeInterval(one, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
@IBAction func onTestButtonTapped(sender: AnyObject) {
showItem()
}
@IBAction func onNotificationButtonTapped(sender: AnyObject) {
sendLocalNotification()
}
func timerAction() {
if(secondsLeft > 0) {
secondsLeft -= 1
} else {
timer.invalidate()
}
updateTimerLabel()
}
func updateTimerLabel() {
minutesLabel.text = String(format: "%02d",(secondsLeft / 60) % 60)
secondsLabel.text = String(format: "%02d", secondsLeft % 60)
}
func showItem(){
let item = Item(name: "15% Off", restaurant: "Deer Island Bakery", image: UIImage(named: "deerislandwin")!)
cardView = CardView.instanceFromNib(CGRectMake(0, 0, 300, 300))
cardView.item = item
cardView.win = false
cardView.initializeView()
cardView.delegate = self
let popupConfig = STZPopupViewConfig()
popupConfig.dismissTouchBackground = true
popupConfig.cornerRadius = 5.0
cardView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.onCardTapped(_:))))
presentPopupView(cardView, config: popupConfig)
cardView.showLoading()
delay(LOADING_DELAY){
self.cardView.stopLoading()
delay(self.CHANGE_MODE_DELAY){
if !self.cardView.showingQRCode {
self.cardView.changeModes()
}
}
}
}
func onCardTapped(sender: AnyObject){
cardView.changeModes()
}
func dismissCard() {
dismissPopupView()
}
@IBAction func onRestaurantButtonTapped(sender: AnyObject) {
performSegueWithIdentifier("vcToLoginVC", sender: nil)
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
extension UIImage {
static func fromColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
|
cfad4bf9dd7a6040a829411d8baabbc9
| 28.732283 | 137 | 0.627648 | false | false | false | false |
storehouse/Advance
|
refs/heads/master
|
Sources/Advance/SpringFunction.swift
|
bsd-2-clause
|
1
|
/// Implements a simple spring acceleration function.
public struct SpringFunction<T>: SimulationFunction where T: VectorConvertible {
/// The target of the spring.
public var target: T
/// Strength of the spring.
public var tension: Double
/// How damped the spring is.
public var damping: Double
/// The minimum Double distance used for settling the spring simulation.
public var threshold: Double
/// Creates a new `SpringFunction` instance.
///
/// - parameter target: The target of the new instance.
public init(target: T, tension: Double = 120.0, damping: Double = 12.0, threshold: Double = 0.1) {
self.target = target
self.tension = tension
self.damping = damping
self.threshold = threshold
}
/// Calculates acceleration for a given state of the simulation.
public func acceleration(value: T.AnimatableData, velocity: T.AnimatableData) -> T.AnimatableData {
let delta = value - target.animatableData
var deltaAccel = delta
deltaAccel.scale(by: -tension)
var dampingAccel = velocity
dampingAccel.scale(by: damping)
return deltaAccel - dampingAccel
}
public func convergence(value: T.AnimatableData, velocity: T.AnimatableData) -> Convergence<T> {
if velocity.magnitudeSquared > threshold*threshold {
return .keepRunning
}
let valueDelta = value - target.animatableData
if valueDelta.magnitudeSquared > threshold*threshold {
return .keepRunning
}
return .converge(atValue: target.animatableData)
}
}
|
797c7a0a38c06f6534152ebeb2de0932
| 31.961538 | 103 | 0.634772 | false | false | false | false |
alvarorgtr/swift_data_structures
|
refs/heads/master
|
DataStructures/TreeMapCollection.swift
|
gpl-3.0
|
1
|
//
// TreeCollection.swift
// DataStructures
//
// Created by Álvaro Rodríguez García on 27/12/16.
// Copyright © 2016 DeltaApps. All rights reserved.
//
import Foundation
public protocol TreeMapCollection: BidirectionalCollection, DictionaryCollection {
associatedtype Iterator: TreeIterator
associatedtype Index = Self.Iterator.Index
associatedtype Node = Self.Iterator.Index.Node
associatedtype Element = (Self.Iterator.Index.Node.Key, Self.Iterator.Index.Node.Value)
associatedtype Key = Self.Iterator.Index.Node.Key
associatedtype Value = Self.Iterator.Index.Node.Value
var root: Node? { get }
var startNode: Node { get }
var endNode: Node { get }
var height: Int { get }
}
public extension TreeMapCollection where Node: TreeNode {
var height: Int {
get {
return root?.height ?? -1
}
}
}
|
d7b88efeac1072cb36a7c6f9f1238f54
| 23.294118 | 88 | 0.74092 | false | false | false | false |
blindsey/Swift-BoxOffice
|
refs/heads/master
|
BoxOffice/MasterViewController.swift
|
mit
|
1
|
//
// MasterViewController.swift
// BoxOffice
//
// Created by Ben Lindsey on 7/14/14.
// Copyright (c) 2014 Ben Lindsey. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
let API_KEY = "esm6sfwy2f2x8brqh3gv6ukk"
var hud = MBProgressHUD()
var movies = [NSDictionary]()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
self.refreshControl = UIRefreshControl()
self.refreshControl.addTarget(self, action: "fetchBoxOffice", forControlEvents: UIControlEvents.ValueChanged)
fetchBoxOffice()
}
// #pragma mark - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
(segue.destinationViewController as DetailViewController).detailItem = movies[indexPath.row]
}
}
// #pragma mark - Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let movie = movies[indexPath.row]
cell.detailTextLabel.text = movie["synopsis"] as? String
cell.textLabel.text = movie["title"] as? String
if let posters = movie["posters"] as? NSDictionary {
if let thumb = posters["thumbnail"] as? String {
let request = NSURLRequest(URL: NSURL(string: thumb))
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in
if data {
cell.imageView.image = UIImage(data: data)
cell.setNeedsLayout()
}
}
}
}
return cell
}
// #pragma mark - Private
func fetchBoxOffice() {
self.refreshControl.endRefreshing()
hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
var url : String
if self.tabBarController.tabBar.selectedItem.title == "Box Office" {
url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=\(API_KEY)";
} else {
url = "http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=\(API_KEY)";
}
let request = NSURLRequest(URL: NSURL(string: url))
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in
self.hud.hide(true)
if error {
println(error.description)
return self.displayError("Network Error")
}
var error: NSError?
let object = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:&error) as? NSDictionary
if let e = error {
println(e.description)
return self.displayError("Error parsing JSON")
} else if let dict = object {
if let e = dict["error"] as? String {
self.displayError(e)
} else if let movies = dict["movies"] as? [NSDictionary] {
self.movies = movies
self.tableView.reloadData()
}
}
}
}
func displayError(error: String) {
let label = UILabel(frame: CGRect(x: 0, y: -44, width:320, height: 44))
label.text = "⚠️ \(error)"
label.textColor = UIColor.whiteColor()
label.backgroundColor = UIColor.blackColor()
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.alpha = 0.8
label.textAlignment = .Center
self.view.addSubview(label)
UIView.animateWithDuration(2.0, animations: {
label.frame.origin.y = 0
}, completion: { completed in
UIView.animateWithDuration(2.0, animations: {
label.alpha = 0
}, completion: { completed in
label.removeFromSuperview()
})
})
}
}
|
26a697ff2a8d246c08f2cce0f38edcbc
| 35.868852 | 146 | 0.604936 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new
|
refs/heads/master
|
Source/AuthenticatedWebViewController.swift
|
apache-2.0
|
3
|
//
// AuthenticatedWebViewController.swift
// edX
//
// Created by Akiva Leffert on 5/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
import WebKit
class HeaderViewInsets : ContentInsetsSource {
weak var insetsDelegate : ContentInsetsSourceDelegate?
var view : UIView?
var currentInsets : UIEdgeInsets {
return UIEdgeInsets(top : view?.frame.size.height ?? 0, left : 0, bottom : 0, right : 0)
}
var affectsScrollIndicators : Bool {
return true
}
}
private protocol WebContentController {
var view : UIView {get}
var scrollView : UIScrollView {get}
var alwaysRequiresOAuthUpdate : Bool { get}
var initialContentState : AuthenticatedWebViewController.State { get }
func loadURLRequest(request : NSURLRequest)
func clearDelegate()
func resetState()
}
private class WKWebViewContentController : WebContentController {
private let webView = WKWebView(frame: CGRectZero)
var view : UIView {
return webView
}
var scrollView : UIScrollView {
return webView.scrollView
}
func clearDelegate() {
return webView.navigationDelegate = nil
}
func loadURLRequest(request: NSURLRequest) {
webView.loadRequest(request)
}
func resetState() {
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
}
var alwaysRequiresOAuthUpdate : Bool {
return false
}
var initialContentState : AuthenticatedWebViewController.State {
return AuthenticatedWebViewController.State.LoadingContent
}
}
private let OAuthExchangePath = "/oauth2/login/"
// Allows access to course content that requires authentication.
// Forwarding our oauth token to the server so we can get a web based cookie
public class AuthenticatedWebViewController: UIViewController, WKNavigationDelegate {
private enum State {
case CreatingSession
case LoadingContent
case NeedingSession
}
public typealias Environment = protocol<OEXAnalyticsProvider, OEXConfigProvider, OEXSessionProvider>
internal let environment : Environment
private let loadController : LoadStateViewController
private let insetsController : ContentInsetsController
private let headerInsets : HeaderViewInsets
private lazy var webController : WebContentController = {
let controller = WKWebViewContentController()
controller.webView.navigationDelegate = self
return controller
}()
private var state = State.CreatingSession
private var contentRequest : NSURLRequest? = nil
var currentUrl: NSURL? {
return contentRequest?.URL
}
public init(environment : Environment) {
self.environment = environment
loadController = LoadStateViewController()
insetsController = ContentInsetsController()
headerInsets = HeaderViewInsets()
insetsController.addSource(headerInsets)
super.init(nibName: nil, bundle: nil)
automaticallyAdjustsScrollViewInsets = false
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// Prevent crash due to stale back pointer, since WKWebView's UIScrollView apparently doesn't
// use weak for its delegate
webController.scrollView.delegate = nil
webController.clearDelegate()
}
override public func viewDidLoad() {
self.state = webController.initialContentState
self.view.addSubview(webController.view)
webController.view.snp_makeConstraints {make in
make.edges.equalTo(self.view)
}
self.loadController.setupInController(self, contentView: webController.view)
webController.view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
webController.scrollView.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
self.insetsController.setupInController(self, scrollView: webController.scrollView)
if let request = self.contentRequest {
loadRequest(request)
}
}
private func resetState() {
loadController.state = .Initial
state = .CreatingSession
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if view.window == nil {
webController.resetState()
}
resetState()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
insetsController.updateInsets()
}
public func showError(error : NSError?, icon : Icon? = nil, message : String? = nil) {
loadController.state = LoadState.failed(error, icon : icon, message : message)
}
// MARK: Header View
var headerView : UIView? {
get {
return headerInsets.view
}
set {
headerInsets.view?.removeFromSuperview()
headerInsets.view = newValue
if let headerView = newValue {
webController.view.addSubview(headerView)
headerView.snp_makeConstraints {make in
if #available(iOS 9.0, *) {
make.top.equalTo(self.topLayoutGuide.bottomAnchor)
}
else {
make.top.equalTo(self.snp_topLayoutGuideBottom)
}
make.leading.equalTo(webController.view)
make.trailing.equalTo(webController.view)
}
webController.view.setNeedsLayout()
webController.view.layoutIfNeeded()
}
}
}
private func loadOAuthRefreshRequest() {
if let hostURL = environment.config.apiHostURL() {
guard let URL = hostURL.URLByAppendingPathComponent(OAuthExchangePath) else { return }
let exchangeRequest = NSMutableURLRequest(URL: URL)
exchangeRequest.HTTPMethod = HTTPMethod.POST.rawValue
for (key, value) in self.environment.session.authorizationHeaders {
exchangeRequest.addValue(value, forHTTPHeaderField: key)
}
self.webController.loadURLRequest(exchangeRequest)
}
}
// MARK: Request Loading
public func loadRequest(request : NSURLRequest) {
contentRequest = request
loadController.state = .Initial
state = webController.initialContentState
if webController.alwaysRequiresOAuthUpdate {
loadOAuthRefreshRequest()
}
else {
webController.loadURLRequest(request)
}
}
// MARK: WKWebView delegate
public func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
switch navigationAction.navigationType {
case .LinkActivated, .FormSubmitted, .FormResubmitted:
if let URL = navigationAction.request.URL {
UIApplication.sharedApplication().openURL(URL)
}
decisionHandler(.Cancel)
default:
decisionHandler(.Allow)
}
}
public func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {
if let
httpResponse = navigationResponse.response as? NSHTTPURLResponse,
statusCode = OEXHTTPStatusCode(rawValue: httpResponse.statusCode),
errorGroup = statusCode.errorGroup
where state == .LoadingContent
{
switch errorGroup {
case .Http4xx:
self.state = .NeedingSession
case .Http5xx:
self.loadController.state = LoadState.failed()
decisionHandler(.Cancel)
}
}
decisionHandler(.Allow)
}
public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
switch state {
case .CreatingSession:
if let request = contentRequest {
state = .LoadingContent
webController.loadURLRequest(request)
}
else {
loadController.state = LoadState.failed()
}
case .LoadingContent:
loadController.state = .Loaded
case .NeedingSession:
state = .CreatingSession
loadOAuthRefreshRequest()
}
}
public func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
showError(error)
}
public func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
showError(error)
}
public func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
// Don't use basic auth on exchange endpoint. That is explicitly non protected
// and it screws up the authorization headers
if let URL = webView.URL where ((URL.absoluteString?.hasSuffix(OAuthExchangePath)) != nil) {
completionHandler(.PerformDefaultHandling, nil)
}
else if let credential = environment.config.URLCredentialForHost(challenge.protectionSpace.host) {
completionHandler(.UseCredential, credential)
}
else {
completionHandler(.PerformDefaultHandling, nil)
}
}
}
|
a56c8b0b7437ba23c14b5ab1b1d7c328
| 31.825083 | 205 | 0.637442 | false | false | false | false |
kar/challenges
|
refs/heads/master
|
hackerrank-algorithms-dynamic-programming/sherlock-and-cost.swift
|
apache-2.0
|
1
|
// Sherlock and Cost
//
// The key observation is that each Ai has to be either 1 or Bi
// (values in between do not lead to the maximum sum), so that
// the result subsequence will have a zigzag pattern:
//
// 1 B2 1 B4 1 B6 ... (or B1 1 B3 1 B5 ...).
//
// In some cases, selecting same value twice next to each other
// may lead to a higher sum (lets call it the jump):
//
// B1 1 1 B4 1 B5 ... (or B1 1 B3 B3 1 B6 ...).
//
// The sums matrix keeps partial sums for each element in the
// subsequence, starting either with B1 (row 0) or 1 (row 1).
// For each cell, we pick the maximum partial sum between
// the zigzag pattern or the jump. You can imagine each cell
// corresponding to the following subsequence pattern:
//
// 0 1 2
// 0 | - | B1 1 | B1 1 1 or 1 B2 1 | ...
// 1 | - | 1 B2 | B1 1 B3 or 1 B2 B2 | ...
//
// Note: This solution scores at 31.25/50 because some test
// cases time out (and I am not sure why).
import Foundation
func solve(n: Int, b: [Int]) -> Int {
var sums = [[Int]](repeating: [Int](repeating: 0, count: 2), count: n)
for i in 1..<n {
var a = sums[i - 1][0]
var y = sums[i - 1][1] + b[i - 1] - 1
sums[i][0] = a
if a < y {
sums[i][0] = y
}
a = sums[i - 1][0] + b[i] - 1
y = sums[i - 1][1]
sums[i][1] = a
if a < y {
sums[i][1] = y
}
}
return max(sums[n - 1][0], sums[n - 1][1])
}
if let cases = Int(readLine()!) {
for c in 0..<cases {
if let n = Int(readLine()!) {
let b = readLine()!.components(separatedBy: " ").map { num in Int(num)! }
let solution = solve(n: n, b: b)
print(solution)
}
}
}
|
278cb3bd1b95200cf0bc402cc0219b32
| 28.2 | 85 | 0.52911 | false | false | false | false |
scoremedia/Fisticuffs
|
refs/heads/master
|
Sources/Fisticuffs/TransformBindingHandler.swift
|
mit
|
1
|
//
// TransformBindingHandler.swift
// Fisticuffs
//
// Created by Darren Clark on 2016-02-12.
// Copyright © 2016 theScore. All rights reserved.
//
import Foundation
private struct NoReverseTransformError: Error {}
open class TransformBindingHandler<Control: AnyObject, InDataValue, OutDataValue, PropertyValue>: BindingHandler<Control, InDataValue, PropertyValue> {
let bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>
let transform: (InDataValue) -> OutDataValue
let reverseTransform: ((OutDataValue) -> InDataValue)?
init(_ transform: @escaping (InDataValue) -> OutDataValue, reverse: ((OutDataValue) -> InDataValue)?, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>) {
self.bindingHandler = bindingHandler
self.transform = transform
self.reverseTransform = reverse
}
open override func set(control: Control, oldValue: InDataValue?, value: InDataValue, propertySetter: @escaping PropertySetter) {
bindingHandler.set(control: control, oldValue: oldValue.map(transform), value: transform(value), propertySetter: propertySetter)
}
open override func get(control: Control, propertyGetter: @escaping PropertyGetter) throws -> InDataValue {
guard let reverseTransform = reverseTransform else {
throw NoReverseTransformError()
}
let value = try bindingHandler.get(control: control, propertyGetter: propertyGetter)
return reverseTransform(value)
}
override open func dispose() {
bindingHandler.dispose()
super.dispose()
}
}
public extension BindingHandlers {
static func transform<Control, DataValue, PropertyValue>(_ block: @escaping (DataValue) -> PropertyValue) -> TransformBindingHandler<Control, DataValue, PropertyValue, PropertyValue> {
TransformBindingHandler(block, reverse: nil, bindingHandler: DefaultBindingHandler())
}
static func transform<Control, DataValue, PropertyValue>(_ block: @escaping (DataValue) -> PropertyValue, reverse: @escaping (PropertyValue) -> DataValue) -> TransformBindingHandler<Control, DataValue, PropertyValue, PropertyValue> {
TransformBindingHandler(block, reverse: reverse, bindingHandler: DefaultBindingHandler())
}
static func transform<Control, InDataValue, OutDataValue, PropertyValue>(_ block: @escaping (InDataValue) -> OutDataValue, reverse: ((OutDataValue) -> InDataValue)?, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>)
-> TransformBindingHandler<Control, InDataValue, OutDataValue, PropertyValue> {
TransformBindingHandler<Control, InDataValue, OutDataValue, PropertyValue>(block, reverse: reverse, bindingHandler: bindingHandler)
}
}
|
30eb5b23e11c387ba4d7bf30af8960ca
| 47.403509 | 239 | 0.742298 | false | false | false | false |
yaobanglin/viossvc
|
refs/heads/master
|
viossvc/Scenes/Chat/ChatLocation/ChatLocationAnotherCell.swift
|
apache-2.0
|
1
|
//
// ChatLocationAnotherCell.swift
// TestAdress
//
// Created by J-bb on 16/12/29.
// Copyright © 2016年 J-bb. All rights reserved.
//
import UIKit
class ChatLocationAnotherCell: ChatLocationCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
bundleImageView.tintColor = UIColor(red: 19/255.0, green: 31/255.0, blue: 50/255.0, alpha: 1.0)
titleLabel.textColor = UIColor.whiteColor()
adressLabel.textColor = UIColor.whiteColor()
bundleImageView.snp_remakeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(5)
make.right.equalTo(-100)
make.bottom.equalTo(-5)
}
}
override func setupDataWithContent(content: String?) {
super.setupDataWithContent(content)
var image = UIImage(named: "msg-bubble-another")
image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
bundleImageView.image = image?.resizableImageWithCapInsets(UIEdgeInsetsMake(17, 23 , 17, 23), resizingMode: UIImageResizingMode.Stretch)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
ca230abe8990ee9644953c2fd0bf56ac
| 30.853659 | 145 | 0.666156 | false | false | false | false |
sully10024/There-Yet
|
refs/heads/master
|
Geotify/Geotification.swift
|
mit
|
1
|
import UIKit
import MapKit
import CoreLocation
struct GeoKey {
static let latitude = "latitude"
static let longitude = "longitude"
static let radius = "radius"
static let identifier = "identifier"
static let note = "note"
}
class Geotification: NSObject, NSCoding, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var radius: CLLocationDistance
var identifier: String
var note: String
var title: String? {
if note.isEmpty {
return "No Note"
}
return note
}
var subtitle: String? {
return "Radius: \(radius)m - On Entry"
}
init(coordinate: CLLocationCoordinate2D, radius: CLLocationDistance, identifier: String, note: String) {
self.coordinate = coordinate
self.radius = radius
self.identifier = identifier
self.note = note
}
// MARK: NSCoding
required init?(coder decoder: NSCoder) {
let latitude = decoder.decodeDouble(forKey: GeoKey.latitude)
let longitude = decoder.decodeDouble(forKey: GeoKey.longitude)
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
radius = decoder.decodeDouble(forKey: GeoKey.radius)
identifier = decoder.decodeObject(forKey: GeoKey.identifier) as! String
note = decoder.decodeObject(forKey: GeoKey.note) as! String
}
func encode(with coder: NSCoder) {
coder.encode(coordinate.latitude, forKey: GeoKey.latitude)
coder.encode(coordinate.longitude, forKey: GeoKey.longitude)
coder.encode(radius, forKey: GeoKey.radius)
coder.encode(identifier, forKey: GeoKey.identifier)
coder.encode(note, forKey: GeoKey.note)
}
}
|
f2c7937cd8416a18734e11182d1c459c
| 27.892857 | 106 | 0.717553 | false | false | false | false |
NoryCao/zhuishushenqi
|
refs/heads/master
|
zhuishushenqi/TXTReader/BookDetail/Views/ToolBar.swift
|
mit
|
1
|
//
// ToolBar.swift
// PageViewController
//
// Created by Nory Cao on 16/10/10.
// Copyright © 2016年 QS. All rights reserved.
//
import UIKit
typealias ZSBgViewHandler = ()->Void
enum ToolBarFontChangeAction {
case plus
case minimus
}
protocol ToolBarDelegate{
func backButtonDidClicked()
func catagoryClicked()
func changeSourceClicked()
func toolBarDidShow()
func toolBarDidHidden()
func readBg(type:Reader)
func fontChange(action:ToolBarFontChangeAction)
func brightnessChange(value:CGFloat)
func cacheAll()
func toolbar(toolbar:ToolBar, clickMoreSetting:UIView)
func listen()
}
class ToolBar: UIView {
private let kBottomBtnTag = 12345
private let TopBarHeight:CGFloat = kNavgationBarHeight
private let BottomBarHeight:CGFloat = 49 + CGFloat(kTabbarBlankHeight)
var toolBarDelegate:ToolBarDelegate?
var topBar:UIView?
var bottomBar:UIView?
var midBar:UIView?
var isShow:Bool = false
var showMid:Bool = false
var whiteBtn:UIButton!
var yellowBtn:UIButton!
var greenBtn:UIButton!
var mode_bgView:UIScrollView!
var fontSize:Int = QSReaderSetting.shared.fontSize
var titleLabel:UILabel!
var title:String = "" {
didSet{
titleLabel.text = self.title
}
}
var bgItemViews:[ZSModeBgItemView] = []
var progressView:ProgressView!
override init(frame: CGRect) {
super.init(frame: frame)
fontSize = QSReaderSetting.shared.fontSize
initSubview()
}
private func initSubview(){
topBar = UIView(frame: CGRect(x: 0, y: -TopBarHeight, width: UIScreen.main.bounds.size.width, height: TopBarHeight))
topBar?.backgroundColor = UIColor(white: 0.0, alpha: 1.0)
addSubview(topBar!)
bottomBar = UIView(frame: CGRect(x:0,y:UIScreen.main.bounds.size.height,width:UIScreen.main.bounds.size.width,height:BottomBarHeight))
bottomBar?.backgroundColor = UIColor(white: 0.0, alpha: 1.0)
addSubview(bottomBar!)
midBar = UIView(frame: CGRect(x:0,y:UIScreen.main.bounds.size.height - 180 - BottomBarHeight,width:UIScreen.main.bounds.size.width,height:180))
midBar?.backgroundColor = UIColor(white: 0.0, alpha: 0.7)
midBarSubviews()
bottomSubviews()
let backBtn = UIButton(type: .custom)
backBtn.setImage(UIImage(named: "sm_exit"), for: .normal)
backBtn.addTarget(self, action: #selector(backAction(btn:)), for: .touchUpInside)
backBtn.frame = CGRect(x:self.bounds.width - 55, y: STATEBARHEIGHT,width: 49,height: 49)
topBar?.addSubview(backBtn)
let changeSourceBtn = UIButton(type: .custom)
changeSourceBtn.setTitle("换源", for: .normal)
changeSourceBtn.setTitleColor(UIColor.white, for: .normal)
changeSourceBtn.addTarget(self, action: #selector(changeSourceAction(btn:)), for: .touchUpInside)
changeSourceBtn.frame = CGRect(x:self.bounds.width - 65, y: 27,width: 50,height: 30)
changeSourceBtn.frame = CGRect(x:10, y:STATEBARHEIGHT + 7,width: 50,height: 30)
topBar?.addSubview(changeSourceBtn)
let listenBtn = UIButton(type: .custom)
listenBtn.setImage(UIImage(named: "readAloud"), for: .normal)
listenBtn.addTarget(self, action: #selector(listenAction(btn:)), for: .touchUpInside)
listenBtn.frame = CGRect(x:self.bounds.width - 104, y: STATEBARHEIGHT,width: 49,height: 49)
topBar?.addSubview(listenBtn)
titleLabel = UILabel(frame: CGRect(x: self.bounds.width/2 - 100, y: STATEBARHEIGHT+7, width: 200, height: 30))
titleLabel.textColor = UIColor.white
titleLabel.textAlignment = .center
topBar?.addSubview(titleLabel)
let tap = UITapGestureRecognizer(target: self, action:#selector(hideWithAnimations(animation:)) )
addGestureRecognizer(tap)
}
func midBarSubviews(){
let progressBar = UISlider(frame: CGRect(x: 50, y: 25, width: self.bounds.width - 100, height: 15))
progressBar.minimumTrackTintColor = UIColor.orange
progressBar.value = Float(UIScreen.main.brightness)
progressBar.addTarget(self, action: #selector(brightnessChange(btn:)), for: .valueChanged)
let leftImg = UIImageView(frame: CGRect(x: 25, y: 25, width: 15, height: 15))
leftImg.image = UIImage(named: "brightess_white_low")
let rightImg = UIImageView(frame: CGRect(x: self.bounds.width - 40, y: 23, width: 25, height: 25))
rightImg.image = UIImage(named: "brightess_white_high")
let fontminus = button(with: UIImage(named:"font_decrease"), selectedImage: nil, title: nil, frame: CGRect(x: 13, y: 55, width: 60, height: 60), selector: #selector(fontMinusAction(btn:)), font: nil)
let fontPlus = button(with: UIImage(named:"font_increase"), selectedImage: nil, title: nil, frame: CGRect(x: fontminus.frame.maxX + 13, y: fontminus.frame.minY, width: 60, height: 60), selector: #selector(fontPlusAction(btn:)), font: nil)
let landscape = button(with: UIImage(named:"landscape"), selectedImage: nil, title: nil, frame: CGRect(x: fontPlus.frame.maxX, y: fontminus.frame.minY + 5, width: 60, height: 50), selector: #selector(landscape(btn:)), font: nil)
let autoReading = button(with: UIImage(named:"autoreading_start"), selectedImage: nil, title: "自动阅读", frame: CGRect(x: landscape.frame.maxX, y: landscape.frame.minY + 10, width: 115, height: 30), selector: #selector(autoReading(btn:)), font: UIFont.systemFont(ofSize: 15))
mode_bgView = UIScrollView(frame: CGRect(x: 0, y: 115, width: self.bounds.width - 140, height: 60))
mode_bgView.isUserInteractionEnabled = true
// mode_bgView.backgroundColor = UIColor.orange
mode_bgView.showsHorizontalScrollIndicator = true
midBar?.addSubview(mode_bgView)
let itemImages = ["white_mode_bg","yellow_mode_bg","green_mode_bg","blackGreen_mode_bg","pink_mode_bg","sheepskin_mode_bg","violet_mode_bg","water_mode_bg","weekGreen_mode_bg","weekPink_mode_bg","coffee_mode_bg"]
var index = 0
for image in itemImages {
let bgView = ZSModeBgItemView(frame: CGRect(x: 25*(index + 1) + 60 * index, y: 0, width: 60, height: 60))
bgView.setImage(image: UIImage(named: image))
bgView.index = index
bgView.selectHandler = {
self.itemAction(index: bgView.index)
}
mode_bgView.addSubview(bgView)
bgItemViews.append(bgView)
index += 1
}
mode_bgView.contentSize = CGSize(width: itemImages.count * (60 + 25), height: 60)
let senior = button(with: UIImage(named:"reading_more_setting"), selectedImage: nil, title: "高级设置", frame: CGRect(x: self.bounds.width - 140, y: 130, width: 115, height: 30), selector: #selector(seniorSettingAction(btn:)), font: UIFont.systemFont(ofSize: 15))
progressView = ProgressView(frame: CGRect(x: 0, y: self.bounds.height - 49 - 20, width: self.bounds.width, height: 20))
progressView.backgroundColor = UIColor.black
progressView.isHidden = true
progressView.alpha = 0.7
addSubview(progressView)
midBar?.addSubview(leftImg)
midBar?.addSubview(rightImg)
midBar?.addSubview(progressBar)
midBar?.addSubview(fontminus)
midBar?.addSubview(fontPlus)
midBar?.addSubview(landscape)
midBar?.addSubview(autoReading)
midBar?.addSubview(senior)
let type = AppStyle.shared.reader
if type.rawValue >= 0 && type.rawValue < bgItemViews.count {
var index = 0
for bgView in bgItemViews {
if type.rawValue == index {
bgView.select(select: true)
} else {
bgView.select(select: false)
}
index += 1
}
}
}
func bottomSubviews(){
let width = UIScreen.main.bounds.width/5
let btnWidth:CGFloat = 30.0
let btnHeight:CGFloat = 34.0
let images = ["night_mode","feedback","directory","preview_btn","reading_setting"]
let titles = ["夜间","反馈","目录","缓存","设置"]
for item in 0..<5 {
let x = (width - btnWidth)/2*CGFloat(item*2 + 1) + btnWidth*CGFloat(item)
let y = 49/2 - btnHeight/2
let btn = CategoryButton(type: .custom)
btn.setImage(UIImage(named: images[item]), for: .normal)
btn.setTitle(titles[item], for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 9)
btn.frame = CGRect(x:x,y: y,width: btnWidth,height: btnHeight)
btn.addTarget(self, action: #selector(bottomBtnAction(btn:)), for: .touchUpInside)
btn.tag = kBottomBtnTag + item
bottomBar?.addSubview(btn)
}
}
func button(with image:UIImage?,selectedImage:UIImage?,title:String?,frame:CGRect,selector:Selector,font:UIFont?)->UIButton{
let button = UIButton(frame: frame)
button.setImage(selectedImage, for: .selected)
button.setImage(image, for: .normal)
button.setTitle(title, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
button.titleLabel?.font = font
return button
}
func showWithAnimations(animation:Bool,inView:UIView){
self.isShow = true
inView.addSubview(self)
UIView.animate(withDuration: 0.35, animations: {
self.topBar?.frame = CGRect(x:0, y:0,width: self.bounds.size.width,height: self.TopBarHeight)
self.bottomBar?.frame = CGRect(x:0,y: self.bounds.size.height - self.BottomBarHeight,width: self.bounds.size.width,height: self.BottomBarHeight)
self.progressView.frame = CGRect(x: 0, y: self.bounds.height - 49 - 20, width: self.bounds.width, height: 20)
}) { (finished) in
}
toolBarDelegate?.toolBarDidShow()
}
@objc func hideWithAnimations(animation:Bool){
midBar?.removeFromSuperview()
showMid = false
UIView.animate(withDuration: 0.35, animations: {
self.topBar?.frame = CGRect(x:0,y: -self.TopBarHeight,width: self.bounds.size.width,height: self.TopBarHeight)
self.bottomBar?.frame = CGRect(x:0, y:self.bounds.size.height + 20, width:self.bounds.size.width, height:self.BottomBarHeight)
self.progressView.frame = CGRect(x: 0, y: self.bounds.height, width: self.bounds.width, height: 20)
}) { (finished) in
self.isShow = false
self.removeFromSuperview()
}
toolBarDelegate?.toolBarDidHidden()
}
@objc private func brightnessChange(btn:UISlider){
//调节屏幕亮度
self.toolBarDelegate?.brightnessChange(value: CGFloat(btn.value))
}
@objc private func fontMinusAction(btn:UIButton){
self.toolBarDelegate?.fontChange(action: .minimus)
}
@objc private func fontPlusAction(btn:UIButton){
self.toolBarDelegate?.fontChange(action: .plus)
}
@objc private func landscape(btn:UIButton){
}
@objc private func autoReading(btn:UIButton){
}
@objc private func whiteAction(btn:UIButton){
btn.isSelected = true
yellowBtn.isSelected = false
greenBtn.isSelected = false
self.toolBarDelegate?.readBg(type: .white)
}
@objc private func yellowAction(btn:UIButton){
btn.isSelected = true
whiteBtn.isSelected = false
greenBtn.isSelected = false
self.toolBarDelegate?.readBg(type: .yellow)
}
@objc private func greenAction(btn:UIButton){
btn.isSelected = true
whiteBtn.isSelected = false
yellowBtn.isSelected = false
self.toolBarDelegate?.readBg(type: .green)
}
@objc private func itemAction(index:Int) {
var viewIndex = 0
for bgView in bgItemViews {
if viewIndex != index {
bgView.select(select: false)
}
viewIndex += 1
}
self.toolBarDelegate?.readBg(type: Reader(rawValue: index) ?? .white)
}
@objc private func seniorSettingAction(btn:UIButton){
self.toolBarDelegate?.toolbar(toolbar: self, clickMoreSetting: btn)
}
@objc private func bottomBtnAction(btn:UIButton){
let tag = btn.tag - kBottomBtnTag
switch tag {
case 0:
darkNight(btn: btn)
break
case 1:
feedback(btn: btn)
break
case 2:
catalogAction(btn: btn)
break
case 3:
cache(btn: btn)
break
case 4:
setting(btn: btn)
break
default:
darkNight(btn: btn)
}
}
@objc private func darkNight(btn:UIButton){
}
@objc private func feedback(btn:UIButton){
}
@objc private func catalogAction(btn:UIButton){
toolBarDelegate?.catagoryClicked()
}
@objc private func cache(btn:UIButton){
toolBarDelegate?.cacheAll()
}
@objc private func setting(btn:UIButton){
showMid = !showMid
if showMid {
self.addSubview(midBar!)
}else{
midBar?.removeFromSuperview()
}
}
@objc private func backAction(btn:UIButton){
toolBarDelegate?.backButtonDidClicked()
}
@objc private func listenAction(btn:UIButton){
toolBarDelegate?.listen()
}
@objc private func changeSourceAction(btn:UIButton){
toolBarDelegate?.changeSourceClicked()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ZSModeBgItemView: UIView {
var backgroundImage:UIImageView!
private var selectedImage:UIImageView!
var selectHandler:ZSBgViewHandler?
var index:Int = 0
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupSubviews() {
isUserInteractionEnabled = true
backgroundImage = UIImageView(frame: self.bounds)
backgroundImage.isUserInteractionEnabled = true
backgroundImage.layer.cornerRadius = self.bounds.width/2
backgroundImage.layer.masksToBounds = true
selectedImage = UIImageView(frame: CGRect(x: self.bounds.width/2 - 18, y: self.bounds.width/2 - 18, width: 36, height: 36))
selectedImage.isUserInteractionEnabled = true
selectedImage.image = UIImage(named: "cell_selected_tip")
selectedImage.isHidden = true
addSubview(backgroundImage)
addSubview(selectedImage)
let tap = UITapGestureRecognizer(target: self, action: #selector(selectAction))
backgroundImage.addGestureRecognizer(tap)
}
@objc
private func selectAction() {
selectedImage.isHidden = false
selectHandler?()
}
func select(select:Bool) {
selectedImage.isHidden = !select
}
func setImage(image:UIImage?) {
backgroundImage.image = image
}
}
|
8031bcfe4164180d55d8f8f52080b3cd
| 37.167076 | 280 | 0.629329 | false | false | false | false |
muenzpraeger/salesforce-einstein-vision-swift
|
refs/heads/master
|
SalesforceEinsteinVision/Classes/http/parts/MultiPartExample.swift
|
apache-2.0
|
1
|
//
// MultiPartExample.swift
// Pods
//
// Created by René Winkelmeyer on 02/28/2017.
//
//
import Alamofire
import Foundation
public struct MultiPartExample : MultiPart {
private let MAX_NAME = 180
private var _name:String?
private var _labelId:Int?
private var _file:URL?
public init() {}
public mutating func build(name: String, labelId: Int, file: URL) throws {
if name.isEmpty {
throw ModelError.noFieldValue(field: "name")
}
if (name.characters.count>MAX_NAME) {
throw ModelError.stringTooLong(field: "name", maxValue: MAX_NAME, currentValue: name.characters.count)
}
if (labelId<0) {
throw ModelError.intTooSmall(field: "labelId", minValue: 0, currentValue: labelId)
}
if file.absoluteString.isEmpty {
throw ModelError.noFieldValue(field: "file")
}
_name = name
_labelId = labelId
_file = file
}
public func form(multipart: MultipartFormData) {
let nameData = _name?.data(using: String.Encoding.utf8)
multipart.append(nameData!, withName: "name")
let labelIdData = String(describing: _labelId).data(using: String.Encoding.utf8)
multipart.append(labelIdData!, withName: "labelId")
multipart.append(_file!, withName: "data")
}
}
|
82c59945d9b3c581c570d085398281bf
| 25.254545 | 114 | 0.590028 | false | false | false | false |
Coderian/SwiftedGPX
|
refs/heads/master
|
SwiftedGPX/Elements/LatitudeType.swift
|
mit
|
1
|
//
// Latitude.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX LatitudeType
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:simpleType name="latitudeType">
/// <xsd:annotation>
/// <xsd:documentation>
/// The latitude of the point. Decimal degrees, WGS84 datum.
/// </xsd:documentation>
/// </xsd:annotation>
/// <xsd:restriction base="xsd:decimal">
/// <xsd:minInclusive value="-90.0"/>
/// <xsd:maxInclusive value="90.0"/>
/// </xsd:restriction>
/// </xsd:simpleType>
public class LatitudeType {
var value:Double = 0.0
var originalValue:String!
public init( latitude: String ){
self.originalValue = latitude
self.value = Double(latitude)!
}
}
|
ad0467070f05cc42db526b1747ec257c
| 25.727273 | 71 | 0.592509 | false | false | false | false |
magicien/MMDSceneKit
|
refs/heads/master
|
Source/Common/MMDIKConstraint.swift
|
mit
|
1
|
//
// MMDIKNode.swift
// MMDSceneKit
//
// Created by magicien on 12/20/15.
// Copyright © 2015 DarkHorse. All rights reserved.
//
import SceneKit
open class MMDIKConstraint {
public var boneArray: [MMDNode]! = []
var minAngleArray: [Float]! = []
var maxAngleArray: [Float]! = []
public var ikBone: MMDNode! = nil
public var targetBone: MMDNode! = nil
var iteration: Int = 0
var weight: Float = 0.0
var linkNo: Int = -1
var isEnable: Bool = true
var angle: SCNVector3! = SCNVector3()
var orgTargetPos: SCNVector3! = SCNVector3()
var rotAxis: SCNVector3! = SCNVector3()
var rotQuat: SCNVector4! = SCNVector4()
var inverseMat: SCNMatrix4! = SCNMatrix4()
var diff: SCNVector3! = SCNVector3()
var effectorPos: SCNVector3! = SCNVector3()
var targetPos: SCNVector3! = SCNVector3()
/*
let ikConstraintBlock = { (node: SCNNode, matrix: SCNMatrix4) -> SCNMatrix4 in
let mmdNode = node as? MMDNode
if(mmdNode == nil){
return matrix
}
let optionalIK = mmdNode!.ikConstraint
if(optionalIK == nil){
return matrix
}
let ik = optionalIK as MMDIKConstraint!
let zeroThreshold = 0.00000001
//let targetMat = matrix
let orgTargetPos = ik.targetBone.position
let pos = SCNVector3(matrix.m41, matrix.m42, matrix.m43)
let rotAxis = ik.rotAxis
let rotQuat = ik.rotQuat
let inverseMat = ik.inverseMat
let diff = ik.diff
let effectorPos = ik.effectorPos
let targetPos = ik.targetPos
/*
for var i = ik!.boneArray.count; i>=0; i-- {
ik.boneArray[i].updateMatrix()
}
ik.effectorBone.updateMatrix()
*/
for calcCount in 0..<ik!.iteration {
for linkIndex in 0..<ik.boneArray.count {
let linkedBone = ik.boneArray[linkIndex]
let effectorMat = ik.effectorBone.representNode.transform
effectorPos.x = effectorMat.m41
effectorPos.y = effectorMat.m42
effectorPos.z = effectorMat.m43
// inverseMat.inverseMatrix(linkedBone.representNode.transform)
effectorPos = effectorPos * inverseMat
targetPos = orgTargetPos * inverseMat
diff = effectorPos - targetPos
if diff.length() < zeroThreshold {
return matrix
}
effectorPos.normalize()
targetPos.normalize()
var eDotT = effectorPos.dot(targetPos)
if(eDotT > 1.0) {
eDotT = 1.0
}
if(eDotT < -1.0) {
edotT = -1.0
}
var rotAngle = acos(eDotT)
if rotAngle > ik.weight * (linkIndex + 1) * 4 {
rotAngle = ik.weight * (linkIndex + 1) * 4
}
rotAxis.cross(effectPos, targetPos)
if rotAxis.length() < zeroThreshold) {
break
}
rotAxis.normalize()
rotQuat.createAxis(rotAxis, rotAngle)
rotQuat.normalize()
if ik.minAngleArray[linkIndex] {
ik.limitAngle(ik.minAngleArray[linkIndex], ik.maxAngleArray[linkIndex])
}
linkedBone.rotate.cross(linkedBone.rotate, rotQuat)
linkedBone.rotate.normalize()
for var i = linkIndex; i>=0; i-- {
ik.boneList[i].updateMatrix()
}
ik.effectorBone.updateMatrix()
}
}
}
*/
func printInfo() {
print("boneArray: \(self.boneArray.count)")
for bone in self.boneArray {
print(" \(String(describing: bone.name))")
}
print("minAngleArray: \(self.minAngleArray.count)")
for val in self.minAngleArray {
print(" \(val)")
}
print("maxAngleArray: \(self.maxAngleArray.count)")
for val in self.maxAngleArray {
print(" \(val)")
}
print("ikBone: \(String(describing: self.ikBone.name))")
print("targetBone: \(String(describing: self.targetBone.name))")
print("iteration: \(self.iteration)")
print("weight: \(self.weight)")
print("isEnable: \(self.isEnable)")
print("")
}
}
|
56ac9738a070229a03bbb714608240d9
| 32.248227 | 91 | 0.515145 | false | false | false | false |
Czajnikowski/TrainTrippin
|
refs/heads/master
|
LibrarySample/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift
|
mit
|
3
|
//
// CurrentThreadScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import Dispatch
let CurrentThreadSchedulerKeyInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey"
let CurrentThreadSchedulerQueueKeyInstance = "RxSwift.CurrentThreadScheduler.Queue"
typealias CurrentThreadSchedulerValue = NSString
let CurrentThreadSchedulerValueInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" as NSString
/**
Represents an object that schedules units of work on the current thread.
This is the default scheduler for operators that generate elements.
This scheduler is also sometimes called `trampoline scheduler`.
*/
public class CurrentThreadScheduler : ImmediateSchedulerType {
typealias ScheduleQueue = RxMutableBox<Queue<ScheduledItemType>>
/**
The singleton instance of the current thread scheduler.
*/
public static let instance = CurrentThreadScheduler()
static var queue : ScheduleQueue? {
get {
return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKeyInstance)
}
set {
Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKeyInstance)
}
}
/**
Gets a value that indicates whether the caller must call a `schedule` method.
*/
public static fileprivate(set) var isScheduleRequired: Bool {
get {
let value: CurrentThreadSchedulerValue? = Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerKeyInstance)
return value == nil
}
set(isScheduleRequired) {
Thread.setThreadLocalStorageValue(isScheduleRequired ? nil : CurrentThreadSchedulerValueInstance, forKey: CurrentThreadSchedulerKeyInstance)
}
}
/**
Schedules an action to be executed as soon as possible on current thread.
If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be
automatically installed and uninstalled after all work is performed.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
if CurrentThreadScheduler.isScheduleRequired {
CurrentThreadScheduler.isScheduleRequired = false
let disposable = action(state)
defer {
CurrentThreadScheduler.isScheduleRequired = true
CurrentThreadScheduler.queue = nil
}
guard let queue = CurrentThreadScheduler.queue else {
return disposable
}
while let latest = queue.value.dequeue() {
if latest.isDisposed {
continue
}
latest.invoke()
}
return disposable
}
let existingQueue = CurrentThreadScheduler.queue
let queue: RxMutableBox<Queue<ScheduledItemType>>
if let existingQueue = existingQueue {
queue = existingQueue
}
else {
queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1))
CurrentThreadScheduler.queue = queue
}
let scheduledItem = ScheduledItem(action: action, state: state)
queue.value.enqueue(scheduledItem)
return scheduledItem
}
}
|
54b73359d85644164379cf550fbe5970
| 33.216981 | 152 | 0.682106 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios
|
refs/heads/develop
|
Pod/Classes/Common/Model/CreativeModels.swift
|
lgpl-3.0
|
1
|
//
// CreativeModels.swift
// SuperAwesome
//
// Created by Gunhan Sancar on 16/04/2020.
//
public struct Creative: Codable {
public let id: Int
let name: String?
let format: CreativeFormatType
public let clickUrl: String?
let details: CreativeDetail
let bumper: Bool?
public let payload: String?
enum CodingKeys: String, CodingKey {
case id
case name
case format
case clickUrl = "click_url"
case details
case bumper
case payload = "customPayload"
}
}
struct CreativeDetail: Codable {
let url: String?
let image: String?
let video: String?
let placementFormat: String
let tag: String?
let width: Int
let height: Int
let duration: Int
let vast: String?
enum CodingKeys: String, CodingKey {
case url
case image
case video
case placementFormat = "placement_format"
case tag
case width
case height
case duration
case vast
}
}
enum CreativeFormatType: String, Codable, DecodableDefaultLastItem {
case video
case imageWithLink = "image_with_link"
case tag
case richMedia = "rich_media"
case unknown
}
|
79285f3b257c80b9f567dc6d8f4a52eb
| 20.293103 | 68 | 0.621862 | false | false | false | false |
Kezuino/SMPT31
|
refs/heads/master
|
NOtification/NOKit/Location.swift
|
mit
|
1
|
//
// Location.swift
// NOtification
//
// Created by Bas on 29/05/2015.
// Copyright (c) 2015 Bas. All rights reserved.
//
import Foundation
import SwiftSerializer
public typealias VIP = User
public class Location: Serializable {
/// Name of the location
public var name: String!
/// The network tied to the location.
public var ssid: SSID! {
didSet {
self.addToManager(self)
}
}
/// The VIPs for the location.
public var vips = [VIP]()
/**
The designated initializer.
:param: name The name of the location.
:param: network The network tied to the location.
*/
public init(name: String, ssid: SSID) {
self.name = name
self.ssid = ssid
}
/**
Initializes a location with a specified array of VIPs.
:param: name The name of the location.
:param: network The network tied to the location.
:param: vips The array of VIPs to add to the location.
*/
public convenience init(name: String, ssid: SSID, vips: [VIP]) {
self.init(name: name, ssid: ssid)
self.vips = vips
}
/**
Initializes a location with one or more VIPs.
:param: name The name of the location.
:param: network The network tied to the location.
:param: vips One or more VIPs to add to the location.
*/
public convenience init(name: String, ssid: SSID, vips: VIP...) {
self.init(name: name, ssid: ssid)
self.vips = vips
}
/**
Adds a VIP to the list of VIPs.
:param: vip The VIP to add to the VIPs.
:returns: VIP if successfully added, nil if already in VIPs.
*/
public func addVIP(vip newVIP: VIP) -> VIP? {
for vip in self.vips {
if vip == newVIP {
return nil
}
}
self.vips.append(newVIP)
return newVIP
}
/**
Removes a VIP from the list of VIPs.
:param: user The VIP to remove from the VIPs.
:returns: VIP if successfully removed, nil if not.
*/
public func removeVIP(vip removeVIP: VIP) -> VIP? {
return self.vips.removeObject(removeVIP) ? removeVIP : nil
}
}
// MARK: - Hashable
extension Location: Hashable {
/// The hash value.
public override var hashValue: Int {
return ssid.hashValue
}
}
public func ==(lhs: Location, rhs: Location) -> Bool {
return lhs.name == rhs.name && lhs.ssid == rhs.ssid && lhs.vips == rhs.vips
}
// MARK: - Printable
extension Location: Printable {
/// A textual representation of `self`.
public override var description: String {
return "Name: \(self.name) on network \(self.ssid), with vips: (\(self.vips))"
}
}
// MARK: - Manageable
extension Location: Manageable {
/**
Adds the location to its manager.
:param: object The Location instance to add.
:returns: True if the location could be added, else false.
*/
public func addToManager(object: Manageable) -> Bool {
return LocationManager.sharedInstance.addLocation(object)
}
/**
Removes the location from its manager.
:param: object The Location instance to remove.
:returns: True if the location could be removed, else false.
*/
public func removeFromManager(object: Manageable) -> Bool {
return LocationManager.sharedInstance.removeLocation(object)
}
}
|
62dff341ec5567b5308c19aba05d8a82
| 20.692308 | 80 | 0.676233 | false | false | false | false |
StreamOneNL/AppleTV-Demo
|
refs/heads/master
|
AppleTV-Demo/Item.swift
|
mit
|
1
|
//
// Item.swift
// AppleTV-Demo
//
// Created by Nicky Gerritsen on 09-01-16.
// Copyright © 2016 StreamOne. All rights reserved.
//
import Foundation
import Argo
import Curry
import StreamOneSDK
struct Item {
let id: String
let title: String
let type: ItemType
let description: String?
let duration: String
let dateCreated: String?
let dateAired: String?
let views: Int
let thumbnail: String?
let progressiveLink: String?
let hlsLink: String?
let account: BasicAccount
var playbackLink: String? {
return hlsLink ?? progressiveLink
}
}
extension Item: Decodable {
static func decode(json: JSON) -> Decoded<Item> {
let i = curry(Item.init)
return i
<^> json <| "id"
<*> json <| "title"
<*> json <| "type"
<*> json <|? "description"
<*> json <| "duration"
<*> json <|? "datecreated"
<*> json <|? "dateaired"
<*> json <| "views"
<*> json <|? "selectedthumbnailurl"
<*> json <|? ["medialink", "progressive"]
<*> json <|? ["medialink", "hls"]
<*> json <| "account"
}
}
extension Item {
func toDictionary() -> [String: AnyObject] {
var result: [String: AnyObject] = [:]
result["id"] = id
result["title"] = title
result["type"] = type.stringValue
result["description"] = description
result["duration"] = duration
result["datecreated"] = dateCreated
result["dateaired"] = dateAired
result["views"] = views
result["selectedthumbnailurl"] = thumbnail
var medialinks: [String: String] = [:]
if let hlsLink = hlsLink {
medialinks["hls"] = hlsLink
}
if let progressiveLink = progressiveLink {
medialinks["progressive"] = progressiveLink
}
result["medialink"] = medialinks
result["account"] = ["id": account.id, "name": account.name]
return result
}
}
extension Item : Equatable {}
func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.id == rhs.id
}
|
4dd2d7a3ef5523098cc0161527d7823d
| 24.435294 | 68 | 0.553447 | false | false | false | false |
neilpa/List
|
refs/heads/master
|
List/ForwardList.swift
|
mit
|
1
|
// Copyright (c) 2015 Neil Pankey. All rights reserved.
import Dumpster
/// A singly-linked list of values.
public struct ForwardList<T> {
// MARK: Constructors
/// Initializes an empty `ForwardList`.
public init() {
}
/// Initializes a `ForwardList` with a single `value`.
public init(value: T) {
self.init(Node(value))
}
/// Initializes a `ForwardList` with a collection of `values`.
public init<S: SequenceType where S.Generator.Element == T>(_ values: S) {
// TODO This should return the tail of the list as well so we don't rely on `head.last`
self.init(Node.create(values))
}
/// Initializes `ForwardList` with `head`.
private init(_ head: Node?) {
self.init(head, head?.last)
}
/// Initializes `ForwardList` with a new set of `ends`
private init(_ ends: ListEnds<Node>?) {
self.init(ends?.head, ends?.tail)
}
/// Initializes `ForwardList` with `head` and `tail`.
private init(_ head: Node?, _ tail: Node?) {
self.head = head
self.tail = tail
}
// MARK: Primitive operations
/// Replace nodes at the given insertion point
private mutating func spliceList(prefixTail: Node?, _ replacementHead: Node?, _ replacementTail: Node?, _ suffixHead: Node?) {
if prefixTail == nil {
head = replacementHead ?? suffixHead
} else {
prefixTail?.next = replacementHead ?? suffixHead
}
if suffixHead == nil {
tail = replacementTail
} else {
replacementTail?.next = suffixHead
}
}
/// Replace the nodes at `subRange` with the given replacements.
private mutating func spliceList(subRange: Range<Index>, _ replacementHead: Node?, _ replacementTail: Node?) {
spliceList(subRange.startIndex.previous, replacementHead, replacementTail, subRange.endIndex.node)
}
/// Inserts a new `node` between `prefix` and `suffix`.
private mutating func insertNode(prefix: Node?, _ node: Node, _ suffix: Node?) {
spliceList(prefix, node, node, suffix)
}
/// Removes the `node` that follows `previous`.
private mutating func removeNode(node: Node, previous: Node?) -> T {
precondition(previous?.next == node || previous == nil)
let value = node.value
spliceList(previous, nil, nil, node.next)
return value
}
/// The type of nodes in `ForwardList`.
private typealias Node = ForwardListNode<T>
/// The first node of `ForwardList`.
private var head: Node?
/// The last node of `ForwardList`.
private var tail: Node?
}
// MARK: Queue/Stack
extension ForwardList : QueueType, StackType {
public typealias Element = T
/// Returns true iff `ForwardList` is empty.
public var isEmpty: Bool {
return head == nil
}
/// Returns the value at the head of `ForwardList`, `nil` if empty.
public var first: T? {
return head?.value
}
/// Returns the value at the tail of `ForwardList`, `nil` if empty.
public var last: T? {
return tail?.value
}
/// Removes the `first` value at the head of `ForwardList` and returns it, `nil` if empty.
public mutating func removeFirst() -> T {
return removeNode(head!, previous: nil)
}
/// Inserts a new `value` _before_ the `first` value.
public mutating func insertFirst(value: T) {
insertNode(nil, Node(value), head)
}
/// Inserts a new `value` _after_ the `last` value.
public mutating func insertLast(value: T) {
insertNode(tail, Node(value), nil)
}
}
// MARK: ArrayLiteralConvertible
extension ForwardList : ArrayLiteralConvertible {
/// Initializes a `ForwardList` with the `elements` from array.
public init(arrayLiteral elements: T...) {
self.init(elements)
}
}
// MARK: SequenceType
extension ForwardList : SequenceType {
public typealias Generator = GeneratorOf<T>
/// Create a `Generator` that enumerates all the values in `ForwardList`.
public func generate() -> Generator {
return head?.values() ?? Generator { nil }
}
}
// MARK: CollectionType, MutableCollectionType
extension ForwardList : CollectionType, MutableCollectionType {
public typealias Index = ForwardListIndex<T>
/// Index to the first element of `ForwardList`.
public var startIndex: Index {
return Index(head)
}
/// Index past the last element of `ForwardList`.
public var endIndex: Index {
return Index(nil, tail)
}
/// Retrieves or updates the element in `ForwardList` at `index`.
public subscript(index: Index) -> T {
get {
return index.node!.value
}
set {
index.node!.value = newValue
}
}
}
// MARK: Sliceable, MutableSliceable
extension ForwardList : Sliceable, MutableSliceable {
public typealias SubSlice = ForwardList
/// Extract a slice of `ForwardList` from bounds.
public subscript (bounds: Range<Index>) -> SubSlice {
get {
// TODO Defer cloning the nodes until modification
var head = bounds.startIndex.node
var tail = bounds.endIndex.node
return head == tail ? ForwardList() : ForwardList(head?.takeUntil(tail))
}
set(newList) {
spliceList(bounds, newList.head, newList.tail)
}
}
}
// MARK: ExtensibleCollectionType
extension ForwardList : ExtensibleCollectionType {
/// Does nothing.
public mutating func reserveCapacity(amount: Index.Distance) {
}
/// Appends `value to the end of `ForwardList`.
public mutating func append(value: T) {
self.insertLast(value)
}
/// Appends multiple elements to the end of `ForwardList`.
public mutating func extend<S: SequenceType where S.Generator.Element == T>(values: S) {
Swift.map(values) { self.insertLast($0) }
}
}
// MARK: RangeReplaceableCollectionType
extension ForwardList : RangeReplaceableCollectionType {
/// Replace the given `subRange` of elements with `values`.
public mutating func replaceRange<C : CollectionType where C.Generator.Element == T>(subRange: Range<Index>, with values: C) {
var replacement = Node.create(values)
spliceList(subRange, replacement.head, replacement.tail)
}
/// Insert `value` at `index`.
public mutating func insert(value: T, atIndex index: Index) {
insertNode(index.previous, Node(value), index.node)
}
/// Insert `values` at `index`.
public mutating func splice<C : CollectionType where C.Generator.Element == T>(values: C, atIndex index: Index) {
var replacement = Node.create(values)
spliceList(index.previous, replacement.head, replacement.tail, index.node)
}
/// Remove the element at `index` and returns it.
public mutating func removeAtIndex(index: Index) -> T {
return removeNode(index.node!, previous: index.previous)
}
/// Remove the indicated `subRange` of values.
public mutating func removeRange(subRange: Range<Index>) {
spliceList(subRange.startIndex.previous, nil, nil, subRange.endIndex.node)
}
/// Remove all values from `ForwardList`.
public mutating func removeAll(#keepCapacity: Bool) {
spliceList(nil, nil, nil, nil)
}
}
// MARK: Printable
extension ForwardList : Printable, DebugPrintable {
/// String representation of `ForwardList`.
public var description: String {
return describe(toString)
}
/// Debug string representation of `ForwardList`.
public var debugDescription: String {
return describe(toDebugString)
}
/// Formats elements of list for printing.
public func describe(stringify: T -> String) -> String {
let string = join(", ", lazy(self).map(stringify))
return "[\(string)]"
}
}
// MARK: Higher-order functions
extension ForwardList {
/// Maps values in `ForwardList` with `transform` to create a new `ForwardList`
public func map<U>(transform: T -> U) -> ForwardList<U> {
return ForwardList<U>(head?.map(transform))
}
/// Filters values from `ForwardList` with `predicate` to create a new `ForwardList`
public func filter(predicate: T -> Bool) -> ForwardList {
return ForwardList(head?.filter(predicate))
}
}
|
9f9627310c5e2f303b85149874ca35b3
| 29.794872 | 130 | 0.6403 | false | false | false | false |
buyiyang/iosstar
|
refs/heads/master
|
iOSStar/Scenes/Discover/Controllers/VoiceManagerVC.swift
|
gpl-3.0
|
3
|
//
// VoiceManagerVC.swift
// iOSStar
//
// Created by mu on 2017/9/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class VoiceManagerVC: UIViewController {
@IBOutlet weak var contentViewtest: UIView!
@IBOutlet weak var askBtn: UIButton!
var videoVC: VoiceQuestionVC?
var starModel: StarSortListModel = StarSortListModel()
override func viewDidLoad() {
super.viewDidLoad()
initUI()
initNav()
}
func initNav() {
let rightItem = UIBarButtonItem.init(title: "历史定制", style: .plain, target: self, action: #selector(rightItemTapped(_:)))
navigationItem.rightBarButtonItem = rightItem
navigationItem.rightBarButtonItem?.tintColor = UIColor.init(hexString: AppConst.Color.titleColor)
}
func rightItemTapped(_ sender: Any) {
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: VoiceHistoryVC.className()) as? VoiceHistoryVC{
vc.starModel = starModel
_ = self.navigationController?.pushViewController(vc, animated: true)
}
}
func initUI() {
title = "语音定制"
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VoiceQuestionVC") as? VoiceQuestionVC{
videoVC = vc
vc.starModel = starModel
contentViewtest.addSubview(vc.view)
// vc.view.backgroundColor = UIColor.red
self.addChildViewController(vc)
vc.view.snp.makeConstraints({ (make) in
make.edges.equalToSuperview()
})
}
}
@IBAction func askBtnTapped(_ sender: UIButton) {
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VoiceAskVC") as? VoiceAskVC{
vc.starModel = starModel
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
b8efadec2f027f1552986170b3fb4022
| 33.169492 | 158 | 0.642361 | false | false | false | false |
hetefe/MyNews
|
refs/heads/master
|
MyNews/MyNews/Module/side/LeftViewController.swift
|
mit
|
1
|
//
// LeftViewController.swift
// MyNews
//
// Created by 赫腾飞 on 15/12/27.
// Copyright © 2015年 hetefe. All rights reserved.
//
import UIKit
let LeftCellID = "LeftCellID"
class LeftViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI(){
view.addSubview(personalView)
personalView.addSubview(heardImageView)
personalView.addSubview(nameBtn)
view.addSubview(tableView)
personalView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(view.snp_top).offset(80)
make.height.equalTo(100)
make.width.equalTo(200)
make.left.equalTo(view.snp_left)
}
heardImageView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(personalView.snp_left).offset(10)
make.top.equalTo(personalView.snp_top).offset(10)
make.width.height.equalTo(60)
}
nameBtn.snp_makeConstraints { (make) -> Void in
make.top.equalTo(heardImageView.snp_top)
make.left.equalTo(heardImageView.snp_right).offset(10)
}
tableView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(view.snp_left)
make.top.equalTo(personalView.snp_bottom).offset(50)
make.width.equalTo(200)
make.bottom.equalTo(view.snp_bottom).offset(-100)
}
}
//MARK:- 数据源方法
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(LeftCellID, forIndexPath: indexPath)
// cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.darkGrayColor() : UIColor.lightGrayColor()
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = .None
switch indexPath.row{
case 0:
cell.imageView?.image = UIImage(named: "IconProfile")
cell.textLabel?.text = "我"
case 1:
cell.imageView?.image = UIImage(named: "IconSettings")
cell.textLabel?.text = "设置"
case 2:
cell.imageView?.image = UIImage(named: "IconHome")
cell.textLabel?.text = "主页"
case 3:
cell.imageView?.image = UIImage(named: "IconCalendar")
cell.textLabel?.text = "日历"
default :
cell.imageView?.image = UIImage(named: "IconProfile")
cell.textLabel?.text = "我"
}
return cell
}
//MARK:- 代理方法监控Cell的点击事件
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch (indexPath.row) {
case 0:
print("Model到个人信息控制器")
case 1:
print("Model到设置界面")
case 2:
print("Model到主页面")
case 3:
print("Model日历界面")
default :
print("其他情况")
}
}
//MARK:- 懒加载视图
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.rowHeight = 50
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: LeftCellID)
tableView.backgroundColor = UIColor.clearColor()
return tableView
}()
private lazy var personalView: UIView = {
let personalView = UIView()
return personalView
}()
//头像
private lazy var heardImageView : UIImageView = {
let headImageView = UIImageView(image: UIImage(named: "pa"))
headImageView.layer.masksToBounds = true
headImageView.layer.cornerRadius = 30
return headImageView
}()
private lazy var nameBtn: UIButton = {
let btn = UIButton()
btn.setTitle("MyNews", forState: .Normal)
btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
return btn
}()
}
|
75bed38cdb3799fd2cb755d057ea98dd
| 27.832258 | 109 | 0.576192 | false | false | false | false |
cwwise/CWWeChat
|
refs/heads/master
|
CWWeChat/Vendor/FPSLabel.swift
|
mit
|
2
|
//
// FPSLabel.swift
// SAC
//
// Created by SAGESSE on 2/1/16.
// Copyright © 2016-2017 Sagesse. All rights reserved.
//
// Reference: ibireme/YYKit/YYFPSLabel
//
import UIKit
///
/// Show Screen FPS.
///
/// The maximum fps in OSX/iOS Simulator is 60.00.
/// The maximum fps on iPhone is 59.97.
/// The maxmium fps on iPad is 60.0.
///
public class FPSLabel: UILabel {
public override init(frame: CGRect) {
super.init(frame: frame)
build()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
build()
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 55, height: 20)
}
public override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if newWindow == nil {
_link.invalidate()
} else {
_link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
}
private func build() {
text = "calc..."
font = UIFont.systemFont(ofSize: 14)
textColor = UIColor.white
textAlignment = .center
backgroundColor = UIColor(white: 0, alpha: 0.7)
layer.cornerRadius = 5
layer.masksToBounds = true
}
@objc private func tack(_ link: CADisplayLink) {
guard let lastTime = _lastTime else {
_lastTime = link.timestamp
return
}
_count += 1
let delta = link.timestamp - lastTime
guard delta >= 1 else {
return
}
let fps = Double(_count) / delta + 0.03
let progress = CGFloat(fps / 60)
let color = UIColor(hue: 0.27 * (progress - 0.2), saturation: 1, brightness: 0.9, alpha: 1)
let text = NSMutableAttributedString(string: "\(Int(fps)) FPS")
text.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSMakeRange(0, text.length - 3))
attributedText = text
_count = 0
_lastTime = link.timestamp
}
private var _count: Int = 0
private var _lastTime: TimeInterval?
private lazy var _link: CADisplayLink = {
return CADisplayLink(target: self, selector: #selector(tack(_:)))
}()
}
|
0f53ca1a5efb89deeaf57156746fe2b4
| 26.650602 | 118 | 0.579521 | false | false | false | false |
letvargo/LVGSwiftAudioFileServices
|
refs/heads/master
|
Source/AudioFileType.swift
|
mit
|
1
|
//
// AudioFileType.swift
// SwiftAudioToolbox
//
// Created by doof nugget on 1/10/16.
// Copyright © 2016 letvargo. All rights reserved.
//
import Foundation
import AudioToolbox
import LVGUtilities
public enum AudioFileType: CodedPropertyType {
/// The equivalent of `kAudioFileAAC_ADTSType`.
case aac_ADTS
/// The equivalent of `kAudioFileAC3Type`.
case ac3
/// The equivalent of `kAudioFileAIFCType`.
case aifc
/// The equivalent of `kAudioFileAIFFType`.
case aiff
/// The equivalent of `kAudioFileAMRType`.
case amr
/// The equivalent of `kAudioFileCAFType`.
case caf
/// The equivalent of `kAudioFileM4AType`.
case m4A
/// The equivalent of `kAudioFileMP1Type`.
case mp1
/// The equivalent of `kAudioFileMP2Type`.
case mp2
/// The equivalent of `kAudioFileMP3Type`.
case mp3
/// The equivalent of `kAudioFileMPEG4Type`.
case mpeg4
/// The equivalent of `kAudioFileNextType`.
case neXT
/// The equivalent of `kAudioFile3GPType`.
case threeGP
/// The equivalent of `kAudioFile3GP2Type`.
case threeGP2
/// The equivalent of `kAudioFileSoundDesigner2Type`.
case soundDesigner2
/// The equivalent of `kAudioFileWAVEType`.
case wave
/// Initializes an `AudioFileType` using an `AudioFileTypeID`
/// defined by Audio File Services.
public init?(code: AudioFileTypeID) {
switch code {
case kAudioFileAIFFType : self = .aiff
case kAudioFileAIFCType : self = .aifc
case kAudioFileWAVEType : self = .wave
case kAudioFileSoundDesigner2Type : self = .soundDesigner2
case kAudioFileNextType : self = .neXT
case kAudioFileMP3Type : self = .mp3
case kAudioFileMP2Type : self = .mp2
case kAudioFileMP1Type : self = .mp1
case kAudioFileAC3Type : self = .ac3
case kAudioFileAAC_ADTSType : self = .aac_ADTS
case kAudioFileMPEG4Type : self = .mpeg4
case kAudioFileM4AType : self = .m4A
case kAudioFileCAFType : self = .caf
case kAudioFile3GPType : self = .threeGP
case kAudioFile3GP2Type : self = .threeGP2
case kAudioFileAMRType : self = .amr
default : return nil
}
}
/// The `AudioFileTypeID` associated with the `AudioFileType`.
public var code: AudioFileTypeID {
switch self {
case .aiff : return kAudioFileAIFFType
case .aifc : return kAudioFileAIFCType
case .wave : return kAudioFileWAVEType
case .soundDesigner2 : return kAudioFileSoundDesigner2Type
case .neXT : return kAudioFileNextType
case .mp3 : return kAudioFileMP3Type
case .mp2 : return kAudioFileMP2Type
case .mp1 : return kAudioFileMP1Type
case .ac3 : return kAudioFileAC3Type
case .aac_ADTS : return kAudioFileAAC_ADTSType
case .mpeg4 : return kAudioFileMPEG4Type
case .m4A : return kAudioFileM4AType
case .caf : return kAudioFileCAFType
case .threeGP : return kAudioFile3GPType
case .threeGP2 : return kAudioFile3GP2Type
case .amr : return kAudioFileAMRType
}
}
/// Returns "Audio File Services Audio File Type" for all cases.
public var domain: String {
return "Audio File Services Audio File Type"
}
/// A short description of the file type.
public var shortDescription: String {
switch self {
case .aac_ADTS: return "An Advanced Audio Coding (AAC) Audio Data Transport Stream (ADTS) file."
case .ac3: return "An AC-3 file."
case .aifc: return "An Audio Interchange File Format Compressed (AIFF-C) file."
case .aiff: return "An Audio Interchange File Format (AIFF) file."
case .amr: return "An AMR (Adaptive Multi-Rate) file suitable for compressed speech."
case .caf: return "A Core Audio File Format file."
case .neXT: return "A NeXT or Sun Microsystems file."
case .m4A: return "An M4A file."
case .mp1: return "An MPEG Audio Layer 1 (.mp1) file."
case .mp2: return "An MPEG Audio Layer 2 (.mp2) file."
case .mp3: return "An MPEG Audio Layer 3 (.mp3) file."
case .mpeg4: return "An MPEG 4 file."
case .threeGP: return "A 3GPP file, suitable for video content on GSM mobile phones."
case .threeGP2: return "A 3GPP2 file, suitable for video content on CDMA mobile phones."
case .soundDesigner2: return "A Sound Designer II file."
case .wave: return "A Microsoft WAVE file."
}
}
}
|
2f87a0174bb2f9df9cb69c3f8eaf803f
| 37.918519 | 112 | 0.572707 | false | false | false | false |
danwood/Resolutionary
|
refs/heads/master
|
Sources/Acronym.swift
|
apache-2.0
|
1
|
import StORM
import PostgresStORM
class Acronym: PostgresStORM {
var id: Int = 0
var short: String = ""
var long: String = ""
override open func table() -> String { return "acronyms" }
override func to(_ this: StORMRow) {
id = this.data["id"] as? Int ?? 0
short = this.data["short"] as? String ?? ""
long = this.data["long"] as? String ?? ""
}
func rows() -> [Acronym] {
var rows = [Acronym]()
for i in 0..<self.results.rows.count {
let row = Acronym()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
func asDictionary() -> [String: Any] {
return [
"id": self.id,
"short": self.short,
"long": self.long
]
}
static func all() throws -> [Acronym] {
let getObj = Acronym()
try getObj.findAll()
return getObj.rows()
}
static func getAcronym(matchingId id:Int) throws -> Acronym {
let getObj = Acronym()
var findObj = [String: Any]()
findObj["id"] = "\(id)"
try getObj.find(findObj)
return getObj
}
static func getAcronyms(matchingShort short:String) throws -> [Acronym] {
let getObj = Acronym()
var findObj = [String: Any]()
findObj["short"] = short
try getObj.find(findObj)
return getObj.rows()
}
static func getAcronyms(notMatchingShort short:String) throws -> [Acronym] {
let getObj = Acronym()
try getObj.select(whereclause: "short != $1", params: [short], orderby: ["id"])
return getObj.rows()
}
}
|
5521dbcfe33a7ba3b55bd309001e0826
| 21.9375 | 83 | 0.609673 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
stdlib/public/core/DurationProtocol.swift
|
apache-2.0
|
9
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that defines a duration for a given `InstantProtocol` type.
@available(SwiftStdlib 5.7, *)
public protocol DurationProtocol: Comparable, AdditiveArithmetic, Sendable {
static func / (_ lhs: Self, _ rhs: Int) -> Self
static func /= (_ lhs: inout Self, _ rhs: Int)
static func * (_ lhs: Self, _ rhs: Int) -> Self
static func *= (_ lhs: inout Self, _ rhs: Int)
static func / (_ lhs: Self, _ rhs: Self) -> Double
}
@available(SwiftStdlib 5.7, *)
extension DurationProtocol {
@available(SwiftStdlib 5.7, *)
public static func /= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs / rhs
}
@available(SwiftStdlib 5.7, *)
public static func *= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs * rhs
}
}
|
01a2f011fbcff158724d2f6e05fbc875
| 34.628571 | 80 | 0.580593 | false | false | false | false |
adamshin/SwiftReorder
|
refs/heads/master
|
Source/ReorderController+SnapshotView.swift
|
mit
|
1
|
//
// Copyright (c) 2016 Adam Shin
//
// 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
extension ReorderController {
func createSnapshotViewForCell(at indexPath: IndexPath) {
guard let tableView = tableView, let superview = tableView.superview else { return }
removeSnapshotView()
tableView.reloadRows(at: [indexPath], with: .none)
guard let cell = tableView.cellForRow(at: indexPath) else { return }
let cellFrame = tableView.convert(cell.frame, to: superview)
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, false, 0)
cell.layer.render(in: UIGraphicsGetCurrentContext()!)
let cellImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let view = UIImageView(image: cellImage)
view.frame = cellFrame
view.layer.masksToBounds = false
view.layer.opacity = Float(cellOpacity)
view.layer.transform = CATransform3DMakeScale(cellScale, cellScale, 1)
view.layer.shadowColor = shadowColor.cgColor
view.layer.shadowOpacity = Float(shadowOpacity)
view.layer.shadowRadius = shadowRadius
view.layer.shadowOffset = shadowOffset
superview.addSubview(view)
snapshotView = view
}
func removeSnapshotView() {
snapshotView?.removeFromSuperview()
snapshotView = nil
}
func updateSnapshotViewPosition() {
guard case .reordering(let context) = reorderState, let tableView = tableView else { return }
var newCenterY = context.touchPosition.y + context.snapshotOffset
let safeAreaFrame: CGRect
if #available(iOS 11, *) {
safeAreaFrame = tableView.frame.inset(by: tableView.safeAreaInsets)
} else {
safeAreaFrame = tableView.frame.inset(by: tableView.scrollIndicatorInsets)
}
newCenterY = min(newCenterY, safeAreaFrame.maxY)
newCenterY = max(newCenterY, safeAreaFrame.minY)
snapshotView?.center.y = newCenterY
}
func animateSnapshotViewIn() {
guard let snapshotView = snapshotView else { return }
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 1
opacityAnimation.toValue = cellOpacity
opacityAnimation.duration = animationDuration
let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
shadowAnimation.fromValue = 0
shadowAnimation.toValue = shadowOpacity
shadowAnimation.duration = animationDuration
let transformAnimation = CABasicAnimation(keyPath: "transform.scale")
transformAnimation.fromValue = 1
transformAnimation.toValue = cellScale
transformAnimation.duration = animationDuration
transformAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
snapshotView.layer.add(opacityAnimation, forKey: nil)
snapshotView.layer.add(shadowAnimation, forKey: nil)
snapshotView.layer.add(transformAnimation, forKey: nil)
}
func animateSnapshotViewOut() {
guard let snapshotView = snapshotView else { return }
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = cellOpacity
opacityAnimation.toValue = 1
opacityAnimation.duration = animationDuration
let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
shadowAnimation.fromValue = shadowOpacity
shadowAnimation.toValue = 0
shadowAnimation.duration = animationDuration
let transformAnimation = CABasicAnimation(keyPath: "transform.scale")
transformAnimation.fromValue = cellScale
transformAnimation.toValue = 1
transformAnimation.duration = animationDuration
transformAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
snapshotView.layer.add(opacityAnimation, forKey: nil)
snapshotView.layer.add(shadowAnimation, forKey: nil)
snapshotView.layer.add(transformAnimation, forKey: nil)
snapshotView.layer.opacity = 1
snapshotView.layer.shadowOpacity = 0
snapshotView.layer.transform = CATransform3DIdentity
}
}
|
831e14cc5b874c557cdb207c6fc266ed
| 40.318182 | 101 | 0.690869 | false | false | false | false |
SteveRohrlack/CitySimCore
|
refs/heads/master
|
src/Model/TileableAttributes/MapStatistic.swift
|
mit
|
1
|
//
// MapStatistic.swift
// CitySimCore
//
// Created by Steve Rohrlack on 17.05.16.
// Copyright © 2016 Steve Rohrlack. All rights reserved.
//
import Foundation
/**
provides specific statistic types
each type consists of:
- radius: Int
- value: Int
*/
public enum MapStatistic {
/// regards the Landvalue statistic layer
case Landvalue(radius: Int, value: Int)
/// regards the Noise statistic layer
case Noise(radius: Int, value: Int)
/// regards the Firesafety statistic layer
case Firesafety(radius: Int, value: Int)
/// regards the Crime statistic layer
case Crime(radius: Int, value: Int)
/// regards the Health statistic layer
case Health(radius: Int, value: Int)
}
/// MapStatistic is Equatable
extension MapStatistic: Equatable {
}
/**
operator "==" to allow comparing MapStatistics
- parameter lhs: MapStatistic
- parameter rhs: MapStatistic
- returns: comparison result
*/
public func == (lhs: MapStatistic, rhs: MapStatistic) -> Bool {
switch (lhs, rhs) {
case (.Landvalue(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Noise(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Firesafety(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Crime(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Health(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
default:
return false
}
}
|
d104b7dfb7e0a013186cb7ae5414e90b
| 24.676923 | 94 | 0.628897 | false | false | false | false |
CoderST/DYZB
|
refs/heads/master
|
DYZB/DYZB/Class/Room/Controller/ShowAnchorListVC.swift
|
mit
|
1
|
//
// ShowAnchorListVC.swift
// DYZB
//
// Created by xiudou on 16/11/5.
// Copyright © 2016年 xiudo. All rights reserved.
//
import UIKit
import MJRefresh
import SVProgressHUD
class ShowAnchorListVC: UIViewController {
// MARK:- 属性
// @IBOutlet weak var collectionView: UICollectionView!
// MARK:- 常量
fileprivate let ShowAnchorListCellInden = "ShowAnchorListCellInden"
// MARK:- 变量
fileprivate var page : Int = 1
// MARK:- 懒加载
fileprivate let roomAnchorVM : RoomAnchorVM = RoomAnchorVM()
fileprivate let collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = CGSize(width: sScreenW, height: sScreenH - sNavatationBarH - sStatusBarH)
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: sScreenW, height: sScreenH), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
return collectionView
}()
@IBAction func quickTopButton(_ sender: UIButton) {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
let indexPath = IndexPath(item: 0, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
})
}
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupCollectionDownReloadData()
setupCollectionUpLoadMore()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
}
func setupCollectionDownReloadData(){
let refreshGifHeader = DYRefreshGifHeader(refreshingTarget: self, refreshingAction: #selector(ShowAnchorListVC.downReloadData))
refreshGifHeader?.stateLabel?.isHidden = true
refreshGifHeader?.setTitle("", for: .pulling)
refreshGifHeader?.setTitle("", for: .idle)
collectionView.mj_header = refreshGifHeader
collectionView.mj_header.isAutomaticallyChangeAlpha = true
collectionView.mj_header.beginRefreshing()
}
func setupCollectionUpLoadMore(){
// MJRefreshAutoFooterIdleText
let foot = DYRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(ShowAnchorListVC.upLoadMore))
collectionView.mj_footer = foot
}
}
// MARK:- 网络请求
extension ShowAnchorListVC {
// 下拉刷新
func downReloadData(){
page = 1
roomAnchorVM.getRoomAnchorData(page, finishCallBack: { () -> () in
self.collectionView.mj_header.endRefreshing()
self.collectionView.reloadData()
}) { () -> () in
print("没有啦")
}
}
// 上拉加载更多
func upLoadMore(){
page += 1
roomAnchorVM.getRoomAnchorData(page, finishCallBack: { () -> () in
self.collectionView.mj_footer.endRefreshing()
self.collectionView.reloadData()
}) { () -> () in
print("没有数据了")
SVProgressHUD.setDefaultStyle(.dark)
SVProgressHUD.showInfo(withStatus: "没有了哦~~")
}
}
}
// MARK:- UI设置
extension ShowAnchorListVC {
// 1 初始化collectionView
fileprivate func setupCollectionView(){
view.addSubview(collectionView)
collectionView.register(UINib(nibName: "ShowAnchorListCell", bundle: nil), forCellWithReuseIdentifier: ShowAnchorListCellInden)
collectionView.dataSource = self
collectionView.delegate = self
}
}
// MARK:- UICollectionViewDataSource
extension ShowAnchorListVC : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return roomAnchorVM.roomYKModelArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ShowAnchorListCellInden, for: indexPath) as! ShowAnchorListCell
let model = roomAnchorVM.roomYKModelArray[indexPath.item]
cell.anchorModel = model
return cell
}
}
// MARK:- UICollectionViewDelegate
extension ShowAnchorListVC : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1 创建主播界面
let showAnchorVC = ShowAnchorVC()
// 2 传递主播数组
showAnchorVC.getShowDatasAndIndexPath(roomAnchorVM.roomYKModelArray, indexPath: indexPath)
// 3 弹出主播界面
present(showAnchorVC, animated: true, completion: nil)
}
}
|
7de94f3ccf08f07e46a529c719c6d6fe
| 29.85 | 138 | 0.646272 | false | false | false | false |
LuAndreCast/iOS_WatchProjects
|
refs/heads/master
|
watchOS3/HealthKit Workout/Utilities.swift
|
mit
|
1
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Utilites for workout management and string formatting.
*/
import Foundation
import HealthKit
//MARK: -
@objc enum workoutState:Int {
case running
case paused
case notStarted
case ended
func toString()->String
{
switch self {
case .running:
return "running"
case .paused:
return "paused"
case .notStarted:
return "notStarted"
case .ended:
return "ended"
}
}//eom
}
//MARK: -
func computeDurationOfWorkout(withEvents workoutEvents: [HKWorkoutEvent]?,
startDate: Date?,
endDate: Date?) -> TimeInterval
{
var duration = 0.0
if var lastDate = startDate {
var paused = false
if let events = workoutEvents {
for event in events {
switch event.type {
case .pause:
duration += event.date.timeIntervalSince(lastDate)
paused = true
case .resume:
lastDate = event.date
paused = false
default:
continue
}
}
}
if !paused {
if let end = endDate {
duration += end.timeIntervalSince(lastDate)
} else {
duration += NSDate().timeIntervalSince(lastDate)
}
}
}
print("\(duration)")
return duration
}
func format(duration: TimeInterval) -> String {
let durationFormatter = DateComponentsFormatter()
durationFormatter.unitsStyle = .positional
durationFormatter.allowedUnits = [.second, .minute, .hour]
durationFormatter.zeroFormattingBehavior = .pad
if let string = durationFormatter.string(from: duration) {
return string
} else {
return ""
}
}
func format(activityType: HKWorkoutActivityType) -> String {
let formattedType : String
switch activityType {
case .walking:
formattedType = "Walking"
case .running:
formattedType = "Running"
case .hiking:
formattedType = "Hiking"
default:
formattedType = "Workout"
}
return formattedType
}
func format(locationType: HKWorkoutSessionLocationType) -> String {
let formattedType : String
switch locationType {
case .indoor:
formattedType = "Indoor"
case .outdoor:
formattedType = "Outdoor"
case .unknown:
formattedType = "Unknown"
}
return formattedType
}
|
91ac987980ee4aed4e94d632518db144
| 21.789063 | 74 | 0.522797 | false | false | false | false |
ianyh/Highball
|
refs/heads/master
|
Highball/PostLinkTableViewCell.swift
|
mit
|
1
|
//
// PostLinkTableViewCell.swift
// Highball
//
// Created by Ian Ynda-Hummel on 8/31/14.
// Copyright (c) 2014 ianynda. All rights reserved.
//
import UIKit
import Cartography
import WCFastCell
class PostLinkTableViewCell: WCFastCell {
var bubbleView: UIView!
var titleLabel: UILabel!
var urlLabel: UILabel!
var post: Post? {
didSet {
guard let post = post else {
return
}
self.titleLabel.text = post.title
self.urlLabel.text = post.url.host
}
}
override required init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpCell()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpCell()
}
func setUpCell() {
bubbleView = UIView()
titleLabel = UILabel()
urlLabel = UILabel()
bubbleView.backgroundColor = UIColor(red: 86.0/255.0, green: 188.0/255.0, blue: 138.0/255.0, alpha: 1)
bubbleView.clipsToBounds = true
titleLabel.font = UIFont.boldSystemFontOfSize(19)
titleLabel.textColor = UIColor.whiteColor()
titleLabel.numberOfLines = 0
titleLabel.textAlignment = NSTextAlignment.Center
urlLabel.font = UIFont.systemFontOfSize(12)
urlLabel.textColor = UIColor(white: 1, alpha: 0.7)
urlLabel.numberOfLines = 1
urlLabel.textAlignment = NSTextAlignment.Center
contentView.addSubview(bubbleView)
contentView.addSubview(titleLabel)
contentView.addSubview(urlLabel)
constrain(bubbleView, contentView) { bubbleView, contentView in
bubbleView.edges == contentView.edges
}
constrain(titleLabel, bubbleView) { titleLabel, bubbleView in
titleLabel.left == bubbleView.left + 10
titleLabel.right == bubbleView.right - 10
titleLabel.top == bubbleView.top + 14
}
constrain(urlLabel, titleLabel, bubbleView) { urlLabel, titleLabel, bubbleView in
urlLabel.left == bubbleView.left + 20
urlLabel.right == bubbleView.right - 20
urlLabel.top == titleLabel.bottom + 4
urlLabel.height == 16
}
}
class func heightForPost(post: Post!, width: CGFloat!) -> CGFloat {
let extraHeight: CGFloat = 14 + 4 + 16 + 14
let modifiedWidth = width - 16
let constrainedSize = CGSize(width: modifiedWidth, height: CGFloat.max)
let titleAttributes = [ NSFontAttributeName : UIFont.boldSystemFontOfSize(19) ]
if let title = post.title as NSString? {
let titleRect = title.boundingRectWithSize(constrainedSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: titleAttributes, context: nil)
return extraHeight + ceil(titleRect.size.height)
} else {
let title = "" as NSString
let titleRect = title.boundingRectWithSize(constrainedSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: titleAttributes, context: nil)
return extraHeight + ceil(titleRect.size.height)
}
}
}
|
b1d7bfba86496aefc60c174f2cd35c36
| 28.34375 | 161 | 0.738729 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk
|
refs/heads/master
|
Demos/SharedSource/PublicationListContentsViewController.swift
|
mit
|
1
|
//
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2019 ShopGun. All rights reserved.
import UIKit
import ShopGunSDK
class PublicationListContentsViewController: UITableViewController {
let publications: [CoreAPI.PagedPublication]
let shouldOpenIncito: (CoreAPI.PagedPublication) -> Void
let shouldOpenPagedPub: (CoreAPI.PagedPublication) -> Void
init(publications: [CoreAPI.PagedPublication],
shouldOpenIncito: @escaping (CoreAPI.PagedPublication) -> Void,
shouldOpenPagedPub: @escaping (CoreAPI.PagedPublication) -> Void
) {
self.publications = publications
self.shouldOpenIncito = shouldOpenIncito
self.shouldOpenPagedPub = shouldOpenPagedPub
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(PublicationListCell.self, forCellReuseIdentifier: "PublicationListCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return publications.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let publication = publications[indexPath.row]
let hasIncito = publication.incitoId != nil
let cell = tableView.dequeueReusableCell(withIdentifier: "PublicationListCell", for: indexPath) as! PublicationListCell
cell.selectionStyle = .none
cell.textLabel?.text = publication.branding.name
cell.incitoPubButton.isHidden = !hasIncito
cell.didTapIncitoButton = { [weak self] in
self?.shouldOpenIncito(publication)
}
cell.didTapPagedPubButton = { [weak self] in
self?.shouldOpenPagedPub(publication)
}
return cell
}
}
class PublicationListCell: UITableViewCell {
var didTapIncitoButton: (() -> Void)?
var didTapPagedPubButton: (() -> Void)?
lazy var incitoPubButton: UIButton = {
let btn = UIButton()
btn.setTitle("Incito", for: .normal)
btn.backgroundColor = .orange
btn.setTitleColor(.white, for: .normal)
btn.layer.cornerRadius = 4
btn.contentEdgeInsets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
btn.addTarget(self, action: #selector(didTapIncito(_:)), for: .touchUpInside)
return btn
}()
lazy var pagedPubButton: UIButton = {
let btn = UIButton()
btn.setTitle("PDF", for: .normal)
btn.backgroundColor = .orange
btn.setTitleColor(.white, for: .normal)
btn.layer.cornerRadius = 4
btn.contentEdgeInsets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
btn.addTarget(self, action: #selector(didTapPagedPub(_:)), for: .touchUpInside)
return btn
}()
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
let stack = UIStackView(arrangedSubviews: [
incitoPubButton, pagedPubButton
])
stack.spacing = 4
stack.axis = .horizontal
stack.alignment = .center
stack.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(stack)
NSLayoutConstraint.activate([
stack.trailingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.trailingAnchor),
stack.topAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.topAnchor),
stack.bottomAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.bottomAnchor)
])
}
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
@objc private func didTapIncito(_ sender: UIButton) {
didTapIncitoButton?()
}
@objc private func didTapPagedPub(_ sender: UIButton) {
didTapPagedPubButton?()
}
}
|
d1b3e8dae373ffb9537c90aabeb8fce9
| 34.719008 | 127 | 0.62633 | false | false | false | false |
naokits/bluemix-swift-demo-ios
|
refs/heads/master
|
Bluemix/bluemix-mobile-app-demo/client/Pods/BMSCore/Source/Network Requests/BMSClient.swift
|
mit
|
2
|
/*
* Copyright 2016 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
A singleton that serves as an entry point to Bluemix client-server communication.
*/
public class BMSClient {
// MARK: Constants
/// The southern United States Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_US_SOUTH = ".ng.bluemix.net"
/// The United Kingdom Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_UK = ".eu-gb.bluemix.net"
/// The Sydney Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_SYDNEY = ".au-syd.bluemix.net"
// MARK: Properties (API)
/// This singleton should be used for all `BMSClient` activity
public static let sharedInstance = BMSClient()
/// Specifies the base backend URL
public private(set) var bluemixAppRoute: String?
// Specifies the bluemix region
public private(set) var bluemixRegion: String?
/// Specifies the backend application id
public private(set) var bluemixAppGUID: String?
/// Specifies the default timeout (in seconds) for all BMS network requests.
public var defaultRequestTimeout: Double = 20.0
public var authorizationManager: AuthorizationManager
// MARK: Initializers
/**
The required intializer for the `BMSClient` class.
Sets the base URL for the authorization server.
- Note: The `backendAppRoute` and `backendAppGUID` parameters are not required to use the `BMSAnalytics` framework.
- parameter backendAppRoute: The base URL for the authorization server
- parameter backendAppGUID: The GUID of the Bluemix application
- parameter bluemixRegion: The region where your Bluemix application is hosted. Use one of the `BMSClient.REGION` constants.
*/
public func initializeWithBluemixAppRoute(bluemixAppRoute: String?, bluemixAppGUID: String?, bluemixRegion: String) {
self.bluemixAppRoute = bluemixAppRoute
self.bluemixAppGUID = bluemixAppGUID
self.bluemixRegion = bluemixRegion
}
private init() {
self.authorizationManager = BaseAuthorizationManager()
} // Prevent users from using BMSClient() initializer - They must use BMSClient.sharedInstance
}
|
c4b6f51e2b49f3c793e44833a0e88aeb
| 37.910256 | 141 | 0.692916 | false | false | false | false |
h-n-y/UICollectionView-TheCompleteGuide
|
refs/heads/master
|
chapter-3/Survey/Survey/CollectionViewCell.swift
|
mit
|
1
|
import UIKit
class CollectionViewCell: UICollectionViewCell {
// MARK: Instance
var image: UIImage? = nil {
didSet {
imageView.image = image
}
}
private let imageView: UIImageView
override init(frame: CGRect) {
imageView = UIImageView(frame: CGRectZero)
imageView.backgroundColor = UIColor.blackColor()
//imageView.contentMode = .ScaleAspectFit
super.init(frame: frame)
self.contentView.addSubview(imageView)
//imageView.frame = CGRectInset(self.contentView.bounds, 30, 10)
imageView.constrainToEdgesOfContainerWithInset(10.0)
let selectedBackgroundView = CollectionViewCell.newSelectedBackgroundView()
self.selectedBackgroundView = selectedBackgroundView
self.backgroundColor = UIColor.whiteColor()
}
required init?(coder aDecoder: NSCoder) {
imageView = CollectionViewCell.newImageView()
super.init(coder: aDecoder)
self.contentView.addSubview(imageView)
//imageView.frame = CGRectInset(self.contentView.bounds, 30, 10)
imageView.constrainToEdgesOfContainerWithInset(10.0)
let selectedBackgroundView = CollectionViewCell.newSelectedBackgroundView()
self.selectedBackgroundView = selectedBackgroundView
self.backgroundColor = UIColor.whiteColor()
}
override func prepareForReuse() {
super.prepareForReuse()
image = nil
self.selected = false
//imageView.constrainToEdgesOfContainerWithInset(10)
}
func setDisabled(disabled: Bool) {
self.contentView.alpha = disabled ? 0.5 : 1.0
self.backgroundColor = disabled ? UIColor.grayColor() : UIColor.whiteColor()
}
// MARK: Class
private static func newImageView() -> UIImageView {
let imageView = UIImageView(frame: CGRectZero)
imageView.backgroundColor = UIColor.blackColor()
return imageView
}
private static func newSelectedBackgroundView() -> UIView {
let selectedBackgroundView = UIView(frame: CGRectZero)
selectedBackgroundView.backgroundColor = UIColor.orangeColor()
return selectedBackgroundView
}
}
// MARK: - UIView Extension ( Constraints )
extension UIView {
/// Constrains `self`'s edges to its superview's edges.
func constrainToEdgesOfContainer() {
self.constrainToEdgesOfContainerWithInset(0.0)
}
/// Constrains `self` such that its edges are inset from its `superview`'s edges by `inset`.
func constrainToEdgesOfContainerWithInset(inset: CGFloat) {
self.constrainToEdgesOfContainerWithInsets(topBottom: inset, leftRight: inset)
}
func constrainToEdgesOfContainerWithInsets(topBottom y: CGFloat, leftRight x: CGFloat) {
guard let superview = self.superview else { print("View does not have a superview."); return }
self.translatesAutoresizingMaskIntoConstraints = false
self.topAnchor.constraintEqualToAnchor(superview.topAnchor, constant: y).active = true
self.bottomAnchor.constraintEqualToAnchor(superview.bottomAnchor, constant: -y).active = true
self.leftAnchor.constraintEqualToAnchor(superview.leftAnchor, constant: x).active = true
self.rightAnchor.constraintEqualToAnchor(superview.rightAnchor, constant: -x).active = true
}
}
|
75cad513cb109637d6d5d4717730f865
| 33.792079 | 102 | 0.670176 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications
|
refs/heads/master
|
lab-3/lab-3/lab-3/Location.swift
|
mit
|
1
|
/*
* @author Tyler Brockett
* @project CSE 394 Lab 4
* @version February 16, 2016
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Tyler Brockett
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
class Location {
var name:String = ""
var image:String = ""
var description:String = ""
init(name:String, image:String, description:String){
self.name = name
self.image = image
self.description = description
}
func getName() -> String {
return self.name
}
func getImage() -> String {
return self.image
}
func getDescription() -> String {
return self.description
}
}
|
a33d8605244bcdeb3a5e70c0bc82cf92
| 29.561404 | 81 | 0.692131 | false | false | false | false |
fromkk/SwiftMaterialButton
|
refs/heads/master
|
MaterialButton/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// MaterialButton
//
// Created by Kazuya Ueoka on 2014/12/29.
// Copyright (c) 2014年 fromKK. All rights reserved.
//
import UIKit
class ViewController: UIViewController, MaterialButtonProtocol {
var debugButton: RippleButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var materialButton1 = MaterialButton(type: MaterialButtonType.ArrowLeft)
materialButton1.delegate = self
self.navigationItem.leftBarButtonItem = materialButton1
var materialButton2 = MaterialButton(type: MaterialButtonType.ArrowRight)
materialButton2.delegate = self
self.navigationItem.rightBarButtonItem = materialButton2
self.debugButton = RippleButton()
self.debugButton.setTitle("Ripple Button", forState: UIControlState.Normal)
self.debugButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
self.debugButton.backgroundColor = UIColor(red: 240.0 / 255.0, green: 240.0 / 255.0, blue: 240.0 / 255.0, alpha: 1.0)
self.view.addSubview(self.debugButton)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.debugButton.frame = CGRect(x: 30.0, y: 100.0, width: 200.0, height: 40.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func materialButtonDidTapped(sender: AnyObject?) {
println("\((sender as MaterialButton).activated)")
}
}
|
7ca1299e0e93ff9904c4c681ffd75624
| 33.285714 | 125 | 0.680952 | false | false | false | false |
drewag/Swiftlier
|
refs/heads/master
|
Sources/Swiftlier/Model/Observable/EventCenter.swift
|
mit
|
1
|
//
// EventCenter.swift
// Swiftlier
//
// Created by Andrew J Wagner on 1/4/15.
// Copyright (c) 2015 Drewag LLC. All rights reserved.
//
import Foundation
/**
Protcol all events must implemenet to work with EventCenter
*/
public protocol EventType: class {
associatedtype CallbackParam
}
/**
A type safe, closure based event center modeled after NSNotificationCenter. Every event is guaranteed
to be unique by the compiler because it is based off of a custom subclass that implements EventType.
That protocol simply requires that the event define a typealias for the parameter to be passed to
registered closures. That type can be `void`, a single type, or a multiple types by using a tuple.
Because the EventCenter is type safe, when registering a callback, the types specified by the event
can be inferred and enforced by the compiler.
*/
open class EventCenter {
fileprivate var _observations = [String:CallbackCollection]()
/**
The main event center
*/
open class func defaultCenter() -> EventCenter {
return Static.DefaultInsance
}
public init() {}
/**
Trigger an event causing all registered callbacks to be called
Callbacks are all executed on the same thread before this method returns
- parameter event: the event to trigger
- parameter params: the parameters to trigger the event with
*/
open func triggerEvent<E: EventType>(_ event: E.Type, params: E.CallbackParam) {
let key = NSStringFromClass(event)
if let callbackCollection = self._observations[key] {
for (_, callbacks) in callbackCollection {
for spec in callbacks {
if let operationQueue = spec.operationQueue {
operationQueue.addOperation {
(spec.callback as! (E.CallbackParam) -> ())(params)
}
}
else {
(spec.callback as! (E.CallbackParam) -> ())(params)
}
}
}
}
}
/**
Add a callback for when an event is triggered
- parameter observer: observing object to be referenced later to remove the hundler
- parameter event: the event to observe
- parameter callback: callback to be called when the event is triggered
*/
open func addObserver<E: EventType>(_ observer: AnyObject, forEvent event: E.Type, callback: @escaping (E.CallbackParam) -> ()) {
self.addObserver(observer, forEvent: event, inQueue: nil, callback: callback)
}
/**
Add a callback for when an event is triggered
- parameter observer: observing object to be referenced later to remove the hundler
- parameter forEvent: the event to observe
- parameter inQueue: queue to call callback in (nil indicates the callback should be called on the same queue as the trigger)
- parameter callback: callback to be called when the event is triggered
*/
open func addObserver<E: EventType>(_ observer: AnyObject, forEvent event: E.Type, inQueue: OperationQueue?, callback: @escaping (E.CallbackParam) -> ()) {
let key = NSStringFromClass(event)
if self._observations[key] == nil {
self._observations[key] = CallbackCollection()
}
addHandler((callback: callback, operationQueue: inQueue), toHandlerCollection: &self._observations[key]!, forObserver: observer)
}
/**
Remove a callback for when an event is triggered
- parameter observer: observing object passed in when registering the callback originally
- parameter event: the event to remove the observer for
*/
open func removeObserver<E: EventType>(_ observer: AnyObject, forEvent event: E.Type?) {
if let event = event {
let key = NSStringFromClass(event)
if var callbackCollection = self._observations[key] {
removecallbacksForObserver(observer, fromHandlerCollection: &callbackCollection)
self._observations[key] = callbackCollection
}
}
}
/**
Remove callbacks for all of the events that an observer is registered for
- parameter observer: observing object passed in when registering the callback originally
*/
open func removeObserverForAllEvents(_ observer: AnyObject) {
for (key, var callbackCollection) in self._observations {
removecallbacksForObserver(observer, fromHandlerCollection: &callbackCollection)
self._observations[key] = callbackCollection
}
}
}
private extension EventCenter {
typealias Callback = Any
typealias CallbackSpec = (callback: Callback, operationQueue: OperationQueue?)
typealias CallbackCollection = [(observer: WeakWrapper<AnyObject>, callbacks: [CallbackSpec])]
struct Static {
static var DefaultInsance = EventCenter()
}
}
private func addHandler(_ handler: EventCenter.CallbackSpec, toHandlerCollection collection: inout EventCenter.CallbackCollection, forObserver observer: AnyObject) {
var found = false
var index = 0
for (possibleObserver, var callbacks) in collection {
if possibleObserver.value === observer {
callbacks.append((callback: handler.callback, operationQueue: handler.operationQueue))
collection[index] = (possibleObserver, callbacks)
found = true
break
}
index += 1
}
if !found {
collection.append((observer: WeakWrapper(observer), callbacks: [handler]))
}
}
private func removecallbacksForObserver(_ observer: AnyObject, fromHandlerCollection collection: inout EventCenter.CallbackCollection) {
var index = 0
for (possibleObserver, _) in collection {
if possibleObserver.value === observer {
collection.remove(at: index)
}
index += 1
}
}
|
2106438b5f5f738dacf6620d6d65facd
| 37.585987 | 165 | 0.65038 | false | false | false | false |
bitboylabs/selluv-ios
|
refs/heads/master
|
selluv-ios/selluv-ios/Classes/Base/Extension/Date.swift
|
mit
|
1
|
//
// Date.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 12..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
extension Date {
static func isBetween(start: Date, end: Date) -> Bool {
return Date.isBetween(start: start, end: end, someday: Date())
}
static func isBetween(start: Date, end: Date, someday: Date) -> Bool {
let fallsBetween = (start...end).contains(someday)
return fallsBetween
}
static func timeAgoSince(_ date: Date) -> String {
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
if let year = components.year, year >= 2 {
return "\(year) 년 전"
}
if let year = components.year, year >= 1 {
return "지난해"
}
if let month = components.month, month >= 2 {
return "\(month) 개월 전"
}
if let month = components.month, month >= 1 {
return "지난달"
}
if let week = components.weekOfYear, week >= 2 {
return "\(week) 주 전"
}
if let week = components.weekOfYear, week >= 1 {
return "지난주"
}
if let day = components.day, day >= 2 {
return "\(day) 일 전"
}
if let day = components.day, day >= 1 {
return "어제"
}
if let hour = components.hour, hour >= 2 {
return "\(hour) 시간 전"
}
if let hour = components.hour, hour >= 1 {
return "한시간 전"
}
if let minute = components.minute, minute >= 2 {
return "\(minute) 분 전"
}
if let minute = components.minute, minute >= 1 {
return "일분전"
}
if let second = components.second, second >= 3 {
return "\(second) seconds ago"
}
return "지금"
}
}
|
c19f086f68731df9331c0336aaa29413
| 24.528736 | 105 | 0.478163 | false | false | false | false |
isaced/ISEmojiView
|
refs/heads/master
|
Sources/ISEmojiView/Classes/Views/EmojiCollectionView/EmojiCollectionView.swift
|
mit
|
1
|
//
// EmojiCollectionView.swift
// ISEmojiView
//
// Created by Beniamin Sarkisyan on 01/08/2018.
//
import Foundation
import UIKit
/// emoji view action callback delegate
internal protocol EmojiCollectionViewDelegate: AnyObject {
/// did press a emoji button
///
/// - Parameters:
/// - emojiView: the emoji view
/// - emoji: a emoji
/// - selectedEmoji: the selected emoji
func emojiViewDidSelectEmoji(emojiView: EmojiCollectionView, emoji: Emoji, selectedEmoji: String)
/// changed section
///
/// - Parameters:
/// - category: current category
/// - emojiView: the emoji view
func emojiViewDidChangeCategory(_ category: Category, emojiView: EmojiCollectionView)
}
/// A emoji keyboard view
internal class EmojiCollectionView: UIView {
// MARK: - Public variables
/// the delegate for callback
internal weak var delegate: EmojiCollectionViewDelegate?
/// long press to pop preview effect like iOS10 system emoji keyboard, Default is true
internal var isShowPopPreview = true
internal var emojis: [EmojiCategory]! {
didSet {
collectionView.reloadData()
}
}
// MARK: - Private variables
private var scrollViewWillBeginDragging = false
private var scrollViewWillBeginDecelerating = false
private let emojiCellReuseIdentifier = "EmojiCell"
private lazy var emojiPopView: EmojiPopView = {
let emojiPopView = EmojiPopView()
emojiPopView.delegate = self
emojiPopView.isHidden = true
return emojiPopView
}()
// MARK: - IBOutlets
@IBOutlet private weak var collectionView: UICollectionView! {
didSet {
collectionView.register(EmojiCollectionCell.self, forCellWithReuseIdentifier: emojiCellReuseIdentifier)
}
}
// MARK: - Override variables
internal override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: frame.size.height)
}
// MARK: - Public
public func popPreviewShowing() -> Bool {
return !self.emojiPopView.isHidden;
}
// MARK: - Init functions
static func loadFromNib(emojis: [EmojiCategory]) -> EmojiCollectionView {
let nibName = String(describing: EmojiCollectionView.self)
guard let nib = Bundle.podBundle.loadNibNamed(nibName, owner: nil, options: nil) as? [EmojiCollectionView] else {
fatalError()
}
guard let view = nib.first else {
fatalError()
}
view.emojis = emojis
view.setupView()
return view
}
// MARK: - Override functions
override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard point.y < 0 else {
return super.point(inside: point, with: event)
}
return point.y >= -TopPartSize.height
}
// MARK: - Internal functions
internal func updateRecentsEmojis(_ emojis: [Emoji]) {
self.emojis[0].emojis = emojis
collectionView.reloadSections(IndexSet(integer: 0))
}
internal func scrollToCategory(_ category: Category) {
guard var section = emojis.firstIndex(where: { $0.category == category }) else {
return
}
if category == .recents && emojis[section].emojis.isEmpty {
section = emojis.firstIndex(where: { $0.category == Category.smileysAndPeople })!
}
let indexPath = IndexPath(item: 0, section: section)
collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}
}
// MARK: - UICollectionViewDataSource
extension EmojiCollectionView: UICollectionViewDataSource {
internal func numberOfSections(in collectionView: UICollectionView) -> Int {
return emojis.count
}
internal func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return emojis[section].emojis.count
}
internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let emojiCategory = emojis[indexPath.section]
let emoji = emojiCategory.emojis[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: emojiCellReuseIdentifier, for: indexPath) as! EmojiCollectionCell
if let selectedEmoji = emoji.selectedEmoji {
cell.setEmoji(selectedEmoji)
} else {
cell.setEmoji(emoji.emoji)
}
return cell
}
}
// MARK: - UICollectionViewDelegate
extension EmojiCollectionView: UICollectionViewDelegate {
internal func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard emojiPopView.isHidden else {
dismissPopView(false)
return
}
let emojiCategory = emojis[indexPath.section]
let emoji = emojiCategory.emojis[indexPath.item]
delegate?.emojiViewDidSelectEmoji(emojiView: self, emoji: emoji, selectedEmoji: emoji.selectedEmoji ?? emoji.emoji)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !scrollViewWillBeginDecelerating && !scrollViewWillBeginDragging {
return
}
if let indexPath = collectionView.indexPathsForVisibleItems.min() {
let emojiCategory = emojis[indexPath.section]
delegate?.emojiViewDidChangeCategory(emojiCategory.category, emojiView: self)
}
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension EmojiCollectionView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
var inset = UIEdgeInsets.zero
if let recentsEmojis = emojis.first(where: { $0.category == Category.recents }) {
if (!recentsEmojis.emojis.isEmpty && section != 0) || (recentsEmojis.emojis.isEmpty && section > 1) {
inset.left = 15
}
}
if section == 0 {
inset.left = 3
}
if section == emojis.count - 1 {
inset.right = 4
}
return inset
}
}
// MARK: - UIScrollView
extension EmojiCollectionView {
internal func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollViewWillBeginDragging = true
}
internal func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
scrollViewWillBeginDecelerating = true
}
internal func scrollViewDidScroll(_ scrollView: UIScrollView) {
dismissPopView(false)
}
internal func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
scrollViewWillBeginDragging = false
}
internal func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewWillBeginDecelerating = false
}
}
// MARK: - EmojiPopViewDelegate
extension EmojiCollectionView: EmojiPopViewDelegate {
internal func emojiPopViewShouldDismiss(emojiPopView: EmojiPopView) {
dismissPopView(true)
}
}
// MARK: - Private functions
extension EmojiCollectionView {
private func setupView() {
let emojiLongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(emojiLongPressHandle))
addGestureRecognizer(emojiLongPressGestureRecognizer)
addSubview(emojiPopView)
}
@objc private func emojiLongPressHandle(sender: UILongPressGestureRecognizer) {
func longPressLocationInEdge(_ location: CGPoint) -> Bool {
let edgeRect = collectionView.bounds.inset(by: collectionView.contentInset)
return edgeRect.contains(location)
}
guard isShowPopPreview else { return }
let location = sender.location(in: collectionView)
guard longPressLocationInEdge(location) else {
dismissPopView(true)
return
}
guard let indexPath = collectionView.indexPathForItem(at: location) else {
return
}
guard let attr = collectionView.layoutAttributesForItem(at: indexPath) else {
return
}
let emojiCategory = emojis[indexPath.section]
let emoji = emojiCategory.emojis[indexPath.item]
if sender.state == .ended && emoji.emojis.count == 1 {
dismissPopView(true)
return
}
emojiPopView.setEmoji(emoji)
let cellRect = attr.frame
let cellFrameInSuperView = collectionView.convert(cellRect, to: self)
let emojiPopLocation = CGPoint(
x: cellFrameInSuperView.origin.x - ((TopPartSize.width - BottomPartSize.width) / 2.0) + 5,
y: cellFrameInSuperView.origin.y - TopPartSize.height - 10
)
emojiPopView.move(location: emojiPopLocation, animation: sender.state != .began)
}
private func dismissPopView(_ usePopViewEmoji: Bool) {
emojiPopView.dismiss()
let currentEmoji = emojiPopView.currentEmoji
if !currentEmoji.isEmpty && usePopViewEmoji {
self.delegate?.emojiViewDidSelectEmoji(emojiView: self, emoji: Emoji(emojis: emojiPopView.emojiArray), selectedEmoji: currentEmoji)
}
emojiPopView.currentEmoji = ""
}
}
|
28414361a39fa708c30190c3fdab3ad5
| 30.025157 | 162 | 0.643016 | false | false | false | false |
terietor/GTForms
|
refs/heads/master
|
Example/SelectionFormTableViewController.swift
|
mit
|
1
|
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// 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
import GTForms
import SnapKit
class ExampleSelectionCustomizedFormCell: SelectionCustomizedFormCell {
fileprivate let label = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.label.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(label)
self.label.snp.makeConstraints() { make in
make.edges.equalToSuperview().inset(UIEdgeInsetsMake(10, 10, 10, 10))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configure(_ text: String, detailText: String?) {
self.label.text = text
self.contentView.backgroundColor = UIColor.red
}
}
class ExampleSelectionCustomizedFormItemCell: SelectionCustomizedFormItemCell {
fileprivate let label = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.label.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(label)
self.label.snp.makeConstraints() { make in
make.edges.equalTo(self.contentView).inset(UIEdgeInsetsMake(10, 10, 10, 10))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configure(_ text: String, detailText: String?, isSelected: Bool) {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = text
self.contentView.addSubview(label)
label.snp.makeConstraints() { make in
make.edges.equalTo(self.contentView).inset(UIEdgeInsetsMake(10, 10, 10, 10))
}
self.contentView.backgroundColor = isSelected ? UIColor.yellow : UIColor.white
}
override func didSelect() {
self.contentView.backgroundColor = UIColor.yellow
}
override func didDeSelect() {
self.contentView.backgroundColor = UIColor.white
}
}
class SelectionFormTableViewController: FormTableViewController {
var selectionForm: SelectionForm!
override func viewDidLoad() {
super.viewDidLoad()
let selectionItems = [
SelectionFormItem(text: "Apple"),
SelectionFormItem(text: "Orange")
]
selectionForm = SelectionForm(
items: selectionItems,
text: "Choose a fruit"
)
selectionForm.textColor = UIColor.red
selectionForm.textFont = UIFont
.preferredFont(forTextStyle: UIFontTextStyle.headline)
selectionForm.allowsMultipleSelection = true
let section = FormSection()
section.addRow(selectionForm)
self.formSections.append(section)
let selectionItems2 = [
SelectionFormItem(text: "vim"),
SelectionFormItem(text: "emacs")
]
let selectionForm2 = SelectionForm(
items: selectionItems2,
text: "Choose an editor"
)
selectionForm2.allowsMultipleSelection = false
selectionForm2.shouldAlwaysShowAllItems = true
selectionForm2.didSelectItem = { item in
print("Did Select: \(item.text)")
}
selectionForm2.didDeselectItem = { item in
print("Did Deselect: \(item.text)")
}
let section2 = FormSection()
section2.addRow(selectionForm2)
self.formSections.append(section2)
let selectionItems3 = [
SelectionCustomizedFormItem(text: "customized vim", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "customized emacs", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "customized atom", cellReuseIdentifier: "selectionCustomizedCellItem")
]
let selectionForm3 = SelectionCustomizedForm(
items: selectionItems3,
text: "Choose an editor (customized)",
cellReuseIdentifier: "selectionCustomizedCell"
)
selectionForm3.allowsMultipleSelection = false
self.tableView.register(
ExampleSelectionCustomizedFormItemCell.self,
forCellReuseIdentifier: "selectionCustomizedCellItem"
)
self.tableView.register(
ExampleSelectionCustomizedFormCell.self,
forCellReuseIdentifier: "selectionCustomizedCell"
)
let section3 = FormSection()
section3.addRow(selectionForm3)
self.formSections.append(section3)
let selectionItems4 = [
SelectionCustomizedFormItem(text: "Apple", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "Orange", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "Carrot", cellReuseIdentifier: "selectionCustomizedCellItem")
]
let selectionForm4 = SelectionCustomizedForm(
items: selectionItems4,
text: "Choose a fruit (customized)",
cellReuseIdentifier: "selectionCustomizedCell"
)
selectionForm4.shouldAlwaysShowAllItems = true
let section4 = FormSection()
section4.addRow(selectionForm4)
self.formSections.append(section4)
}
}
|
81b67afea9c52f42de35aebfed8c11ac
| 34.094737 | 118 | 0.683413 | false | false | false | false |
pikachu987/PKCUtil
|
refs/heads/master
|
PKCUtil/Classes/UI/UIView+.swift
|
mit
|
1
|
//Copyright (c) 2017 pikachu987 <[email protected]>
//
//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
public extension UIView {
// MARK: initialize
public convenience init(color: UIColor) {
self.init()
self.backgroundColor = color
}
// MARK: property
/// view To UIImage
public var imageWithView: UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
// MARK: func
/**
addSubviewEdgeConstraint
- parameter view: UIView
- parameter leading: CGFloat
- parameter top: CGFloat
- parameter trailing: CGFloat
- parameter bottom: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func addSubviewEdgeConstraint(
_ view: UIView,
leading: CGFloat = 0,
top: CGFloat = 0,
trailing: CGFloat = 0,
bottom: CGFloat = 0) -> [NSLayoutConstraint]{
self.addSubview(view)
return self.addEdgesConstraints(view, leading: leading, top: top, trailing: trailing, bottom: bottom)
}
/**
addEdgesConstraints
- parameter view: UIView
- parameter leading: CGFloat
- parameter top: CGFloat
- parameter trailing: CGFloat
- parameter bottom: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func addEdgesConstraints(
_ view: UIView,
leading: CGFloat = 0,
top: CGFloat = 0,
trailing: CGFloat = 0,
bottom: CGFloat = 0) -> [NSLayoutConstraint]{
view.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(
item: self,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1,
constant: leading
)
let trailingConstraint = NSLayoutConstraint(
item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1,
constant: trailing
)
let topConstraint = NSLayoutConstraint(
item: self,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1,
constant: top
)
let bottomConstraint = NSLayoutConstraint(
item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1,
constant: bottom
)
let constraints = [ leadingConstraint, trailingConstraint, topConstraint, bottomConstraint ]
self.addConstraints(constraints)
return constraints
}
/**
horizontalLayout
- parameter left: CGFloat
- parameter right: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func horizontalLayout(left: CGFloat = 0, right: CGFloat = 0) -> [NSLayoutConstraint]{
return NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(left)-[view]-\(right)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": self])
}
/**
verticalLayout
- parameter top: CGFloat
- parameter bottom: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func verticalLayout(top: CGFloat = 0, bottom: CGFloat = 0) -> [NSLayoutConstraint]{
return NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(top)-[view]-\(bottom)-|", options: NSLayoutFormatOptions.alignAllLeading, metrics: nil, views: ["view": self])
}
/**
pattern border
- parameter color: UIColor
- parameter width: CGFloat
- parameter cornerRadius: CGFloat
- parameter dashPattern: [NSNumber]
- returns: CAShapeLayer
*/
@discardableResult
public func addDashedBorder(_ color : UIColor, borderwidth : CGFloat = 1, cornerRadius : CGFloat, dashPattern : [NSNumber]) -> CAShapeLayer{
let shapeLayer:CAShapeLayer = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = borderwidth
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPattern = dashPattern
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: cornerRadius).cgPath
self.layer.addSublayer(shapeLayer)
return shapeLayer
}
}
|
39ae2d5248956ff5d3c8ae0ad1aa0012
| 31.621053 | 181 | 0.633269 | false | false | false | false |
crossroadlabs/ExecutionContext
|
refs/heads/master
|
ExecutionContext/DefaultExecutionContext.swift
|
apache-2.0
|
1
|
//===--- DefaultExecutionContext.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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
#if !os(Linux) || dispatch
public typealias DefaultExecutionContext = DispatchExecutionContext
#else
public typealias DefaultExecutionContext = PThreadExecutionContext
#endif
public protocol DefaultExecutionContextType : ExecutionContextType {
init(kind:ExecutionContextKind)
static var main:ExecutionContextType {
get
}
static var global:ExecutionContextType {
get
}
}
|
eb355d106f023862eff49c9ae7df1993
| 30.692308 | 98 | 0.652632 | false | false | false | false |
popricoly/Contacts
|
refs/heads/master
|
Sources/Contacts/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Contacts
//
// Created by Olexandr Matviichuk on 7/25/17.
// Copyright © 2017 Olexandr Matviichuk. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if UserDefaults.standard.runFirstly {
loadContacts()
UserDefaults.standard.runFirstly = false
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
func loadContacts() {
do {
if let contactsJsonPath = Bundle.main.url(forResource: "Contacts", withExtension: "json") {
let data = try Data(contentsOf: contactsJsonPath)
let json = try JSONSerialization.jsonObject(with: data, options: [])
for contactInDictionary in (json as? [Dictionary<String, String>])! {
let firstName = contactInDictionary["firstName"] ?? ""
let lastName = contactInDictionary["lastName"] ?? ""
let phoneNumber = contactInDictionary["phoneNumber"] ?? ""
let streetAddress1 = contactInDictionary["streetAddress1"] ?? ""
let streetAddress2 = contactInDictionary["streetAddress2"] ?? ""
let city = contactInDictionary["city"] ?? ""
let state = contactInDictionary["state"] ?? ""
let zipCode = contactInDictionary["zipCode"] ?? ""
OMContactsStorage.sharedStorage.saveContactWith(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, StreetAddress1: streetAddress1, StreetAddress2: streetAddress2, city: city, state: state, zipCode: zipCode)
}
}
} catch {
print("\(error.localizedDescription)")
}
}
}
|
e3d118e416cd2a5f9bd96e56d27b41fd
| 51.366197 | 285 | 0.681011 | false | false | false | false |
objecthub/swift-numberkit
|
refs/heads/master
|
Sources/NumberKit/IntegerNumber.swift
|
apache-2.0
|
1
|
//
// IntegerNumber.swift
// NumberKit
//
// Created by Matthias Zenger on 23/09/2017.
// Copyright © 2015-2020 Matthias Zenger. All rights reserved.
//
// 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
/// Protocol `IntegerNumber` is used in combination with struct `Rational<T>`.
/// It defines the functionality needed for a signed integer implementation to
/// build rational numbers on top. The `SignedInteger` protocol from the Swift 4
/// standard library is unfortunately not sufficient as it doesn't provide access
/// to methods reporting overflows explicitly. Furthermore, `BigInt` is not yet
/// compliant with `SignedInteger`.
public protocol IntegerNumber: SignedNumeric,
Comparable,
Hashable,
CustomStringConvertible {
/// Value zero
static var zero: Self { get }
/// Value one
static var one: Self { get }
/// Value two
static var two: Self { get }
/// Division operation.
///
/// - Note: It's inexplicable to me why this operation is missing in `SignedNumeric`.
static func /(lhs: Self, rhs: Self) -> Self
/// Division operation.
///
/// - Note: It's inexplicable to me why this operation is missing in `SignedNumeric`.
static func /=(lhs: inout Self, rhs: Self)
/// Remainder operation.
///
/// - Note: It's inexplicable to me why this operation is missing in `SignedNumeric`.
static func %(lhs: Self, rhs: Self) -> Self
/// Constructs an `IntegerNumber` from an `Int64` value. This constructor might crash if
/// the value cannot be converted to this type.
///
/// - Note: This is a hack right now.
init(_ value: Int64)
/// Constructs an `IntegerNumber` from a `Double` value. This constructor might crash if
/// the value cannot be converted to this type.
init(_ value: Double)
/// Returns the integer as a `Double`.
var doubleValue: Double { get }
/// Computes the power of `self` with exponent `exp`.
func toPower(of exp: Self) -> Self
/// Returns true if this is an odd number.
var isOdd: Bool { get }
/// Adds `rhs` to `self` and reports the result together with a boolean indicating an overflow.
func addingReportingOverflow(_ rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Subtracts `rhs` from `self` and reports the result together with a boolean indicating
/// an overflow.
func subtractingReportingOverflow(_ rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Multiplies `rhs` with `self` and reports the result together with a boolean indicating
/// an overflow.
func multipliedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Divides `self` by `rhs` and reports the result together with a boolean indicating
/// an overflow.
func dividedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Computes the remainder from dividing `self` by `rhs` and reports the result together
/// with a boolean indicating an overflow.
func remainderReportingOverflow(dividingBy rhs: Self) -> (partialValue: Self, overflow: Bool)
}
/// Provide default implementations of this protocol
extension IntegerNumber {
public func toPower(of exp: Self) -> Self {
precondition(exp >= 0, "IntegerNumber.toPower(of:) with negative exponent")
var (expo, radix) = (exp, self)
var res = Self.one
while expo != 0 {
if expo.isOdd {
res *= radix
}
expo /= Self.two
radix *= radix
}
return res
}
}
/// Provide default implementations of fields needed by this protocol in all the fixed
/// width numeric types.
extension FixedWidthInteger {
public static var zero: Self {
return 0
}
public static var one: Self {
return 1
}
public static var two: Self {
return 2
}
public var isOdd: Bool {
return (self & 1) == 1
}
}
extension Int: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int8: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt8: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int16: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt16: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int32: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt32: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int64: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt64: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
|
011a03a7fba39740ebdf9ae3679e5aa7
| 27.186528 | 97 | 0.678125 | false | false | false | false |
CoreAnimationAsSwift/WZHQZhiBo
|
refs/heads/master
|
ZhiBo/ZhiBo/Main/View/PageContentView.swift
|
mit
|
1
|
//
// PageContentView.swift
// ZhiBo
//
// Created by mac on 16/10/30.
// Copyright © 2016年 mac. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(_ contentView : PageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}
private let contentCellID = "contentCellID"
class PageContentView: UIView {
//是否禁止执行代理方法
var isYes:Bool = false
weak var delegate:PageContentViewDelegate?
fileprivate var startOffsetX :CGFloat = 0
fileprivate var childVCs:[UIViewController]
fileprivate weak var prententVC:UIViewController?
//MARK:-懒加载属性
fileprivate lazy var collectionView:UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = self!.bounds.size
layout.scrollDirection = .horizontal
let collecton = UICollectionView(frame: self!.bounds, collectionViewLayout: layout)
collecton.showsHorizontalScrollIndicator = false
collecton.bounces = false
collecton.isPagingEnabled = true
collecton.dataSource = self
collecton.delegate = self
collecton.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID)
return collecton
}()
init(frame: CGRect,childVCs:[UIViewController],prententVC:UIViewController?) {
self.childVCs = childVCs
self.prententVC = prententVC
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView {
fileprivate func setupUI() {
//1将子控制器添加到父控制器上
for childVC in childVCs {
prententVC!.addChildViewController(childVC)
}
//2创建集合视图
addSubview(self.collectionView)
}
}
//MARK:-数据源协议
extension PageContentView:UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath)
//循环利用,先移除,在添加
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let chiledVC = childVCs[indexPath.item]
chiledVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(chiledVC.view)
return cell
}
}
//MARK: - 公开的方法
extension PageContentView {
func setupSelectedIndex(_ index:Int) {
isYes = true
let offsetX = CGFloat(index) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
// collectionView.scrollRectToVisible(CGRect(origin: CGPoint(x: offsetX, y: 0), size: frame.size), animated: true)
}
}
//MARK: - 代理
extension PageContentView:UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isYes = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isYes {
return
}
//1定义需要获取的数据
var progress :CGFloat = 0
var sourceIndex :Int = 0
var targetIndex : Int = 0
//2判断滑动方向
let currecntOffsetX = scrollView.contentOffset.x
if currecntOffsetX > startOffsetX { //左滑
//floor 取整
progress = currecntOffsetX / bounds.width - floor(currecntOffsetX / bounds.width)
sourceIndex = Int(currecntOffsetX / bounds.width)
targetIndex = sourceIndex + 1
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
if currecntOffsetX - startOffsetX == bounds.width {
progress = 1
targetIndex = sourceIndex
}
}else {
progress = 1 - (currecntOffsetX / bounds.width - floor(currecntOffsetX / bounds.width))
targetIndex = Int(currecntOffsetX / bounds.width)
sourceIndex = targetIndex + 1
if sourceIndex >= childVCs.count {
sourceIndex = childVCs.count - 1
}
if currecntOffsetX - startOffsetX == -bounds.width {
progress = 1
sourceIndex = targetIndex
}
}
//3
// print("1--\(progress) + 2--\(sourceIndex) + 3--\(targetIndex)")
delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
|
d94097bfc973ad551b82a2de7107741d
| 35.218045 | 121 | 0.647498 | false | false | false | false |
Tanglo/VergeOfStrife
|
refs/heads/master
|
Vos Map Maker/VoSMapDocument.swift
|
mit
|
1
|
//
// VoSMapDocument
// Vos Map Maker
//
// Created by Lee Walsh on 30/03/2015.
// Copyright (c) 2015 Lee David Walsh. All rights reserved.
//
import Cocoa
class VoSMapDocument: NSDocument {
var map = VoSMap()
var mapView: VoSMapView?
@IBOutlet var scrollView: NSScrollView?
@IBOutlet var tileWidthField: NSTextField?
@IBOutlet var tileHeightField: NSTextField?
override init() {
super.init()
// Add your subclass-specific initialization here.
map = VoSMap()
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
let (rows,columns) = map.grid.gridSize()
mapView = VoSMapView(frame: NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height))
scrollView!.documentView = mapView
tileWidthField!.doubleValue = map.tileSize.width
tileHeightField!.doubleValue = map.tileSize.height
}
override class func autosavesInPlace() -> Bool {
return true
}
override var windowNibName: String? {
// Returns the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
return "VoSMapDocument"
}
override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return NSKeyedArchiver.archivedDataWithRootObject(map)
}
override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
// let testData = NSData() //data
// println("before: \(map.someVar)")
let newMap: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(data) //testData)
if let testMap = newMap as? VoSMap {
map = newMap! as! VoSMap
// println("after: \(map.someVar)")
return true
}
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return false
}
@IBAction func importMapFromCSV(sender: AnyObject) {
let importOpenPanel = NSOpenPanel()
importOpenPanel.canChooseDirectories = false
importOpenPanel.canChooseFiles = true
importOpenPanel.allowsMultipleSelection = false
importOpenPanel.allowedFileTypes = ["csv", "CSV"]
let result = importOpenPanel.runModal()
if result == NSModalResponseOK {
var outError: NSError?
let mapString: String? = String(contentsOfFile: importOpenPanel.URL!.path!, encoding: NSUTF8StringEncoding, error: &outError)
if (mapString != nil) {
map.importMapFromString(mapString!)
updateMapView()
} else {
let errorAlert = NSAlert(error: outError!)
errorAlert.runModal()
}
}
}
func updateMapView() {
let (rows,columns) = map.grid.gridSize()
mapView!.frame = NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height)
mapView!.needsDisplay = true
}
@IBAction func saveAsPdf(sender: AnyObject){
let savePanel = NSSavePanel()
savePanel.allowedFileTypes = ["pdf", "PDF"]
let saveResult = savePanel.runModal()
if saveResult == NSModalResponseOK {
let pdfData = mapView!.dataWithPDFInsideRect(mapView!.frame)
let success = pdfData.writeToURL(savePanel.URL!, atomically: true)
}
}
override func printOperationWithSettings(printSettings: [NSObject : AnyObject], error outError: NSErrorPointer) -> NSPrintOperation? {
let printOp = NSPrintOperation(view: mapView!)
printOp.printPanel.options = printOp.printPanel.options | NSPrintPanelOptions.ShowsPageSetupAccessory
return printOp
}
@IBAction func updateTileSize(sender: AnyObject){
if sender as? NSTextField == tileWidthField {
map.tileSize.width = sender.doubleValue
} else if sender as? NSTextField == tileHeightField {
map.tileSize.height = sender.doubleValue
}
let (rows,columns) = map.grid.gridSize()
mapView!.frame = NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height)
mapView!.needsDisplay = true
}
}
|
e0279e7adcd9ed177f101f113e14f39b
| 44.983471 | 198 | 0.667685 | false | false | false | false |
megabitsenmzq/PomoNow-iOS
|
refs/heads/master
|
Old-1.0/PomoNow/PomoNow/ChartViewController.swift
|
mit
|
1
|
//
// ChartViewController.swift
// PomoNow
//
// Created by Megabits on 15/11/24.
// Copyright © 2015年 ScrewBox. All rights reserved.
//
import UIKit
class ChartViewController: UIViewController {
@IBOutlet var StartLabel: UILabel!
@IBOutlet var StatisticsContainer: UIView!
@IBAction func cancel(sender: AnyObject) {
timer?.invalidate()
timer = nil
self.performSegueWithIdentifier("backToList", sender: self)
}
@IBAction func ok(sender: AnyObject) {
timer?.invalidate()
timer = nil
self.performSegueWithIdentifier("backToList", sender: self)
}
@IBOutlet weak var TimerView: CProgressView!
@IBOutlet weak var timeLabel: UILabel!
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
process = pomodoroClass.process
updateUI()
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(ChartViewController.getNowtime(_:)), userInfo: nil, repeats: true)
}
var process: Float { //进度条
get {
return TimerView.valueProgress / 67 * 100
}
set {
TimerView.valueProgress = newValue / 100 * 67
updateUI()
}
}
private func updateUI() {
TimerView.setNeedsDisplay()
timeLabel.text = pomodoroClass.timerLabel
var haveData = 0
for i in 0...6 {
if cManager.chart[i][0] > 0{
haveData += 1
}
}
if haveData == 0 {
StartLabel.hidden = false
StatisticsContainer.hidden = true
} else {
StartLabel.hidden = true
StatisticsContainer.hidden = false
}
}
func getNowtime(timer:NSTimer) { //同步时间
process = pomodoroClass.process
updateUI()
}
}
|
55cde1ff67e57da96df70829ca83bfd5
| 26.086957 | 160 | 0.58962 | false | false | false | false |
DrGo/LearningSwift
|
refs/heads/master
|
PLAYGROUNDS/LSB_002_VariablesAndConstants.playground/section-2.swift
|
gpl-3.0
|
2
|
import UIKit
/*--------------------------/
// Variables and Constants
/--------------------------*/
/*---------------------/
// Let and Var
/---------------------*/
let x = 10
//x++ // error
var y = 10
y++
/*---------------------/
// Computed Variables
/---------------------*/
var w = 10.0
var h = 20.0
var area: Double {
get {
return w * h
}
set(newArea) {
w = newArea
h = 1.0
}
}
w
h
area
area = 100.0
w
h
// Use the default `newValue` in the setter:
var squareArea: Double {
get {
return w * h
}
set {
w = sqrt(newValue)
h = sqrt(newValue)
}
}
w = 100.0
h = 20.0
squareArea
squareArea = 100.0
w
h
// No setter, so we can omit the `get` and `set` keywords:
var fortune: String {
return "You will find \(arc4random_uniform(100)) potatoes."
}
fortune
fortune
/*---------------------/
// Variable Observers
/---------------------*/
var calMsg0 = ""
var calMsg1 = ""
var caloriesEaten: Int = 0 {
willSet(cals) {
calMsg0 = "You are about to eat \(cals) calories."
}
didSet(cals) {
calMsg1 = "Last time you ate \(cals) calories"
}
}
calMsg0
calMsg1
caloriesEaten = 140
calMsg0
calMsg1
// Default variable names:
var alert0 = ""
var alert1 = ""
var alertLevel: Int = 1 {
willSet {
alert0 = "The new alert level is: \(newValue)"
}
didSet {
alert1 = "No longer at alert level: \(oldValue)"
}
}
alert0
alert1
alertLevel = 5
alert0
alert1
// Pick and choose:
alert0 = ""
var defcon: Int = 1 {
willSet {
if newValue >= 5 {
alert0 = "BOOM!"
}
}
}
defcon = 4
alert0
defcon = 5
alert0
|
c6f6bcbf2d977735a96a1730f54208d8
| 11.822581 | 61 | 0.526415 | false | false | false | false |
eshurakov/SwiftHTTPClient
|
refs/heads/master
|
HTTPClient/DefaultHTTPSession.swift
|
mit
|
1
|
//
// DefaultHTTPSession.swift
// HTTPClient
//
// Created by Evgeny Shurakov on 30.07.16.
// Copyright © 2016 Evgeny Shurakov. All rights reserved.
//
import Foundation
public class DefaultHTTPSession: NSObject, HTTPSession {
fileprivate var taskContexts: [Int: TaskContext] = [:]
fileprivate var session: Foundation.URLSession?
private let sessionFactory: HTTPSessionFactory
public var logger: HTTPLogger?
fileprivate class TaskContext {
lazy var data = Data()
let completion: (HTTPRequestResult) -> Void
init(completion: @escaping (HTTPRequestResult) -> Void) {
self.completion = completion
}
}
private override init() {
fatalError("Not implemented")
}
public init(sessionFactory: HTTPSessionFactory) {
self.sessionFactory = sessionFactory
super.init()
}
public func execute(_ request: URLRequest, completion: @escaping (HTTPRequestResult) -> Void) {
if self.session == nil {
self.session = self.sessionFactory.session(withDelegate: self)
}
guard let session = self.session else {
fatalError("Session is nil right after it was created")
}
let task = session.dataTask(with: request)
self.logger?.logStart(of: task)
// TODO: call completion with a failure?
assert(self.taskContexts[task.taskIdentifier] == nil)
self.taskContexts[task.taskIdentifier] = TaskContext(completion: completion)
task.resume()
}
}
extension DefaultHTTPSession: URLSessionDelegate {
public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
self.session = nil
self.logger?.logSessionFailure(error)
let taskContexts = self.taskContexts
self.taskContexts = [:]
for (_, context) in taskContexts {
context.completion(.failure(HTTPSessionError.becameInvalid(error)))
}
}
}
extension DefaultHTTPSession: URLSessionTaskDelegate {
public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
self.logger?.logRedirect(of: task)
completionHandler(request)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let context = self.taskContexts[task.taskIdentifier] else {
return
}
self.taskContexts[task.taskIdentifier] = nil
if let error = error {
self.logger?.logFailure(of: task, with: error)
context.completion(.failure(error))
} else {
if let response = task.response {
if let httpResponse = response as? HTTPURLResponse {
let response = HTTPResponse(with: httpResponse,
data: context.data)
self.logger?.logSuccess(of: task, with: response)
context.completion(.success(response))
} else {
let error = HTTPSessionError.unsupportedURLResponseSubclass(String(describing: type(of: response)))
self.logger?.logFailure(of: task, with: error)
context.completion(.failure(error))
}
} else {
let error = HTTPSessionError.missingURLResponse
self.logger?.logFailure(of: task, with: error)
context.completion(.failure(error))
}
}
}
}
extension DefaultHTTPSession: URLSessionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let context = self.taskContexts[dataTask.taskIdentifier] else {
return
}
context.data.append(data)
}
}
|
bb3224c175c5abcdbbd7a14f479d0dad
| 33.788136 | 211 | 0.609501 | false | false | false | false |
flodolo/firefox-ios
|
refs/heads/main
|
Client/Frontend/Home/Wallpapers/v1/UI/WallpaperBackgroundView.swift
|
mpl-2.0
|
2
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
class WallpaperBackgroundView: UIView {
// MARK: - UI Elements
private lazy var pictureView: UIImageView = .build { imageView in
imageView.image = nil
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
// MARK: - Variables
private var wallpaperManager = WallpaperManager()
var notificationCenter: NotificationProtocol = NotificationCenter.default
// MARK: - Initializers & Setup
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupNotifications(forObserver: self,
observing: [.WallpaperDidChange])
updateImageToCurrentWallpaper()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
notificationCenter.removeObserver(self)
}
private func setupView() {
backgroundColor = .clear
addSubview(pictureView)
NSLayoutConstraint.activate([
pictureView.leadingAnchor.constraint(equalTo: leadingAnchor),
pictureView.topAnchor.constraint(equalTo: topAnchor),
pictureView.bottomAnchor.constraint(equalTo: bottomAnchor),
pictureView.trailingAnchor.constraint(equalTo: trailingAnchor),
])
}
// MARK: - Methods
public func updateImageForOrientationChange() {
updateImageToCurrentWallpaper()
}
private func updateImageToCurrentWallpaper() {
ensureMainThread {
let currentWallpaper = self.currentWallpaperImage()
UIView.animate(withDuration: 0.3) {
self.pictureView.image = currentWallpaper
}
}
}
private func currentWallpaperImage() -> UIImage? {
return UIDevice.current.orientation.isLandscape ? wallpaperManager.currentWallpaper.landscape : wallpaperManager.currentWallpaper.portrait
}
}
// MARK: - Notifiable
extension WallpaperBackgroundView: Notifiable {
func handleNotifications(_ notification: Notification) {
switch notification.name {
case .WallpaperDidChange: updateImageToCurrentWallpaper()
default: break
}
}
}
|
0534765a6799a110e74de7872fc0bbe7
| 30.346154 | 146 | 0.667485 | false | false | false | false |
PiXeL16/BudgetShare
|
refs/heads/master
|
BudgetShare/Modules/BudgetCreate/Wireframe/BudgetCreateWireframeProvider.swift
|
mit
|
1
|
//
// Created by Chris Jimenez on 3/5/17.
// Copyright (c) 2017 Chris Jimenez. All rights reserved.
//
import Foundation
import UIKit
internal class BudgetCreateWireframeProvider: Wireframe, BudgetCreateWireframe {
var root: RootWireframeInterface?
// Inits and starts all the wiring
required init(root: RootWireframeInterface?) {
self.root = root
}
// Show the view controller in the window
func attachRoot(with controller: UIViewController, in window: UIWindow) {
root?.showRoot(with: controller, in: window)
}
// Show an error Alert
func showErrorAlert(title: String, message: String, from controller: UIViewController?) {
guard let viewController = controller else {
return
}
// Use the dialog util provider
let alert = AlertDialogUtilProvider()
alert.showErrorAlert(message: message, title: title, with: viewController)
}
}
extension BudgetCreateWireframeProvider {
class func createViewController() -> UINavigationController {
let sb = UIStoryboard(name: "BudgetCreateModule", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "BudgetCreateNavigationViewController") as! UINavigationController
return vc
}
// func pushSignUp(from controller: UIViewController?) {
// // TODO: Use SignUp wireframe to push it
//
// guard controller != nil else {
// return
// }
//
// let vc = SignUpWireframe.createViewController()
// let wireframe = SignUpWireframe(root: root, view: vc)
// wireframe.push(controller: vc, from: controller!)
//
// }
}
|
6820617b935bcf232d254c1325b958e9
| 29.017544 | 128 | 0.654004 | false | false | false | false |
heilb1314/500px_Challenge
|
refs/heads/master
|
PhotoWall_500px_challenge/PhotoWall_500px_challenge/PhotoWallViewController.swift
|
mit
|
1
|
//
// PhotoWallViewController.swift
// PhotoWall_500px_challenge
//
// Created by Jianxiong Wang on 2/1/17.
// Copyright © 2017 JianxiongWang. All rights reserved.
//
import UIKit
class PhotoWallViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
fileprivate var photos:[Photo]!
fileprivate var gridSizes: [CGSize]!
fileprivate var itemsPerRow: Int = 3
fileprivate var lastViewdIndexPath: IndexPath?
fileprivate var isLandscape = false
fileprivate var isLoading = false
fileprivate var searchController: UISearchController!
fileprivate var searchTerm: String = CATEGORIES[0]
fileprivate var page: Int = 1
private var pageSize: Int = 30
private var photoSizes: [Int] = [3,4]
private var selectedIndex: Int?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.barStyle = .default
self.navigationController?.navigationBar.titleTextAttributes = nil
let rightBarItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(changeTerm(sender:)))
rightBarItem.tintColor = UIColor.orange
self.navigationItem.rightBarButtonItem = rightBarItem
self.navigationItem.title = searchTerm.capitalized
self.updateCollectionViewLayout()
}
func changeTerm(sender: UIBarButtonItem) {
self.performSegue(withIdentifier: "showCategories", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.isLandscape = UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation)
if let layout = collectionView?.collectionViewLayout as? PhotoWallLayout {
layout.delegate = self
}
self.photos = [Photo]()
getPhotos(resetPhotos: true, completionHandler: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/// Get next page Photos. Auto reload collectionView.
fileprivate func getPhotos(resetPhotos: Bool, completionHandler handler: (()->())?) {
QueryModel.getPhotos(forSearchTerm: searchTerm, page: page, resultsPerPage: pageSize, photoSizes: photoSizes) { (photos, error) in
if(photos != nil) {
self.page += 1
resetPhotos ? self.photos = photos : self.photos.append(contentsOf: photos!)
self.collectionView.layoutIfNeeded()
self.collectionView.reloadData()
} else {
let alert = UIAlertController(title: "Oops", message: error?.localizedDescription, preferredStyle: .alert)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
handler?()
}
}
/// update collectionView layout and move to last viewed indexPath if any.
fileprivate func updateCollectionViewLayout() {
self.collectionView.collectionViewLayout.invalidateLayout()
let curOrientation = UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation)
if self.lastViewdIndexPath != nil && self.isLandscape != curOrientation {
self.isLandscape = curOrientation
DispatchQueue.main.async {
self.collectionView.scrollToItem(at: self.lastViewdIndexPath!, at: curOrientation ? .right : .bottom, animated: false)
}
}
}
// MARK: - UIScrollView Delegates
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.lastViewdIndexPath = self.collectionView.indexPathsForVisibleItems.last
// load next page when scrollView reaches the end
guard self.isLoading == false else { return }
var offset:CGFloat = 0
var sizeLength:CGFloat = 0
if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
offset = scrollView.contentOffset.x
sizeLength = scrollView.contentSize.width - scrollView.frame.size.width
} else {
offset = scrollView.contentOffset.y
sizeLength = scrollView.contentSize.height - scrollView.frame.size.height
}
if offset >= sizeLength {
self.isLoading = true
self.getPhotos(resetPhotos: false, completionHandler: {
self.isLoading = false
})
}
}
// MARK: - UICollectionView DataSources
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PhotoThumbnailCollectionViewCell
cell.photo = self.photos?[indexPath.row]
return cell
}
// MARK: - UICollectionView Delegates
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectedIndex = indexPath.row
performSegue(withIdentifier: "showPhotoDetail", sender: self)
}
// Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPhotoDetail" {
let svc = segue.destination as! PhotoDetailViewController
if self.photos != nil && self.selectedIndex != nil && self.selectedIndex! < self.photos!.count {
svc.photo = self.photos![self.selectedIndex!]
}
} else if segue.identifier == "showCategories" {
let svc = segue.destination as! SearchTermTableViewController
svc.delegate = self
}
}
}
// MARK: Extension - PhotoWallLayoutDelegate
extension PhotoWallViewController: PhotoWallLayoutDelegate {
func collectionView(collectionView: UICollectionView, sizeForPhotoAtIndexPath indexPath: IndexPath) -> CGSize {
return photos[indexPath.item].getPhotoSize()
}
// Update grids when device rotates
override func viewWillLayoutSubviews() {
if self.isLandscape != UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
updateCollectionViewLayout()
}
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
updateCollectionViewLayout()
}
}
// MARK: Extension - SearchTerm Delegate
extension PhotoWallViewController: SearchTermDelegate {
func searchTermDidChange(sender: SearchTermTableViewController, newTerm: String) {
if newTerm != self.searchTerm {
self.searchTerm = newTerm
self.page = 1
self.getPhotos(resetPhotos: true, completionHandler: {
self.collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: false)
})
}
}
}
|
019b3d862d31010927fda05b10b0deea
| 38.175532 | 138 | 0.664902 | false | false | false | false |
imfeemily/NPSegmentedControl
|
refs/heads/master
|
NPSegmentedControl/Classes/NPSegmentedControl/NPSegmentedControl.swift
|
apache-2.0
|
1
|
/*
Copyright 2015 NEOPIXL S.A.
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 UIKit
public class NPSegmentedControl : UIControl {
private var views = [UIView]()
private var labels = [UILabel]()
public var cursor:UIView?
{
didSet{
if views.count > 0
{
self.setItems(items)
if let cur = oldValue
{
cur.removeFromSuperview()
}
}
}
}
private var animationChecks = [Bool]()
private var items:[String]!
private var currentIndex:Int = 0
public var selectedColor:UIColor? = UIColor.lightGrayColor()
{
didSet{
if self.currentIndex <= views.count - 1 && self.currentIndex >= 0
{
var view = views[self.currentIndex]
view.backgroundColor = self.selectedColor
}
}
}
public var selectedTextColor:UIColor?
{
didSet{
if self.currentIndex <= views.count - 1 && self.currentIndex >= 0
{
var lab = labels[self.currentIndex]
lab.textColor = self.selectedTextColor
}
}
}
public var unselectedColor:UIColor? = UIColor.grayColor()
{
didSet{
for index in 0..<views.count
{
if(index != self.currentIndex)
{
var view = views[index]
view.backgroundColor = self.unselectedColor
}
}
}
}
public var unselectedTextColor:UIColor?
{
didSet{
for index in 0..<views.count
{
if(index != self.currentIndex)
{
var lab = labels[index]
lab.textColor = self.unselectedTextColor
}
}
}
}
public var selectedFont:UIFont?
{
didSet{
if self.currentIndex <= views.count - 1 && self.currentIndex >= 0
{
var lab = labels[self.currentIndex]
lab.font = self.selectedFont
}
}
}
public var unselectedFont:UIFont?
{
didSet{
for index in 0..<views.count
{
if(index != self.currentIndex)
{
var lab = labels[index]
lab.font = self.unselectedFont
}
}
}
}
private var cursorCenterXConstraint:NSLayoutConstraint!
private var tapGestureRecogniser:UITapGestureRecognizer!
private func initComponents()
{
tapGestureRecogniser = UITapGestureRecognizer(target: self, action: "didTap:")
self.addGestureRecognizer(tapGestureRecogniser)
}
init() {
super.init(frame: CGRectZero)
self.initComponents()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initComponents()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initComponents()
}
public func setItems(items:[String])
{
self.items = items
var previousView:UIView?
for lab in labels
{
lab.removeFromSuperview()
}
for view in views
{
view.removeFromSuperview()
}
labels.removeAll(keepCapacity: false)
views.removeAll(keepCapacity: false)
for i in 0..<items.count
{
var view = UIView()
view.backgroundColor = unselectedColor
self.addSubview(view)
views.append(view)
var label = UILabel()
label.text = items[i]
label.textColor = unselectedTextColor
if let font = unselectedFont
{
label.font = font
}
view.addSubview(label)
labels.append(label)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
var itemHeight = self.frame.height
if let cur = self.cursor
{
itemHeight -= cur.frame.height
}
let centerXConstraint = NSLayoutConstraint(item:label,
attribute:NSLayoutAttribute.CenterX,
relatedBy:NSLayoutRelation.Equal,
toItem:view,
attribute:NSLayoutAttribute.CenterX,
multiplier:1,
constant:0)
view.addConstraint(centerXConstraint)
let centerYConstraint = NSLayoutConstraint(item:label,
attribute:NSLayoutAttribute.CenterY,
relatedBy:NSLayoutRelation.Equal,
toItem:view,
attribute:NSLayoutAttribute.CenterY,
multiplier:1,
constant:0)
view.addConstraint(centerYConstraint)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
var viewDict = [ "view" : view ] as Dictionary<NSObject,AnyObject>
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[view(\(itemHeight))]", options: nil, metrics: nil, views: viewDict)
view.addConstraints(constraints)
if let previous = previousView
{
let leftConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Left,
relatedBy:NSLayoutRelation.Equal,
toItem:previous,
attribute:NSLayoutAttribute.Right,
multiplier:1,
constant:0)
self.addConstraint(leftConstraint)
let widthConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Width,
relatedBy:NSLayoutRelation.Equal,
toItem:previous,
attribute:NSLayoutAttribute.Width,
multiplier:1,
constant:0)
self.addConstraint(widthConstraint)
}
else
{
let leftConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Left,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Left,
multiplier:1.0,
constant:0)
self.addConstraint(leftConstraint)
}
let topConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Top,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Top,
multiplier:1.0,
constant:0)
self.addConstraint(topConstraint)
previousView = view
}
if let previous = previousView
{
let leftConstraint = NSLayoutConstraint(item:previous,
attribute:NSLayoutAttribute.Right,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Right,
multiplier:1.0,
constant:0)
self.addConstraint(leftConstraint)
}
if let cur = cursor
{
cur.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(cur)
let bottomConstraint = NSLayoutConstraint(item:cur,
attribute:NSLayoutAttribute.Bottom,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Bottom,
multiplier:1.0,
constant:0)
self.addConstraint(bottomConstraint)
cursorCenterXConstraint = NSLayoutConstraint(item:cur,
attribute:NSLayoutAttribute.CenterX,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.CenterX,
multiplier:1.0,
constant:0)
self.addConstraint(cursorCenterXConstraint)
var viewDict = [ "cursor" : cur ] as Dictionary<NSObject,AnyObject>
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[cursor(\(cur.frame.height))]", options: nil, metrics: nil, views: viewDict)
cur.addConstraints(constraints)
constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:[cursor(\(cur.frame.width))]", options: nil, metrics: nil, views: viewDict)
cur.addConstraints(constraints)
}
selectCell(currentIndex,animate: false)
}
//MARK: select cell at index
public func selectCell(index:Int, animate:Bool)
{
var newView = views[index]
var newLabel = labels[index]
var oldView = views[currentIndex]
var oldLabel = labels[currentIndex]
var duration:NSTimeInterval = 0
if animate
{
duration = 0.4
}
if (duration == 0 || index != currentIndex) && index < items.count
{
UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 10, options: .CurveEaseInOut | .AllowUserInteraction, animations:
{
self.animationChecks.append(true)
oldView.backgroundColor = self.unselectedColor
oldLabel.textColor = self.unselectedTextColor
if let font = self.unselectedFont
{
oldLabel.font = font
}
newView.backgroundColor = self.selectedColor
newLabel.textColor = self.selectedTextColor
if let font = self.selectedFont
{
newLabel.font = font
}
if let cur = self.cursor
{
cur.center.x = newView.center.x
}
},
completion: { finished in
if self.animationChecks.count == 1
{
if let cur = self.cursor
{
self.removeConstraint(self.cursorCenterXConstraint)
self.cursorCenterXConstraint = NSLayoutConstraint(item:cur,
attribute:NSLayoutAttribute.CenterX,
relatedBy:NSLayoutRelation.Equal,
toItem:newView,
attribute:NSLayoutAttribute.CenterX,
multiplier:1.0,
constant:0)
self.addConstraint(self.cursorCenterXConstraint)
}
}
self.animationChecks.removeLast()
})
currentIndex = index
}
}
internal func didTap(recognizer:UITapGestureRecognizer)
{
if recognizer.state == UIGestureRecognizerState.Ended
{
var currentPoint = recognizer.locationInView(self)
var index = indexFromPoint(currentPoint)
selectCell(index, animate: true)
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
}
}
//MARK: getIndex from point
private func indexFromPoint(point:CGPoint) -> Int
{
var position = 0
for pos in 0..<views.count
{
let view = views[pos]
if point.x >= view.frame.minX && point.x < view.frame.maxX
{
return pos
}
}
return 0
}
//MARK: selectedIndex
public func selectedIndex() -> Int
{
return self.currentIndex
}
}
|
c638437a8ebaad751081e079ee12da33
| 31.912145 | 174 | 0.523241 | false | false | false | false |
klaaspieter/Letters
|
refs/heads/master
|
Sources/Recorder/Prelude/Parallel.swift
|
mit
|
1
|
import Dispatch
final class Parallel<A> {
private let queue = DispatchQueue(label: "Recorder.Parellel")
private var computed: A?
private let compute: (@escaping (A) -> Void) -> Void
init(_ compute: @escaping (@escaping (A) -> Void) -> Void) {
self.compute = compute
}
func run(_ callback: @escaping (A) -> Void) {
queue.async {
guard let computed = self.computed else {
return self.compute { computed in
self.computed = computed
callback(computed)
}
}
callback(computed)
}
}
}
extension Parallel {
static func pure(_ x: A) -> Parallel<A> {
return Parallel({ $0(x) })
}
func map<B>(_ f: @escaping (A) -> B) -> Parallel<B> {
return Parallel<B> { completion in
self.run({ completion(f($0)) })
}
}
static func <^> <B> (_ f: @escaping (A) -> B, _ x: Parallel<A>) -> Parallel<B> {
return x.map(f)
}
func apply<B>(_ f: Parallel<(A) -> B>) -> Parallel<B> {
return Parallel<B> { g in
f.run { f in if let x = self.computed { g(f(x)) } }
self.run { x in if let f = f.computed { g(f(x)) } }
}
}
static func <*> <B> (_ f: Parallel<(A) -> B>, _ x: Parallel<A>) -> Parallel<B> {
return x.apply(f)
}
}
|
81f43aa7c3b8ef154cb1caa55b16e016
| 23.333333 | 82 | 0.547945 | false | false | false | false |
aKirill1942/NetRoute
|
refs/heads/master
|
NetRoute/NetResponse.swift
|
apache-2.0
|
1
|
//
// NetResponse.swift
// NetRoute
//
// Created by Kirill Averkiev on 15.04.16.
// Copyright © 2016 Kirill Averkiev. All rights reserved.
//
// 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
/// The response of the request.
public class NetResponse: NetRouteObject {
// MARK: - Constants
/// Response data.
public let data: Data?
/// HTTP response.
public let httpResponse: URLResponse?
/// Error.
public let error: Error?
// MARK: - Variables
/// Encoding for the string conversion. Default is `NSUTF8StringEncoding`.
public var encoding = String.Encoding.utf8
/// String conversion.Returns nil if the data can not be presented as `String`.
public override var description: String {
if let dictionary = dictionary {
var finalString = "{\n"
for (key, value) in dictionary {
finalString += " " + "\(key): \(value)\n"
}
finalString += "}"
return finalString
}
return "Response"
}
/// String value of the data. Returns nil if the data can not be presented as `String`.
public var stringValue: String? {
// Check if data is not nil.
if data != nil {
if let responseString = String(data: data!, encoding: encoding) {
return responseString
} else {
return nil
}
} else {
return nil
}
}
/// Dictionary of the data. Returns nil if the data can not be presented as `Dictionary`.
public var dictionary: Dictionary<String, AnyObject>? {
// Check if data is not nil.
if data != nil {
do {
let responseJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
return responseJSON as? Dictionary
} catch _ {
return nil
}
} else {
return nil
}
}
// MARK: - Initialization
/// Initializes a new instance from default `NSURLSession` output.
public init(data: Data?, response: URLResponse?, error: Error?) {
self.data = data
self.httpResponse = response
self.error = error
}
// MARK: - Header Values
/// Get a header value from response.
///
/// - Parameter forHeader: Name of the header.
///
/// - Returns: Value for provided header. Nil if no response or the provided header is wrong.
public func value(for header: String) -> Any? {
if let response = httpResponse as? HTTPURLResponse {
return response.allHeaderFields[header]
} else {
return nil
}
}
/// Get a header value from response.
///
/// - Parameter forHeader: Name of the header.
///
/// - Returns: String for provided header converted to String. Nil if no response, the provided header is wrong or the data cannot be converted to String.
public func string(for header: String) -> String? {
return self.value(forHeader: header) as? String
}
}
|
c6853a39926ba4021e385a5ffae7aa29
| 26.856115 | 158 | 0.573089 | false | false | false | false |
steveholt55/Football-College-Trivia-iOS
|
refs/heads/master
|
FootballCollegeTrivia/Game/GameTimer.swift
|
mit
|
1
|
//
// Copyright © 2016 Brandon Jenniges. All rights reserved.
//
import UIKit
protocol GameTimerProtocol {
func timeTicked(displayText: String, color: UIColor)
func timeFinished()
}
class GameTimer: NSObject {
static var timer = NSTimer()
static var minutes = 0
static var seconds = 0
static var secondsLeft = 0
static var presenter: GamePresenter!
static func start() {
secondsLeft = 120;
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(GameTimer.updateCounter), userInfo: nil, repeats: true)
}
static func stop() {
timer.invalidate()
}
static func updateCounter() {
if GameTimer.secondsLeft > 0 {
GameTimer.secondsLeft -= 1
GameTimer.minutes = (GameTimer.secondsLeft % 3600) / 60
GameTimer.seconds = (GameTimer.secondsLeft % 3600) % 60
let displayText = String(format: "%d", GameTimer.minutes) + ":" + String(format: "%02d", GameTimer.seconds)
var color: UIColor = .darkGrayColor()
if GameTimer.secondsLeft <= 10 {
color = .redColor()
}
presenter.timeTicked(displayText, color: color)
} else {
stop()
presenter.timeFinished()
}
}
}
|
8f2affc694d0fac58ad40a6f40a91cc3
| 28.6 | 149 | 0.601052 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK
|
refs/heads/master
|
BridgeAppSDKTests/SBAOnboardingManagerTests.swift
|
bsd-3-clause
|
1
|
//
// SBAOnboardingManagerTests.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
import BridgeAppSDK
class SBAOnboardingManagerTests: ResourceTestCase {
override func setUp() {
super.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.
super.tearDown()
}
func testCreateManager() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")
XCTAssertNotNil(manager)
XCTAssertNotNil(manager?.sections)
guard let sections = manager?.sections else { return }
XCTAssertEqual(sections.count, 8)
}
func testShouldInclude() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
let expectedNonNil: [SBAOnboardingSectionBaseType : [SBAOnboardingTaskType]] = [
.login: [.login],
.eligibility: [.signup],
.consent: [.login, .signup, .reconsent],
.registration: [.signup],
.passcode: [.login, .signup, .reconsent],
.emailVerification: [.signup],
.permissions: [.login, .signup],
.profile: [.signup],
.completion: [.login, .signup]]
for sectionType in SBAOnboardingSectionBaseType.all {
let include = expectedNonNil[sectionType]
XCTAssertNotNil(include, "\(sectionType)")
if include != nil {
for taskType in SBAOnboardingTaskType.all {
let expectedShouldInclude = include!.contains(taskType)
let section: NSDictionary = ["onboardingType": sectionType.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertEqual(shouldInclude, expectedShouldInclude, "\(sectionType) \(taskType)")
}
}
}
}
func testShouldInclude_HasPasscode() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
manager._hasPasscode = true
// Check that if the passcode has been set that it is not included
for taskType in SBAOnboardingTaskType.all {
let section: NSDictionary = ["onboardingType": SBAOnboardingSectionBaseType.passcode.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertFalse(shouldInclude, "\(taskType)")
}
}
func testShouldInclude_HasRegistered() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
// If the user has registered and this is a completion of the registration
// then only include email verification and those sections AFTER verification
// However, if the user is being reconsented then include the reconsent section
manager.mockAppDelegate.mockCurrentUser.isRegistered = true
manager._hasPasscode = true
let taskTypes: [SBAOnboardingTaskType] = [.signup, .reconsent]
let expectedNonNil: [SBAOnboardingSectionBaseType : [SBAOnboardingTaskType]] = [
.login: [.login],
// eligibility should *not* be included in registration if the user is at the email verification step
.eligibility: [],
// consent should *not* be included in registration if the user is at the email verification step
.consent: [.login, .reconsent],
// registration should *not* be included in registration if the user is at the email verification step
.registration: [],
// passcode should *not* be included in registration if the user is at the email verification step
// and has already set the passcode
.passcode: [],
.emailVerification: [.signup],
.permissions: [.login, .signup],
.profile: [.signup],
.completion: [.login, .signup]]
for sectionType in SBAOnboardingSectionBaseType.all {
let include = expectedNonNil[sectionType]
XCTAssertNotNil(include, "\(sectionType)")
if include != nil {
for taskType in taskTypes {
let expectedShouldInclude = include!.contains(taskType)
let section: NSDictionary = ["onboardingType": sectionType.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertEqual(shouldInclude, expectedShouldInclude, "\(sectionType) \(taskType)")
}
}
}
}
func testSortOrder() {
let inputSections = [
["onboardingType" : "customWelcome"],
["onboardingType" : "consent"],
["onboardingType" : "passcode"],
["onboardingType" : "emailVerification"],
["onboardingType" : "registration"],
["onboardingType" : "login"],
["onboardingType" : "eligibility"],
["onboardingType" : "profile"],
["onboardingType" : "permissions"],
["onboardingType" : "completion"],
["onboardingType" : "customEnd"],]
let input: NSDictionary = ["sections" : inputSections];
guard let sections = SBAOnboardingManager(dictionary: input).sections else {
XCTAssert(false, "failed to create onboarding manager sections")
return
}
let expectedOrder = ["customWelcome",
"login",
"eligibility",
"consent",
"registration",
"passcode",
"emailVerification",
"permissions",
"profile",
"completion",
"customEnd",]
let actualOrder = sections.sba_mapAndFilter({ $0.onboardingSectionType?.identifier })
XCTAssertEqual(actualOrder, expectedOrder)
}
func testEligibilitySection() {
guard let steps = checkOnboardingSteps( .base(.eligibility), .signup) else { return }
let expectedSteps: [ORKStep] = [SBAToggleFormStep(identifier: "inclusionCriteria"),
SBAInstructionStep(identifier: "ineligibleInstruction"),
SBAInstructionStep(identifier: "eligibleInstruction")]
XCTAssertEqual(steps.count, expectedSteps.count)
for (idx, expectedStep) in expectedSteps.enumerated() {
if idx < steps.count {
XCTAssertEqual(steps[idx].identifier, expectedStep.identifier)
let stepClass = NSStringFromClass(steps[idx].classForCoder)
let expectedStepClass = NSStringFromClass(expectedStep.classForCoder)
XCTAssertEqual(stepClass, expectedStepClass)
}
}
}
func testPasscodeSection() {
guard let steps = checkOnboardingSteps( .base(.passcode), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? ORKPasscodeStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "passcode")
XCTAssertEqual(step.passcodeType, ORKPasscodeType.type4Digit)
XCTAssertEqual(step.title, "Identification")
XCTAssertEqual(step.text, "Select a 4-digit passcode. Setting up a passcode will help provide quick and secure access to this application.")
}
func testLoginSection() {
guard let steps = checkOnboardingSteps( .base(.login), .login) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBALoginStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "login")
}
func testRegistrationSection() {
guard let steps = checkOnboardingSteps( .base(.registration), .signup) else { return }
XCTAssertEqual(steps.count, 2)
guard let step1 = steps.first as? SBASinglePermissionStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step1.identifier, "healthKitPermissions")
guard let step2 = steps.last as? SBARegistrationStep else {
XCTAssert(false, "\(String(describing: steps.last)) not of expected type")
return
}
XCTAssertEqual(step2.identifier, "registration")
}
func testEmailVerificationSection() {
guard let steps = checkOnboardingSteps( .base(.emailVerification), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBAEmailVerificationStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "emailVerification")
}
func testProfileSection() {
guard let steps = checkOnboardingSteps( .base(.profile), .signup) else { return }
XCTAssertEqual(steps.count, 3)
for step in steps {
XCTAssertTrue(step is SBAProfileFormStep)
}
}
func testPermissionsSection() {
guard let steps = checkOnboardingSteps( .base(.permissions), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBAPermissionsStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "permissions")
}
func testCreateTask_Login() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .login) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 4
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBALoginStep)
XCTAssertEqual(task.steps[ii].identifier, "login")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "consent")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
}
func testCreateTask_SignUp_Row0() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .signup, tableRow: 0) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 7
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "eligibility")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "consent")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "registration")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAEmailVerificationStep)
XCTAssertEqual(task.steps[ii].identifier, "emailVerification")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "profile")
}
func testCreateTask_SignUp_Row2() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .signup, tableRow: 2) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 5
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "registration")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAEmailVerificationStep)
XCTAssertEqual(task.steps[ii].identifier, "emailVerification")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "profile")
}
func testSignupState() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
let eligibilityState1 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState1, .current)
let consentState1 = manager.signupState(for: 1)
XCTAssertEqual(consentState1, .locked)
let registrationState1 = manager.signupState(for: 2)
XCTAssertEqual(registrationState1, .locked)
let profileState1 = manager.signupState(for: 3)
XCTAssertEqual(profileState1, .locked)
// For any step in the consent flow except the last, then the consent is the current section
manager.sharedUser.onboardingStepIdentifier = "eligibility.eligibleInstruction"
let eligibilityState2 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState2, .completed)
let consentState2 = manager.signupState(for: 1)
XCTAssertEqual(consentState2, .current)
let registrationState2 = manager.signupState(for: 2)
XCTAssertEqual(registrationState2, .locked)
let profileState2 = manager.signupState(for: 3)
XCTAssertEqual(profileState2, .locked)
// Once we enter the consent flow then that becomes the current section
manager.sharedUser.onboardingStepIdentifier = "consent.consentVisual"
let eligibilityState3 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState3, .completed)
let consentState3 = manager.signupState(for: 1)
XCTAssertEqual(consentState3, .current)
let registrationState3 = manager.signupState(for: 2)
XCTAssertEqual(registrationState3, .locked)
let profileState3 = manager.signupState(for: 3)
XCTAssertEqual(profileState3, .locked)
// For any step in the consent flow except the last, then the consent is the current section
manager.sharedUser.onboardingStepIdentifier = "consent.consentCompletion"
let eligibilityState4 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState4, .completed)
let consentState4 = manager.signupState(for: 1)
XCTAssertEqual(consentState4, .completed)
let registrationState4 = manager.signupState(for: 2)
XCTAssertEqual(registrationState4, .current)
let profileState4 = manager.signupState(for: 3)
XCTAssertEqual(profileState4, .locked)
// Set the steps to the registration section
manager.sharedUser.onboardingStepIdentifier = "registration.registration"
let eligibilityState5 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState5, .completed)
let consentState5 = manager.signupState(for: 1)
XCTAssertEqual(consentState5, .completed)
let registrationState5 = manager.signupState(for: 2)
XCTAssertEqual(registrationState5, .current)
let profileState5 = manager.signupState(for: 3)
XCTAssertEqual(profileState5, .locked)
// For registration, there isn't a completion step and the final step is email verification
// so the current section remains the email verification *until* login is verified
manager.sharedUser.isRegistered = true
manager.sharedUser.isLoginVerified = false
manager.sharedUser.isConsentVerified = false
manager.sharedUser.onboardingStepIdentifier = "emailVerification"
let eligibilityState6 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState6, .completed)
let consentState6 = manager.signupState(for: 1)
XCTAssertEqual(consentState6, .completed)
let registrationState6 = manager.signupState(for: 2)
XCTAssertEqual(registrationState6, .current)
let profileState6 = manager.signupState(for: 3)
XCTAssertEqual(profileState6, .locked)
// Once login and consent are verified, then ready for the profile section
manager.sharedUser.isLoginVerified = true
manager.sharedUser.isConsentVerified = true
let eligibilityState7 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState7, .completed)
let consentState7 = manager.signupState(for: 1)
XCTAssertEqual(consentState7, .completed)
let registrationState7 = manager.signupState(for: 2)
XCTAssertEqual(registrationState7, .completed)
let profileState7 = manager.signupState(for: 3)
XCTAssertEqual(profileState7, .current)
manager.sharedUser.onboardingStepIdentifier = "SBAOnboardingCompleted"
let eligibilityState8 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState8, .completed)
let consentState8 = manager.signupState(for: 1)
XCTAssertEqual(consentState8, .completed)
let registrationState8 = manager.signupState(for: 2)
XCTAssertEqual(registrationState8, .completed)
let profileState8 = manager.signupState(for: 3)
XCTAssertEqual(profileState8, .completed)
}
func checkOnboardingSteps(_ sectionType: SBAOnboardingSectionType, _ taskType: SBAOnboardingTaskType) -> [ORKStep]? {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")
let section = manager?.section(for: sectionType)
XCTAssertNotNil(section, "sectionType:\(sectionType) taskType:\(taskType)")
guard section != nil else { return nil}
let steps = manager?.steps(for: section!, with: taskType)
XCTAssertNotNil(steps, "sectionType:\(sectionType) taskType:\(taskType)")
return steps
}
}
class MockOnboardingManager: SBAOnboardingManager {
var mockAppDelegate:MockAppInfoDelegate = MockAppInfoDelegate()
override var sharedAppDelegate: SBAAppInfoDelegate {
get { return mockAppDelegate }
set {}
}
var _hasPasscode = false
override var hasPasscode: Bool {
return _hasPasscode
}
}
|
ca5ddbc9b0dabdf09fa93c0176f99a40
| 39.771481 | 148 | 0.627881 | false | false | false | false |
hovansuit/FoodAndFitness
|
refs/heads/master
|
FoodAndFitness/Controllers/SignUp/Cell/Avatar/AvatarCell.swift
|
mit
|
1
|
//
// AvatarCell.swift
// FoodAndFitness
//
// Created by Mylo Ho on 4/5/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
protocol AvatarCellDelegate: NSObjectProtocol {
func cell(_ cell: AvatarCell, needsPerformAction action: AvatarCell.Action)
}
final class AvatarCell: BaseTableViewCell {
@IBOutlet fileprivate(set) weak var titleLabel: UILabel!
@IBOutlet fileprivate(set) weak var avatarImageView: UIImageView!
weak var delegate: AvatarCellDelegate?
enum Action {
case showActionSheet
}
struct Data {
var title: String
var image: UIImage?
}
var data: Data? {
didSet {
guard let data = data else { return }
titleLabel.text = data.title
if let image = data.image {
avatarImageView.image = image
} else {
avatarImageView.image = #imageLiteral(resourceName: "img_avatar_default")
}
}
}
@IBAction fileprivate func showActionSheet(_ sender: Any) {
delegate?.cell(self, needsPerformAction: .showActionSheet)
}
}
|
d1b2c25ce6492b0adcf870dc04ad5fe6
| 24.111111 | 89 | 0.629204 | false | false | false | false |
22377832/ccyswift
|
refs/heads/master
|
EnumPlayground.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
enum SomeEnumerstion{
}
enum CompassPoint{
case north
case south
case east
case west
}
enum Planet{
case mercury, venus, earth, mars, jupoter
}
var directionToHead: CompassPoint = .east
switch directionToHead {
case .north:
print("")
default:
print("")
}
// 关联值 ..
enum Barcode{
case upa(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.qrCode("asdfasdfasd")
productBarcode = .upa(0, 9, 0, 9)
// 原始值
enum StatusCode: String{
case 你好
case status2 = "ab"
case status3 = "abc"
case status4 = "abcd"
func statusString() -> String{
return self.rawValue
}
}
let status = StatusCode.你好
status.rawValue
// 递归枚举
enum ArithmeticExpression0{
case number(Int)
indirect case addition(ArithmeticExpression0, ArithmeticExpression0)
indirect case nultiplication(ArithmeticExpression0, ArithmeticExpression0)
}
indirect enum ArithmeticExpression{
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// (5 + 4) * 2
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
print(product)
func evaluate(_ expression: ArithmeticExpression) -> Int{
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}
print(evaluate(product))
|
a46ef8d5153e3e5801801e4655c95ec4
| 18.136842 | 86 | 0.69912 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/ListViewIntermediateState.swift
|
gpl-2.0
|
1
|
//
// ListViewIntermediateState.swift
// Telegram
//
// Created by keepcoder on 19/04/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
public enum ListViewCenterScrollPositionOverflow {
case Top
case Bottom
}
public enum ListViewScrollPosition: Equatable {
case Top
case Bottom
case Center(ListViewCenterScrollPositionOverflow)
}
public func ==(lhs: ListViewScrollPosition, rhs: ListViewScrollPosition) -> Bool {
switch lhs {
case .Top:
switch rhs {
case .Top:
return true
default:
return false
}
case .Bottom:
switch rhs {
case .Bottom:
return true
default:
return false
}
case let .Center(lhsOverflow):
switch rhs {
case let .Center(rhsOverflow) where lhsOverflow == rhsOverflow:
return true
default:
return false
}
}
}
public enum ListViewScrollToItemDirectionHint {
case Up
case Down
}
public enum ListViewAnimationCurve {
case Spring(duration: Double)
case Default
}
public struct ListViewScrollToItem {
public let index: Int
public let position: ListViewScrollPosition
public let animated: Bool
public let curve: ListViewAnimationCurve
public let directionHint: ListViewScrollToItemDirectionHint
public init(index: Int, position: ListViewScrollPosition, animated: Bool, curve: ListViewAnimationCurve, directionHint: ListViewScrollToItemDirectionHint) {
self.index = index
self.position = position
self.animated = animated
self.curve = curve
self.directionHint = directionHint
}
}
public enum ListViewItemOperationDirectionHint {
case Up
case Down
}
public struct ListViewDeleteItem {
public let index: Int
public let directionHint: ListViewItemOperationDirectionHint?
public init(index: Int, directionHint: ListViewItemOperationDirectionHint?) {
self.index = index
self.directionHint = directionHint
}
}
public struct ListViewInsertItem {
public let index: Int
public let previousIndex: Int?
public let item: ListViewItem
public let directionHint: ListViewItemOperationDirectionHint?
public let forceAnimateInsertion: Bool
public init(index: Int, previousIndex: Int?, item: ListViewItem, directionHint: ListViewItemOperationDirectionHint?, forceAnimateInsertion: Bool = false) {
self.index = index
self.previousIndex = previousIndex
self.item = item
self.directionHint = directionHint
self.forceAnimateInsertion = forceAnimateInsertion
}
}
public struct ListViewUpdateItem {
public let index: Int
public let previousIndex: Int
public let item: ListViewItem
public let directionHint: ListViewItemOperationDirectionHint?
public init(index: Int, previousIndex: Int, item: ListViewItem, directionHint: ListViewItemOperationDirectionHint?) {
self.index = index
self.previousIndex = previousIndex
self.item = item
self.directionHint = directionHint
}
}
public struct ListViewDeleteAndInsertOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let AnimateInsertion = ListViewDeleteAndInsertOptions(rawValue: 1)
public static let AnimateAlpha = ListViewDeleteAndInsertOptions(rawValue: 2)
public static let LowLatency = ListViewDeleteAndInsertOptions(rawValue: 4)
public static let Synchronous = ListViewDeleteAndInsertOptions(rawValue: 8)
public static let RequestItemInsertionAnimations = ListViewDeleteAndInsertOptions(rawValue: 16)
public static let AnimateTopItemPosition = ListViewDeleteAndInsertOptions(rawValue: 32)
public static let PreferSynchronousDrawing = ListViewDeleteAndInsertOptions(rawValue: 64)
public static let PreferSynchronousResourceLoading = ListViewDeleteAndInsertOptions(rawValue: 128)
}
public struct ListViewItemRange: Equatable {
public let firstIndex: Int
public let lastIndex: Int
}
public func ==(lhs: ListViewItemRange, rhs: ListViewItemRange) -> Bool {
return lhs.firstIndex == rhs.firstIndex && lhs.lastIndex == rhs.lastIndex
}
public struct ListViewDisplayedItemRange: Equatable {
public let loadedRange: ListViewItemRange?
public let visibleRange: ListViewItemRange?
}
public func ==(lhs: ListViewDisplayedItemRange, rhs: ListViewDisplayedItemRange) -> Bool {
return lhs.loadedRange == rhs.loadedRange && lhs.visibleRange == rhs.visibleRange
}
struct IndexRange {
let first: Int
let last: Int
func contains(_ index: Int) -> Bool {
return index >= first && index <= last
}
var empty: Bool {
return first > last
}
}
struct OffsetRanges {
var offsets: [(IndexRange, CGFloat)] = []
mutating func append(_ other: OffsetRanges) {
self.offsets.append(contentsOf: other.offsets)
}
mutating func offset(_ indexRange: IndexRange, offset: CGFloat) {
self.offsets.append((indexRange, offset))
}
func offsetForIndex(_ index: Int) -> CGFloat {
var result: CGFloat = 0.0
for offset in self.offsets {
if offset.0.contains(index) {
result += offset.1
}
}
return result
}
}
func binarySearch(_ inputArr: [Int], searchItem: Int) -> Int? {
var lowerIndex = 0;
var upperIndex = inputArr.count - 1
if lowerIndex > upperIndex {
return nil
}
while (true) {
let currentIndex = (lowerIndex + upperIndex) / 2
if (inputArr[currentIndex] == searchItem) {
return currentIndex
} else if (lowerIndex > upperIndex) {
return nil
} else {
if (inputArr[currentIndex] > searchItem) {
upperIndex = currentIndex - 1
} else {
lowerIndex = currentIndex + 1
}
}
}
}
struct TransactionState {
let visibleSize: CGSize
let items: [ListViewItem]
}
enum ListViewInsertionOffsetDirection {
case Up
case Down
init(_ hint: ListViewItemOperationDirectionHint) {
switch hint {
case .Up:
self = .Up
case .Down:
self = .Down
}
}
func inverted() -> ListViewInsertionOffsetDirection {
switch self {
case .Up:
return .Down
case .Down:
return .Up
}
}
}
struct ListViewInsertionPoint {
let index: Int
let point: CGPoint
let direction: ListViewInsertionOffsetDirection
}
public protocol ListViewItem {
}
public struct ListViewUpdateSizeAndInsets {
public let size: CGSize
public let insets: NSEdgeInsets
public let duration: Double
public let curve: ListViewAnimationCurve
public init(size: CGSize, insets: NSEdgeInsets, duration: Double, curve: ListViewAnimationCurve) {
self.size = size
self.insets = insets
self.duration = duration
self.curve = curve
}
}
|
9f10a8173a97f05023dca71cdbcf5025
| 25.955224 | 160 | 0.665975 | false | false | false | false |
tempestrock/CarPlayer
|
refs/heads/master
|
CarPlayer/TrackListViewController.swift
|
gpl-3.0
|
1
|
//
// TrackListViewController.swift
// CarPlayer
//
// Created by Peter Störmer on 18.12.14.
// Copyright (c) 2014 Tempest Rock Studios. All rights reserved.
//
import Foundation
import UIKit
import MediaPlayer
//
// A view controller to show the list of tracks in a modal view.
//
class TracklistViewController: ModalViewController {
var scrollView: UIScrollView!
var _initialSetup: Bool = true
override func viewDidLoad() {
super.viewDidLoad() // Paints the black background rectangle
// Set notification handler for music changing in the background. The complete track list is re-painted
_controller.setNotificationHandler(self, notificationFunctionName: #selector(TracklistViewController.createTrackList))
createTrackList()
}
//
// Creates the complete track list.
//
func createTrackList() {
// DEBUG print("TrackListViewController.createTrackList()")
// Set some hard-coded limit for the number of tracks to be shown:
let maxNum = MyBasics.TrackListView_MaxNumberOfTracks
// Find out whether we are creating the tracklist for the first time:
_initialSetup = (scrollView == nil)
if _initialSetup {
// This is the initial setup of the scroll view.
scrollView = UIScrollView()
// Create an underlying close button also on the scrollview:
let closeButtonOnScrollView = UIButton(type: UIButtonType.Custom)
var ySizeOfButton = CGFloat(_controller.currentPlaylist().count * yPosOfView * 2 + yPosOfView)
if ySizeOfButton < CGFloat(heightOfView) - 20.0 {
ySizeOfButton = CGFloat(heightOfView) - 20.0
}
closeButtonOnScrollView.addTarget(self,
action: #selector(ModalViewController.closeViewWithoutAction),
forControlEvents: .TouchUpInside)
closeButtonOnScrollView.frame = CGRectMake(CGFloat(xPosOfView) + 10.0, CGFloat(yPosOfView) + 5.0, CGFloat(widthOfView) - 20.0, ySizeOfButton)
scrollView.addSubview(closeButtonOnScrollView)
// Set basic stuff for scrollview:
scrollView.scrollEnabled = true
scrollView.frame = CGRectMake(CGFloat(xPosOfView), CGFloat(yPosOfView) + 5.0,
CGFloat(widthOfView) - 20.0, CGFloat(heightOfView) - 20.0)
}
// Variable to keep the y position of the now playing item:
var yPosOfNowPlayingItem: CGFloat = -1.0
// Fill the scrollview with track names:
var curYPos: Int = 0
var counter: Int = 1
for track in _controller.currentPlaylist() {
// Set the text color depending on whether we show the name of the currently playing item or not:
var labelTextColor: UIColor
if track == _controller.nowPlayingItem() {
labelTextColor = UIColor.darkGrayColor()
yPosOfNowPlayingItem = CGFloat(curYPos)
} else {
labelTextColor = UIColor.whiteColor()
}
// Make a label for the counter:
let number = UILabel()
number.text = counter.description
number.font = MyBasics.fontForMediumText
number.textColor = labelTextColor
number.textAlignment = NSTextAlignment.Right
number.frame = CGRect(x: 0.0, y: CGFloat(curYPos) + 7.5, width: CGFloat(60), height: CGFloat(2 * yPosOfView))
scrollView.addSubview(number)
// Make a small album artwork for an easier identification if an artwork exists:
if (track.artwork != nil) {
let sizeOfArtistImage = CGSize(width: MyBasics.TrackListView_ArtistImage_Width, height: MyBasics.TrackListView_ArtistImage_Height)
let albumCoverImage: UIImageView = UIImageView()
albumCoverImage.image = track.artwork!.imageWithSize(sizeOfArtistImage)
albumCoverImage.frame = CGRectMake(70, CGFloat(curYPos) + 10,
CGFloat(MyBasics.TrackListView_ArtistImage_Width), CGFloat(MyBasics.TrackListView_ArtistImage_Height))
scrollView.addSubview(albumCoverImage)
}
// Make a button for the actual track title:
let button = UIButtonWithFeatures(type: UIButtonType.Custom)
button.setTitle(track.title!, forState: .Normal)
button.titleLabel!.font = MyBasics.fontForMediumText
button.setTitleColor(labelTextColor, forState: UIControlState.Normal)
button.titleLabel!.textAlignment = NSTextAlignment.Left
button.frame = CGRect(x: 110, y: curYPos, width: widthOfView, height: heightOfView) // width and height are just dummies due to following "sizeToFit"
button.sizeToFit()
button.addTarget(self, action: #selector(TracklistViewController.trackNameTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
button.setMediaItem(track)
scrollView.addSubview(button)
// Increase y position:
curYPos += 2 * yPosOfView
counter += 1
if counter > maxNum {
break
}
}
if _initialSetup {
scrollView.contentSize = CGSizeMake(CGFloat(widthOfView) - 20.0, CGFloat(curYPos + yPosOfView));
scrollView.contentOffset = CGPoint(x: 0, y: 0)
}
view.addSubview(scrollView)
// Tweak the y-position of the currently playing item in order to find a nice looking position:
tweakYPosOfNowPlayingItem(curYPos, scrollView: scrollView, yPosOfNowPlayingItem: &yPosOfNowPlayingItem)
// Force jumping to the new y position into a different runloop.
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
self.jumpToPosition(yPosOfNowPlayingItem)
}
}
//
// Tweaks the y-position of the currently playing item in order to find a nice looking position.
//
func tweakYPosOfNowPlayingItem(totalHeightOfScrollView: Int, scrollView: UIScrollView, inout yPosOfNowPlayingItem: CGFloat) {
let minVal: CGFloat = 80.0
let maxVal: CGFloat = scrollView.contentSize.height - CGFloat(self.heightOfView) + CGFloat(self.yPosOfView / 2)
// DEBUG print("yPosOfNowPlayingItem: \(yPosOfNowPlayingItem), maxVal: \(maxVal)")
if totalHeightOfScrollView < self.heightOfView {
// The list is smaller than the screen height. => Set the scroll position to the top:
// DEBUG print("list is smaller than screen height")
yPosOfNowPlayingItem = 0
return
}
if yPosOfNowPlayingItem < minVal {
// This track is among the first ones or not on the list (if it is -1). => Move to the top:
yPosOfNowPlayingItem = 0
// DEBUG print("track is one of the first tracks => moving yPos to the top")
return
}
yPosOfNowPlayingItem -= minVal
// DEBUG print("track is in mid range => moving yPos up by \(minVal) to \(yPosOfNowPlayingItem)")
if yPosOfNowPlayingItem >= maxVal {
// DEBUG print("yPos too high -> setting yPos to \(maxVal)")
yPosOfNowPlayingItem = maxVal
}
}
//
// Jumps the scroll view to the position of the currently playing track.
//
func jumpToPosition(yPosOfNowPlayingItem: CGFloat) {
UIView.jumpSpringyToPosition(scrollView, pointToJumpTo: CGPoint(x: 0.0, y: yPosOfNowPlayingItem))
}
//
// This function is called whenever a track name has been tapped on.
// The chosen track is found out, the music player is switched to that track, and the modal view closes.
//
func trackNameTapped(sender: UIButtonWithFeatures) {
// var trackName: String = sender.mediaItem().title!
// DEBUG print("New track title: \"\(trackName)\"")
// Set the chosen track:
_controller.setTrack(sender.mediaItem())
// Close this view:
// dismissViewControllerAnimated(true, completion: nil) // Feature: We do not close the view! :)
}
}
|
d9c0b64f28f7ce3e75f4dbdce5fe4411
| 37.781395 | 162 | 0.638402 | false | false | false | false |
coodly/ios-gambrinus
|
refs/heads/main
|
Packages/Sources/KioskCore/Network/PullPostMappingsOperation.swift
|
apache-2.0
|
1
|
/*
* Copyright 2018 Coodly LLC
*
* 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 CloudKit
import CoreDataPersistence
import Foundation
import Puff
import PuffSerialization
internal struct CloudPost: RemoteRecord {
var parent: CKRecord.ID?
var recordData: Data?
var recordName: String?
static var recordType: String {
return "Post"
}
var identifier: String?
var rateBeers: [String]?
var untappd: [NSNumber]?
var modificationDate: Date?
mutating func loadFields(from record: CKRecord) -> Bool {
identifier = record["identifier"] as? String
rateBeers = record["rateBeers"] as? [String]
untappd = record["untappd"] as? [NSNumber]
modificationDate = record.modificationDate
return true
}
}
internal class PullPostMappingsOperation: CloudKitRequest<CloudPost>, GambrinusContainerConsumer, PersistenceConsumer {
var gambrinusContainer: CKContainer! {
didSet {
container = gambrinusContainer
}
}
var persistence: Persistence!
override func performRequest() {
Log.debug("Pull mapping updates")
persistence.performInBackground() {
context in
let lastKnownTime = context.lastKnownMappingTime
Log.debug("Pull mappings after \(lastKnownTime)")
let sort = NSSortDescriptor(key: "modificationDate", ascending: true)
let timePredicate = NSPredicate(format: "modificationDate >= %@", lastKnownTime as NSDate)
self.fetch(predicate: timePredicate, sort: [sort], inDatabase: .public)
}
}
override func handle(result: CloudResult<CloudPost>, completion: @escaping () -> ()) {
let save: ContextClosure = {
context in
context.createMappings(from: result.records)
guard let maxDate = result.records.compactMap({ $0.modificationDate }).max() else {
return
}
Log.debug("Mark mappings max time to \(maxDate)")
context.lastKnownMappingTime = maxDate
}
persistence.performInBackground(task: save, completion: completion)
}
}
|
01d57b1c6a3e87aa875cbc7c3af92bb7
| 31.505882 | 119 | 0.64857 | false | false | false | false |
2794129697/-----mx
|
refs/heads/master
|
CoolXuePlayer/ViewController.swift
|
lgpl-3.0
|
1
|
//
// ViewController.swift
// CoolXuePlayer
//
// Created by lion-mac on 15/5/29.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate {
@IBOutlet weak var bigScrollView: UIScrollView!
@IBOutlet weak var channelTableView: UITableView!
@IBOutlet weak var topscrollview: UIScrollView!
var channelList:Array<Channel> = []
func getChannelData(){
var channel_url = "http://www.icoolxue.com/album/recommend/100"
var url = NSURL(string: channel_url)
var request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
println("responseerror=\(error)")
var httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode == 200 {
var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary
//println(bdict)
var c_array = bdict["data"] as! NSArray
if c_array.count > 0 {
for dict in c_array{
var channel = Channel(dictChannel: dict as! NSDictionary)
self.channelList.append(channel)
var uv = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
var imgview = UIImageView()
var imgurl:NSURL = NSURL(string: "")!
if channel.defaultCover != nil {
imgurl = NSURL(string:channel.defaultCover)!
}else if channel.cover != nil {
imgurl = NSURL(string:channel.cover)!
}
uv.addSubview(imgview)
imgview.sd_setImageWithURL(imgurl)
self.topscrollview.addSubview(uv)
//self.topscrollview.insertSubview(uv, atIndex: 0)
}
self.topscrollview.contentSize = CGSize(width: 2000, height: 100)
self.channelTableView.reloadData()
}
}
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.isKindOfClass(UITableView){
println("tableview move")
channelTableView.scrollEnabled = false;
}else{
println("scrollview move")
}
}
override func viewDidLoad() {
super.viewDidLoad()
getChannelData()
self.bigScrollView.contentSize=CGSizeMake(320, 1264);
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("numberOfRowsInSection=\(section)")
return self.channelList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("channelCell", forIndexPath: indexPath) as! UITableViewCell
var channel = self.channelList[indexPath.row]
if channel.name == nil {
return cell
}
cell.textLabel?.text = channel.name
var imgurl:NSURL = NSURL(string: "")!
if channel.defaultCover != nil {
imgurl = NSURL(string:channel.defaultCover)!
}else if channel.cover != nil {
imgurl = NSURL(string:channel.cover)!
}
println("imgurl=\(imgurl)")
cell.imageView?.sd_setImageWithURL(imgurl, placeholderImage: UIImage(named: "default_hoder_170x100.jpg"), options: SDWebImageOptions.ContinueInBackground, progress: { (a:Int, b:Int) -> Void in
println("image pross=\(a/b)")
}, completed: { (image:UIImage!, error:NSError!, cacheType:SDImageCacheType, imgurl:NSURL!) -> Void in
println("cached finished")
})
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
308f4ba62e2c6e843ef53c7791cc421b
| 42.219048 | 200 | 0.578669 | false | false | false | false |
LocationKit/Vacation-Tracker-Swift
|
refs/heads/master
|
Vacation-Tracker-Swift/VTTabBarViewController.swift
|
mit
|
2
|
//
// VTTabBarViewController.swift
// Vacation-Tracker-Swift
//
// Created by Spencer Atkin on 7/29/15.
// Copyright (c) 2015 SocialRadar. All rights reserved.
//
import Foundation
import UIKit
class VTTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
super.loadView()
self.tabBar.tintColor = UIColor(red: 0.97, green: 0.33, blue: 0.1, alpha: 1)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !NSUserDefaults.standardUserDefaults().boolForKey("HasLaunchedOnce") {
VTTabBarViewController.showWelcome(self)
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasLaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
static func showWelcome(sender: UIViewController) {
// Welcome page
var welcomePage = OnboardingContentViewController(title: "Welcome!", body: "Thank you for downloading VacationTracker.", image: nil, buttonText: nil, action: nil)
welcomePage.titleTextColor = UIColor(red: 0.97, green: 0.33, blue: 0.1, alpha: 1)
welcomePage.underTitlePadding = 185
// First info page
var firstPage = OnboardingContentViewController(title: "Introduction", body: "VacationTracker automatically saves the places you visit during your vacations so they can easily be viewed later.", image: nil, buttonText: nil, action: nil)
firstPage.underTitlePadding = 150
// Second info page
var secondPage = OnboardingContentViewController(title: "Features", body: "Visits can be shown on the map or viewed in the list view. When viewing a visit, you can add a rating and comments.", image: nil, buttonText: nil, action: nil)
secondPage.underTitlePadding = 150
// Third info page
var thirdPage = OnboardingContentViewController(title: "Controls", body: "You can use the search button to discover places around you, and the pin button creates a visit at your current location.", image: nil, buttonText: "Get Started!") { () -> Void in
sender.dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().statusBarHidden = false
}
thirdPage.underTitlePadding = 150
thirdPage.buttonTextColor = UIColor(red: 0.97, green: 0.33, blue: 0.1, alpha: 1)
// Main onboarding vc
var onboardingVC = OnboardingViewController(backgroundImage: UIImage(named: "info-background"), contents: [welcomePage, firstPage, secondPage, thirdPage])
// Configures appearance
onboardingVC.topPadding = 10
onboardingVC.bottomPadding = 10
onboardingVC.shouldFadeTransitions = true
// Configures page control
onboardingVC.pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
onboardingVC.pageControl.backgroundColor = UIColor.clearColor()
onboardingVC.pageControl.opaque = false
// Allows info to be skipped
onboardingVC.allowSkipping = true
onboardingVC.skipHandler = { () -> Void in
sender.dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().statusBarHidden = true
}
sender.presentViewController(onboardingVC, animated: true, completion: nil)
UIApplication.sharedApplication().statusBarHidden = true
}
}
|
d9a5e4766e17a9deb3a633729d0326e3
| 45.894737 | 261 | 0.681729 | false | false | false | false |
jakub-tucek/fit-checker-2.0
|
refs/heads/master
|
fit-checker/controller/SettingsViewController.swift
|
mit
|
1
|
//
// SettingsViewController.swift
// fit-checker
//
// Created by Josef Dolezal on 20/01/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
/// User settings view controller.
class SettingsViewController: UIViewController {
/// Shared operations queue
private let operationQueue = OperationQueue()
/// Database context manager
private let contextManager: ContextManager
//MARK: - Initializers
init(contextManager: ContextManager) {
self.contextManager = contextManager
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Logic
/// Logout button
private let logoutButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(tr(.logout), for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
/// Run logout procedure
func logout() {
let logoutOperation = LogoutOperation(contextManager: contextManager)
operationQueue.addOperation(logoutOperation)
}
//MARK: - Private methods
/// Configure view and subviews
private func configureView() {
view.addSubview(logoutButton)
view.backgroundColor = .white
logoutButton.addTarget(self, action: #selector(logout),
for: .touchUpInside)
logoutButton.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
logoutButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
logoutButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),
logoutButton.widthAnchor.constraint(equalToConstant: 150),
logoutButton.heightAnchor.constraint(equalToConstant: 22)
]
constraints.forEach({ $0.isActive = true })
}
}
|
50a0ec145070ab0575d743593b9c5fca
| 25.306667 | 79 | 0.65484 | false | false | false | false |
lyft/SwiftLint
|
refs/heads/master
|
Source/SwiftLintFramework/Models/Correction.swift
|
mit
|
1
|
public struct Correction: Equatable {
public let ruleDescription: RuleDescription
public let location: Location
public var consoleDescription: String {
return "\(location) Corrected \(ruleDescription.name)"
}
}
// MARK: Equatable
public func == (lhs: Correction, rhs: Correction) -> Bool {
return lhs.ruleDescription == rhs.ruleDescription &&
lhs.location == rhs.location
}
|
c33018f0a324b353d20737d12d33802d
| 26.533333 | 62 | 0.694915 | false | false | false | false |
finngaida/wwdc
|
refs/heads/master
|
2016/Finn Gaida/AppBoxWidget.swift
|
gpl-2.0
|
1
|
//
// AppBoxWidget.swift
// Finn Gaida
//
// Created by Finn Gaida on 24.04.16.
// Copyright © 2016 Finn Gaida. All rights reserved.
//
import UIKit
import GradientView
class AppBoxWidget: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.masksToBounds = true
self.layer.cornerRadius = frame.height / 20
let gradientView = GradientView(frame: CGRectMake(0, 0, frame.width, frame.height))
gradientView.colors = [UIColor(red: 229/255, green: 57/255, blue: 53/255, alpha: 1), UIColor(red: 255/255, green: 179/255, blue: 0/255, alpha: 1)]
self.addSubview(gradientView)
let confetti = SAConfettiView(frame: gradientView.frame)
confetti.startConfetti()
self.layer.addSublayer(confetti.layer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
308d5e99566105e4e8e2adcd29ebbce3
| 27.147059 | 154 | 0.636364 | false | false | false | false |
ArnavChawla/InteliChat
|
refs/heads/master
|
CodedayProject/EulaViewController.swift
|
mit
|
1
|
import UIKit
import FirebaseAuth
import FirebaseDatabase
class EulaViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Disagree(_ sender: Any) {
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "hello")as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
}
@IBAction func agree(_ sender: Any) {
if x == true
{
let user = FIRAuth.auth()!.currentUser
let newUser = FIRDatabase.database().reference().child("Users").child(user!.uid)
newUser.setValue(["dislayName": "\(user!.displayName!)", "id": "\(user!.uid)", "url": "\(user!.photoURL!)", "Agreed": "true", "blocked by" : "nil"])
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "yo")as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
}
else
{
FIRAuth.auth()?.createUser(withEmail: EmailString, password: PASSWORD, completion: { (user, error) in
if error != nil{
print(error?.localizedDescription)
}
else
{
isNew = true
print("userLoggedIn")
FIRAuth.auth()?.signIn(withEmail: EmailString, password: PASSWORD, completion: { (user, error) in
if error != nil{
print(error?.localizedDescription)
}
else
{
print(user?.uid)
}
})
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "eula") as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
ne = true
}
})
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "pls")as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
2ab7e66cf4147948759538fa472f2248
| 36.532544 | 160 | 0.49125 | false | false | false | false |
swizzlr/Either
|
refs/heads/master
|
Either/EitherType.swift
|
mit
|
1
|
// Copyright (c) 2014 Rob Rix. All rights reserved.
/// A type representing an alternative of one of two types.
///
/// By convention, and where applicable, `Left` is used to indicate failure, while `Right` is to indicate success. (Mnemonic: “right is right,” i.e. “right” is a synonym for “correct.”)
///
/// Otherwise it is implied that `Left` and `Right` are effectively unordered.
public protocol EitherType {
typealias Left
typealias Right
/// Constructs a `Left` instance.
class func left(value: Left) -> Self
/// Constructs a `Right` instance.
class func right(value: Right) -> Self
/// Returns the result of applying `f` to `Left` values, or `g` to `Right` values.
func either<Result>(f: Left -> Result, _ g: Right -> Result) -> Result
}
// MARK: API
/// Equality (tho not `Equatable`) over `EitherType` where `Left` & `Right` : `Equatable`.
public func == <E: EitherType where E.Left: Equatable, E.Right: Equatable> (lhs: E, rhs: E) -> Bool {
return lhs.either({ $0 == rhs.either(id, const(nil)) }, { $0 == rhs.either(const(nil), id) })
}
/// Inequality over `EitherType` where `Left` & `Right` : `Equatable`.
public func != <E: EitherType where E.Left: Equatable, E.Right: Equatable> (lhs: E, rhs: E) -> Bool {
return !(lhs == rhs)
}
// MARK: Imports
import Prelude
|
087cbbc4f25f864d9e036bbbf70a4f51
| 32.307692 | 185 | 0.665897 | false | false | false | false |
X140Yu/Lemon
|
refs/heads/master
|
Lemon/Library/GitHub API/User.swift
|
gpl-3.0
|
1
|
import Foundation
import ObjectMapper
enum UserType {
case User
case Organization
}
extension UserType {
init(typeString: String) {
if typeString == "Organization" {
self = .Organization
// } else if typeString == "User" {
// self = .User
} else {
self = .User
}
}
}
class User: Mappable {
var avatarUrl : String?
var bio : String?
var blog : String?
var company : String?
var createdAt : String?
var email : String?
var eventsUrl : String?
var followers : Int = 0
var followersUrl : String?
var following : Int = 0
var followingUrl : String?
var gistsUrl : String?
var gravatarId : String?
var hireable : Bool?
var htmlUrl : String?
var id : Int?
var location : String?
var login : String?
var name : String?
var organizationsUrl : String?
var publicGists : Int = 0
var publicRepos : Int = 0
var receivedEventsUrl : String?
var reposUrl : String?
var siteAdmin : Bool?
var starredUrl : String?
var subscriptionsUrl : String?
var type : UserType = .User
var updatedAt : String?
var url : String?
public init(){}
public required init?(map: Map) {}
public func mapping(map: Map)
{
avatarUrl <- map["avatar_url"]
bio <- map["bio"]
blog <- map["blog"]
company <- map["company"]
createdAt <- map["created_at"]
email <- map["email"]
eventsUrl <- map["events_url"]
followers <- map["followers"]
followersUrl <- map["followers_url"]
following <- map["following"]
followingUrl <- map["following_url"]
gistsUrl <- map["gists_url"]
gravatarId <- map["gravatar_id"]
hireable <- map["hireable"]
htmlUrl <- map["html_url"]
id <- map["id"]
location <- map["location"]
login <- map["login"]
name <- map["name"]
organizationsUrl <- map["organizations_url"]
publicGists <- map["public_gists"]
publicRepos <- map["public_repos"]
receivedEventsUrl <- map["received_events_url"]
reposUrl <- map["repos_url"]
siteAdmin <- map["site_admin"]
starredUrl <- map["starred_url"]
subscriptionsUrl <- map["subscriptions_url"]
if let typeString = map["type"].currentValue as? String {
type = UserType(typeString: typeString)
}
// type <- map["type"]
updatedAt <- map["updated_at"]
url <- map["url"]
}
}
extension User: CustomStringConvertible {
var description: String {
return "User: `\(login ?? "")` `\(bio ?? "")` `\(blog ?? "")` `\(company ?? "")`"
}
}
|
d249e87b47e23c146f21aa8fe4ee10aa
| 24.171717 | 85 | 0.615169 | false | false | false | false |
takeo-asai/math-puzzle
|
refs/heads/master
|
problems/22.swift
|
mit
|
1
|
var memo: [Int: Int] = Dictionary()
func partition(n: Int) -> Int {
if n%2 != 0 {
return 0
} else if n == 0 {
return 1
}
var count = 0
for k in 1 ... n-1 {
let x = partition(k-1)
let y = partition(n-k-1)
count += x * y
memo[k-1] = x
memo[n-k-1] = y
}
return count
}
let n = 16
let p = partition(n)
print(p)
|
d2ec9171f4fd011cc62d981adf2868b9
| 14 | 35 | 0.539394 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.