repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
flagoworld/romp
|
Romp/Shared/GameViewController.swift
|
1
|
1300
|
//
// GameViewController.swift
// Romp
//
// Created by Ryan Layne on 2/1/17.
// Copyright © 2017 Ryan Layne. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameViewController: ViewController, EventSubscriber {
let game: Game = Game()
required init?(coder: NSCoder) {
super.init(coder: coder)
game.eventCenter.subscribe(self);
}
override func viewDidLoad() {
super.viewDidLoad()
// Present the scene
let skView = self.view as! SKView
skView.ignoresSiblingOrder = true
skView.showsFPS = true
skView.showsNodeCount = true
// For now, start up in editor mode
game.eventCenter.send(SceneEvent(MainMenuScene.self))
}
func handleEvent(_ event: Event) {
if let sceneEvent = event as? SceneEvent {
self.view.nextResponder = self
let skView = self.view as! SKView
let scene = sceneEvent.sceneClass.init(game: game)
scene.size = CGSize(width: 1366.0, height: 1024.0)
scene.scaleMode = .aspectFill;
skView.presentScene(scene)
}
}
}
|
mit
|
7c0451cf03b48fcffbcba1460c856ac2
| 21.016949 | 62 | 0.547344 | 4.811111 | false | false | false | false |
stripe/stripe-ios
|
Example/UI Examples/UI Examples/AUBECSDebitFormViewController.swift
|
1
|
1496
|
//
// AUBECSDebitFormViewController.swift
// UI Examples
//
// Created by Cameron Sabol on 3/16/20.
// Copyright © 2020 Stripe. All rights reserved.
//
import Stripe
import UIKit
class AUBECSDebitFormViewController: UIViewController {
let becsFormView = STPAUBECSDebitFormView(companyName: "Great Company Inc.")
var theme = STPTheme.defaultTheme
override func viewDidLoad() {
super.viewDidLoad()
title = "BECS Debit Form"
view.backgroundColor = UIColor.white
view.addSubview(becsFormView)
edgesForExtendedLayout = []
view.backgroundColor = theme.primaryBackgroundColor
becsFormView.formTextColor = theme.primaryForegroundColor
becsFormView.formPlaceholderColor = theme.secondaryForegroundColor
becsFormView.formTextErrorColor = theme.errorColor
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done, target: self, action: #selector(done))
navigationController?.navigationBar.stp_theme = theme
becsFormView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
becsFormView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
becsFormView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
becsFormView.topAnchor.constraint(equalTo: view.topAnchor, constant: 15),
])
}
@objc func done() {
dismiss(animated: true, completion: nil)
}
}
|
mit
|
a848571cc72e23b3114d94f9cce4c2c5
| 34.595238 | 85 | 0.711706 | 4.901639 | false | false | false | false |
ArthurGuibert/Knitstagram
|
Knitstagram/CaptureSession.swift
|
1
|
2064
|
//
// CaptureSession.swift
// Knitstagram
//
// Created by Arthur Guibert on 04/01/2017.
// Copyright © 2017 Arthur Guibert. All rights reserved.
//
import UIKit
import GLKit
import AVFoundation
class CaptureSession {
var session: AVCaptureSession!
var textureCache: CVOpenGLESTextureCache? = nil
func setup(context: EAGLContext, useFrontCamera: Bool, outputDelegate: AVCaptureVideoDataOutputSampleBufferDelegate) -> Bool {
let result = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, nil, context, nil, &textureCache)
guard result == kCVReturnSuccess else {
print("Could not create texture cache")
return false
}
session = AVCaptureSession()
session.beginConfiguration()
session.sessionPreset = AVCaptureSessionPreset640x480
let videoDevice = AVCaptureDevice.defaultDevice(withDeviceType: AVCaptureDeviceType.builtInWideAngleCamera,
mediaType: AVMediaTypeVideo,
position: useFrontCamera ? AVCaptureDevicePosition.front : AVCaptureDevicePosition.back)
guard videoDevice != nil else {
print("Could not get video device")
return false
}
let input = try? AVCaptureDeviceInput(device: videoDevice)
guard input != nil else {
print("Could not initialize video input")
return false
}
session.addInput(input)
let output = AVCaptureVideoDataOutput()
output.alwaysDiscardsLateVideoFrames = true
output.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)]
output.setSampleBufferDelegate(outputDelegate, queue: DispatchQueue.main)
session.addOutput(output)
session.commitConfiguration()
session.startRunning()
return true
}
}
|
mit
|
a209a9002695a179538715e02741c370
| 33.966102 | 145 | 0.628696 | 5.997093 | false | false | false | false |
zslzhappy/JNPlayer2GitHub
|
JNPlayerKit/JNPlayerKit/JNPlayerView.swift
|
1
|
20186
|
//
// JNPlayerView.swift
// JNPlayerKit
//
// Created by mac on 16/10/12.
// Copyright © 2016年 Magugi. All rights reserved.
//
// 新版本
// 1.0.7
import UIKit
import AVFoundation
public typealias JNPlayerItem = (URL:String, title:String?)
public protocol JNPlayerViewDelegate: class{
// 当前正在播放的视频, 该方法会在加载视频时执行
func playerView(player:JNPlayerView, playingItem:JNPlayerItem, index:Int)
// 播放完成的视频, 该方法会在视频播放完成时执行
func playerView(player:JNPlayerView, playEndItem:JNPlayerItem)
// 返回按钮点击回调
func playerViewBackAction(player:JNPlayerView)
// 播放失败
func playerView(player:JNPlayerView, playingItem:JNPlayerItem, error:NSError)
/// 是否播放item
///
/// - Parameters:
/// - player: 播放器
/// - willPlayItem: 将要播放的item
/// - Returns: true OR false
func playerViewWillPlayItem(player:JNPlayerView, willPlayItem:JNPlayerItem) -> Bool
}
private protocol JNPlayerDelegate: class {
func jnPlayerStatusChanged(_ status:JNPlayerStatus)
func jnPlayerTimeChanged(_ currentTime: TimeInterval, totalTime:TimeInterval)
func jnPlayerLoadedChanged(_ loadedTime: TimeInterval, totalTime: TimeInterval)
}
public enum JNPlayerStatus {
case Play
case Pause
case PlayEnd
case Failed
case Unknown
case ReadyToPlay
}
public class JNPlayerView: UIView {
public var backAction:(() -> Void)?
fileprivate var player:JNPlayer = JNPlayer()
public var status:JNPlayerStatus = .Pause{
didSet{
self.playerControl.playerStatus = status
}
}
public weak var delegate:JNPlayerViewDelegate? = nil
public var autoPlay:Bool = true
fileprivate var playerControl:JNPlayerControlView = JNPlayerControlView()
public var playingIndex:Int{
get{
guard self.playerItems != nil && self.playingItem != nil else {
return 0
}
return self.playerItems?.index(where: { (element) -> Bool in
return element.URL == playingItem?.URL
}) ?? 0
}
}
fileprivate var playingItem:JNPlayerItem? = nil{
didSet{
guard playingItem != nil else{return}
self.player.url = URL(string: playingItem!.URL)
self.playerControl.title = playingItem?.title
self.delegate?.playerView(player: self, playingItem: playingItem!, index: playingIndex)
//self.delegate?.playerView(self, playingItem: playingItem!, index: self.playingIndex)
}
}
fileprivate var playerItems:[JNPlayerItem]? = nil{
didSet{
self.playingItem = playerItems?.first
}
}
override init(frame: CGRect) {
super.init(frame: frame)
NotificationCenter.default.addObserver(self, selector: #selector(self.appWillResignActiveNotification(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
self.setUpUI()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUpUI()
}
fileprivate func setUpUI(){
self.translatesAutoresizingMaskIntoConstraints = false
// Player
self.addSubview(self.player)
self.player.delegate = self
self.addConstraints({[unowned self] in
let left = NSLayoutConstraint(item: self.player, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: self.player, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: self.player, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: self.player, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
return [left, top, right, bottom]
}())
// PlayerControl
self.addSubview(self.playerControl)
self.playerControl.delegate = self
self.addConstraints({[unowned self] in
let left = NSLayoutConstraint(item: self.playerControl, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: self.playerControl, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: self.playerControl, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: self.playerControl, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
return [left, top, right, bottom]
}())
}
func appWillResignActiveNotification(notification:NSNotification){
self.pause()
}
deinit{
NotificationCenter.default.removeObserver(self)
}
}
extension JNPlayerView{
public func play(url:String?, title:String? = nil){
guard url != nil else {
self.player.url = nil
self.playerItems = nil
return
}
self.play(items: [(url!, title)])
}
public func play(items:[JNPlayerItem]){
let tmpItems:[JNPlayerItem] = items.map({ (item) -> JNPlayerItem in
let urlStr = (item.URL as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
return (urlStr!, item.title)
})
self.playerItems = tmpItems
}
public func play(index:Int){
guard index < (self.playerItems?.count ?? 0) && index > 0 else{return}
self.playerControl.showLoading()
self.playingItem = self.playerItems?[index]
}
// 播放下一个
public func playNext(){
self.play(index: self.playingIndex + 1)
}
// 播放上一个
public func playLast(){
self.play(index: self.playingIndex - 1)
}
/// 暂停
public func pause() {
self.player.pause()
self.status = .Pause
}
/// 播放
public func play() {
if self.shouldPlay {
self.player.play()
self.status = .Play
}else{
self.pause()
}
}
var shouldPlay:Bool{
get{
let canPlay = self.delegate?.playerViewWillPlayItem(player: self, willPlayItem: self.playingItem!) ?? true
return canPlay
}
}
}
extension JNPlayerView: JNPlayerControlDelegate{
internal func ct_play(){
self.play()
}
internal func ct_pause() {
self.pause()
}
internal func ct_back() {
if JNTool.deviceIsHorizontal(){
self.changeDeviceOrientation(isHorizontal: false)
}else{
self.player.url = nil
self.backAction?()
self.delegate?.playerViewBackAction(player: self)
}
}
func ct_jnPlayerTimes() -> (total: TimeInterval, current: TimeInterval) {
if let totalTime = self.player.player?.currentItem?.duration, let currentTime = self.player.player?.currentItem?.currentTime(){
if totalTime == currentTime{
self.status = .PlayEnd
}
return (CMTimeGetSeconds(totalTime), CMTimeGetSeconds(currentTime))
}else{
return (0, 0)
}
}
func ct_jnPlayerSeekTime(time: TimeInterval) {
if time.isNaN {
return
}
if self.player.player?.currentItem?.status == AVPlayerItemStatus.readyToPlay {
let draggedTime = CMTimeMake(Int64(time), 1)
self.player.player?.seek(to: draggedTime, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero, completionHandler: { (success) in
})
}
}
func ct_jnPlayerFullScreen(full: Bool) {
if full{
var supportFullScreen:Bool = false
let support = UIApplication.shared.delegate?.application?(UIApplication.shared, supportedInterfaceOrientationsFor: UIApplication.shared.keyWindow)
if (support != nil){
supportFullScreen = support!.contains([.landscapeLeft, .landscapeRight])
}else{
let support = UIApplication.shared.supportedInterfaceOrientations(for: UIApplication.shared.keyWindow)
supportFullScreen = support.contains([.landscapeLeft, .landscapeRight])
}
guard supportFullScreen else {
return
}
self.changeDeviceOrientation(isHorizontal: true)
}else{
self.changeDeviceOrientation(isHorizontal: false)
}
}
func changeDeviceOrientation(isHorizontal: Bool){
if isHorizontal{
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.fade)
UIApplication.shared.setStatusBarOrientation(UIInterfaceOrientation.landscapeRight, animated: false)
}else{
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.fade)
UIApplication.shared.setStatusBarOrientation(UIInterfaceOrientation.portrait, animated: false)
}
}
}
extension JNPlayerView: JNPlayerDelegate{
func jnPlayerStatusChanged(_ status: JNPlayerStatus) {
switch status {
case .Failed:
print("Fail")
case .Unknown:
print("Unknown")
case .Pause, .Play:
print("")
case .ReadyToPlay:
if let second = self.player.player?.currentTime().seconds, second <= 0{
self.playerControl.closeLoading()
if self.autoPlay{
if self.shouldPlay{
self.play()
self.playerControl.isShow = true
}
}
}
case .PlayEnd:
self.status = .PlayEnd
if status == .PlayEnd && self.playingItem != nil{
self.delegate?.playerView(player: self, playEndItem: self.playingItem!)
}
if self.autoPlay{
self.playNext()
}
}
}
fileprivate func jnPlayerTimeChanged(_ currentTime: TimeInterval, totalTime: TimeInterval) {
self.playerControl.playProgress = Float(currentTime / totalTime)
self.playerControl.currentTime = currentTime
self.playerControl.totalTime = totalTime
}
fileprivate func jnPlayerLoadedChanged(_ loadedTime: TimeInterval, totalTime: TimeInterval) {
self.playerControl.bufferProgress = Float(loadedTime / totalTime)
}
}
private class JNPlayer: UIView{
let playerLayer = AVPlayerLayer()
var playerTimeObserverToken:Any?
weak var delegate:JNPlayerDelegate? = nil
var url:URL? = nil{
didSet{
if let _ = url{
self.playerItem = AVPlayerItem(url: url!)
}else{
self.playerItem = nil
}
self.player?.replaceCurrentItem(with: self.playerItem)
}
}
var player:AVPlayer? = nil{
didSet{
self.playerLayer.player = player
let timeScale = CMTimeScale(NSEC_PER_SEC)
let time = CMTime(seconds: 0.5, preferredTimescale: timeScale)
self.playerTimeObserverToken = self.player?.addPeriodicTimeObserver(forInterval: time, queue: DispatchQueue.main, using: {[unowned self] time in
guard self.player?.currentItem != nil else{
return
}
// update Slider and Progress
let currentTime = self.player!.currentItem!.currentTime()
let current = CMTimeGetSeconds(currentTime)
let totalTime = self.player!.currentItem!.duration
let total = CMTimeGetSeconds(totalTime)
if let urlStr = self.url?.absoluteString{
if currentTime == totalTime{
JNCache[urlStr] = nil
}else{
JNCache[urlStr] = currentTime
}
}
self.delegate?.jnPlayerTimeChanged(current, totalTime: total)
})
}
willSet{
if let _ = self.playerTimeObserverToken{
self.player?.removeTimeObserver(self.playerTimeObserverToken!)
}
}
}
let PlayerItemStatusKey = "status"
let PlayerLoadTimeRangeKey = "loadedTimeRanges"
let PlaybackBufferEmptyKey = "playbackBufferEmpty"
let PlaybackBufferLikelyToKeepUpKey = "playbackLikelyToKeepUp"
private var playerItem:AVPlayerItem? = nil{
didSet{
if let _ = playerItem{
playerItem?.addObserver(self, forKeyPath: PlayerItemStatusKey, options: .new, context: nil)
playerItem?.addObserver(self, forKeyPath: PlayerLoadTimeRangeKey, options: .new, context: nil)
playerItem?.addObserver(self, forKeyPath: PlaybackBufferEmptyKey, options: .new, context: nil)
playerItem?.addObserver(self, forKeyPath: PlaybackBufferLikelyToKeepUpKey, options: .new, context: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
self.player = AVPlayer(playerItem: self.playerItem)
}
}
willSet{
playerItem?.removeObserver(self, forKeyPath: PlayerItemStatusKey, context: nil)
playerItem?.removeObserver(self, forKeyPath: PlayerLoadTimeRangeKey, context: nil)
playerItem?.removeObserver(self, forKeyPath: PlaybackBufferEmptyKey, context: nil)
playerItem?.removeObserver(self, forKeyPath: PlaybackBufferLikelyToKeepUpKey, context: nil)
NotificationCenter.default.removeObserver(self)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setUpUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUpUI()
}
private func setUpUI(){
self.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.black
self.layer.addSublayer(playerLayer)
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
}
fileprivate override func layoutSubviews() {
self.playerLayer.frame = self.layer.bounds
}
fileprivate override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let item = object as? AVPlayerItem, item == self.player?.currentItem{
if keyPath == PlayerItemStatusKey{
switch item.status {
case .failed:
self.delegate?.jnPlayerStatusChanged(.Failed)
case .unknown:
self.delegate?.jnPlayerStatusChanged(.Unknown)
case .readyToPlay:
self.delegate?.jnPlayerStatusChanged(.ReadyToPlay)
}
return
}
if keyPath == PlayerLoadTimeRangeKey{
let loadTimeRange = item.loadedTimeRanges
if let timeRangeValue = loadTimeRange.first{
let timeRange = timeRangeValue.timeRangeValue
let start = CMTimeGetSeconds(timeRange.start)
let duration = CMTimeGetSeconds(timeRange.duration)
let loaded = start + duration
let total = CMTimeGetSeconds(item.duration)
self.delegate?.jnPlayerLoadedChanged(loaded, totalTime: total)
}
return
}
if keyPath == PlaybackBufferEmptyKey{
return
}
if keyPath == PlaybackBufferLikelyToKeepUpKey{
return
}
}
}
// private func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutableRawPointer) {
//
// if let item = object as? AVPlayerItem, item == self.player?.currentItem{
// if keyPath == PlayerItemStatusKey{
// switch item.status {
// case .failed:
// self.delegate?.jnPlayerStatusChanged(status: .Failed)
// case .unknown:
// self.delegate?.jnPlayerStatusChanged(status: .Unknown)
// case .readyToPlay:
// self.delegate?.jnPlayerStatusChanged(status: .ReadyToPlay)
// }
// return
// }
//
// if keyPath == PlayerLoadTimeRangeKey{
//
// let loadTimeRange = item.loadedTimeRanges
//
// if let timeRangeValue = loadTimeRange.first{
//
// let timeRange = timeRangeValue.timeRangeValue
//
// let start = CMTimeGetSeconds(timeRange.start)
// let duration = CMTimeGetSeconds(timeRange.duration)
//
// let loaded = start + duration
// let total = CMTimeGetSeconds(item.duration)
//
// self.delegate?.jnPlayerLoadedChanged(loadedTime: loaded, totalTime: total)
// }
//
//
//
// return
// }
//
// if keyPath == PlaybackBufferEmptyKey{
//
// return
// }
//
// if keyPath == PlaybackBufferLikelyToKeepUpKey{
//
// return
// }
//
// }
// }
@objc func playerDidPlayEnd(notification:NSNotification){
if let item = notification.object as? AVPlayerItem, item == self.player?.currentItem{
// 清除播放完视频的时间点
if let urlStr = self.url?.absoluteString{
JNCache[urlStr] = nil
}
self.delegate?.jnPlayerStatusChanged(.PlayEnd)
}
}
deinit {
self.url = nil
self.playerItem = nil
self.player = nil
NotificationCenter.default.removeObserver(self)
}
}
extension JNPlayer{
fileprivate func play(){
if self.player?.currentItem?.duration == self.player?.currentItem?.currentTime(){
self.player?.seek(to: kCMTimeZero)
}
if let urlStr = self.url?.absoluteString{
if let time = JNCache[urlStr]{
self.player?.seek(to: time)
}
}
self.playerLayer.player?.play()
}
fileprivate func pause() {
self.playerLayer.player?.pause()
}
}
|
apache-2.0
|
3129dd5ed1c13c0510a0aed0fa17be69
| 33.713542 | 196 | 0.575194 | 5.122982 | false | false | false | false |
manavgabhawala/swift
|
test/SILGen/objc_dictionary_bridging.swift
|
1
|
6765
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
@objc class Foo : NSObject {
// Bridging dictionary parameters
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
func bridge_Dictionary_param(_ dict: Dictionary<Foo, Foo>) {
// CHECK: bb0([[NSDICT:%[0-9]+]] : $NSDictionary, [[SELF:%[0-9]+]] : $Foo):
// CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
// CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
// CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
// CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}F
// CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
}
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo'
// Bridging dictionary results
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
func bridge_Dictionary_result() -> Dictionary<Foo, Foo> {
// CHECK: bb0([[SELF:%[0-9]+]] : $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: [[DICT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF
// CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]]
// CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]]
// CHECK: destroy_value [[DICT]]
// CHECK: return [[NSDICT]] : $NSDictionary
}
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo'
var property: Dictionary<Foo, Foo> = [:]
// Property getter
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
// CHECK: bb0([[SELF:%[0-9]+]] : $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[GETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfg : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: [[DICT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF
// CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]]
// CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]]
// CHECK: destroy_value [[DICT]]
// CHECK: return [[NSDICT]] : $NSDictionary
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfgTo'
// Property setter
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfsTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
// CHECK: bb0([[NSDICT:%[0-9]+]] : $NSDictionary, [[SELF:%[0-9]+]] : $Foo):
// CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
// CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
// CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
// CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfs : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}fgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}fsTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
@objc var nonVerbatimProperty: Dictionary<String, Int> = [:]
}
func ==(x: Foo, y: Foo) -> Bool { }
|
apache-2.0
|
735c2c9230f3d98fb309dfe074952f38
| 71.634409 | 208 | 0.640118 | 3.374126 | false | false | false | false |
apple/swift
|
validation-test/Sema/OverridesAndOverloads.swift
|
2
|
9899
|
// RUN: %target-typecheck-verify-swift -D ERRORS
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
struct Token1 {}
struct Token2 {}
struct Token3 {}
class C1 {}
class C1x : C1 {}
class C1xx : C1x {}
protocol P1 {}
protocol P1x : P1 {}
struct P1ImplS1 : P1 {}
struct P1xImplS1 : P1x {}
class P1ImplC1x : C1, P1 {}
class P1ImplC1xx {}
class P1xImplC1x : C1, P1x {}
var which = ""
var Overrides = TestSuite("Overrides")
Overrides.test("covariant argument override, non-optional to optional") {
class Base {
func foo(_: C1) { which = "Base.foo(C1)" }
}
class Derived : Base {
override func foo(_: C1?) { which = "Derived.foo(C1?)" }
}
Derived().foo(C1())
expectEqual("Derived.foo(C1?)", which)
Derived().foo(nil as C1?)
expectEqual("Derived.foo(C1?)", which)
}
Overrides.test("covariant argument override, derived class to base class") {
class Base {
func foo(_: C1x) { which = "Base.foo(C1x)" }
}
class Derived : Base {
override func foo(_: C1) { which = "Derived.foo(C1)" }
}
Derived().foo(C1())
expectEqual("Derived.foo(C1)", which)
Derived().foo(C1x())
expectEqual("Derived.foo(C1)", which)
}
Overrides.test("covariant argument override, optional derived class to non-optional base class") {
class Base {
func foo(_: C1x) { which = "Base.foo(C1x)" }
}
class Derived : Base {
override func foo(_: C1?) { which = "Derived.foo(C1?)" }
}
Derived().foo(C1())
expectEqual("Derived.foo(C1?)", which)
Derived().foo(C1x())
expectEqual("Derived.foo(C1?)", which)
Derived().foo(nil)
expectEqual("Derived.foo(C1?)", which)
}
Overrides.test("covariant argument override, protocol to protocol") {
// FIXME: https://github.com/apple/swift/issues/43346
// Covariant overrides don't work with protocols
class Base {
func foo(_: P1x) { which = "Base.foo(P1x)" }
}
class Derived : Base {
/*FIXME: override */ func foo(_: P1) { which = "Derived.foo(P1)" }
}
Derived().foo(P1ImplS1())
expectEqual("Derived.foo(P1)", which)
Derived().foo(P1xImplS1())
expectEqual("Base.foo(P1x)", which)
}
Overrides.test("covariant argument override, struct to protocol") {
// FIXME: https://github.com/apple/swift/issues/43346
// Covariant overrides don't work with protocols
class Base {
func foo(_: P1ImplS1) { which = "Base.foo(P1ImplS1)" }
}
class Derived : Base {
/*FIXME: override */ func foo(_: P1) { which = "Derived.foo(P1)" }
}
// FIXME: https://github.com/apple/swift/issues/43346
Derived().foo(P1ImplS1())
expectEqual("Base.foo(P1ImplS1)", which)
Derived().foo(P1xImplS1())
expectEqual("Derived.foo(P1)", which)
}
Overrides.test("contravariant return type override, optional to non-optional") {
class Base {
func foo() -> C1? { which = "Base.foo() -> C1?"; return C1() }
}
class Derived : Base {
override func foo() -> C1 {
which = "Derived.foo() -> C1"; return C1()
}
}
_ = Derived().foo() as C1
expectEqual("Derived.foo() -> C1", which)
_ = Derived().foo() as C1?
expectEqual("Derived.foo() -> C1", which)
}
Overrides.test("contravariant return type override, base class to derived class") {
class Base {
func foo() -> C1 { which = "Base.foo() -> C1"; return C1() }
}
class Derived : Base {
override func foo() -> C1x {
which = "Derived.foo() -> C1x"; return C1x()
}
}
_ = Derived().foo() as C1
expectEqual("Derived.foo() -> C1x", which)
_ = Derived().foo() as C1x
expectEqual("Derived.foo() -> C1x", which)
}
Overrides.test("contravariant return type override, optional base class to non-optional derived class") {
class Base {
func foo() -> C1? { which = "Base.foo() -> C1?"; return C1() }
}
class Derived : Base {
override func foo() -> C1x {
which = "Derived.foo() -> C1x"; return C1x()
}
}
_ = Derived().foo() as C1
expectEqual("Derived.foo() -> C1x", which)
_ = Derived().foo() as C1x
expectEqual("Derived.foo() -> C1x", which)
}
Overrides.test("contravariant return type override, protocol to protocol") {
// FIXME: https://github.com/apple/swift/issues/43348
// Contravariant overrides on return type don't work with protocols
class Base {
// expected-note@+1 {{found this candidate}}
func foo() -> P1 { which = "Base.foo() -> P1"; return P1ImplS1() }
}
class Derived : Base {
// expected-note@+1 {{found this candidate}}
/*FIXME: override */ func foo() -> P1x {
which = "Derived.foo() -> P1x"; return P1xImplS1()
}
}
#if ERRORS
// FIXME: https://github.com/apple/swift/issues/43348
Derived().foo() as P1 // expected-error {{ambiguous use of 'foo()'}}
expectEqual("Derived.foo() -> P1x", which)
#endif
_ = Derived().foo() as P1x
expectEqual("Derived.foo() -> P1x", which)
}
Overrides.test("contravariant return type override, protocol to struct") {
// FIXME: https://github.com/apple/swift/issues/43348
// Contravariant overrides on return type don't work with protocols
class Base {
// expected-note@+1 {{found this candidate}}
func foo() -> P1 { which = "Base.foo() -> P1"; return P1ImplS1() }
}
class Derived : Base {
// expected-note@+1 {{found this candidate}}
/*FIXME: override */ func foo() -> P1ImplS1 {
which = "Derived.foo() -> P1ImplS1"; return P1ImplS1()
}
}
#if ERRORS
// FIXME: https://github.com/apple/swift/issues/43348
Derived().foo() as P1 // expected-error {{ambiguous use of 'foo()'}}
expectEqual("Derived.foo() -> P1ImplS1", which)
#endif
_ = Derived().foo() as P1ImplS1
expectEqual("Derived.foo() -> P1ImplS1", which)
}
Overrides.test("overrides don't affect overload resolution") {
class Base {
func foo(_: P1) { which = "Base.foo(P1)" }
}
class Derived : Base {
func foo(_: P1x) { which = "Derived.foo(P1x)" }
}
class MoreDerived : Derived {
override func foo(_: P1) { which = "MoreDerived.foo(P1)" }
}
Base().foo(P1ImplS1())
expectEqual("Base.foo(P1)", which)
Derived().foo(P1ImplS1())
expectEqual("Base.foo(P1)", which)
Derived().foo(P1xImplS1())
expectEqual("Derived.foo(P1x)", which)
MoreDerived().foo(P1ImplS1())
expectEqual("MoreDerived.foo(P1)", which)
MoreDerived().foo(P1xImplS1())
expectEqual("Derived.foo(P1x)", which)
}
var Overloads = TestSuite("Overloads")
Overloads.test("perfect match") {
class Base {
func foo(_: C1, _: C1, _: C1) { which = "C1, C1, C1" }
func foo(_: C1, _: C1, _: C1x) { which = "C1, C1, C1x" }
func foo(_: C1, _: C1x, _: C1) { which = "C1, C1x, C1" }
func foo(_: C1, _: C1x, _: C1x) { which = "C1, C1x, C1x" }
func foo(_: C1x, _: C1, _: C1) { which = "C1x, C1, C1" }
func foo(_: C1x, _: C1, _: C1x) { which = "C1x, C1, C1x" }
func foo(_: C1x, _: C1x, _: C1) { which = "C1x, C1x, C1" }
func foo(_: C1x, _: C1x, _: C1x) { which = "C1x, C1x, C1x" }
}
Base().foo(C1(), C1(), C1()); expectEqual("C1, C1, C1", which)
Base().foo(C1(), C1(), C1x()); expectEqual("C1, C1, C1x", which)
Base().foo(C1(), C1x(), C1()); expectEqual("C1, C1x, C1", which)
Base().foo(C1(), C1x(), C1x()); expectEqual("C1, C1x, C1x", which)
Base().foo(C1x(), C1(), C1()); expectEqual("C1x, C1, C1", which)
Base().foo(C1x(), C1(), C1x()); expectEqual("C1x, C1, C1x", which)
Base().foo(C1x(), C1x(), C1()); expectEqual("C1x, C1x, C1", which)
Base().foo(C1x(), C1x(), C1x()); expectEqual("C1x, C1x, C1x", which)
}
Overloads.test("implicit conversion to superclass") {
class Base {
func foo(_: C1) { which = "foo(C1)" }
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(C1x()); expectEqual("foo(C1)", which)
Base().foo(C1xx()); expectEqual("foo(C1)", which)
}
Overloads.test("implicit conversion to protocol existential") {
class Base {
func foo(_: P1) { which = "foo(P1)" }
}
Base().foo(P1ImplS1()); expectEqual("foo(P1)", which)
Base().foo(P1xImplS1()); expectEqual("foo(P1)", which)
}
Overloads.test("implicit conversion to a superclass is better than conversion to an optional") {
class Base {
func foo(_: C1) { which = "foo(C1)" }
func foo(_: C1x?) { which = "foo(C1x?)" }
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(C1x()); expectEqual("foo(C1)", which)
Base().foo(C1xx()); expectEqual("foo(C1)", which)
Base().foo(C1x() as C1x?); expectEqual("foo(C1x?)", which)
Base().foo(C1xx() as C1xx?); expectEqual("foo(C1x?)", which)
}
Overloads.test("implicit conversion to a protocol existential is better than conversion to an optional") {
class Base {
func foo(_: P1) { which = "foo(P1)" }
func foo(_: P1x?) { which = "foo(P1x?)" }
}
Base().foo(P1ImplS1()); expectEqual("foo(P1)", which)
Base().foo(P1xImplS1()); expectEqual("foo(P1)", which)
Base().foo(P1xImplS1() as P1x?); expectEqual("foo(P1x?)", which)
}
Overloads.test("implicit conversion to a superclass is ambiguous with conversion to a protocol existential") {
class Base {
func foo(_: C1) { which = "foo(C1)" } // expected-note {{found this candidate}}
func foo(_: P1) { which = "foo(P1)" } // expected-note {{found this candidate}}
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(P1ImplS1()); expectEqual("foo(P1)", which)
#if ERRORS
Base().foo(P1ImplC1x())
// expected-error @-1 {{ambiguous use of 'foo'}}
#endif
}
Overloads.test("generic methods are worse than non-generic") {
class Base {
func foo(_: C1) { which = "foo(C1)" }
func foo(_: Any) { which = "foo(Any)" }
func foo<T>(_: T) { which = "foo(T)" }
func bar(_: C1) { which = "bar(C1)" }
func bar<T>(_: T) { which = "bar(T)" }
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(Token1()); expectEqual("foo(T)", which)
Base().bar(C1()); expectEqual("bar(C1)", which)
Base().bar(Token1()); expectEqual("bar(T)", which)
}
runAllTests()
|
apache-2.0
|
70b269622412a0858e57cb04606e1131
| 28.029326 | 110 | 0.609557 | 2.961113 | false | true | false | false |
apple/swift
|
test/AutoDiff/SILGen/differentiable_function.swift
|
13
|
8070
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// Test SILGen for `@differentiable` function typed values.
import _Differentiation
//===----------------------------------------------------------------------===//
// Return `@differentiable` function typed values unmodified.
//===----------------------------------------------------------------------===//
@_silgen_name("differentiable")
func differentiable(_ fn: @escaping @differentiable(reverse) (Float) -> Float)
-> @differentiable(reverse) (Float) -> Float {
return fn
}
@_silgen_name("linear")
func linear(_ fn: @escaping @differentiable(_linear) (Float) -> Float)
-> @differentiable(_linear) (Float) -> Float {
return fn
}
@_silgen_name("differentiable_noDerivative")
func differentiable_noDerivative(
_ fn: @escaping @differentiable(reverse) (Float, @noDerivative Float) -> Float
) -> @differentiable(reverse) (Float, @noDerivative Float) -> Float {
return fn
}
@_silgen_name("linear_noDerivative")
func linear_noDerivative(
_ fn: @escaping @differentiable(_linear) (Float, @noDerivative Float) -> Float
) -> @differentiable(_linear) (Float, @noDerivative Float) -> Float {
return fn
}
// CHECK-LABEL: sil hidden [ossa] @differentiable : $@convention(thin) (@guaranteed @differentiable(reverse) @callee_guaranteed (Float) -> Float) -> @owned @differentiable(reverse) @callee_guaranteed (Float) -> Float {
// CHECK: bb0([[FN:%.*]] : @guaranteed $@differentiable(reverse) @callee_guaranteed (Float) -> Float):
// CHECK: [[COPIED_FN:%.*]] = copy_value [[FN]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: return [[COPIED_FN]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: }
// CHECK-LABEL: sil hidden [ossa] @linear : $@convention(thin) (@guaranteed @differentiable(_linear) @callee_guaranteed (Float) -> Float) -> @owned @differentiable(_linear) @callee_guaranteed (Float) -> Float {
// CHECK: bb0([[FN:%.*]] : @guaranteed $@differentiable(_linear) @callee_guaranteed (Float) -> Float):
// CHECK: [[COPIED_FN:%.*]] = copy_value [[FN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: return [[COPIED_FN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: }
// CHECK-LABEL: sil hidden [ossa] @differentiable_noDerivative : $@convention(thin) (@guaranteed @differentiable(reverse) @callee_guaranteed (Float, @noDerivative Float) -> Float) -> @owned @differentiable(reverse) @callee_guaranteed (Float, @noDerivative Float) -> Float {
// CHECK: bb0([[FN:%.*]] : @guaranteed $@differentiable(reverse) @callee_guaranteed (Float, @noDerivative Float) -> Float):
// CHECK: [[COPIED_FN:%.*]] = copy_value [[FN]] : $@differentiable(reverse) @callee_guaranteed (Float, @noDerivative Float) -> Float
// CHECK: return [[COPIED_FN]] : $@differentiable(reverse) @callee_guaranteed (Float, @noDerivative Float) -> Float
// CHECK: }
// CHECK-LABEL: sil hidden [ossa] @linear_noDerivative : $@convention(thin) (@guaranteed @differentiable(_linear) @callee_guaranteed (Float, @noDerivative Float) -> Float) -> @owned @differentiable(_linear) @callee_guaranteed (Float, @noDerivative Float) -> Float {
// CHECK: bb0([[FN:%.*]] : @guaranteed $@differentiable(_linear) @callee_guaranteed (Float, @noDerivative Float) -> Float):
// CHECK: [[COPIED_FN:%.*]] = copy_value [[FN]] : $@differentiable(_linear) @callee_guaranteed (Float, @noDerivative Float) -> Float
// CHECK: return [[COPIED_FN]] : $@differentiable(_linear) @callee_guaranteed (Float, @noDerivative Float) -> Float
// CHECK: }
//===----------------------------------------------------------------------===//
// Closure conversion
//===----------------------------------------------------------------------===//
func thin(x: Float) -> Float { return x }
func myfunction(_ f: @escaping @differentiable(reverse) (Float) -> (Float)) -> (Float) -> Float {
// @differentiable(reverse) functions should be callable.
_ = f(.zero)
return f
}
func myfunction2(_ f: @escaping @differentiable(_linear) (Float) -> (Float)) -> (Float) -> Float {
// @differentiable(_linear) functions should be callable.
_ = f(.zero)
return f
}
var global_f: @differentiable(reverse) (Float) -> Float = {$0}
var global_f_linear: @differentiable(_linear) (Float) -> Float = {$0}
func calls_global_f() {
_ = global_f(10)
// TODO(TF-900, TF-902): Uncomment the following line to test loading a linear function from memory and direct calls to a linear function.
// _ = global_f_linear(10)
}
func apply() {
_ = myfunction(thin)
_ = myfunction2(thin)
}
// CHECK-LABEL: @{{.*}}myfunction{{.*}}
// CHECK: bb0([[DIFF:%.*]] : @guaranteed $@differentiable(reverse) @callee_guaranteed (Float) -> Float):
// CHECK: [[COPIED_DIFF:%.*]] = copy_value [[DIFF]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: [[BORROWED_DIFF:%.*]] = begin_borrow [[COPIED_DIFF]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: apply [[BORROWED_DIFF]]({{%.*}}) : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: end_borrow [[BORROWED_DIFF]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: destroy_value [[COPIED_DIFF]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: [[COPIED_DIFF:%.*]] = copy_value [[DIFF]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: [[BORROWED_DIFF:%.*]] = begin_borrow [[COPIED_DIFF]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: [[BORROWED_ORIG:%.*]] = differentiable_function_extract [original] [[BORROWED_DIFF]] : $@differentiable(reverse) @callee_guaranteed (Float) -> Float
// CHECK: [[COPIED_ORIG:%.*]] = copy_value [[BORROWED_ORIG]] : $@callee_guaranteed (Float) -> Float
// CHECK: return [[COPIED_ORIG]] : $@callee_guaranteed (Float) -> Float
// CHECK-LABEL: @{{.*}}myfunction2{{.*}}
// CHECK: bb0([[LIN:%.*]] : @guaranteed $@differentiable(_linear) @callee_guaranteed (Float) -> Float):
// CHECK: [[COPIED_LIN:%.*]] = copy_value [[LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: [[BORROWED_LIN:%.*]] = begin_borrow [[COPIED_LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: apply [[BORROWED_LIN]]({{%.*}}) : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: end_borrow [[BORROWED_LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: [[COPIED_LIN:%.*]] = copy_value [[LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: [[BORROWED_LIN:%.*]] = begin_borrow [[COPIED_LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: [[BORROWED_ORIG:%.*]] = linear_function_extract [original] [[BORROWED_LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: [[COPIED_ORIG:%.*]] = copy_value [[BORROWED_ORIG]] : $@callee_guaranteed (Float) -> Float
// CHECK: end_borrow [[BORROWED_LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: destroy_value [[COPIED_LIN]] : $@differentiable(_linear) @callee_guaranteed (Float) -> Float
// CHECK: return [[COPIED_ORIG]] : $@callee_guaranteed (Float) -> Float
// CHECK-LABEL: @{{.*}}apply{{.*}}
// CHECK: [[ORIG:%.*]] = function_ref @{{.*}}thin{{.*}} : $@convention(thin) (Float) -> Float
// CHECK-NEXT: [[ORIG_THICK:%.*]] = thin_to_thick_function [[ORIG]] : $@convention(thin) (Float) -> Float to $@callee_guaranteed (Float) -> Float
// CHECK-NEXT: [[DIFFED:%.*]] = differentiable_function [parameters 0] [results 0] [[ORIG_THICK]] : $@callee_guaranteed (Float) -> Float
// CHECK: [[ORIG:%.*]] = function_ref @{{.*}}thin{{.*}} : $@convention(thin) (Float) -> Float
// CHECK-NEXT: [[ORIG_THICK:%.*]] = thin_to_thick_function [[ORIG]] : $@convention(thin) (Float) -> Float to $@callee_guaranteed (Float) -> Float
// CHECK-NEXT: [[LIN:%.*]] = linear_function [parameters 0] [[ORIG_THICK]] : $@callee_guaranteed (Float) -> Float
|
apache-2.0
|
87d67a812efd1ef9a768b8551b6e7f3c
| 62.543307 | 273 | 0.63544 | 3.866794 | false | false | false | false |
yaobanglin/viossvc
|
viossvc/Scenes/User/RegisterViewController.swift
|
2
|
4329
|
//
// RegisterViewController.swift
// viossvc
//
// Created by yaowang on 2016/10/27.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import Foundation
import XCGLogger
class RegisterViewController: BaseLoginViewController {
var registerModel:RegisterModel = RegisterModel();
var childViewControllerData:Bool = true;
@IBOutlet weak var smsButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
private var timer:NSTimer?
private var timeSecond:Int = 0
@IBAction func didActionLogin(sender: AnyObject) {
let navController = navigationController
navController!.popViewControllerAnimated(false);
navController?.pushViewControllerWithIdentifier(MainViewController.className(), animated: false, valuesForKeys: [MainViewController.childViewControllerIdentifierKey:LoginViewController.className()])
}
@IBAction func didActionNext(sender: AnyObject) {
guard textField3.text?.length() <= 0 else {
checkInviteCode()
return
}
pushToNextPage()
}
func checkInviteCode() {
AppAPIHelper.userAPI().checkInviteCode(textField1.text!, inviteCode: (textField3.text?.change32To10())!, complete: { (response) in
self.checkWithResult(response as! Int)
}, error: errorBlockFunc())
}
func checkWithResult(result:Int) {
if result == 0 {
showErrorWithStatus(AppConst.Text.CheckInviteCodeErr);
} else if result == 1 {
registerModel.invitation_phone_num = textField3.text!.change32To10()
pushToNextPage()
}
}
func pushToNextPage() {
MobClick.event(AppConst.Event.sign_next)
if checkTextFieldEmpty([textField1,textField2]) && checkPhoneFormat(textField1.text!) {
let verify_code:Int? = Int(textField2.text!.trim());
if( verify_code != nil ) {
registerModel.verify_code = verify_code!;
self.stopTimer()
navigationController?.pushViewControllerWithIdentifier(MainViewController.className(), animated: true, valuesForKeys: [MainViewController.childViewControllerIdentifierKey:PasswordViewController.className(),MainViewController.childViewControllerDataKey:registerModel])
}
else {
showErrorWithStatus(AppConst.Text.VerifyCodeErr );
}
}
}
@IBAction func didActionSMS(sender: AnyObject) {
if checkTextFieldEmpty([textField1]) && checkPhoneFormat(textField1.text!) {
registerModel.phone_num = textField1.text
registerModel.smsType = childViewControllerData ? .Register : .Login
AppAPIHelper.userAPI().smsVerify(registerModel.smsType, phone: registerModel.phone_num, complete: { [weak self] (model) in
self?.didSMSVerifyComplete(model as? SMSVerifyRetModel)
}, error: { [weak self ] (error) in
self?.showErrorWithStatus(AppConst.Text.SMSVerifyCodeErr)
self?.stopTimer()
})
smsButton.enabled = false;
setupTimer();
}
}
func didSMSVerifyComplete(model:SMSVerifyRetModel?) {
registerModel.timestamp = model!.timestamp
registerModel.token = model?.token
nextButton.enabled = true;
nextButton.backgroundColor = AppConst.Color.CR
}
//MARK: --计时器
func setupTimer() {
timeSecond = 60
updateSMSButtonTitle()
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(didActionTimer), userInfo: nil, repeats: true)
}
func stopTimer() {
timeSecond = 0;
smsButton.enabled = true
smsButton.setTitle(AppConst.Text.ReSMSVerifyCode, forState: .Normal)
timer?.invalidate()
timer = nil
}
func updateSMSButtonTitle() {
let showInfo = String(format: "%ds", timeSecond)
smsButton.setTitle(showInfo, forState: .Disabled)
}
func didActionTimer() {
timeSecond -= 1
if timeSecond > 0 {
updateSMSButtonTitle()
} else {
stopTimer()
}
}
deinit {
XCGLogger.debug("deinit \(self)")
}
}
|
apache-2.0
|
7246f341f7990712651910a17df2e362
| 34.702479 | 283 | 0.633796 | 4.925884 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/majority-element.swift
|
2
|
623
|
/**
* https://leetcode.com/problems/majority-element/
*
*
*/
// Date: Tue Sep 22 09:28:10 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(n)
/// - Space: O(1)
func majorityElement(_ nums: [Int]) -> Int {
var result = nums[0]
var count = 1
for index in stride(from: 1, to: nums.count, by: 1) {
if count == 0 {
result = nums[index]
count = 1
} else if result == nums[index] {
count += 1
} else {
count -= 1
}
}
return result
}
}
|
mit
|
9270bd4398e005362a3cc5e2a611d40f
| 23 | 61 | 0.425361 | 3.79878 | false | false | false | false |
Quick/Quick
|
Sources/Quick/SubclassDetection.swift
|
2
|
1730
|
#if canImport(Darwin)
import Foundation
/// Determines if a class is a subclass of another by looping over the superclasses of the given class.
/// Apparently, `isSubclass(of:)` uses a different method to check this, which can cause exceptions to
/// be raised under certain circumstances when used in conjuction with `objc_getClassList`.
/// See https://github.com/Quick/Quick/issues/1155, and https://openradar.appspot.com/FB9854851.
func isClass(_ klass: AnyClass, aSubclassOf targetClass: AnyClass) -> Bool {
var superclass: AnyClass? = klass
while superclass != nil {
superclass = class_getSuperclass(superclass)
if superclass == targetClass { return true }
}
return false
}
#endif
/// Retrieves the current list of all known classes that are a subtype of the desired type.
/// This uses `objc_copyClassList` instead of `objc_getClassList` because the get function
/// is subject to race conditions and buffer overflow issues. The copy function handles all of that for us.
/// Note: On non-Apple platforms, this will return an empty array.
func allSubclasses<T: AnyObject>(ofType targetType: T.Type) -> [T.Type] {
#if canImport(Darwin)
// See https://developer.apple.com/forums/thread/700770.
var classesCount: UInt32 = 0
guard let classList = objc_copyClassList(&classesCount) else { return [] }
defer { free(UnsafeMutableRawPointer(classList)) }
let classes = UnsafeBufferPointer(start: classList, count: Int(classesCount))
guard classesCount > 0 else {
return []
}
return classes.filter { isClass($0, aSubclassOf: targetType) }
// swiftlint:disable:next force_cast
.map { $0 as! T.Type }
#else
return []
#endif
}
|
apache-2.0
|
380faa0bedf3b61b9ab6a26cc04674de
| 41.195122 | 107 | 0.709827 | 4.128878 | false | false | false | false |
mozilla/focus
|
Blockzilla/SearchSettingsViewController.swift
|
4
|
9603
|
/* 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 Foundation
import Telemetry
protocol SearchSettingsViewControllerDelegate: class {
func searchSettingsViewController(_ searchSettingsViewController: SearchSettingsViewController, didSelectEngine engine: SearchEngine)
}
class SearchSettingsViewController: UITableViewController {
weak var delegate: SearchSettingsViewControllerDelegate?
private let searchEngineManager: SearchEngineManager
private var isInEditMode = false
init(searchEngineManager: SearchEngineManager) {
self.searchEngineManager = searchEngineManager
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = UIConstants.strings.settingsSearchLabel
view.backgroundColor = UIConstants.colors.background
tableView.separatorColor = UIConstants.colors.settingsSeparator
tableView.selectRow(at: IndexPath(row: 0, section: 1), animated: false, scrollPosition: .none)
tableView.tableFooterView = UIView()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: UIConstants.strings.Edit, style: .plain, target: self, action: #selector(SearchSettingsViewController.toggleEditing))
navigationItem.rightBarButtonItem?.accessibilityIdentifier = "edit"
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = UITableViewCell()
cell.textLabel?.text = " "
cell.backgroundColor = UIConstants.colors.background
if section == 0 {
let label = SmartLabel()
label.text = UIConstants.strings.InstalledSearchEngines
label.textColor = UIConstants.colors.tableSectionHeader
label.font = UIConstants.fonts.tableSectionHeader
cell.contentView.addSubview(label)
label.snp.makeConstraints { make in
make.leading.trailing.equalTo(cell.textLabel!)
make.centerY.equalTo(cell.textLabel!).offset(3)
}
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
if isInEditMode {
return 1
} else {
return 2
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfEngines = searchEngineManager.engines.count
if isInEditMode { // NOTE: This is false when a user is swiping to delete but tableView.isEditing is true
return numberOfEngines
}
switch section {
case 1:
return 1
default:
return numberOfEngines + 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let engines = searchEngineManager.engines
if indexPath.item == engines.count {
let cell = UITableViewCell(style: .default, reuseIdentifier: "addSearchEngine")
cell.textLabel?.text = UIConstants.strings.AddSearchEngineButton
cell.textLabel?.textColor = UIConstants.colors.settingsTextLabel
cell.backgroundColor = UIConstants.colors.cellBackground
cell.accessibilityIdentifier = "addSearchEngine"
cell.selectedBackgroundView = getBackgroundView()
return cell
} else if indexPath.section == 1 && indexPath.row == 0 {
let cell = UITableViewCell(style: .default, reuseIdentifier: "restoreDefaultEngines")
cell.textLabel?.text = UIConstants.strings.RestoreSearchEnginesLabel
cell.textLabel?.font = UIFont.systemFont(ofSize: 17)
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
cell.backgroundColor = UIConstants.colors.cellBackground
cell.accessibilityIdentifier = "restoreDefaults"
cell.selectedBackgroundView = getBackgroundView()
if searchEngineManager.hasDisabledDefaultEngine() {
cell.textLabel?.textColor = UIConstants.colors.settingsTextLabel
cell.selectionStyle = .default
cell.isUserInteractionEnabled = true
} else {
cell.textLabel?.textColor = UIConstants.colors.settingsDisabled
cell.selectionStyle = .none
cell.isUserInteractionEnabled = false
}
return cell
} else {
let engine = engines[indexPath.item]
let cell = UITableViewCell(style: .default, reuseIdentifier: engine.image == nil ? "empty-image-cell" : nil)
cell.textLabel?.text = engine.name
cell.textLabel?.textColor = UIConstants.colors.settingsTextLabel
cell.imageView?.image = engine.image?.createScaled(size: CGSize(width: 24, height: 24))
cell.selectedBackgroundView = getBackgroundView()
cell.backgroundColor = UIConstants.colors.cellBackground
cell.accessibilityIdentifier = engine.name
if tableView.isEditing {
cell.contentView.snp.makeConstraints({ (make) in
make.leading.equalTo(0)
})
cell.imageView?.snp.makeConstraints({ (make) in
make.leading.equalTo(50)
make.centerY.equalTo(cell)
})
if let imageView = cell.imageView {
cell.textLabel?.snp.makeConstraints({ (make) in
make.centerY.equalTo(imageView.snp.centerY)
make.leading.equalTo(imageView.snp.trailing).offset(10)
})
}
}
if engine === searchEngineManager.activeEngine {
cell.accessoryType = .checkmark
if tableView.isEditing {
cell.textLabel?.textColor = UIConstants.colors.settingsDisabled.withAlphaComponent(0.5)
cell.separatorInset = UIEdgeInsets(top: 0, left: 93, bottom: 0, right: 0)
cell.tintColor = tableView.tintColor.withAlphaComponent(0.5)
cell.imageView?.alpha = 0.5
}
}
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.row == searchEngineManager.engines.count+1 ? 44*2 : 44
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let engines = searchEngineManager.engines
if indexPath.item == engines.count {
// Add search engine tapped
let vc = AddSearchEngineViewController(delegate: self, searchEngineManager: searchEngineManager)
navigationController?.pushViewController(vc, animated: true)
} else if indexPath.section == 1 {
// Restore default engines tapped
if searchEngineManager.hasDisabledDefaultEngine() {
searchEngineManager.restoreDisabledDefaultEngines()
tableView.reloadData()
}
} else {
let engine = engines[indexPath.item]
searchEngineManager.activeEngine = engine
Telemetry.default.configuration.defaultSearchEngineProvider = engine.name
_ = navigationController?.popViewController(animated: true)
delegate?.searchSettingsViewController(self, didSelectEngine: engine)
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
let engines = searchEngineManager.engines
if indexPath.row >= engines.count {
// Can not edit the add engine or restore default rows
return false
}
let engine = engines[indexPath.row]
return engine != searchEngineManager.activeEngine
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
searchEngineManager.removeEngine(engine: searchEngineManager.engines[indexPath.row])
tableView.reloadData()
}
}
@objc func toggleEditing() {
isInEditMode = !isInEditMode
navigationItem.rightBarButtonItem?.title = tableView.isEditing ? UIConstants.strings.Edit : UIConstants.strings.Done
tableView.setEditing(!tableView.isEditing, animated: true)
tableView.reloadData()
navigationItem.hidesBackButton = tableView.isEditing
}
private func getBackgroundView(bgColor: UIColor = UIConstants.colors.cellSelected) -> UIView {
let view = UIView()
view.backgroundColor = bgColor
return view
}
}
extension SearchSettingsViewController: AddSearchEngineDelegate {
func addSearchEngineViewController(_ addSearchEngineViewController: AddSearchEngineViewController, name: String, searchTemplate: String) {
let engine = searchEngineManager.addEngine(name: name, template: searchTemplate)
tableView.reloadData()
delegate?.searchSettingsViewController(self, didSelectEngine: engine)
}
}
|
mpl-2.0
|
7dae59a22a6721939f722d45dd8f40c9
| 41.49115 | 184 | 0.654587 | 5.685613 | false | false | false | false |
mokemokechicken/DeepTransition
|
Pod/Classes/Model/TransitionPath.swift
|
1
|
12729
|
//
// ViewControllerPath.swift
// DeepTransitionSample
//
// Created by 森下 健 on 2014/12/15.
// Copyright (c) 2014年 Yumemi. All rights reserved.
//
import Foundation
@objc public class TransitionPath : Printable, Equatable {
public let path: String
public private(set) var componentList = [TransitionPathComponent]()
public var depth : Int { return componentList.count }
public init(path: String) {
self.path = path
self.componentList = splitPath(path)
}
private init(componentList: [TransitionPathComponent]) {
self.path = TransitionPath.componentListToPath(componentList)
self.componentList = componentList
}
public func appendPath(#component: TransitionPathComponent) -> TransitionPath {
return TransitionPath(componentList: self.componentList + [component])
}
public func appendPath(#list: [TransitionPathComponent]) -> TransitionPath {
return TransitionPath(componentList: self.componentList + componentList)
}
public func appendPath(path: TransitionPath) -> TransitionPath {
return TransitionPath(componentList: self.componentList + path.componentList)
}
public func up(depth: Int = 1) -> TransitionPath? {
if depth <= self.depth {
var list = [TransitionPathComponent]()
for i in 0..<self.depth-depth {
list.append(self.componentList[i])
}
return TransitionPath(componentList: list)
}
return nil
}
public func relativeTo(path: String, basePath: TransitionPath? = nil) -> TransitionPath {
var base = basePath ?? self
if path.hasPrefix("^") {
return TransitionPath(path: path.substringFromIndex(advance(path.startIndex, 1)))
}
// 何個戻るか? と そういうのを除去したPath文字列
let info = howManyUp(path)
var comList = [TransitionPathComponent]()
for var i=0; i < (base.componentList.count-info.upCount); i++ {
comList.append(base.componentList[i])
}
let retPath = TransitionPath(componentList: comList).path + info.remainPath
return TransitionPath(path: retPath)
}
private func howManyUp(path: String, upCount: Int = 0, lastSegue: String? = nil) -> (upCount: Int, remainPath: String) {
if path.isEmpty {
return (upCount: upCount, remainPath: "")
}
if path.hasPrefix("..") {
var segue:String?
var cutCount = 2
if path.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 2 {
segue = String(path[advance(path.startIndex, 2)])
cutCount = 3
}
return howManyUp(path.substringFromIndex(advance(path.startIndex, cutCount)), upCount: upCount+1, lastSegue: segue)
} else {
var retPath = (lastSegue ?? "") + path
switch String(retPath[retPath.startIndex]) {
case "/", "#", "!":
break
default:
retPath = "/" + retPath
}
return (upCount: upCount, remainPath: retPath)
}
}
public class func diff(#path1: TransitionPath, path2: TransitionPath) -> (common: TransitionPath, d1: [TransitionPathComponent], d2: [TransitionPathComponent]) {
let minDepth = min(path1.depth, path2.depth)
var common = [TransitionPathComponent]()
var d1 = [TransitionPathComponent]()
var d2 = [TransitionPathComponent]()
var diffRootIndex = 0
for i in 0..<minDepth {
if path1.componentList[i] == path2.componentList[i] {
common.append(path1.componentList[i])
diffRootIndex = i+1
} else {
break
}
}
for i1 in diffRootIndex..<path1.depth {
d1.append(path1.componentList[i1])
}
for i2 in diffRootIndex..<path2.depth {
d2.append(path2.componentList[i2])
}
return (TransitionPath(componentList: common), d1, d2)
}
public class func componentListToPath(componentList: [TransitionPathComponent]) -> String {
if componentList.isEmpty {
return ""
}
var str = ""
for c in componentList {
str += c.description
}
return str
}
// MARK: Enums
public enum SegueKind : String {
case Show = "/"
case Modal = "!"
case Tab = "#"
}
public enum ContainerKind : String, Printable {
case None = "None"
case Navigation = "Navigation"
public var description : String {
return "ContainerKind.\(self.rawValue)"
}
}
// MARK: Printable
public var description: String { return path }
// MARK: Private
// Private なんだけど UnitTest用にPublic
public func splitPath(path: String) -> [TransitionPathComponent] {
var pathList = [TransitionPathComponent]()
let tokens = tokenize(path)
var alreadyHasNavigationController = false
var ownContainer = ContainerKind.None
var segue: SegueKind?
var name: String? = nil
var paramKey: String?
var params = [String:String]()
func addPath() {
if let id = name {
if let seg = segue {
pathList.append(TransitionPathComponent(identifier: id, segueKind: seg, params:params, ownRootContainer: ownContainer))
if !alreadyHasNavigationController && ownContainer == .Navigation {
alreadyHasNavigationController = true
}
name = nil
params = [String:String]()
segue = nil
ownContainer = .None
}
}
}
for token in tokens {
switch token {
case .KindShow:
addPath()
switch (alreadyHasNavigationController, segue) {
case (_, .Some(.Modal)): // "!/"
ownContainer = .Navigation
case (_, .Some(.Tab)): // "#/"
ownContainer = .Navigation
case (false, .None):
ownContainer = .Navigation
segue = .Show
default:
segue = .Show
}
case .KindModal:
addPath()
segue = .Modal
alreadyHasNavigationController = false
case .KindTab:
addPath()
segue = .Tab
case .VC(let n):
name = n
segue = segue ?? .Show
case .ParamKey(let k): paramKey = k
case .ParamValue(let v): if let k = paramKey { params[k] = v }
case .End:
addPath()
break
}
}
return pathList
}
private enum State {
case Normal, ParamKey, ParamValue
}
public enum Token : Equatable, Printable {
case VC(String)
case ParamKey(String)
case ParamValue(String)
case KindShow, KindModal, KindTab
case End
public var description: String {
switch self {
case .VC(let s):
return "VC(\(s))"
case .ParamKey(let s):
return "Key(\(s))"
case .ParamValue(let s):
return "Val(\(s))"
case .KindShow:
return "/"
case .KindModal:
return "!"
case .KindTab:
return "#"
case .End:
return "$"
}
}
}
public func tokenize(path: String) -> [Token] {
var tokens = [Token]()
var tstr: String?
let end = "\u{0}"
var state: State = .Normal
func addToken(ch: String) {
tstr = (tstr ?? "") + ch
}
for chara in (path+end) {
let ch = String(chara)
switch state {
case .Normal:
switch ch {
case SegueKind.Show.rawValue:
if let t = tstr { tokens.append(Token.VC(t)); tstr = nil }
tokens.append(Token.KindShow)
case SegueKind.Modal.rawValue:
if let t = tstr { tokens.append(Token.VC(t)); tstr = nil }
tokens.append(Token.KindModal)
case SegueKind.Tab.rawValue:
if let t = tstr { tokens.append(Token.VC(t)); tstr = nil }
tokens.append(Token.KindTab)
case end:
if let t = tstr { tokens.append(Token.VC(t)); tstr = nil }
tokens.append(.End)
break
case "(":
if let t = tstr { tokens.append(Token.VC(t)); tstr = nil }
state = .ParamKey
default:
addToken(ch)
}
case .ParamKey:
switch ch {
case "=":
if let t = tstr { tokens.append(Token.ParamKey(t)); tstr = nil }
state = .ParamValue
default:
addToken(ch)
}
case .ParamValue:
switch ch {
case ",":
if let t = tstr { tokens.append(Token.ParamValue(t)); tstr = nil }
state = .ParamKey
case ")":
if let t = tstr { tokens.append(Token.ParamValue(t)); tstr = nil }
state = .Normal
default:
addToken(ch)
}
}
}
return tokens
}
}
public func ==(lhs: TransitionPath, rhs: TransitionPath) -> Bool {
if lhs.depth == rhs.depth {
for i in 0..<lhs.depth {
if lhs.componentList[i] != rhs.componentList[i] {
return false
}
}
return true
}
return false
}
public func ==(lhs: TransitionPath.Token, rhs: TransitionPath.Token) -> Bool {
switch (lhs, rhs) {
case (.VC(let a), .VC(let b)) where a == b: return true
case (.ParamKey(let a), .ParamKey(let b)) where a == b: return true
case (.ParamValue(let a), .ParamValue(let b)) where a == b: return true
case (.KindShow, .KindShow): return true
case (.KindModal, .KindModal): return true
case (.KindTab, .KindTab): return true
case (.End, .End): return true
default:
return false
}
}
public func ==(lhs: TransitionPathComponent, rhs: TransitionPathComponent) -> Bool {
return lhs.isEqual(rhs)
}
@objc public class TransitionPathComponent : Printable, Equatable {
public let segueKind: TransitionPath.SegueKind
public let identifier: String
public var params: [String:String]
public let ownRootContainer: TransitionPath.ContainerKind
public init(identifier: String, segueKind: TransitionPath.SegueKind, params:[String:String], ownRootContainer: TransitionPath.ContainerKind) {
self.identifier = identifier
self.segueKind = segueKind
self.params = params
self.ownRootContainer = ownRootContainer
}
public func isEqual(other: TransitionPathComponent) -> Bool {
return
self.identifier == other.identifier &&
self.segueKind == other.segueKind &&
self.ownRootContainer == other.ownRootContainer &&
self.paramString() == other.paramString()
}
public var description: String {
var pstr = paramString()
if !pstr.isEmpty {
pstr = "(\(pstr))"
}
var ret = ""
switch ownRootContainer {
case .None:
ret = "\(segueKind.rawValue)\(identifier)\(pstr)"
case .Navigation:
if segueKind != TransitionPath.SegueKind.Show {
ret = "\(segueKind.rawValue)/\(identifier)\(pstr)"
} else {
ret = "\(segueKind.rawValue)\(identifier)\(pstr)"
}
}
return ret
}
public func paramString() -> String {
var kvList = [String]()
for k in params.keys.array.sorted(<) {
kvList.append("\(k)=\(params[k]!)")
}
return join(",", kvList)
}
}
|
mit
|
28e98ab0c8eabfaf70fac18b25f02c01
| 31.816062 | 165 | 0.518039 | 4.669001 | false | false | false | false |
jeffreybergier/WaterMe2
|
WaterMe/WaterMe/Miscellaneous/UserActivityConfigurator.swift
|
1
|
7407
|
//
// UserActivityConfigurator.swift
// WaterMe
//
// Created by Jeffrey Bergier on 9/29/18.
// Copyright © 2018 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import Foundation
protocol UserActivityConfiguratorProtocol: NSUserActivityDelegate {
var currentReminderAndVessel: (() -> ReminderAndVesselValue?)? { get set }
var currentReminderVessel: (() -> ReminderVesselValue?)? { get set }
var requiresMainThreadExecution: Bool { get set }
}
class UserActivityConfigurator: NSObject, UserActivityConfiguratorProtocol {
var currentReminderAndVessel: (() -> ReminderAndVesselValue?)?
var currentReminderVessel: (() -> ReminderVesselValue?)?
var requiresMainThreadExecution = true
}
extension UserActivityConfigurator: NSUserActivityDelegate {
func userActivityWillSave(_ activity: NSUserActivity) {
let workItem = {
guard let kind = RawUserActivity(rawValue: activity.activityType) else {
assertionFailure("Unsupported User Activity Type")
return
}
let reminderVessel = self.currentReminderVessel?()
let reminder = self.currentReminderAndVessel?()
switch kind {
case .editReminderVessel:
self.updateEditReminderVessel(activity: activity,
reminderVessel: reminderVessel)
case .editReminder:
self.updateEditReminder(activity: activity, value: reminder)
case .viewReminder:
self.updateViewReminder(activity: activity, value: reminder)
case .performReminder:
self.updatePerformReminder(activity: activity,
value: reminder)
case .indexedItem:
assertionFailure("Cannot update the data on a CoreSpotlight activity")
}
}
// check if we're NOT on the main thread
// if we are just, execute the workitem
guard DispatchQueue.isMain == false else {
workItem()
return
}
// check if the user of this class needs
// the execution to happen on the main thread
// if they don't, just execute the work item
guard self.requiresMainThreadExecution else {
workItem()
return
}
// now hop on the main thread and execute
DispatchQueue.main.sync() {
workItem()
return
}
}
}
private extension UserActivityConfigurator {
private func updateEditReminderVessel(activity: NSUserActivity, reminderVessel: ReminderVesselValue?) {
assert(activity.activityType == RawUserActivity.editReminderVessel.rawValue)
guard let reminderVessel = reminderVessel else {
log.error("Unable to save Activity: Missing Reminder Vessel")
activity.waterme_isEligibleForNeededServices = false
return
}
activity.waterme_isEligibleForNeededServices = true
let uuid = reminderVessel.uuid
let title = LocalizedString.editVesselTitle(fromVesselName: reminderVessel.name)
let phrase = LocalizedString.randomLocalizedPhrase
let description = LocalizedString.editReminderVesselDescription
activity.update(uuid: uuid,
title: title,
phrase: phrase,
description: description,
thumbnailData: reminderVessel.imageData)
}
private func updateViewReminder(activity: NSUserActivity, value: ReminderAndVesselValue?) {
assert(activity.activityType == RawUserActivity.viewReminder.rawValue)
guard let value = value else {
log.error("Unable to save Activity: Missing Reminder")
activity.waterme_isEligibleForNeededServices = false
return
}
activity.waterme_isEligibleForNeededServices = true
let uuid = value.reminder.uuid
let title = LocalizedString.viewReminderTitle(for: value.reminder.kind,
andVesselName: value.reminderVessel.name)
let phrase = LocalizedString.randomLocalizedPhrase
let description = LocalizedString.viewReminderDescription
activity.update(uuid: uuid,
title: title,
phrase: phrase,
description: description,
thumbnailData: value.reminderVessel.imageData)
}
private func updatePerformReminder(activity: NSUserActivity,
value: ReminderAndVesselValue?)
{
assert(activity.activityType == RawUserActivity.performReminder.rawValue)
guard let value = value else {
log.error("Unable to save Activity: Missing Reminder")
activity.waterme_isEligibleForNeededServices = false
return
}
activity.waterme_isEligibleForNeededServices = true
let uuid = value.reminder.uuid
let title = LocalizedString.performReminderTitle(for: value.reminder.kind,
andVesselName: value.reminderVessel.name)
let description = LocalizedString.performReminderDescription
let phrase = LocalizedString.randomLocalizedPhrase
activity.update(uuid: uuid,
title: title,
phrase: phrase,
description: description,
thumbnailData: value.reminderVessel.imageData)
}
private func updateEditReminder(activity: NSUserActivity,
value: ReminderAndVesselValue?)
{
assert(activity.activityType == RawUserActivity.editReminder.rawValue)
guard let value = value else {
log.error("Unable to save Activity: Missing Reminder")
activity.waterme_isEligibleForNeededServices = false
return
}
activity.waterme_isEligibleForNeededServices = true
let uuid = value.reminder.uuid
let title = LocalizedString.editReminderTitle(for: value.reminder.kind,
andVesselName: value.reminderVessel.name)
let phrase = LocalizedString.randomLocalizedPhrase
let description = LocalizedString.editReminderDescription
activity.update(uuid: uuid,
title: title,
phrase: phrase,
description: description,
thumbnailData: value.reminderVessel.imageData)
}
}
|
gpl-3.0
|
f973057017834887aa1bca46e37b9b15
| 39.917127 | 107 | 0.625979 | 5.51452 | false | false | false | false |
indragiek/MarkdownTextView
|
Example/ViewController.swift
|
1
|
1587
|
//
// ViewController.swift
// MarkdownTextView
//
// Created by Indragie on 4/27/15.
// Copyright (c) 2015 Indragie Karunaratne. All rights reserved.
//
import UIKit
import MarkdownTextView
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let attributes = MarkdownAttributes()
let textStorage = MarkdownTextStorage(attributes: attributes)
do {
textStorage.addHighlighter(try LinkHighlighter())
} catch let error {
fatalError("Error initializing LinkHighlighter: \(error)")
}
textStorage.addHighlighter(MarkdownStrikethroughHighlighter())
textStorage.addHighlighter(MarkdownSuperscriptHighlighter())
if let codeBlockAttributes = attributes.codeBlockAttributes {
textStorage.addHighlighter(MarkdownFencedCodeHighlighter(attributes: codeBlockAttributes))
}
let textView = MarkdownTextView(frame: CGRectZero, textStorage: textStorage)
textView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(textView)
let views = ["textView": textView]
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[textView]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[textView]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
NSLayoutConstraint.activateConstraints(constraints)
}
}
|
mit
|
bc223ec8daa626b821703255037b1644
| 40.763158 | 171 | 0.705734 | 5.62766 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures
|
Data Structures/BinarySearchTree.playground/Contents.swift
|
1
|
7689
|
//Binary search tree with some search capabilities
public class BinarySearchTree<T:Comparable>{
private(set) public var value:T
private(set) public var parent:BinarySearchTree?
private(set) public var left:BinarySearchTree?
private(set) public var right:BinarySearchTree?
init(value:T){
self.value = value
}
func isRoot() -> Bool{
return self.parent == nil
}
func isLeaf() -> Bool{
return self.right == nil && self.left == nil
}
func hasLeftChild() -> Bool{
return self.left != nil
}
func hasRightChild() -> Bool{
return self.right != nil
}
func hasBothChildren()-> Bool{
return self.hasLeftChild() && self.hasRightChild()
}
func isLeftChild() -> Bool{
return self.parent?.left === self
}
func isRightChild() -> Bool{
return self.parent?.right === self
}
func count() -> Int{
return (self.left?.count() ?? 0) + 1 + (self.right?.count() ?? 0)
}
convenience init(array:[T]){
precondition(array.count > 0)
self.init(value:array[0])
for a in array.dropFirst(){
insert(a)
}
}
func insert(_ newValue:T){
if newValue < self.value{
if let left = self.left{
left.insert(newValue)
}else{
left = BinarySearchTree(value:newValue)
left?.parent = self
}
}else{
if let right = self.right{
right.insert(newValue)
}else{
right = BinarySearchTree(value:newValue)
right?.parent = self
}
}
}
func search(searchValue:T) -> BinarySearchTree?{
if searchValue < self.value{
return left?.search(searchValue:searchValue)
}else if searchValue > self.value{
return right?.search(searchValue:searchValue)
}else{
return self
}
}
func reconnectWithParent(node:BinarySearchTree?){
if let parent = self.parent{
if isLeftChild(){
parent.left = node
}else{
parent.right = node
}
node?.parent = parent
}
}
func minimum() -> BinarySearchTree{
var node = self
while let next = node.left{
node = next
}
return node
}
func maximum() -> BinarySearchTree{
var node = self
while let next = node.right{
node = next
}
return node
}
func deleteNode() -> BinarySearchTree?{
let replacement:BinarySearchTree?
if let right = self.right{
replacement = right.minimum()
}else if let left = self.left{
replacement = left.maximum()
}else{
replacement = nil
}
replacement?.deleteNode()
replacement?.left = left
replacement?.right = right
left?.parent = replacement
right?.parent = replacement
self.reconnectWithParent(node:replacement)
parent = nil
left = nil
right = nil
return replacement
}
func getHeight() -> Int{
if isLeaf(){
return 0
}else{
return 1 + max(left?.getHeight() ?? 0, right?.getHeight() ?? 0)
}
}
func getDepth() -> Int{
if isRoot(){
return 0
}else{
var edges = 0
var node = self
while let parent = node.parent{
node = parent
edges += 1
}
return edges
}
}
func predecessor() -> BinarySearchTree<T>?{
if let left = self.left{
return left.maximum()
}else{
let originalValue = self.value
var node = self
while let parent = node.parent{
if parent.value < originalValue {return parent}
node = parent
}
return nil
}
}
func successor() -> BinarySearchTree<T>?{
if let right = self.right{
return right.minimum()
}else{
let originalValue = self.value
var node = self
while let parent = node.parent{
if parent.value > originalValue {return parent}
node = parent
}
return nil
}
}
}
extension BinarySearchTree: CustomStringConvertible{
public var description:String{
var s = ""
if let left = self.left{
s += "\(left.description) <- "
}
s += "\(value)"
if let right = self.right{
s += " -> \(right.description)"
}
return s
}
}
public class Stack{
var top:Node?
init(_ top:BinarySearchTree<Int>){
let newNode = Node(top)
self.top = newNode
}
func push(_ node:BinarySearchTree<Int>){
let newNode = Node(node)
if top != nil{
newNode.setNext(top!)
top = newNode
}else{
top = newNode
}
}
func pop() -> BinarySearchTree<Int>?{
guard let node = top else { return nil }
top = node.next
return node.value
}
}
public class FIFOQueue{
var front:Node?
var end:Node?
init(_ node:BinarySearchTree<Int>){
let newNode = Node(node)
self.front = newNode
self.end = newNode
}
func enqueue(_ node:BinarySearchTree<Int>){
let newNode = Node(node)
if let end = self.end{
end.setNext(newNode)
self.end = newNode
}else{
front = newNode
end = newNode
}
}
func dequeue() -> BinarySearchTree<Int>?{
if let front = self.front{
let returnVal = front.value
self.front = front.next
if self.front == nil {
self.end = nil
}
return returnVal
}else{
return nil
}
}
}
public class Node{
private(set) public var value:BinarySearchTree<Int>?
private(set) public var next:Node?
init(_ value:BinarySearchTree<Int>) {
self.value = value
}
func setNext(_ node:Node){
self.next = node
}
}
func depthFirstSearch(_ value:Int, firstNode:BinarySearchTree<Int>){
let stack = Stack(firstNode)
while let current = stack.pop() {
let currentVal = current.value
if value == currentVal{
break
}else{
if let right = current.right{
stack.push(right)
}
if let left = current.left{
stack.push(left)
}
print(currentVal)
}
}
}
func breathFirstSearch(_ value:Int, firstNode:BinarySearchTree<Int>){
let queue = FIFOQueue(firstNode)
while let current = queue.dequeue() {
print(current.value)
if current.value == value{
print("found value")
break
}
if let left = current.left{
queue.enqueue(left)
}
if let right = current.right{
queue.enqueue(right)
}
}
}
|
mit
|
05cfa71ea3b2b655289969e3cbf685cc
| 21.41691 | 75 | 0.481467 | 4.835849 | false | false | false | false |
DianQK/Flix
|
Flix/Provider/CollectionViewEvent.swift
|
1
|
1345
|
//
// CollectionViewEvent.swift
// Flix
//
// Created by DianQK on 2018/4/17.
// Copyright © 2018 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
public class CollectionViewEvent<Provider: CollectionViewMultiNodeProvider> {
public typealias Value = Provider.Value
public typealias EventValue = (collectionView: UICollectionView, indexPath: IndexPath, value: Value)
public var selectedEvent: ControlEvent<()> { return ControlEvent(events: self._itemSelected.map { _ in }) }
public var modelSelected: ControlEvent<Value> { return ControlEvent(events: self.itemSelected.map { $0.value }) }
public var itemSelected: ControlEvent<EventValue> { return ControlEvent(events: self._itemSelected) }
private(set) lazy var _itemSelected = PublishSubject<EventValue>()
public var modelDeselected: ControlEvent<Value> { return ControlEvent(events: self.itemDeselected.map { $0.value }) }
public var itemDeselected: ControlEvent<EventValue> { return ControlEvent(events: self._itemDeselected) }
private(set) lazy var _itemDeselected = PublishSubject<EventValue>()
public typealias MoveEventValue = (collectionView: UICollectionView, sourceIndex: Int, destinationIndex: Int, value: Value)
private(set) lazy var _moveItem = PublishSubject<MoveEventValue>()
init() { }
}
|
mit
|
552ed7b9b3c85046c17fe93f78a48ac7
| 36.333333 | 127 | 0.748512 | 4.555932 | false | false | false | false |
zakkhoyt/ColorPicKit
|
ColorPicKit/Classes/VideoPixelPicker.swift
|
1
|
12754
|
//
// VideoPixelPicker.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 11/13/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
private let invalidPositionValue = CGFloat(-1.0)
@IBDesignable public class VideoPixelPicker: UIControl, PositionableControl, Colorable {
// MARK: Variables
private var _position: CGPoint = CGPoint(x: invalidPositionValue, y: invalidPositionValue)
@IBInspectable public var position: CGPoint {
get {
return _position
}
set {
// We don't want to accept infinities or NaN
if abs(newValue.x) == CGFloat.infinity ||
abs(newValue.y) == CGFloat.infinity {
return
}
if newValue.x == CGFloat.nan || newValue.y == CGFloat.nan {
return
}
if _position != newValue {
updatePositionFrom(point: newValue)
updateKnob()
}
}
}
private var _knobView: KnobView = KnobView()
public var knobView: KnobView {
get {
return _knobView
}
set {
_knobView = newValue
updateKnob()
}
}
private var _knobSize: CGSize = CGSize(width: 30, height: 30)
@IBInspectable public var knobSize: CGSize {
get {
return _knobSize
}
set {
_knobSize = newValue
updateKnob()
}
}
private var _colorKnob: Bool = true
@IBInspectable public var colorKnob: Bool {
get {
return _colorKnob
}
set {
_colorKnob = newValue
updateKnob()
}
}
private var _borderColor: UIColor = .lightGray
@IBInspectable public var borderColor: UIColor{
get {
return _borderColor
}
set {
_borderColor = newValue
self.layer.borderColor = newValue.cgColor
}
}
private var _borderWidth: CGFloat = 0.5
@IBInspectable public var borderWidth: CGFloat{
get {
return _borderWidth
}
set {
_borderWidth = newValue
self.layer.borderWidth = newValue
}
}
private var _roundedCornders: Bool = false
@IBInspectable public var roundedCorners: Bool {
get {
return _roundedCornders
}
set {
_roundedCornders = newValue
if _roundedCornders == false {
self.layer.masksToBounds = false
self.layer.cornerRadius = 0
} else {
self.layer.masksToBounds = true
self.layer.cornerRadius = 40.0
}
}
}
public override var intrinsicContentSize: CGSize {
get {
return CGSize(width: bounds.width, height: bounds.width)
}
}
private var _color: UIColor = .white
/*@IBInspectable*/ public var color: UIColor {
get {
guard let pixelBuffer = self.pixelBuffer else {
print("No pixel buffer to calc frame")
return _color
}
if self.pixelBufferSize == nil {
print("No pixel buffer size")
return _color
}
// guard let pixelBufferSize = self.pixelBufferSize else {
// print("No pixel buffer size")
// return _color
// }
// let frame = frameForImageView()
// let knobPoint = knobViewPointWithinImage()
//
// var x = knobPoint.x / frame.size.width
// var y = knobPoint.y / frame.size.height
//
// x = x * pixelBufferSize.width
// y = y * pixelBufferSize.height
//
// let point = CGPoint(x: x, y: y)
//
// if let color = pixelBuffer.getColorAt(point: point) {
// return color
// } else {
// print("Failed to get color from pixelBuffer")
// }
//
// return _color
let point = knobViewPointWithinImage()
if let color = pixelBuffer.getColorAt(point: point) {
return color
} else {
print("Failed to get color from pixelBuffer")
}
return _color
}
}
private var videoCaptureView = VideoCaptureView()
private var pixelBuffer: CVPixelBuffer? = nil
private var pixelBufferSize: CGSize? = nil
// MARK: Init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
fileprivate func commonInit() {
self.backgroundColor = UIColor.clear
self.roundedCorners = _roundedCornders
self.borderWidth = _borderWidth
self.borderColor = _borderColor
// ImageView
videoCaptureView.contentMode = .scaleAspectFit
//videoCaptureView.image = image
videoCaptureView.clipsToBounds = true
videoCaptureView.pixelBufferCallback = { pixelBuffer in
self.pixelBuffer = pixelBuffer
// Get size from pixel buffer
CVPixelBufferLockBaseAddress(pixelBuffer, [])
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
self.pixelBufferSize = CGSize(width: width, height: height)
CVPixelBufferUnlockBaseAddress(pixelBuffer, [])
self.updateKnob()
}
addSubview(videoCaptureView)
// KnobView
updateKnobSize()
addSubview(knobView)
// // Pan gesture
// let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureHappened))
// panGesture.minimumNumberOfTouches = 1
// panGesture.maximumNumberOfTouches = 1
// panGesture.delegate = self
// self.addGestureRecognizer(panGesture)
//
// // Long press gesture
// let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGestureHappened))
// self.addGestureRecognizer(longPressGesture)
}
override open func layoutSubviews() {
super.layoutSubviews()
// ImageView
videoCaptureView.frame = frameForImageView()
// Position
if position.x == invalidPositionValue || position.y == invalidPositionValue {
position = CGPoint(x: videoCaptureView.frame.midX, y: videoCaptureView.frame.midY)
}
// KnobView
updateKnob()
}
// MARK: Gestures
fileprivate var knobStart: CGPoint!
fileprivate var panStart: CGPoint!
@objc private func panGestureHappened(sender: UIPanGestureRecognizer) {
// Position
if sender.state == .began {
knobStart = knobView.center
panStart = sender.location(in: self)
}
let deltaX = sender.location(in: self).x - panStart.x
let newX = knobStart.x + deltaX
let deltaY = sender.location(in: self).y - panStart.y
let newY = knobStart.y + deltaY
let point = CGPoint(x: newX, y: newY)
knobView.center = point
// Events
if sender.state == .began {
touchesHappened(point)
touchDown()
} else if sender.state == .changed {
touchesHappened(point)
} else if sender.state == .ended {
touchesHappened(point)
touchUpInside()
}
}
@objc private func longPressGestureHappened(sender: UILongPressGestureRecognizer) {
let point = sender.location(in: self)
if sender.state == .began {
touchesHappened(point)
touchDown()
} else if sender.state == .changed {
touchesHappened(point)
} else if sender.state == .ended {
touchesHappened(point)
touchUpInside()
}
}
private func touchesHappened(_ point: CGPoint) {
updatePositionFrom(point: point)
updateKnob()
valueChanged()
}
func touchDown() {
self.sendActions(for: .touchDown)
}
func touchUpInside() {
self.sendActions(for: .touchUpInside)
}
func valueChanged() {
self.sendActions(for: .valueChanged)
}
// MARK: Private methods
private func updateKnob() {
updateKnobSize()
updateKnobPosition()
updateKnobColor()
}
private func updateKnobSize() {
let center = knobView.center
knobView.bounds = CGRect(x: 0, y: 0, width: knobSize.width, height: knobSize.height)
knobView.center = center
}
private func updateKnobPosition() {
knobView.center = position
}
private func updateKnobColor() {
if colorKnob {
knobView.color = color
} else {
knobView.color = .white
}
}
private func frameForImageView() -> CGRect {
guard let pixelBufferSize = self.pixelBufferSize else {
print("No pixel buffer size")
return self.bounds
}
if pixelBufferSize.width == 0 || pixelBufferSize.height == 0 {
return bounds
}
let imageRatio = pixelBufferSize.width / pixelBufferSize.height
let ratio = self.bounds.width / self.bounds.height
if imageRatio > ratio {
// image is wider than self. Bars on top/bottom
let w = bounds.width
let h = w / (pixelBufferSize.width / pixelBufferSize.height)
let x = CGFloat(0)
let y = (bounds.height - h) / 2.0
return CGRect(x: x, y: y, width: w, height: h)
} else {
// image is taller than self. Bars on left/right
let h = bounds.height
let w = h / (pixelBufferSize.height / pixelBufferSize.width)
let x = (bounds.width - w) / 2.0
let y = CGFloat(0)
return CGRect(x: x, y: y, width: w, height: h)
}
//return self.bounds
}
private func updatePositionFrom(point: CGPoint) {
let imageFrame = videoCaptureView.frame
var mPoint = point
if mPoint.x < imageFrame.origin.x {
mPoint.x = imageFrame.origin.x
}
if mPoint.x > imageFrame.origin.x + imageFrame.size.width - 1.0 {
mPoint.x = imageFrame.origin.x + imageFrame.size.width - 1.0
}
if mPoint.y < imageFrame.origin.y {
mPoint.y = imageFrame.origin.y
}
if mPoint.y > imageFrame.origin.y + imageFrame.size.height - 1.0 {
mPoint.y = imageFrame.origin.y + imageFrame.size.height - 1.0
}
//print("point: \(point) mPoint: \(mPoint)")
_position = mPoint
}
private func knobViewPointWithinImage() -> CGPoint {
guard let pixelBuffer = self.pixelBuffer else {
print("pixelBuffer is nil")
return CGPoint(x: bounds.midX, y: bounds.midY)
}
let knobCenter = knobView.center
let adjustedPoint = self.convert(knobCenter, to: videoCaptureView)
let pixelBufferSize = UIImage.getSizeOf(pixelBuffer: pixelBuffer)
let ratioX = adjustedPoint.x / videoCaptureView.bounds.width
let ratioY = adjustedPoint.y / videoCaptureView.bounds.height
let x = ratioX * (pixelBufferSize.width - 1.0)
let y = ratioY * (pixelBufferSize.height - 1.0)
let point = CGPoint(x: x, y: y)
// print("-----------------")
// print("adjustedPoint: \(adjustedPoint)")
// print("point: \(point)")
// print("pixelBufferImage.size: \(pixelBufferImage.size)")
return point
}
}
extension VideoPixelPicker: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
|
mit
|
c1266eb27ef34fb3c7b50d44c6991cfb
| 27.722973 | 164 | 0.539795 | 4.960327 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Client/Frontend/Widgets/TabsButton.swift
|
2
|
8196
|
// 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 Foundation
import SnapKit
import Shared
class TabsButton: UIButton {
struct UX {
static let cornerRadius: CGFloat = 2
static let titleFont: UIFont = UIConstants.DefaultChromeSmallFontBold
}
var textColor = UIColor.Photon.Blue40 {
didSet {
countLabel.textColor = textColor
}
}
var titleBackgroundColor = UIColor.Photon.Blue40 {
didSet {
labelBackground.backgroundColor = titleBackgroundColor
}
}
var highlightTextColor: UIColor?
var highlightBackgroundColor: UIColor?
var inTopTabs = false
// When all animations are completed, this is the most-recently assigned tab count that is shown.
// updateTabCount() can be called in rapid succession, this ensures only final tab count is displayed.
private var countToBe = "1"
// Re-entrancy guard to ensure the function is complete before starting another animation.
private var isUpdatingTabCount = false
override var transform: CGAffineTransform {
didSet {
clonedTabsButton?.transform = transform
}
}
lazy var countLabel: UILabel = {
let label = UILabel()
label.font = UX.titleFont
label.layer.cornerRadius = UX.cornerRadius
label.textAlignment = .center
label.isUserInteractionEnabled = false
return label
}()
lazy var insideButton: UIView = {
let view = UIView()
view.clipsToBounds = false
view.isUserInteractionEnabled = false
return view
}()
fileprivate lazy var labelBackground: UIView = {
let background = UIView()
background.layer.cornerRadius = UX.cornerRadius
background.isUserInteractionEnabled = false
return background
}()
fileprivate lazy var borderView: UIImageView = {
let border = UIImageView(image: UIImage(named: ImageIdentifiers.navTabCounter)?.withRenderingMode(.alwaysTemplate))
border.tintColor = UIColor.theme.browser.tint
return border
}()
// Used to temporarily store the cloned button so we can respond to layout changes during animation
fileprivate weak var clonedTabsButton: TabsButton?
override init(frame: CGRect) {
super.init(frame: frame)
insideButton.addSubview(labelBackground)
insideButton.addSubview(borderView)
insideButton.addSubview(countLabel)
addSubview(insideButton)
isAccessibilityElement = true
accessibilityTraits.insert(.button)
}
override func updateConstraints() {
super.updateConstraints()
labelBackground.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
borderView.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
countLabel.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
insideButton.snp.remakeConstraints { (make) -> Void in
make.size.equalTo(24)
make.center.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createTabsButton() -> TabsButton {
let button = TabsButton()
button.accessibilityLabel = accessibilityLabel
button.countLabel.text = countLabel.text
// Copy all of the styable properties over to the new TabsButton
button.countLabel.font = countLabel.font
button.countLabel.textColor = countLabel.textColor
button.countLabel.layer.cornerRadius = countLabel.layer.cornerRadius
button.labelBackground.backgroundColor = labelBackground.backgroundColor
button.labelBackground.layer.cornerRadius = labelBackground.layer.cornerRadius
return button
}
func updateTabCount(_ count: Int, animated: Bool = true) {
let count = max(count, 1)
let currentCount = self.countLabel.text
let infinity = "\u{221E}"
countToBe = (count < 100) ? count.description : infinity
// only animate a tab count change if the tab count has actually changed
guard currentCount != count.description || (clonedTabsButton?.countLabel.text ?? count.description) != count.description else { return }
// Re-entrancy guard: if this code is running just update the tab count value without starting another animation.
if isUpdatingTabCount {
if let clone = self.clonedTabsButton {
clone.countLabel.text = countToBe
clone.accessibilityValue = countToBe
}
return
}
isUpdatingTabCount = true
if self.clonedTabsButton != nil {
self.clonedTabsButton?.layer.removeAllAnimations()
self.clonedTabsButton?.removeFromSuperview()
insideButton.layer.removeAllAnimations()
}
let newTabsButton = createTabsButton()
self.clonedTabsButton = newTabsButton
newTabsButton.frame = self.bounds
newTabsButton.addTarget(self, action: #selector(cloneDidClickTabs), for: .touchUpInside)
newTabsButton.countLabel.text = countToBe
newTabsButton.accessibilityValue = countToBe
newTabsButton.insideButton.frame = self.insideButton.frame
newTabsButton.snp.removeConstraints()
self.addSubview(newTabsButton)
newTabsButton.snp.makeConstraints { make in
make.center.equalTo(self)
}
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
let frame = self.insideButton.frame
let halfTitleHeight = frame.height / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-(Double.pi / 2)), 1.0, 0.0, 0.0)
newTabsButton.insideButton.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(-(Double.pi / 2)), 1.0, 0.0, 0.0)
let animate = {
newTabsButton.insideButton.layer.transform = CATransform3DIdentity
self.insideButton.layer.transform = oldFlipTransform
self.insideButton.layer.opacity = 0
}
let completion: (Bool) -> Void = { completed in
let noActiveAnimations = self.insideButton.layer.animationKeys()?.isEmpty ?? true
if completed || noActiveAnimations {
newTabsButton.removeFromSuperview()
self.insideButton.layer.opacity = 1
self.insideButton.layer.transform = CATransform3DIdentity
}
self.accessibilityLabel = .TabsButtonShowTabsAccessibilityLabel
self.countLabel.text = self.countToBe
self.accessibilityValue = self.countToBe
self.isUpdatingTabCount = false
}
if animated {
UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: [], animations: animate, completion: completion)
} else {
completion(true)
}
}
@objc func cloneDidClickTabs() {
sendActions(for: .touchUpInside)
}
}
extension TabsButton: NotificationThemeable {
func applyTheme() {
borderView.tintColor = UIColor.theme.browser.tint
if inTopTabs {
textColor = UIColor.theme.topTabs.buttonTint
} else {
textColor = UIColor.theme.browser.tint
}
}
}
|
mpl-2.0
|
f16347a6e1da6771ff43908f24a701b0
| 36.769585 | 170 | 0.662396 | 5.332466 | false | false | false | false |
dansbastian/iOS-Swift-MVVM
|
iOS-Swift-MVVM/Extension/UIView+Init.swift
|
1
|
2544
|
//
// UIView+Init.swift
// iOS-Swift-Base-MVVM
//
// Created by Daniel Yanuar Sebastian on 10/4/16.
// Copyright © 2016 Daniel Yanuar Sebastian. All rights reserved.
//
import UIKit
extension UIView {
//MARK: Public Static Function
static func getViewFromNib(bundle bdl: Bundle? = nil) -> UIView? {
return self.getViewFromNib(bundle: bdl, nibName: nil, tag: -1)
}
static func getViewFromNib(bundle bdl: Bundle? = nil, nibName strNibName: String? = nil, tag intTag: Int) -> UIView? {
let nib: UINib
let bdlSelected: Bundle
if let _bdl = bdl {
bdlSelected = _bdl
} else {
bdlSelected = Bundle(for: self.classForCoder())
}
if let strNibName = strNibName {
nib = UINib(nibName: strNibName, bundle: bdlSelected)
} else {
nib = UINib(nibName: String(describing: self.classForCoder()), bundle: bdlSelected)
}
let arrObj: [Any] = nib.instantiate(withOwner: nil, options: nil)
var vwSelected: UIView?
if let arrVw: [UIView] = arrObj as? [UIView] {
for vw in arrVw {
if intTag == -1 {
if vw.isKind(of: self.classForCoder()) {
vwSelected = vw
break
}
} else if vw.tag == intTag {
vwSelected = vw
break
}
}
}
return vwSelected
}
//MARK: Public Function
func getViewFromNib(bundle bdl: Bundle? = nil) -> UIView? {
return getViewFromNib(bundle: bdl, nibName: nil, tag: -1)
}
func getViewFromNib(bundle bdl: Bundle? = nil, nibName strNibName: String? = nil, tag intTag: Int) -> UIView? {
let nib: UINib
let bdlSelected: Bundle
if let _bdl = bdl {
bdlSelected = _bdl
} else {
bdlSelected = Bundle(for: self.classForCoder)
}
if let strNibName = strNibName {
nib = UINib(nibName: strNibName, bundle: bdlSelected)
} else {
nib = UINib(nibName: String(describing: self.classForCoder), bundle: bdlSelected)
}
let arrObj: [Any] = nib.instantiate(withOwner: nil, options: nil)
var vwSelected: UIView?
if let arrVw: [UIView] = arrObj as? [UIView] {
for vw in arrVw {
if intTag == -1 {
vwSelected = vw
break
} else if vw.tag == intTag {
vwSelected = vw
break
}
}
}
if let _vwSelected: UIView = vwSelected {
_vwSelected.frame = bounds
}
return vwSelected
}
}
|
mit
|
277079e8d290b91768a32e0c98f60829
| 23.68932 | 120 | 0.570193 | 3.806886 | false | false | false | false |
colemancda/NetworkObjects
|
Source/Store.swift
|
1
|
6227
|
//
// Store.swift
// NetworkObjects
//
// Created by Alsey Coleman Miller on 9/14/15.
// Copyright © 2015 ColemanCDA. All rights reserved.
//
import SwiftFoundation
import CoreModel
public extension CoreModel.Store {
/// Caches the values of a response.
///
/// - Note: Request and Response must be of the same type or this method will do nothing.
func cacheResponse(response: Response, forRequest request: Request, dateCachedAttributeName: String?) throws {
switch (request, response) {
// 404 responses
case let (.Get(resource), .Error(errorStatusCode)):
// delete object from cache if not found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
case let (.Edit(resource, _), .Error(errorStatusCode)):
// delete object from cache if not found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
case let (.Delete(resource), .Error(errorStatusCode)):
// delete object from cache if now found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
// standard responses
case (.Get(let resource), .Get(var values)):
try self.createCachePlaceholders(values, entityName: resource.entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
// update values
if try self.exists(resource) {
try self.edit(resource, changes: values)
}
// create resource and set values
else {
try self.create(resource, initialValues: values)
}
case (let .Edit(resource, _), .Edit(var values)):
try self.createCachePlaceholders(values, entityName: resource.entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
// update values
if try self.exists(resource) {
try self.edit(resource, changes: values)
}
// create resource and set values
else {
try self.create(resource, initialValues: values)
}
case (let .Create(entityName, _), .Create(let resourceID, var values)):
try self.createCachePlaceholders(values, entityName: entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
let resource = Resource(entityName, resourceID)
try self.create(resource, initialValues: values)
case let (.Delete(resource), .Delete):
if try self.exists(resource) {
try self.delete(resource)
}
case let (.Search(fetchRequest), .Search(resourceIDs)):
for resourceID in resourceIDs {
let resource = Resource(fetchRequest.entityName, resourceID)
// create placeholder resources for results
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
}
default: break
}
}
}
private extension CoreModel.Store {
/// Resolves relationships in the values and creates placeholder resources.
private func createCachePlaceholders(values: ValuesObject, entityName: String) throws {
guard let entity = self.model[entityName] else { throw StoreError.InvalidEntity }
for (key, value) in values {
switch value {
case let .Relationship(relationshipValue):
guard let relationship = entity.relationships[key] else { throw StoreError.InvalidValues }
switch relationshipValue {
case let .ToOne(resourceID):
let resource = Resource(relationship.destinationEntityName, resourceID)
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
case let .ToMany(resourceIDs):
for resourceID in resourceIDs {
let resource = Resource(relationship.destinationEntityName, resourceID)
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
}
}
default: break
}
}
}
}
|
mit
|
0a0cb0e07c70a83de85330c7a3ffe28a
| 31.941799 | 114 | 0.473338 | 6.471933 | false | false | false | false |
BranchMetrics/iOS-Deferred-Deep-Linking-SDK
|
Branch-TestBed-Swift/TestBed-Swift/ProductTableViewController.swift
|
1
|
3942
|
//
// ProductTableViewController.swift
// TestBed-Swift
//
// Created by David Westgate on 7/13/17.
// Copyright © 2016 Branch Metrics. All rights reserved.
//
import UIKit
class ProductTableViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
// MARK: - Controls
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var productNameTextField: UITextField!
@IBOutlet weak var productBrandTextField: UITextField!
@IBOutlet weak var productSKUTextField: UITextField!
@IBOutlet weak var productQuantityTextField: UITextField!
@IBOutlet weak var productPriceTextField: UITextField!
@IBOutlet weak var productVariantTextField: UITextField!
@IBOutlet weak var productCategoryTextField: UITextField!
var defaults = CommerceEventData.productDefaults()
let picker = UIPickerView()
let productCategories = CommerceEventData.productCategories()
// MARK: - Core View Functions
override func viewDidLoad() {
super.viewDidLoad()
productNameTextField.delegate = self
productBrandTextField.delegate = self
productSKUTextField.delegate = self
productQuantityTextField.delegate = self
productPriceTextField.delegate = self
productVariantTextField.delegate = self
productCategoryTextField.delegate = self
productNameTextField.placeholder = defaults["name"]
productBrandTextField.placeholder = defaults["brand"]
productSKUTextField.placeholder = defaults["sku"]
productQuantityTextField.placeholder = defaults["quantity"]
productPriceTextField.placeholder = defaults["price"]
productVariantTextField.placeholder = defaults["variant"]
productCategoryTextField.placeholder = defaults["category"]
productCategoryTextField.inputView = picker
productCategoryTextField.inputAccessoryView = createToolbar(true)
picker.dataSource = self
picker.delegate = self
picker.showsSelectionIndicator = true
productNameTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - PickerView
func createToolbar(_ withCancelButton: Bool) -> UIToolbar {
let toolbar = UIToolbar(frame: CGRect(x: 0,y: 0,width: self.view.frame.size.width,height: 44))
toolbar.tintColor = UIColor.gray
let donePickingButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.donePicking))
let emptySpace = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
if (withCancelButton) {
let cancelPickingButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(self.cancelPicking))
toolbar.setItems([cancelPickingButton, emptySpace, donePickingButton], animated: true)
} else {
toolbar.setItems([emptySpace, donePickingButton], animated: true)
}
return toolbar
}
@objc func cancelPicking() {
productCategoryTextField.resignFirstResponder()
}
@objc func donePicking() {
self.productCategoryTextField.text = productCategories[picker.selectedRow(inComponent: 0)]
self.productCategoryTextField.resignFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return productCategories.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return productCategories[row]
}
}
|
mit
|
afea413623526f57441efbdf66103396
| 38.41 | 162 | 0.70642 | 5.481224 | false | false | false | false |
PD-Jell/Swift_study
|
SwiftStudy/Local-push/LocalPushViewController.swift
|
1
|
1491
|
//
// LocalPushViewController.swift
// SwiftStudy
//
// Created by Jell PD on 2020/07/05.
// Copyright © 2020 Jell PD. All rights reserved.
//
import UIKit
import UserNotifications
class LocalPushViewController: UIViewController {
let userNotificationCenter = UNUserNotificationCenter.current()
override func viewDidLoad() {
super.viewDidLoad()
requestNotificationAuthorization()
sendNotification(seconds: 5)
}
func requestNotificationAuthorization() {
let authOptions = UNAuthorizationOptions(arrayLiteral: .alert, .badge, .sound)
userNotificationCenter.requestAuthorization(options: authOptions) { success, error in
if let error = error {
print("Error: \(error)")
}
}
}
func sendNotification(seconds: Double) {
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "알림 테스트"
notificationContent.body = "이것은 알림을 테스트 하는 것이다"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: seconds, repeats: false)
let request = UNNotificationRequest(identifier: "testNotification", content: notificationContent, trigger: trigger)
userNotificationCenter.add(request) { error in
if let error = error {
print("Notification Error: ", error)
}
}
}
}
|
mit
|
00730caa43e12666c73866b0bd06618e
| 29.25 | 123 | 0.641873 | 5.26087 | false | false | false | false |
slavapestov/swift
|
test/attr/attr_availability.swift
|
2
|
8135
|
// RUN: %target-parse-verify-swift
@available(*, unavailable)
func unavailable_func() {}
@available(*, unavailable, message="message")
func unavailable_func_with_message() {}
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(iOS, unavailable)
@available(OSX, unavailable)
func unavailable_multiple_platforms() {}
@available // expected-error {{expected '(' in 'available' attribute}}
func noArgs() {}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func noKind() {}
@available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}}
func unavailable_bad_platform() {}
// Handle unknown platform.
@available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}}
func availabilityUnknownPlatform() {}
// <rdar://problem/17669805> Availability can't appear on a typealias
@available(*, unavailable, message="oh no you dont")
typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}}
@available(*, unavailable, renamed="Float")
typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}}
struct MyCollection<Element> {
@available(*, unavailable, renamed="Element")
typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}}
func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}}
}
extension MyCollection {
func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}}
}
var x : int // expected-error {{'int' is unavailable: oh no you dont}}
var y : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}}
// Encoded message
@available(*, unavailable, message="This message has a double quote \"")
func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}}
func useWithEscapedMessage() {
unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}}
}
// More complicated parsing.
@available(OSX, message="x", unavailable)
let _: Int
@available(OSX, introduced=1, deprecated=2.0, obsoleted=3.0.0)
let _: Int
@available(OSX, introduced=1.0.0, deprecated=2.0, obsoleted=3, unavailable, renamed="x")
let _: Int
// Meaningless but accepted.
@available(OSX, message="x")
let _: Int
// Parse errors.
@available() // expected-error{{expected platform name or '*' for 'available' attribute}}
let _: Int
@available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}}
let _: Int
@available(OSX, message) // expected-error{{expected '=' after 'message' in 'available' attribute}}
let _: Int
@available(OSX, message=) // expected-error{{expected string literal in 'available' attribute}} expected-error{{'=' must have consistent whitespace on both sides}}
let _: Int
@available(OSX, message=x) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, unavailable=) // expected-error{{expected ')' in 'available' attribute}} expected-error{{'=' must have consistent whitespace on both sides}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced) // expected-error{{expected '=' after 'introduced' in 'available' attribute}}
let _: Int
@available(OSX, introduced=) // expected-error{{expected version number in 'available' attribute}} expected-error{{'=' must have consistent whitespace on both sides}}
let _: Int
@available(OSX, introduced=x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced=1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}}
let _: Int
@available(OSX, introduced=1.0.x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced=0x1) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced=1.0e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced=-1) // expected-error{{expected '=' after 'introduced' in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced=1.0.1e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced=1.0.0x4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(*, deprecated, unavailable, message="message") // expected-error{{'available' attribute cannot be both unconditionally 'unavailable' and 'deprecated'}}
struct BadUnconditionalAvailability { };
// Encoding in messages
@available(*, deprecated, message="Say \"Hi\"")
func deprecated_func_with_message() {}
// 'PANDA FACE' (U+1F43C)
@available(*, deprecated, message="Pandas \u{1F43C} are cute")
struct DeprecatedTypeWithMessage { }
func use_deprecated_with_message() {
deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}}
var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}}
}
@available(*, deprecated, message="message")
func use_deprecated_func_with_message2() {
deprecated_func_with_message() // no diagnostic
}
@available(*, deprecated, renamed="blarg")
func deprecated_func_with_renamed() {}
@available(*, deprecated, message="blarg is your friend", renamed="blarg")
func deprecated_func_with_message_renamed() {}
@available(*, deprecated, renamed="wobble")
struct DeprecatedTypeWithRename { }
func use_deprecated_with_renamed() {
deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}}
// expected-note@-1{{use 'blarg'}}{{3-31=blarg}}
deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}}
// expected-note@-1{{use 'blarg'}}{{3-39=blarg}}
var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}}
// expected-note@-1{{use 'wobble'}}{{10-34=wobble}}
}
// Short form of @available()
@available(iOS 8.0, *)
func functionWithShortFormIOSAvailable() {}
@available(iOS 8, *)
func functionWithShortFormIOSVersionNoPointAvailable() {}
@available(iOS 8.0, OSX 10.10.3, *)
func functionWithShortFormIOSOSXAvailable() {}
@available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}}
func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(iOS 8.0, // expected-error {{expected platform name}}
func shortFormMissingPlatform() {
}
@available(iOS 8.0, *
func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func onlyWildcardInAvailable() {}
@available(iOS 8.0, *, OSX 10.10.3)
func shortFormWithWildcardInMiddle() {}
@available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}}
func shortFormMissingWildcard() {}
@availability(OSX, introduced=10.10) // expected-error {{@availability has been renamed to @available}} {{2-14=available}}
func someFuncUsingOldAttribute() { }
// <rdar://problem/23853709> Compiler crash on call to unavailable "print"
func OutputStreamTest(message: String, inout to: OutputStreamType) {
print(message, &to) // expected-error {{'print' is unavailable: Please use the 'toStream' label for the target stream: 'print((...), toStream: &...)'}}
}
// expected-note@+1{{'T' has been explicitly marked unavailable here}}
struct UnavailableGenericParam<@available(*, unavailable, message="nope") T> {
func f(t: T) { } // expected-error{{'T' is unavailable: nope}}
}
|
apache-2.0
|
d50c29f1d2516386faffd3598e0b9dbe
| 38.490291 | 195 | 0.725138 | 3.851799 | false | false | false | false |
hayleyqinn/windWeather
|
风生/Pods/Alamofire/Source/TaskDelegate.swift
|
125
|
15437
|
//
// TaskDelegate.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
open class TaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
open let queue: OperationQueue
var task: URLSessionTask? {
didSet { reset() }
}
var data: Data? { return nil }
var error: Error?
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
var metrics: AnyObject? // URLSessionTaskMetrics
// MARK: Lifecycle
init(task: URLSessionTask?) {
self.task = task
self.queue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
func reset() {
error = nil
initialResponseTime = nil
}
// MARK: URLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
@objc(URLSession:task:didCompleteWithError:)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
if self.error == nil { self.error = error }
if
let downloadDelegate = self as? DownloadTaskDelegate,
let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
{
downloadDelegate.resumeData = resumeData
}
}
queue.isSuspended = false
}
}
}
// MARK: -
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
mutableData = Data()
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
totalBytesReceived = 0
mutableData = Data()
expectedContentLength = nil
}
// MARK: URLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
// MARK: Properties
var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var resumeData: Data?
override var data: Data? { return resumeData }
var destination: DownloadRequest.DownloadFileDestination?
var temporaryURL: URL?
var destinationURL: URL?
var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL }
// MARK: Lifecycle
override init(task: URLSessionTask?) {
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
resumeData = nil
}
// MARK: URLSessionDownloadDelegate
var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
temporaryURL = location
if let destination = destination {
let result = destination(location, downloadTask.response as! HTTPURLResponse)
let destination = result.destinationURL
let options = result.options
do {
destinationURL = destination
if options.contains(.removePreviousFile) {
if FileManager.default.fileExists(atPath: destination.path) {
try FileManager.default.removeItem(at: destination)
}
}
if options.contains(.createIntermediateDirectories) {
let directory = destination.deletingLastPathComponent()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
}
try FileManager.default.moveItem(at: location, to: destination)
} catch {
self.error = error
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: -
class UploadTaskDelegate: DataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
var uploadProgress: Progress
var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
uploadProgress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
uploadProgress = Progress(totalUnitCount: 0)
}
// MARK: URLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
if let uploadProgressHandler = uploadProgressHandler {
uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
}
}
}
}
|
mit
|
db370ce0e85a2e7fb7bc11b9a4ffeb9f
| 33.380846 | 149 | 0.661268 | 6.202089 | false | false | false | false |
nodes-ios/NStackSDK
|
NStackSDK/NStackSDK/Classes/Other/UILabel+NstackLocalizable.swift
|
1
|
2269
|
//
// UILabel+NstackLocalizable.swift
// NStackSDK
//
// Created by Nicolai Harbo on 30/07/2019.
// Copyright © 2019 Nodes ApS. All rights reserved.
//
import Foundation
import UIKit
extension UILabel: NStackLocalizable {
private static var _backgroundColor = [String: UIColor?]()
private static var _userInteractionEnabled = [String: Bool]()
private static var _translationIdentifier = [String: TranslationIdentifier]()
@objc public func localize(for stringIdentifier: String) {
guard let identifier = SectionKeyHelper.transform(stringIdentifier) else { return }
NStack.sharedInstance.translationsManager?.localize(component: self, for: identifier)
}
@objc public func setLocalizedValue(_ localizedValue: String) {
text = localizedValue
}
public var translatableValue: String? {
get {
return text
}
set {
text = newValue
}
}
public var translationIdentifier: TranslationIdentifier? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UILabel._translationIdentifier[tmpAddress]
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UILabel._translationIdentifier[tmpAddress] = newValue
}
}
public var originalBackgroundColor: UIColor? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UILabel._backgroundColor[tmpAddress] ?? .clear
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UILabel._backgroundColor[tmpAddress] = newValue
}
}
public var originalIsUserInteractionEnabled: Bool {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UILabel._userInteractionEnabled[tmpAddress] ?? false
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UILabel._userInteractionEnabled[tmpAddress] = newValue
}
}
public var backgroundViewToColor: UIView? {
return self
}
}
|
mit
|
5f23800287c2f13d7a888cd3e1f9b594
| 30.068493 | 93 | 0.626984 | 4.846154 | false | false | false | false |
katsana/katsana-sdk-ios
|
KatsanaSDK/Manager/KatsanaAPI+Other.swift
|
1
|
2684
|
//
// KatsanaAPI+Other.swift
// KatsanaSDK
//
// Created by Wan Ahmad Lutfi on 17/10/2016.
// Copyright © 2016 pixelated. All rights reserved.
//
extension KatsanaAPI{
func uploadImage(image : KMImage, path : String, completion : @escaping (Bool, Error?) -> Void) -> Void {
// let path = self.baseURL().absoluteString + "profile/avatar"
#if os(iOS)
let data = image.jpegData(compressionQuality: 0.9)
#elseif os(OSX)
let data = image.tiffRepresentation(using: .JPEG, factor: 0.9)! //Change to data
#endif
Just.post(
path,
headers: ["Authorization" : ("Bearer " + self.authToken)],
files: ["file": .data("avatar.png", data!, "image/jpeg")]
) { r in
// let strData = NSString(data: r.content!, encoding: String.Encoding.utf8.rawValue)
if r.ok {
DispatchQueue.main.sync{completion(true, nil)}
}else{
DispatchQueue.main.sync{completion(false, r.APIError())}
}
}
}
/// Request custom response from other application using current KatsanaAPI endpoint.
///
/// - parameter path: path to append to current endpoint
/// - parameter completion: completion
public func requestResponse(for path: String, completion: @escaping (_ response: Dictionary<String, Any>?, _ error: Error?) -> Void) -> Void {
let resource = API.resource(path);
let request = resource.loadIfNeeded()
request?.onSuccess({(entity) in
let json = entity.content as? JSON
let dicto = json?.dictionaryObject
completion(dicto, nil)
}).onFailure({ (error) in
completion(nil, error)
self.log.error("Error request custom response for path \(path), \(error)")
})
if request == nil {
let json = resource.latestData?.content as? JSON
let dicto = json?.dictionaryObject
completion(dicto, nil)
}
}
public func requestResponseUsing(fullPath: String, defaultHeaders: Dictionary<String, String> = [:], parameters:Dictionary<String, String> = [:], completion: @escaping (_ response: Dictionary<String, Any>?, _ error: Error?) -> Void) -> Void {
Just.get(
fullPath,
params: parameters,
headers: defaultHeaders
) { r in
let json = JSON(data: r.content!)
let dicto = json.dictionaryObject
DispatchQueue.main.sync {
completion(dicto, r.APIError())
}
}
}
}
|
apache-2.0
|
212629ca08aada868b9bd453ae64f129
| 36.788732 | 246 | 0.56243 | 4.547458 | false | false | false | false |
novi/proconapp
|
ProconApp/ProconApp WatchKit Extension/GlanceController.swift
|
1
|
2820
|
//
// GlanceController.swift
// ProconApp WatchKit Extension
//
// Created by ito on 2015/07/29.
// Copyright (c) 2015年 Procon. All rights reserved.
//
import WatchKit
import Foundation
import ProconBase
import APIKit
class GlanceController: InterfaceController {
@IBOutlet weak var sectionTitleLabel: WKInterfaceLabel!
@IBOutlet weak var titleLabel: WKInterfaceLabel!
@IBOutlet weak var schoolTable: WKInterfaceTable!
@IBOutlet weak var noResultLabel: WKInterfaceLabel!
var gameResults: [GameResult] = []
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
fetchContents()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
override func fetchContents() {
if let me = UserContext.defaultContext.me {
let r = AppAPI.FetchGameResults(auth: me, filter: .OnlyForNotification, count: 1)
API.sendRequest(r) { res in
switch res {
case .Success(let results):
Logger.debug("\(results)")
self.gameResults = results
self.noResultLabel.setHidden(self.gameResults.count != 0)
self.noResultLabel.setText("設定した学校の競技結果はまだありません")
self.createGameData()
self.createTableData()
case .Failure(let error):
// TODO, error
Logger.error(error)
}
}
} else {
self.noResultLabel.setHidden(false)
self.noResultLabel.setText(MainInterfaceController.noLoginMessage)
let delay = 2 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
self.fetchContents()
})
}
}
func createGameData() {
if let gameResult = gameResults.first {
titleLabel.setText(gameResult.title)
}
}
func createTableData() {
if let results = gameResults.first?.resultsByRank {
let count = min(results.count, 3)
schoolTable.setNumberOfRows(count, withRowType: .GlanceSchool)
for i in 0..<count {
let cell = schoolTable.rowControllerAtIndex(i) as! SchoolTableCell
cell.result = results[i]
}
}
}
}
|
bsd-3-clause
|
99aaf386cd5e2e669b84cee0cd422d0c
| 30.954023 | 93 | 0.58705 | 4.818024 | false | false | false | false |
squall09s/VegOresto
|
VegoResto/CommentTableViewCell.swift
|
1
|
2865
|
//
// CommentTableViewCell.swift
// VegoResto
//
// Created by Laurent Nicolas (141 - LILLE TOURCOING) on 05/01/2017.
// Copyright © 2017 Nicolas Laurent. All rights reserved.
//
import UIKit
import SDWebImage
import Keys
class CommentTableViewCell: UITableViewCell {
@IBOutlet weak var varIB_label_comment: UILabel?
@IBOutlet var varIB_subtitle_label: UILabel!
@IBOutlet var varIB_starRating0: UIImageView?
@IBOutlet var varIB_starRating1: UIImageView?
@IBOutlet var varIB_starRating2: UIImageView?
@IBOutlet var varIB_starRating3: UIImageView?
@IBOutlet var varIB_starRating4: UIImageView?
@IBOutlet var varIB_imageComment: UIImageView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setImage(url: String?) {
if let _url = url {
self.varIB_imageComment?.isHidden = false
if let _url = URL(string: _url ) {
let sdDownloader = SDWebImageDownloader.shared()
sdDownloader.username = APIConfig.apiBasicAuthLogin
sdDownloader.password = APIConfig.apiBasicAuthPassword
sdDownloader.downloadImage(with: _url, options: .continueInBackground, progress: { (_, _, _) in
}, completed: { (image, _, _, _) in
self.varIB_imageComment?.image = image
self.varIB_imageComment?.contentMode = .scaleAspectFit
})
} else {
self.varIB_imageComment?.isHidden = true
}
}
}
func setRating(ratting: Int?) {
self.varIB_starRating0?.image = UIImage(named: "img_favoris_star_off")
self.varIB_starRating1?.image = UIImage(named: "img_favoris_star_off")
self.varIB_starRating2?.image = UIImage(named: "img_favoris_star_off")
self.varIB_starRating3?.image = UIImage(named: "img_favoris_star_off")
self.varIB_starRating4?.image = UIImage(named: "img_favoris_star_off")
if let _ratting = ratting {
if _ratting > 0 {
self.varIB_starRating0?.image = UIImage(named: "img_favoris_star_on")
}
if _ratting > 1 {
self.varIB_starRating1?.image = UIImage(named: "img_favoris_star_on")
}
if _ratting > 2 {
self.varIB_starRating2?.image = UIImage(named: "img_favoris_star_on")
}
if _ratting > 3 {
self.varIB_starRating3?.image = UIImage(named: "img_favoris_star_on")
}
if _ratting > 4 {
self.varIB_starRating4?.image = UIImage(named: "img_favoris_star_on")
}
}
}
}
|
gpl-3.0
|
62f9884ceb625c513e756327d3708a97
| 28.525773 | 107 | 0.606844 | 4.005594 | false | false | false | false |
ovchinnikoff/FolioReaderKit
|
FolioReaderKit/FRMetadata.swift
|
2
|
2054
|
//
// FRMetadata.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 04/05/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
/**
Represents one of the authors of the book.
*/
struct Author {
var name: String!
var role: String!
var fileAs: String!
init(name: String, role: String, fileAs: String) {
self.name = name
self.role = role
self.fileAs = fileAs
}
}
/**
A Book's identifier.
*/
struct Identifier {
var scheme: String!
var value: String!
init(scheme: String, value: String) {
self.scheme = scheme
self.value = value
}
}
/**
A date and his event.
*/
struct Date {
var date: String!
var event: String!
init(date: String, event: String!) {
self.date = date
self.event = event
}
}
/**
A metadata tag data.
*/
struct Meta {
var name: String?
var content: String?
var id: String?
var property: String?
var value: String?
init(name: String, content: String) {
self.name = name
self.content = content
}
init(id: String, property: String, value: String) {
self.id = id
self.property = property
self.value = value
}
}
/**
Manages book metadata.
*/
class FRMetadata: NSObject {
var creators = [Author]()
var contributors = [Author]()
var dates = [Date]()
var language = "en"
var titles = [String]()
var identifiers = [Identifier]()
var subjects = [String]()
var descriptions = [String]()
var publishers = [String]()
var format = FRMediaType.EPUB.name
var rights = [String]()
var metaAttributes = [Meta]()
func findMetaByName(name: String) -> String? {
if name.isEmpty {
return nil
}
for meta in metaAttributes {
if meta.name != nil {
if meta.name == name {
return meta.content
}
}
}
return nil
}
}
|
gpl-2.0
|
74a8f7521c406016194268682e500ddb
| 18.377358 | 57 | 0.549172 | 3.927342 | false | false | false | false |
Qminder/swift-api
|
QminderAPITests/Dictionary+Extensions.swift
|
1
|
1206
|
//
// Dictionary+Extensions.swift
// QminderAPITests
//
// Created by Kristaps Grinbergs on 15/03/2018.
// Copyright © 2018 Kristaps Grinbergs. All rights reserved.
//
import Foundation
public extension Dictionary {
/**
JSON data of Dictionary
- Parameters:
- prettify: Pretify JSON
- Returns: Optional data as JSON
*/
func jsonData(prettify: Bool = false) -> Data? {
guard JSONSerialization.isValidJSONObject(self) else {
return nil
}
let options = (prettify == true) ?
JSONSerialization.WritingOptions.prettyPrinted :
JSONSerialization.WritingOptions()
return try? JSONSerialization.data(withJSONObject: self, options: options)
}
}
public extension Dictionary where Key == String, Value == Any {
/**
Decode Dictionary [String: Any] to decodable
- Parameters:
- type: Decodable type
- Returns: Decoded decodable as given type
*/
func decodeAs<T>(_ type: T.Type, decoder: JSONDecoder = JSONDecoder()) throws -> T where T: Decodable {
let data = try JSONSerialization.data(withJSONObject: self, options: [])
let object = try decoder.decode(type, from: data)
return object
}
}
|
mit
|
3e0cebdfb9ca634d184e25bbcec4890e
| 23.591837 | 105 | 0.670539 | 4.365942 | false | false | false | false |
auth0/Auth0.swift
|
Auth0/Auth0.swift
|
1
|
7796
|
import Foundation
/**
`Result` wrapper for Authentication API operations.
*/
public typealias AuthenticationResult<T> = Result<T, AuthenticationError>
/**
`Result` wrapper for Management API operations.
*/
public typealias ManagementResult<T> = Result<T, ManagementError>
#if WEB_AUTH_PLATFORM
/**
`Result` wrapper for Web Auth operations.
*/
public typealias WebAuthResult<T> = Result<T, WebAuthError>
#endif
/**
`Result` wrapper for Credentials Manager operations.
*/
public typealias CredentialsManagerResult<T> = Result<T, CredentialsManagerError>
/**
Default scope value used across Auth0.swift. Equals to `openid profile email`.
*/
public let defaultScope = "openid profile email"
/**
Auth0 [Authentication API](https://auth0.com/docs/api/authentication) client to authenticate your user using Database, Social, Enterprise or Passwordless connections.
## Usage
```swift
Auth0.authentication(clientId: "client-id", domain: "samples.us.auth0.com")
```
- Parameters:
- clientId: Client ID of your Auth0 application.
- domain: Domain of your Auth0 account, for example `samples.us.auth0.com`.
- session: `URLSession` instance used for networking. Defaults to `URLSession.shared`.
- Returns: Auth0 Authentication API client.
*/
public func authentication(clientId: String, domain: String, session: URLSession = .shared) -> Authentication {
return Auth0Authentication(clientId: clientId, url: .httpsURL(from: domain), session: session)
}
/**
Auth0 [Authentication API](https://auth0.com/docs/api/authentication) client to authenticate your user using Database,
Social, Enterprise or Passwordless connections.
## Usage
```swift
Auth0.authentication()
```
The Auth0 Client ID & Domain are loaded from the `Auth0.plist` file in your main bundle. It should have the following
content:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ClientId</key>
<string>YOUR_AUTH0_CLIENT_ID</string>
<key>Domain</key>
<string>YOUR_AUTH0_DOMAIN</string>
</dict>
</plist>
```
- Parameters:
- session: `URLSession` instance used for networking. Defaults to `URLSession.shared`.
- bundle: Bundle used to locate the `Auth0.plist` file. Defaults to `Bundle.main`.
- Returns: Auth0 Authentication API client.
- Warning: Calling this method without a valid `Auth0.plist` file will crash your application.
*/
public func authentication(session: URLSession = .shared, bundle: Bundle = .main) -> Authentication {
let values = plistValues(bundle: bundle)!
return authentication(clientId: values.clientId, domain: values.domain, session: session)
}
/**
Auth0 [Management API v2](https://auth0.com/docs/api/management/v2) client to perform operations with the Users
endpoints.
## Usage
```swift
Auth0.users(token: credentials.accessToken)
```
Currently you can only perform the following operations:
* Get a user by ID
* Update an user, for example by adding `user_metadata`
* Link users
* Unlink users
The Auth0 Domain is loaded from the `Auth0.plist` file in your main bundle. It should have the following content:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ClientId</key>
<string>YOUR_AUTH0_CLIENT_ID</string>
<key>Domain</key>
<string>YOUR_AUTH0_DOMAIN</string>
</dict>
</plist>
```
- Parameters:
- token: Management API token with the correct allowed scopes to perform the desired action.
- session: `URLSession` instance used for networking. Defaults to `URLSession.shared`.
- bundle: Bundle used to locate the `Auth0.plist` file. Defaults to `Bundle.main`.
- Returns: Auth0 Management API v2 client.
- Warning: Calling this method without a valid `Auth0.plist` file will crash your application.
*/
public func users(token: String, session: URLSession = .shared, bundle: Bundle = .main) -> Users {
let values = plistValues(bundle: bundle)!
return users(token: token, domain: values.domain, session: session)
}
/**
Auth0 [Management API v2](https://auth0.com/docs/api/management/v2) client to perform operations with the Users
endpoints.
## Usage
```swift
Auth0.users(token: credentials.accessToken, domain: "samples.us.auth0.com")
```
Currently you can only perform the following operations:
* Get a user by ID
* Update an user, for example by adding `user_metadata`
* Link users
* Unlink users
- Parameters:
- token: Management API token with the correct allowed scopes to perform the desired action.
- domain: Domain of your Auth0 account, for example `samples.us.auth0.com`.
- session: `URLSession` instance used for networking. Defaults to `URLSession.shared`.
- Returns: Auth0 Management API v2 client.
*/
public func users(token: String, domain: String, session: URLSession = .shared) -> Users {
return Management(token: token, url: .httpsURL(from: domain), session: session)
}
#if WEB_AUTH_PLATFORM
/**
Auth0 client for performing web-based authentication with [Universal Login](https://auth0.com/docs/authenticate/login/auth0-universal-login).
## Usage
```swift
Auth0.webAuth()
```
The Auth0 Domain is loaded from the `Auth0.plist` file in your main bundle. It should have the following content:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ClientId</key>
<string>YOUR_AUTH0_CLIENT_ID</string>
<key>Domain</key>
<string>YOUR_AUTH0_DOMAIN</string>
</dict>
</plist>
```
- Parameters:
- session: `URLSession` instance used for networking. Defaults to `URLSession.shared`.
- bundle: Bundle used to locate the `Auth0.plist` file. Defaults to `Bundle.main`.
- Returns: Auth0 Web Auth client.
- Warning: Calling this method without a valid `Auth0.plist` file will crash your application.
*/
public func webAuth(session: URLSession = .shared, bundle: Bundle = Bundle.main) -> WebAuth {
let values = plistValues(bundle: bundle)!
return webAuth(clientId: values.clientId, domain: values.domain, session: session)
}
/**
Auth0 client for performing web-based authentication with [Universal Login](https://auth0.com/docs/authenticate/login/auth0-universal-login).
## Usage
```swift
Auth0.webAuth(clientId: "client-id", domain: "samples.us.auth0.com")
```
- Parameters:
- clientId: Client ID of your Auth0 application.
- domain: Domain of your Auth0 account, for example `samples.us.auth0.com`.
- session: `URLSession` instance used for networking. Defaults to `URLSession.shared`.
- Returns: Auth0 Web Auth client.
*/
public func webAuth(clientId: String, domain: String, session: URLSession = .shared) -> WebAuth {
return Auth0WebAuth(clientId: clientId, url: .httpsURL(from: domain), session: session)
}
#endif
func plistValues(bundle: Bundle) -> (clientId: String, domain: String)? {
guard let path = bundle.path(forResource: "Auth0", ofType: "plist"),
let values = NSDictionary(contentsOfFile: path) as? [String: Any] else {
print("Missing Auth0.plist file with 'ClientId' and 'Domain' entries in main bundle!")
return nil
}
guard let clientId = values["ClientId"] as? String, let domain = values["Domain"] as? String else {
print("Auth0.plist file at \(path) is missing 'ClientId' and/or 'Domain' entries!")
print("File currently has the following entries: \(values)")
return nil
}
return (clientId: clientId, domain: domain)
}
|
mit
|
f6b210f89a36f6bc8380dd5192539f72
| 33.495575 | 167 | 0.711904 | 3.780795 | false | false | false | false |
DonMag/ScratchPad
|
Swift3/scratchy/cubeRotate.playground/Pages/two tone.xcplaygroundpage/Contents.swift
|
1
|
7136
|
import UIKit
import CoreImage
import PlaygroundSupport
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
func scaledImage(image: UIImage, w: CGFloat, h: CGFloat) -> UIImage {
var sz = image.size
sz.width = w
sz.height = h
let hasAlpha = true
let scale: CGFloat = image.scale
UIGraphicsBeginImageContextWithOptions(sz, !hasAlpha, scale)
image.draw(in: CGRect(origin: CGPoint.zero, size: sz))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func boundedImage(image: UIImage, w: CGFloat, h: CGFloat) -> UIImage {
var imgsz = image.size
var sz = CGSize(width: w, height: h)
let xoff = (w - imgsz.width) / 2
let yoff = (h - imgsz.height) / 2
let p = CGPoint(x: xoff, y: yoff)
let hasAlpha = true
let scale: CGFloat = image.scale
UIGraphicsBeginImageContextWithOptions(sz, !hasAlpha, scale)
image.draw(in: CGRect(origin: p, size: imgsz))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func maskImage(image:UIImage, mask:UIImage) -> UIImage? {
if let imageReference = image.cgImage {
if let maskReference = mask.cgImage {
let imageMask = CGImage(
maskWidth: maskReference.width,
height: maskReference.height,
bitsPerComponent: maskReference.bitsPerComponent,
bitsPerPixel: maskReference.bitsPerPixel,
bytesPerRow: maskReference.bytesPerRow,
provider: maskReference.dataProvider!,
decode: nil,
shouldInterpolate: true)
let maskedReference = imageReference.masking(imageMask!)
let maskedImage = UIImage(cgImage:maskedReference!)
return maskedImage
}
}
return nil
}
let cView = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
cView.backgroundColor = UIColor.blue
PlaygroundPage.current.liveView = cView
var targImage = UIImage(named: "car")
var drop = UIImage(named: "iconOutline")
drop = UIImage(named: "bwDrop")
drop = UIImage(named: "whiteTranDrop")
let m = maskImage(image: targImage!, mask: drop!)
//targImage = UIImage(color: UIColor.clear, size: CGSize(width: 200, height: 200))
var iv = UIImageView(image: m)
iv.frame = CGRect(x: 10, y: 10, width: (750 / 4), height: 100)
cView.addSubview(iv)
var rd = UIImage(color: .red, size: (drop?.size)!)
let sc = UIImage(cgImage: (drop?.cgImage)!, scale: 0.75, orientation: (drop?.imageOrientation)!)
var m2 = maskImage(image: sc, mask: drop!)
let _m = drop
let _t = sc
let w = (drop?.size.width)! + 6 // * 1.01
let h = (drop?.size.height)! + 6 // * 1.01
let sDrop = scaledImage(image: drop!, w: w, h: h)
let bDrop = boundedImage(image: drop!, w: w, h: h)
m2 = maskImage(image: sDrop, mask: bDrop)
var iv2 = UIImageView(image: m2)
iv2.frame.origin.x = 20
iv2.frame.origin.y = 140
//iv2.backgroundColor = UIColor.yellow
cView.addSubview(iv2)
//UIImage *scaledImage =
// [UIImage imageWithCGImage:[imageToScale CGImage]
// scale:(imageToScale.scale * 3.0)
// orientation:(imageToScale.imageOrientation)];
//
//
//
//if 0 == 1 {
//if let maskImage = tmpMaskImage {
//
// var r = CGRect(origin: CGPoint.zero, size: maskImage.size)
//
// UIGraphicsBeginImageContextWithOptions(maskImage.size, false, maskImage.scale)
// var context = UIGraphicsGetCurrentContext()
//
// context?.setFillColor(UIColor.white.cgColor)
//
// context?.fill(r)
//
// var tmpWhiteImage = UIGraphicsGetImageFromCurrentImageContext()
//
// UIGraphicsEndImageContext()
//
// var ciContext = CIContext(options: nil)
// var filter = CIFilter(name: "CIBlendWithAlphaMask")
//
// var ciInput = CIImage(image: tmpWhiteImage!)
// var ciMask = CIImage(image: maskImage)
//
// filter?.setDefaults()
// filter?.setValue(ciInput, forKey: kCIInputImageKey)
// filter?.setValue(ciMask, forKey: kCIInputMaskImageKey)
//
// var whiteBackground = filter?.outputImage
//
// var scImage = scaledImage(image: targImage!, w: maskImage.size.width, h: maskImage.size.height)
//
//// scImage = scaledImage(image: maskImage, w: maskImage.size.width, h: maskImage.size.height - 20)
//
//
// filter = CIFilter(name: "CIBlendWithMask")
//
// ciInput = CIImage(image: scImage)
// ciMask = CIImage(image: maskImage)
//
// var ciBKG = whiteBackground
//
// filter?.setDefaults()
// filter?.setValue(ciInput, forKey: kCIInputImageKey)
// filter?.setValue(ciMask, forKey: kCIInputMaskImageKey)
//
// filter?.setValue(ciBKG, forKey: kCIInputBackgroundImageKey)
//
// let image = UIImage(cgImage: ciContext.createCGImage((filter?.outputImage)!, from: (filter?.outputImage?.extent)!)!)
//
//// image = [UIImage imageWithCGImage: [ciContext createCGImage: filter.outputImage
// //fromRect: [filter.outputImage extent]]];
//
// let imgV = UIImageView(image: image)
//
//// cView.addSubview(imgV)
//}
//
//}
//// The two-tone mask image
//UIImage *maskImage = [UIImage imageNamed: @"Mask"];
//
//// Create a filler image of whatever color we want the border to be (in my case white)
//UIGraphicsBeginImageContextWithOptions(maskImage.size, NO, maskImage.scale);
//CGContextRef context = UIGraphicsGetCurrentContext();
//CGContextSetFillColorWithColor(context, UIColor.whiteColor.CGColor);
//CGContextFillRect(context, CGRectMake(0.f, 0.f, maskImage.size.width, maskImage.size.height));
//UIImage *whiteImage = UIGraphicsGetImageFromCurrentImageContext();
//UIGraphicsEndImageContext();
//
//// Use CoreImage to mask the colored background to the mask (the entire opaque region of the mask)
//CIContext *ciContext = [CIContext contextWithOptions: nil];
//CIFilter *filter = [CIFilter filterWithName: @"CIBlendWithAlphaMask"];
//[filter setValue: [CIImage imageWithCGImage: whiteImage.CGImage]
//forKey: kCIInputImageKey];
//[filter setValue: [CIImage imageWithCGImage: maskImage.CGImage]
//forKey: kCIInputMaskImageKey];
//
//CIImage *whiteBackground = filter.outputImage;
//
//// scale the target image to the size of the mask (accounting for image scale)
//// ** Uses NYXImageKit
//image = [image scaleToSize: CGSizeMake(maskImage.size.width * maskImage.scale, maskImage.size.height * maskImage.scale)
//usingMode: NYXResizeModeAspectFill];
//
//// finally use Core Image to create our image using the masked white from above for our border and the inner (white) area of our mask image to mask the target image before compositing
//filter = [CIFilter filterWithName: @"CIBlendWithMask"];
//[filter setValue: [CIImage imageWithCGImage: image.CGImage]
//forKey: kCIInputImageKey];
//[filter setValue: whiteBackground
//forKey: kCIInputBackgroundImageKey];
//[filter setValue: [CIImage imageWithCGImage: maskImage.CGImage]
//forKey: kCIInputMaskImageKey];
//
//image = [UIImage imageWithCGImage: [ciContext createCGImage: filter.outputImage
//fromRect: [filter.outputImage extent]]];
|
mit
|
24391a39b475ff07d937422ce96f09e9
| 28.983193 | 185 | 0.727719 | 3.648262 | false | false | false | false |
netguru/inbbbox-ios
|
Unit Tests/AnimatableShotImageViewSpec.swift
|
1
|
1914
|
//
// ShotDetailsViewControllerSpec.swift
// Inbbbox
//
// Created by Blazej Wdowikowski on 12/6/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Quick
import Nimble
import Mockingjay
import Haneke
@testable import Inbbbox
class AnimatableShotImageViewSpec: QuickSpec {
override func spec() {
var imageView: AnimatableShotImageView!
beforeEach {
imageView = AnimatableShotImageView(frame: .zero)
}
afterEach {
imageView = nil
}
describe("when loading new imgae") {
var shot: ShotType!
var imageData: Data!
var url: URL!
beforeEach {
shot = Shot.fixtureGifShotWithIdentifier("fixture gif shot")
imageData = UIImagePNGRepresentation(#imageLiteral(resourceName: "ic-ball"))!
url = shot.shotImage.normalURL
Shared.dataCache.removeAll()
}
afterEach {
shot = nil
imageData = nil
url = nil
}
it("should download image only once with same given url ") {
imageView.loadAnimatableShotFromUrl(url)
imageView.loadAnimatableShotFromUrl(url)
expect(imageView.downloader.tasks).toEventually(haveCount(1))
}
it("shouldn't have tasks after download completion") {
self.stub(uri(url.absoluteString), http(200, headers: nil, download: .content(imageData)))
imageView.loadAnimatableShotFromUrl(url)
expect(imageView.downloader.tasks).toEventually(haveCount(0))
}
}
}
}
|
gpl-3.0
|
5aa85f0cfa575716c71add8b8ffc9eee
| 27.132353 | 106 | 0.520648 | 5.593567 | false | false | false | false |
GEOSwift/GEOSwift
|
Sources/GEOSwift/GEOS/GeometryConvertible+GEOS.swift
|
1
|
16667
|
import geos
public extension GeometryConvertible {
// MARK: - Misc Functions
func length() throws -> Double {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
var length: Double = 0
// returns 0 on exception
guard GEOSLength_r(context.handle, geosObject.pointer, &length) != 0 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return length
}
func distance(to geometry: GeometryConvertible) throws -> Double {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
let otherGeosObject = try geometry.geometry.geosObject(with: context)
var dist: Double = 0
// returns 0 on exception
guard GEOSDistance_r(context.handle, geosObject.pointer, otherGeosObject.pointer, &dist) != 0 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return dist
}
func area() throws -> Double {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
var area: Double = 0
// returns 0 on exception
guard GEOSArea_r(context.handle, geosObject.pointer, &area) != 0 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return area
}
func nearestPoints(with geometry: GeometryConvertible) throws -> [Point] {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
let otherGeosObject = try geometry.geometry.geosObject(with: context)
guard let coordSeq = GEOSNearestPoints_r(
context.handle, geosObject.pointer, otherGeosObject.pointer) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
defer { GEOSCoordSeq_destroy_r(context.handle, coordSeq) }
var point0 = Point(x: 0, y: 0)
GEOSCoordSeq_getX_r(context.handle, coordSeq, 0, &point0.x)
GEOSCoordSeq_getY_r(context.handle, coordSeq, 0, &point0.y)
var point1 = Point(x: 0, y: 0)
GEOSCoordSeq_getX_r(context.handle, coordSeq, 1, &point1.x)
GEOSCoordSeq_getY_r(context.handle, coordSeq, 1, &point1.y)
return [point0, point1]
}
// MARK: - Unary Predicates
internal typealias UnaryPredicate = (GEOSContextHandle_t, OpaquePointer) -> Int8
internal func evaluateUnaryPredicate(_ predicate: UnaryPredicate) throws -> Bool {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
// returns 2 on exception, 1 on true, 0 on false
let result = predicate(context.handle, geosObject.pointer)
guard result != 2 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return result == 1
}
func isEmpty() throws -> Bool {
try evaluateUnaryPredicate(GEOSisEmpty_r)
}
func isRing() throws -> Bool {
try evaluateUnaryPredicate(GEOSisRing_r)
}
func isValid() throws -> Bool {
try evaluateUnaryPredicate(GEOSisValid_r)
}
func isValidReason() throws -> String {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
guard let cString = GEOSisValidReason_r(context.handle, geosObject.pointer) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
defer { GEOSFree_r(context.handle, cString) }
return String(cString: cString)
}
func isValidDetail(allowSelfTouchingRingFormingHole: Bool = false) throws -> IsValidDetailResult {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
let flags: Int32 = allowSelfTouchingRingFormingHole
? Int32(GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE.rawValue)
: 0
var optionalReason: UnsafeMutablePointer<Int8>?
var optionalLocation: OpaquePointer?
switch GEOSisValidDetail_r(
context.handle, geosObject.pointer, flags, &optionalReason, &optionalLocation) {
case 1: // Valid
if let reason = optionalReason {
GEOSFree_r(context.handle, reason)
}
if let location = optionalLocation {
GEOSGeom_destroy_r(context.handle, location)
}
return .valid
case 0: // Invalid
let reason = optionalReason.map { (reason) -> String in
defer { GEOSFree_r(context.handle, reason) }
return String(cString: reason)
}
let location = try optionalLocation.map { (location) -> Geometry in
let locationGEOSObject = GEOSObject(context: context, pointer: location)
return try Geometry(geosObject: locationGEOSObject)
}
return .invalid(reason: reason, location: location)
default: // Error
throw GEOSError.libraryError(errorMessages: context.errors)
}
}
// MARK: - Binary Predicates
private typealias BinaryPredicate = (GEOSContextHandle_t, OpaquePointer, OpaquePointer) -> Int8
private func evaluateBinaryPredicate(_ predicate: BinaryPredicate,
with geometry: GeometryConvertible) throws -> Bool {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
let otherGeosObject = try geometry.geometry.geosObject(with: context)
// returns 2 on exception, 1 on true, 0 on false
let result = predicate(context.handle, geosObject.pointer, otherGeosObject.pointer)
guard result != 2 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return result == 1
}
func isTopologicallyEquivalent(to geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSEquals_r, with: geometry)
}
func isDisjoint(with geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSDisjoint_r, with: geometry)
}
func touches(_ geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSTouches_r, with: geometry)
}
func intersects(_ geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSIntersects_r, with: geometry)
}
func crosses(_ geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSCrosses_r, with: geometry)
}
func isWithin(_ geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSWithin_r, with: geometry)
}
func contains(_ geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSContains_r, with: geometry)
}
func overlaps(_ geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSOverlaps_r, with: geometry)
}
func covers(_ geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSCovers_r, with: geometry)
}
func isCovered(by geometry: GeometryConvertible) throws -> Bool {
try evaluateBinaryPredicate(GEOSCoveredBy_r, with: geometry)
}
// MARK: - Dimensionally Extended 9 Intersection Model Functions
/// Parameter mask: A DE9-IM mask pattern
func relate(_ geometry: GeometryConvertible, mask: String) throws -> Bool {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
let otherGeosObject = try geometry.geometry.geosObject(with: context)
// returns 2 on exception, 1 on true, 0 on false
let result = mask.withCString {
GEOSRelatePattern_r(context.handle, geosObject.pointer, otherGeosObject.pointer, $0)
}
guard result != 2 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return result == 1
}
func relate(_ geometry: GeometryConvertible) throws -> String {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
let otherGeosObject = try geometry.geometry.geosObject(with: context)
guard let cString = GEOSRelate_r(context.handle, geosObject.pointer, otherGeosObject.pointer) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
defer { GEOSFree_r(context.handle, cString) }
return String(cString: cString)
}
// MARK: - Topology Operations
internal typealias UnaryOperation = (GEOSContextHandle_t, OpaquePointer) -> OpaquePointer?
internal func performUnaryTopologyOperation<T>(_ operation: UnaryOperation) throws -> T
where T: GEOSObjectInitializable {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
guard let pointer = operation(context.handle, geosObject.pointer) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return try T(geosObject: GEOSObject(context: context, pointer: pointer))
}
private typealias BinaryOperation = (GEOSContextHandle_t, OpaquePointer, OpaquePointer) -> OpaquePointer?
private func performBinaryTopologyOperation(_ operation: BinaryOperation,
geometry: GeometryConvertible) throws -> Geometry {
let context = try GEOSContext()
let geosObject = try self.geometry.geosObject(with: context)
let otherGeosObject = try geometry.geometry.geosObject(with: context)
guard let pointer = operation(context.handle, geosObject.pointer, otherGeosObject.pointer) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return try Geometry(geosObject: GEOSObject(context: context, pointer: pointer))
}
func envelope() throws -> Envelope {
let geometry: Geometry = try performUnaryTopologyOperation(GEOSEnvelope_r)
switch geometry {
case let .point(point):
return Envelope(minX: point.x, maxX: point.x, minY: point.y, maxY: point.y)
case let .polygon(polygon):
var minX = Double.nan
var maxX = Double.nan
var minY = Double.nan
var maxY = Double.nan
for point in polygon.exterior.points {
minX = .minimum(minX, point.x)
maxX = .maximum(maxX, point.x)
minY = .minimum(minY, point.y)
maxY = .maximum(maxY, point.y)
}
return Envelope(minX: minX, maxX: maxX, minY: minY, maxY: maxY)
default:
throw GEOSwiftError.unexpectedEnvelopeResult(geometry)
}
}
func intersection(with geometry: GeometryConvertible) throws -> Geometry? {
do {
return try performBinaryTopologyOperation(GEOSIntersection_r, geometry: geometry)
} catch GEOSwiftError.tooFewPoints {
return nil
} catch {
throw error
}
}
func makeValid() throws -> Geometry {
try performUnaryTopologyOperation(GEOSMakeValid_r)
}
func normalized() throws -> Geometry {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
// GEOSNormalize_r returns -1 on exception
guard GEOSNormalize_r(context.handle, geosObject.pointer) != -1 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return try Geometry(geosObject: geosObject)
}
func convexHull() throws -> Geometry {
try performUnaryTopologyOperation(GEOSConvexHull_r)
}
func minimumRotatedRectangle() throws -> Geometry {
try performUnaryTopologyOperation(GEOSMinimumRotatedRectangle_r)
}
func minimumWidth() throws -> LineString {
try performUnaryTopologyOperation(GEOSMinimumWidth_r)
}
func difference(with geometry: GeometryConvertible) throws -> Geometry? {
do {
return try performBinaryTopologyOperation(GEOSDifference_r, geometry: geometry)
} catch GEOSwiftError.tooFewPoints {
return nil
} catch {
throw error
}
}
func symmetricDifference(with geometry: GeometryConvertible) throws -> Geometry? {
do {
return try performBinaryTopologyOperation(GEOSSymDifference_r, geometry: geometry)
} catch GEOSwiftError.tooFewPoints {
return nil
} catch {
throw error
}
}
func union(with geometry: GeometryConvertible) throws -> Geometry {
try performBinaryTopologyOperation(GEOSUnion_r, geometry: geometry)
}
func unaryUnion() throws -> Geometry {
try performUnaryTopologyOperation(GEOSUnaryUnion_r)
}
func pointOnSurface() throws -> Point {
try performUnaryTopologyOperation(GEOSPointOnSurface_r)
}
func centroid() throws -> Point {
try performUnaryTopologyOperation(GEOSGetCentroid_r)
}
func minimumBoundingCircle() throws -> Circle {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
var radius: Double = 0
var optionalCenterPointer: OpaquePointer?
guard let geometryPointer = GEOSMinimumBoundingCircle_r(
context.handle, geosObject.pointer, &radius, &optionalCenterPointer) else {
// if we somehow end up with a non-null center and a null geometry,
// we must still destroy the center before throwing an error
if let centerPointer = optionalCenterPointer {
GEOSGeom_destroy_r(context.handle, centerPointer)
}
throw GEOSError.libraryError(errorMessages: context.errors)
}
// For our purposes, we only care about the center and radius.
GEOSGeom_destroy_r(context.handle, geometryPointer)
guard let centerPointer = optionalCenterPointer else {
throw GEOSError.noMinimumBoundingCircle
}
let center = try Point(geosObject: GEOSObject(context: context, pointer: centerPointer))
return Circle(center: center, radius: radius)
}
func polygonize() throws -> GeometryCollection {
try [self].polygonize()
}
// MARK: - Buffer Functions
func buffer(by width: Double) throws -> Geometry? {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
// the last parameter in GEOSBuffer_r is called `quadsegs` and in other places in GEOS, it defaults to
// 8, which seems to produce an "expected" result. See https://github.com/GEOSwift/GEOSwift/issues/216
//
// returns nil on exception
guard let resultPointer = GEOSBuffer_r(context.handle, geosObject.pointer, width, 8) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
do {
return try Geometry(geosObject: GEOSObject(context: context, pointer: resultPointer))
} catch GEOSwiftError.tooFewPoints {
return nil
} catch {
throw error
}
}
// MARK: - Simplify Functions
func simplify(withTolerance tolerance: Double) throws -> Geometry {
let context = try GEOSContext()
let geosObject = try geometry.geosObject(with: context)
guard let resultPointer = GEOSSimplify_r(context.handle, geosObject.pointer, tolerance) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return try Geometry(geosObject: GEOSObject(context: context, pointer: resultPointer))
}
}
public extension Collection where Element: GeometryConvertible {
func polygonize() throws -> GeometryCollection {
let context = try GEOSContext()
let geosObjects = try map { try $0.geometry.geosObject(with: context) }
guard let pointer = GEOSPolygonize_r(
context.handle,
geosObjects.map { $0.pointer },
UInt32(geosObjects.count)) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return try GeometryCollection(geosObject: GEOSObject(context: context, pointer: pointer))
}
}
public enum IsValidDetailResult: Equatable {
case valid
case invalid(reason: String?, location: Geometry?)
}
|
mit
|
caf9d8e885885fbb31c7d83861f8a9e9
| 39.453883 | 110 | 0.649847 | 4.93837 | false | false | false | false |
victorchee/NavigationController
|
NavigationAppearance/NavigationAppearance/UIColor+Extension.swift
|
1
|
1370
|
//
// UIColor+Extension.swift
// NavigationAppearance
//
// Created by qihaijun on 12/2/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
extension UIColor {
// used solution from http://stackoverflow.com/a/29806108/4405316
var brightness: CGFloat {
let colorSpace = self.cgColor.colorSpace
let colorSpaceModel = colorSpace?.model
var brightness: CGFloat = 0
if colorSpaceModel == .rgb {
let components = self.cgColor.components
brightness = (components![0] * 299 + components![1] * 587 + components![2] * 114) / 1000
} else {
getWhite(&brightness, alpha: nil)
}
return brightness
}
var isBright: Bool {
return brightness > 0.5
}
func inverse() -> UIColor {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return UIColor(red: 1 - red, green: 1 - green, blue: 1 - blue, alpha: alpha)
}
class func randomColor() -> UIColor {
return UIColor(red: CGFloat(arc4random_uniform(255)) / 255, green: CGFloat(arc4random_uniform(255)) / 255, blue: CGFloat(arc4random_uniform(255)) / 255, alpha: CGFloat(arc4random_uniform(100)) / 100)
}
}
|
mit
|
5bb9064adbbeb6b1f1c1c5cc6383f41a
| 30.837209 | 207 | 0.601899 | 3.968116 | false | false | false | false |
damienpontifex/SwiftOpenCL
|
Sources/SimpleKernel/main.swift
|
1
|
1423
|
//
// main.swift
// SimpleKernel
//
// Created by Damien Pontifex on 26/07/2016.
// Copyright © 2016 Pontifex. All rights reserved.
//
import Foundation
import SwiftOpenCL
import OpenCL
guard let device = Device.default() else {
exit(EXIT_FAILURE)
}
do {
print("Using device \(device)")
let context = try Context(device: device)
let aInput: [cl_float] = [1, 2, 3, 4]
let bInput: [cl_float] = [5, 6, 7, 8]
let a = try Buffer<cl_float>(context: context, readOnlyData: aInput)
let b = try Buffer<cl_float>(context: context, readOnlyData: bInput)
let c = try Buffer<cl_float>(context: context, count: 4)
let source =
"__kernel void add(__global const float *a," +
" __global const float *b," +
" __global float *c)" +
"{" +
" const uint i = get_global_id(0);" +
" c[i] = a[i] + b[i];" +
"}";
let program = try Program(context: context, programSource: source)
try program.build(device)
let kernel = try Kernel(program: program, kernelName: "add")
try kernel.setArgs(a, b, c)
let queue = try CommandQueue(context: context, device: device)
let range = NDRange(size: 4)
try queue.enqueueNDRangeKernel(kernel, offset: NDRange(size: 0), global: range)
let cResult = c.enqueueRead(queue)
print("a: \(aInput)")
print("b: \(bInput)")
print("c: \(cResult)")
} catch let error as ClError {
print("Error \(error.err). \(error.errString)")
}
|
mit
|
1d4a7acf40db0ef9a85bc67ae4f17fe4
| 23.947368 | 80 | 0.637834 | 2.931959 | false | false | false | false |
jeesmon/varamozhi-ios
|
varamozhi/KeyboardInputTraits.swift
|
1
|
1889
|
//
// KeyboardInputTraits.swift
// RussianPhoneticKeyboard
//
// Created by Alexei Baboulevitch on 11/1/14.
// Copyright (c) 2014 Alexei Baboulevitch. All rights reserved.
//
import Foundation
import QuartzCore
import UIKit
// optional var autocorrectionType: UITextAutocorrectionType { get set } // default is UITextAutocorrectionTypeDefault
// @availability(iOS, introduced=5.0)
// optional var spellCheckingType: UITextSpellCheckingType { get set } // default is UITextSpellCheckingTypeDefault;
// optional var keyboardType: UIKeyboardType { get set } // default is UIKeyboardTypeDefault
// optional var returnKeyType: UIReturnKeyType { get set } // default is UIReturnKeyDefault (See note under UIReturnKeyType enum)
// optional var enablesReturnKeyAutomatically: Bool { get set } // default is NO (when YES, will automatically disable return key when text widget has zero-length contents, and will automatically enable when text widget has non-zero-length contents)
var traitPollingTimer: CADisplayLink?
extension KeyboardViewController {
func addInputTraitsObservers() {
// note that KVO doesn't work on textDocumentProxy, so we have to poll
traitPollingTimer?.invalidate()
traitPollingTimer = UIScreen.main.displayLink(withTarget: self, selector: #selector(KeyboardViewController.pollTraits))
traitPollingTimer?.add(to: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
}
@objc func pollTraits() {
let proxy = (self.textDocumentProxy as UITextInputTraits)
if let layout = self.layout {
let appearanceIsDark = (proxy.keyboardAppearance == UIKeyboardAppearance.dark)
if appearanceIsDark != layout.darkMode {
self.updateAppearances(appearanceIsDark)
}
}
}
}
|
gpl-2.0
|
250762a2bbfe593d6333ebc0f61848c7
| 45.073171 | 256 | 0.708841 | 5.291317 | false | false | false | false |
DrabWeb/Azusa
|
Source/Yui/Yui/Objects/Artist.swift
|
1
|
1108
|
//
// Artist.swift
// Yui
//
// Created by Ushio on 2/11/17.
//
import Foundation
/// The object to represent an artist in the user's music collection
public class Artist: Equatable, CustomStringConvertible {
// MARK: - Properties
// MARK: Public Properties
public var name : String = "";
public var albums : [Album] = [];
public var displayName : String {
return ((self.name != "") ? self.name : "Unknown Artist");
}
public var description : String {
return "AZArtist: \(self.displayName), \(self.albums.count) albums"
}
// MARK: - Methods
public static func ==(lhs : Artist, rhs : Artist) -> Bool {
return lhs.name == rhs.name;
}
// MARK: - Initialization and Deinitialization
public init(name : String, albums : [Album]) {
self.name = name;
self.albums = albums;
}
public init(name : String) {
self.name = name;
self.albums = [];
}
public init() {
self.name = "";
self.albums = [];
}
}
|
gpl-3.0
|
100aeeb3ced6dc5921cccab4e9c2d37e
| 19.90566 | 75 | 0.539711 | 4.277992 | false | false | false | false |
itszero/ZRTusKit
|
ZRTusKit/ZRTusUtils.swift
|
1
|
3336
|
//
// ZRTusUtils.swift
// ZRTusKit
//
// Created by Zero Cho on 4/18/15.
// Copyright (c) 2015 Zero. All rights reserved.
//
import Foundation
import BrightFutures
public class ZRTusUtils {
struct ZRTusHTTPResponse {
var httpResponse: NSHTTPURLResponse
var data: NSData
}
class ZRTusRequestDelegate : NSObject, NSURLConnectionDataDelegate {
let progressHandler: ((Int, Int) -> ())?
let completionHandler: (ZRTusRequestDelegate, NSHTTPURLResponse, NSData) -> ()
let errorHandler: (ZRTusRequestDelegate, NSError) -> ()
var response : NSHTTPURLResponse?
var data : NSMutableData?
init(
progressHandler: ((Int, Int) -> ())?,
completionHandler: (ZRTusRequestDelegate, NSHTTPURLResponse, NSData) -> (),
errorHandler: (ZRTusRequestDelegate, NSError) -> ()
) {
self.progressHandler = progressHandler
self.completionHandler = completionHandler
self.errorHandler = errorHandler
}
func connection(connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {
if let handler = progressHandler {
let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) * 100
handler(totalBytesWritten, totalBytesExpectedToWrite)
}
}
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
if (response.isKindOfClass(NSHTTPURLResponse)) {
self.response = response as? NSHTTPURLResponse
self.data = NSMutableData()
}
}
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
self.data!.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection) {
self.completionHandler(self, response!, data!)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
self.errorHandler(self, error)
}
}
static var delegates : [ZRTusRequestDelegate] = []
class func sendRequest(request: NSMutableURLRequest, progressHandler: ((Int, Int) -> ())? = nil) -> Future<ZRTusHTTPResponse> {
let promise = Promise<ZRTusHTTPResponse>()
var resp: NSURLResponse? = nil
var error: NSError? = nil
self.injectHeaders(request)
func completionHandler(delegate: ZRTusRequestDelegate, resp: NSHTTPURLResponse, data: NSData) {
removeObject(delegate, fromArray: &delegates)
let myResponse = ZRTusHTTPResponse(httpResponse: resp, data: data)
promise.success(myResponse)
}
func errorHandler(delegate: ZRTusRequestDelegate, error: NSError) {
removeObject(delegate, fromArray: &delegates)
promise.failure(error)
}
let delegate = ZRTusRequestDelegate(
progressHandler: progressHandler,
completionHandler: completionHandler,
errorHandler: errorHandler
)
delegates.append(delegate)
let urlConnection = NSURLConnection(
request: request,
delegate: delegate,
startImmediately: true
)
return promise.future
}
class func injectHeaders(request: NSMutableURLRequest) {
request.addValue("1.0", forHTTPHeaderField: "Tus-Resumable")
}
}
private func removeObject<T : Equatable>(object: T, inout fromArray array: [T])
{
var index = find(array, object)
array.removeAtIndex(index!)
}
|
mit
|
a0cbc197678b5b0b268a52e4c2c90187
| 30.186916 | 141 | 0.706235 | 4.934911 | false | false | false | false |
InsectQY/HelloSVU_Swift
|
HelloSVU_Swift/Classes/Module/Map/Route/Bus/Detail/View/TableView/SectionFooter/BusRouteDetailCellFooter.swift
|
1
|
1757
|
//
// BusRouteDetailCellFooter.swift
// HelloSVU_Swift
//
// Created by Insect on 2017/10/16.
// Copyright © 2017年 Insect. All rights reserved.
//
import UIKit
class BusRouteDetailCellFooter: UITableViewHeaderFooterView,NibReusable {
@IBOutlet private weak var distanceLabel: UILabel!
@IBOutlet private weak var arrivalStopLabel: UILabel!
@IBOutlet private weak var exitNameBtn: UIButton!
@IBOutlet private weak var walkNaviBtn: UIButton!
@IBOutlet private weak var durationLabel: UILabel!
/// 包含是否展开,是否有多条busline 以及选择的是第几组的信息
var info: BusSegment?
var segment: AMapSegment? {
didSet {
var busLineIndex = 0
if info?.isSpecified == true {
busLineIndex = info?.busLineIndex ?? 0
}
arrivalStopLabel.text = segment?.buslines[busLineIndex].arrivalStop.name
checkEnterAndExitName()
}
}
var walking: AMapWalking? {
didSet {
durationLabel.isHidden = walking?.duration == 0
walkNaviBtn.isHidden = walking?.duration == 0
durationLabel.text = CalculateTool.getDuration(walking?.duration ?? 0)
distanceLabel.text = CalculateTool.getWalkDistance(CGFloat(walking?.distance ?? 0))
}
}
}
extension BusRouteDetailCellFooter {
// MARK: - 检查是否存在进站口和出站口
private func checkEnterAndExitName() {
exitNameBtn.isHidden = (segment?.exitName.length != nil)
if segment?.exitName.length != nil {
exitNameBtn.setTitle("\(String(describing: segment?.exitName))出", for: .normal)
}
}
}
|
apache-2.0
|
67fda563c3e0887c94b0e922bdb28fd6
| 28.438596 | 95 | 0.626341 | 4.510753 | false | false | false | false |
Mykhailo-Vorontsov-owo/OfflineCommute
|
OfflineCommute/Sources/Controllers/SyncOperations/UpdateDistanceSyncOperation.swift
|
1
|
1469
|
//
// UpdateDistanceSyncOperation.swift
// OfflineCommute
//
// Created by Mykhailo Vorontsov on 27/02/2016.
// Copyright © 2016 Mykhailo Vorontsov. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class UpdateDistanceSyncOperation: DataRetrievalOperation, ManagedObjectRetrievalOperationProtocol {
let center:CLLocationCoordinate2D
var dataManager: CoreDataManager!
init(center:CLLocationCoordinate2D) {
self.center = center
super.init()
}
// override func main() {
override func parseData() throws {
var internalError:ErrorType? = nil
let context = dataManager.dataContext
context.performBlockAndWait { () -> Void in
// Clear old data
do {
guard let allDocks = try context.executeFetchRequest(NSFetchRequest(entityName: "DockStation")) as? [DockStation] else {
return
}
let location = CLLocation(latitude: self.center.latitude, longitude: self.center.longitude)
for dock in allDocks {
let dockLocation = CLLocation(latitude:dock.latitude.doubleValue, longitude: dock.longitude.doubleValue)
let distance = location.distanceFromLocation(dockLocation)
dock.distance = distance
}
try context.save()
} catch {
internalError = error
}
}
guard nil == internalError else {
throw internalError!
}
}
}
|
mit
|
e95e1c95a5160bb7e69e1e68ea9c646a
| 24.310345 | 128 | 0.653951 | 4.781759 | false | false | false | false |
whatme/BSImagePicker
|
Pod/Classes/Controller/AlbumsViewController.swift
|
1
|
1701
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
final class AlbumsViewController: UITableViewController {
override func loadView() {
super.loadView()
// Add a little bit of blur to the background
let visualEffectView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: UIBlurEffect(style: .Light)))
visualEffectView.frame = tableView.bounds
visualEffectView.autoresizingMask = [.FlexibleWidth , .FlexibleHeight]
tableView.backgroundView = visualEffectView
tableView.backgroundColor = UIColor.clearColor()
}
}
|
mit
|
4611f4bd63e08feef27a9a6b381aa7ed
| 46.222222 | 119 | 0.746471 | 5.014749 | false | false | false | false |
powerytg/PearlCam
|
PearlCam/PearlFX/Filters/VibranceFilterNode.swift
|
2
|
700
|
//
// VibranceFilterNode.swift
// PearlCam
//
// Created by Tiangong You on 6/10/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import GPUImage
class VibranceFilterNode: FilterNode {
var vibranceFilter = Vibrance()
init() {
super.init(filter: vibranceFilter)
enabled = true
}
var vibrance : Float? {
didSet {
if vibrance != nil {
vibranceFilter.vibrance = vibrance!
}
}
}
override func cloneFilter() -> FilterNode? {
let clone = VibranceFilterNode()
clone.enabled = enabled
clone.vibrance = vibrance
return clone
}
}
|
bsd-3-clause
|
8e9da5b8a3f88d2a292f8d9475293ce3
| 18.971429 | 55 | 0.573677 | 3.971591 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
src/AsciiArtPlayer/Pods/DKImagePickerController/DKImagePickerController/View/DKPermissionView.swift
|
7
|
2001
|
//
// DKPermissionView.swift
// DKImagePickerControllerDemo
//
// Created by ZhangAo on 15/12/17.
// Copyright © 2015年 ZhangAo. All rights reserved.
//
import UIKit
@objc
open class DKPermissionView: UIView {
private let titleLabel = UILabel()
private let permitButton = UIButton()
open class func permissionView(_ style: DKImagePickerControllerSourceType) -> DKPermissionView {
let permissionView = DKPermissionView()
permissionView.addSubview(permissionView.titleLabel)
permissionView.addSubview(permissionView.permitButton)
if style == .photo {
permissionView.titleLabel.text = DKImageLocalizedStringWithKey("permissionPhoto")
permissionView.titleLabel.textColor = UIColor.gray
} else {
permissionView.titleLabel.textColor = UIColor.white
permissionView.titleLabel.text = DKImageLocalizedStringWithKey("permissionCamera")
}
permissionView.titleLabel.sizeToFit()
permissionView.permitButton.setTitle(DKImageLocalizedStringWithKey("permit"), for: .normal)
permissionView.permitButton.setTitleColor(UIColor(red: 0, green: 122.0 / 255, blue: 1, alpha: 1), for: .normal)
permissionView.permitButton.addTarget(permissionView, action: #selector(DKPermissionView.gotoSettings), for: .touchUpInside)
permissionView.permitButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
permissionView.permitButton.sizeToFit()
permissionView.permitButton.center = CGPoint(x: permissionView.titleLabel.center.x,
y: permissionView.titleLabel.bounds.height + 40)
permissionView.frame.size = CGSize(width: max(permissionView.titleLabel.bounds.width, permissionView.permitButton.bounds.width),
height: permissionView.permitButton.frame.maxY)
return permissionView
}
open override func didMoveToWindow() {
super.didMoveToWindow()
self.center = self.superview!.center
}
open func gotoSettings() {
if let appSettings = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(appSettings)
}
}
}
|
mit
|
48df7ae66db04114e641343579651ca9
| 33.448276 | 130 | 0.777778 | 4.44 | false | false | false | false |
getsentry/sentry-swift
|
Tests/SentryTests/Integrations/Performance/SentrySubClassFinderTests.swift
|
1
|
4036
|
import ObjectiveC
import XCTest
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
class SentrySubClassFinderTests: XCTestCase {
private class Fixture {
lazy var runtimeWrapper: SentryTestObjCRuntimeWrapper = {
let result = SentryTestObjCRuntimeWrapper()
result.classesNames = { _ in
return self.testClassesNames
}
return result
}()
let imageName: String
let testClassesNames = [NSStringFromClass(FirstViewController.self),
NSStringFromClass(SecondViewController.self),
NSStringFromClass(ViewControllerNumberThree.self),
NSStringFromClass(VCAnyNaming.self),
NSStringFromClass(FakeViewController.self)]
init() {
if let name = class_getImageName(FirstViewController.self) {
imageName = String(cString: name, encoding: .utf8) ?? ""
} else {
imageName = ""
}
}
var sut: SentrySubClassFinder {
return SentrySubClassFinder(dispatchQueue: SentryDispatchQueueWrapper(), objcRuntimeWrapper: runtimeWrapper)
}
}
private var fixture: Fixture!
override func setUp() {
super.setUp()
fixture = Fixture()
}
func testActOnSubclassesOfViewController() {
testActOnSubclassesOfViewController(expected: [FirstViewController.self, SecondViewController.self, ViewControllerNumberThree.self, VCAnyNaming.self])
}
func testActOnSubclassesOfViewController_NoViewController() {
fixture.runtimeWrapper.classesNames = { _ in [] }
testActOnSubclassesOfViewController(expected: [])
}
func testActOnSubclassesOfViewController_IgnoreFakeViewController() {
fixture.runtimeWrapper.classesNames = { _ in [NSStringFromClass(FakeViewController.self)] }
testActOnSubclassesOfViewController(expected: [])
}
func testActOnSubclassesOfViewController_WrongImage_NoViewController() {
fixture.runtimeWrapper.classesNames = nil
testActOnSubclassesOfViewController(expected: [], imageName: "OtherImage")
}
func testGettingSublcasses_DoesNotCallInitializer() {
let sut = SentrySubClassFinder(dispatchQueue: TestSentryDispatchQueueWrapper(), objcRuntimeWrapper: fixture.runtimeWrapper)
var actual: [AnyClass] = []
sut.actOnSubclassesOfViewController(inImage: fixture.imageName) { subClass in
actual.append(subClass)
}
XCTAssertFalse(SentryInitializeForGettingSubclassesCalled.wasCalled())
}
private func testActOnSubclassesOfViewController(expected: [AnyClass]) {
testActOnSubclassesOfViewController(expected: expected, imageName: fixture.imageName)
}
private func testActOnSubclassesOfViewController(expected: [AnyClass], imageName: String) {
let expect = expectation(description: "")
if expected.isEmpty {
expect.isInverted = true
} else {
expect.expectedFulfillmentCount = expected.count
}
var actual: [AnyClass] = []
fixture.sut.actOnSubclassesOfViewController(inImage: imageName) { subClass in
XCTAssertTrue(Thread.isMainThread, "Block must be executed on the main thread.")
actual.append(subClass)
expect.fulfill()
}
wait(for: [expect], timeout: 1)
let count = actual.filter { element in
return expected.contains { ex in
return element == ex
}
}.count
XCTAssertEqual(expected.count, count)
}
}
class FirstViewController: UIViewController {}
class SecondViewController: UIViewController {}
class ViewControllerNumberThree: UIViewController {}
class VCAnyNaming: UIViewController {}
class FakeViewController {}
#endif
|
mit
|
b6209cf37cdfa52e8eec08d21fd653f9
| 36.37037 | 158 | 0.643954 | 5.551582 | false | true | false | false |
paulofaria/SwiftHTTPServer
|
Log/Log.swift
|
3
|
5188
|
// Log.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
struct Log {
// MARK: - Levels
struct Levels: OptionSetType {
let rawValue: Int32
static let Trace = Levels(rawValue: 1 << 0)
static let Debug = Levels(rawValue: 1 << 1)
static let Info = Levels(rawValue: 1 << 2)
static let Warning = Levels(rawValue: 1 << 3)
static let Error = Levels(rawValue: 1 << 4)
static let Fatal = Levels(rawValue: 1 << 5)
}
static var levels: Levels = [.Trace, .Debug, .Info, .Warning, .Error, .Fatal]
// MARK: - Colors
static var colorsEnabled: Bool {
let xcodeColors = getenv("XcodeColors")
if let enabled = String.fromCString(xcodeColors) where enabled == "YES" {
return true
}
return false
}
// TODO: Make all of this variables return empty string when color is not available
static let escape = "\u{001b}["
static let resetForeground = escape + "fg;"
static let resetBackground = escape + "bg;"
static let reset = escape + ";"
static let lightBlue = escape + "fg33,183,195;"
static let red = escape + "fg179,67,62;"
//static let darkPurple = escape + "fg89,87,185;"
static let darkPurple = escape + "fg60,58,123;"
static let purple = escape + "fg97,92,168;"
//static let lightPurple = escape + "fg118,112,205;"
static let lightPurple = escape + "fg139,110,255;"
static let darkGreen = escape + "fg55,86,66;"
static let green = escape + "fg82,128,97;"
static let lightGreen = escape + "fg96,172,127;"
}
// MARK: - Public
extension Log {
private static func log<T>(object: T, color: String) {
if colorsEnabled {
print("\(color)\(object)\(reset)")
} else {
print(object)
}
}
static func trace<T>(object: T) {
if levels.contains(.Trace) {
log("\(object)", color: red)
}
}
static func debug<T>(object: T) {
if levels.contains(.Debug) {
log("\(object)", color: red)
}
}
static func info<T>(object: T) {
if levels.contains(.Info) {
log("\(object)", color: lightGreen)
}
}
static func warning<T>(object: T) {
if levels.contains(.Warning) {
log("\(object)", color: red)
}
}
static func error<T>(object: T) {
if levels.contains(.Error) {
log("\(object)", color: red)
}
}
static func fatal<T>(object: T) {
if levels.contains(.Fatal) {
log("\(object)", color: red)
}
}
}
protocol CustomColorLogStringConvertible {
var logDescription: String { get }
}
extension Log {
private static func customColorLog(object: CustomColorLogStringConvertible) {
if colorsEnabled {
print(object.logDescription)
} else {
print(object)
}
}
static func trace(object: CustomColorLogStringConvertible) {
if levels.contains(.Trace) {
customColorLog(object)
}
}
static func debug(object: CustomColorLogStringConvertible) {
if levels.contains(.Debug) {
customColorLog(object)
}
}
static func info(object: CustomColorLogStringConvertible) {
if levels.contains(.Info) {
customColorLog(object)
}
}
static func warning(object: CustomColorLogStringConvertible) {
if levels.contains(.Warning) {
customColorLog(object)
}
}
static func error(object: CustomColorLogStringConvertible) {
if levels.contains(.Error) {
customColorLog(object)
}
}
static func fatal(object: CustomColorLogStringConvertible) {
if levels.contains(.Fatal) {
customColorLog(object)
}
}
}
|
mit
|
a84ae5c44bdaf86616f3bb95b694fc7c
| 20.179592 | 87 | 0.587895 | 4.422847 | false | false | false | false |
apple/swift
|
test/Compatibility/special_case_name.swift
|
4
|
776
|
// RUN: %target-typecheck-verify-swift -swift-version 4
// https://github.com/apple/swift/issues/44269
enum DayOfTheWeek : Int {
case monday = 0
case `inout` = 1
case `init` = 2
case friday = 3
case tuesday = 4
}
let _: DayOfTheWeek = DayOfTheWeek.init
let _: DayOfTheWeek = DayOfTheWeek.`init`
func match(_ d: DayOfTheWeek) {
switch d {
case .monday: break
case .`inout`: break
case .`init`: break
case .friday: break
case .tuesday: break
}
}
enum Fox {
case `init`(Int)
init() {
self = .`init`(10)
}
}
let _: Fox = Fox(10)
// expected-error@-1 {{argument passed to call that takes no arguments}}
let _: () -> Fox = Fox.init
let _: (Int) -> Fox = Fox.`init`
func match(_ f: Fox) {
switch f {
case .`init`(let n): _ = n
}
}
|
apache-2.0
|
d2ce8abd653fe89e4c35ffbae32a681e
| 16.244444 | 72 | 0.608247 | 3.067194 | false | false | false | false |
noblakit01/PhotoCollectionView
|
PhotoCollectionViewDemo/URLTableViewCell.swift
|
1
|
1242
|
//
// URLTableViewCell.swift
// PhotoCollectionView
//
// Created by Minh Luan Tran on 9/20/17.
//
//
import UIKit
import PhotoCollectionView
class URLTableViewCell: UITableViewCell {
@IBOutlet weak var photoCollectionView: PhotoCollectionView!
@IBOutlet weak var indexLabel: UILabel!
@IBOutlet weak var photoCollectionViewHeight: NSLayoutConstraint!
var urls: [String] = [] {
didSet {
if urls != oldValue {
photoCollectionView.reloadData()
}
photoCollectionViewHeight.constant = photoCollectionView.intrinsicContentSize.height
}
}
override func awakeFromNib() {
super.awakeFromNib()
photoCollectionView.dataSource = self
}
func set(index: Int) {
photoCollectionView.tag = index
indexLabel.text = "Cell \(index)"
}
}
extension URLTableViewCell: PhotoCollectionViewDataSource {
func photoCollectionView(_ photoCollectionView: PhotoCollectionView, photoSource index: Int) -> PhotoSource {
return .url(URL(string: urls[index]))
}
func numPhotos(in photoCollectionView: PhotoCollectionView) -> Int {
return urls.count
}
}
|
mit
|
67062b184dbf828e66a499fb12174ef8
| 23.352941 | 113 | 0.648148 | 5.218487 | false | false | false | false |
SamirTalwar/advent-of-code
|
2018/AOC_01_2.swift
|
1
|
277
|
func main() {
let numbers = StdIn().map { Int($0)! }
var seen: Set<Int> = []
var i = 0
var current = 0
while !seen.contains(current) {
seen.insert(current)
current += numbers[i]
i = (i + 1) % numbers.count
}
print(current)
}
|
mit
|
aa89fb7ed3ee5d47016d022cadd68ccb
| 22.083333 | 42 | 0.512635 | 3.297619 | false | false | false | false |
WhisperSystems/Signal-iOS
|
Signal/src/ViewControllers/MediaGallery/MediaPageViewController.swift
|
1
|
33085
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
import PromiseKit
// Objc wrapper for the MediaGalleryItem struct
@objc
public class GalleryItemBox: NSObject {
public let value: MediaGalleryItem
init(_ value: MediaGalleryItem) {
self.value = value
}
@objc
public var attachmentStream: TSAttachmentStream {
return value.attachmentStream
}
}
fileprivate extension MediaDetailViewController {
var galleryItem: MediaGalleryItem {
return self.galleryItemBox.value
}
}
class MediaPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, MediaDetailViewControllerDelegate, MediaGalleryDataSourceDelegate {
private weak var mediaGalleryDataSource: MediaGalleryDataSource?
private weak var mediaPageViewDelegate: MediaPageViewDelegate?
var mediaInteractiveDismiss: MediaInteractiveDismiss!
private var cachedPages: [MediaGalleryItem: MediaDetailViewController] = [:]
private var initialPage: MediaDetailViewController!
public var currentViewController: MediaDetailViewController {
return viewControllers!.first as! MediaDetailViewController
}
public var currentItem: MediaGalleryItem! {
return currentViewController.galleryItemBox.value
}
public func setCurrentItem(_ item: MediaGalleryItem, direction: UIPageViewController.NavigationDirection, animated isAnimated: Bool) {
guard let galleryPage = self.buildGalleryPage(galleryItem: item) else {
owsFailDebug("unexpectedly unable to build new gallery page")
return
}
updateTitle(item: item)
updateCaption(item: item)
setViewControllers([galleryPage], direction: direction, animated: isAnimated)
updateFooterBarButtonItems(isPlayingVideo: false)
updateMediaRail()
}
private let showAllMediaButton: Bool
private let sliderEnabled: Bool
init(initialItem: MediaGalleryItem,
mediaGalleryDataSource: MediaGalleryDataSource,
mediaPageViewDelegate: MediaPageViewDelegate,
options: MediaGalleryOption) {
self.mediaGalleryDataSource = mediaGalleryDataSource
self.mediaPageViewDelegate = mediaPageViewDelegate
self.showAllMediaButton = options.contains(.showAllMediaButton)
self.sliderEnabled = options.contains(.sliderEnabled)
let kSpacingBetweenItems: CGFloat = 20
let pageViewOptions: [UIPageViewController.OptionsKey: Any] = [.interPageSpacing: kSpacingBetweenItems]
super.init(transitionStyle: .scroll,
navigationOrientation: .horizontal,
options: pageViewOptions)
self.dataSource = self
self.delegate = self
guard let initialPage = self.buildGalleryPage(galleryItem: initialItem) else {
owsFailDebug("unexpectedly unable to build initial gallery item")
return
}
self.initialPage = initialPage
self.setViewControllers([initialPage], direction: .forward, animated: false, completion: nil)
}
@available(*, unavailable, message: "Unimplemented")
required init?(coder: NSCoder) {
notImplemented()
}
deinit {
Logger.debug("deinit")
}
// MARK: - Dependencies
var databaseStorage: SDSDatabaseStorage {
return SDSDatabaseStorage.shared
}
// MARK: - Subview
// MARK: Bottom Bar
var bottomContainer: UIView!
var footerBar: UIToolbar!
let captionContainerView: CaptionContainerView = CaptionContainerView()
var galleryRailView: GalleryRailView = GalleryRailView()
var pagerScrollView: UIScrollView!
// MARK: UIViewController overrides
// HACK: Though we don't have an input accessory view, the VC we are presented above (ConversationVC) does.
// If the app is backgrounded and then foregrounded, when OWSWindowManager calls mainWindow.makeKeyAndVisible
// the ConversationVC's inputAccessoryView will appear *above* us unless we'd previously become first responder.
override public var canBecomeFirstResponder: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Navigation
// Note: using a custom leftBarButtonItem breaks the interactive pop gesture, but we don't want to be able
// to swipe to go back in the pager view anyway, instead swiping back should show the next page.
let backButton = OWSViewController.createOWSBackButton(withTarget: self, selector: #selector(didPressDismissButton))
self.navigationItem.leftBarButtonItem = backButton
mediaInteractiveDismiss = MediaInteractiveDismiss(mediaPageViewController: self)
mediaInteractiveDismiss.addGestureRecognizer(to: view)
self.navigationItem.titleView = portraitHeaderView
if showAllMediaButton {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: MediaStrings.allMedia, style: .plain, target: self, action: #selector(didPressAllMediaButton))
}
// Even though bars are opaque, we want content to be layed out behind them.
// The bars might obscure part of the content, but they can easily be hidden by tapping
// The alternative would be that content would shift when the navbars hide.
self.extendedLayoutIncludesOpaqueBars = true
self.automaticallyAdjustsScrollViewInsets = false
// Get reference to paged content which lives in a scrollView created by the superclass
// We show/hide this content during presentation
for view in self.view.subviews {
if let pagerScrollView = view as? UIScrollView {
self.pagerScrollView = pagerScrollView
}
}
// Hack to avoid "page" bouncing when not in gallery view.
// e.g. when getting to media details via message details screen, there's only
// one "Page" so the bounce doesn't make sense.
pagerScrollView.isScrollEnabled = sliderEnabled
pagerScrollViewContentOffsetObservation = pagerScrollView.observe(\.contentOffset, options: [.new]) { [weak self] _, change in
guard let strongSelf = self else { return }
strongSelf.pagerScrollView(strongSelf.pagerScrollView, contentOffsetDidChange: change)
}
// Views
view.backgroundColor = Theme.darkThemeBackgroundColor
captionContainerView.delegate = self
updateCaptionContainerVisibility()
galleryRailView.delegate = self
galleryRailView.autoSetDimension(.height, toSize: 72)
let footerBar = self.makeClearToolbar()
self.footerBar = footerBar
footerBar.tintColor = .white
let bottomContainer = UIView()
self.bottomContainer = bottomContainer
bottomContainer.backgroundColor = UIColor.ows_black.withAlphaComponent(0.4)
let bottomStack = UIStackView(arrangedSubviews: [captionContainerView, galleryRailView, footerBar])
bottomStack.axis = .vertical
bottomContainer.addSubview(bottomStack)
bottomStack.autoPinEdgesToSuperviewEdges()
self.view.addSubview(bottomContainer)
bottomContainer.autoPinWidthToSuperview()
bottomContainer.autoPinEdge(toSuperviewEdge: .bottom)
footerBar.autoPin(toBottomLayoutGuideOf: self, withInset: 0)
footerBar.autoSetDimension(.height, toSize: 44)
updateTitle()
updateCaption(item: currentItem)
updateMediaRail()
updateFooterBarButtonItems(isPlayingVideo: true)
// Gestures
let verticalSwipe = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeView))
verticalSwipe.direction = [.up, .down]
view.addGestureRecognizer(verticalSwipe)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let isLandscape = size.width > size.height
self.navigationItem.titleView = isLandscape ? nil : self.portraitHeaderView
}
override func didReceiveMemoryWarning() {
Logger.info("")
super.didReceiveMemoryWarning()
self.cachedPages = [:]
}
// MARK: KVO
var pagerScrollViewContentOffsetObservation: NSKeyValueObservation?
func pagerScrollView(_ pagerScrollView: UIScrollView, contentOffsetDidChange change: NSKeyValueObservedChange<CGPoint>) {
guard let newValue = change.newValue else {
owsFailDebug("newValue was unexpectedly nil")
return
}
let width = pagerScrollView.frame.size.width
guard width > 0 else {
return
}
let ratioComplete = abs((newValue.x - width) / width)
captionContainerView.updatePagerTransition(ratioComplete: ratioComplete)
}
// MARK: View Helpers
public func willBePresentedAgain() {
updateFooterBarButtonItems(isPlayingVideo: false)
}
public func wasPresented() {
let currentViewController = self.currentViewController
if currentViewController.galleryItem.isVideo {
currentViewController.playVideo()
}
}
private func makeClearToolbar() -> UIToolbar {
let toolbar = UIToolbar()
toolbar.backgroundColor = UIColor.clear
// Making a toolbar transparent requires setting an empty uiimage
toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
// hide 1px top-border
toolbar.clipsToBounds = true
return toolbar
}
private var shouldHideToolbars: Bool = false {
didSet {
if (oldValue == shouldHideToolbars) {
return
}
// Hiding the status bar affects the positioning of the navbar. We don't want to show that in an animation, it's
// better to just have everythign "flit" in/out.
UIApplication.shared.setStatusBarHidden(shouldHideToolbars, with: .none)
self.navigationController?.setNavigationBarHidden(shouldHideToolbars, animated: false)
UIView.animate(withDuration: 0.1) {
self.currentViewController.setShouldHideToolbars(self.shouldHideToolbars)
self.bottomContainer.isHidden = self.shouldHideToolbars
}
}
}
// MARK: Bar Buttons
lazy var shareBarButton: UIBarButtonItem = {
let shareBarButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(didPressShare))
shareBarButton.tintColor = Theme.darkThemePrimaryColor
return shareBarButton
}()
lazy var deleteBarButton: UIBarButtonItem = {
let deleteBarButton = UIBarButtonItem(barButtonSystemItem: .trash,
target: self,
action: #selector(didPressDelete))
deleteBarButton.tintColor = Theme.darkThemePrimaryColor
return deleteBarButton
}()
func buildFlexibleSpace() -> UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}
lazy var videoPlayBarButton: UIBarButtonItem = {
let videoPlayBarButton = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(didPressPlayBarButton))
videoPlayBarButton.tintColor = Theme.darkThemePrimaryColor
return videoPlayBarButton
}()
lazy var videoPauseBarButton: UIBarButtonItem = {
let videoPauseBarButton = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action:
#selector(didPressPauseBarButton))
videoPauseBarButton.tintColor = Theme.darkThemePrimaryColor
return videoPauseBarButton
}()
private func updateFooterBarButtonItems(isPlayingVideo: Bool) {
// TODO do we still need this? seems like a vestige
// from when media detail view was used for attachment approval
if self.footerBar == nil {
owsFailDebug("No footer bar visible.")
return
}
var toolbarItems: [UIBarButtonItem] = [
shareBarButton,
buildFlexibleSpace()
]
if (self.currentItem.isVideo) {
toolbarItems += [
isPlayingVideo ? self.videoPauseBarButton : self.videoPlayBarButton,
buildFlexibleSpace()
]
}
toolbarItems.append(deleteBarButton)
self.footerBar.setItems(toolbarItems, animated: false)
}
func updateMediaRail() {
guard let currentItem = self.currentItem else {
owsFailDebug("currentItem was unexpectedly nil")
return
}
galleryRailView.configureCellViews(itemProvider: currentItem.album,
focusedItem: currentItem,
cellViewBuilder: { _ in return GalleryRailCellView() })
}
// MARK: Actions
@objc
public func didPressAllMediaButton(sender: Any) {
Logger.debug("")
guard let mediaPageViewDelegate = self.mediaPageViewDelegate else {
owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
return
}
mediaPageViewDelegate.mediaPageViewControllerDidTapAllMedia(self)
}
@objc
public func didSwipeView(sender: Any) {
Logger.debug("")
self.dismissSelf(animated: true)
}
@objc
public func didPressDismissButton(_ sender: Any) {
dismissSelf(animated: true)
}
@objc
public func didPressShare(_ sender: Any) {
guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
owsFailDebug("currentViewController was unexpectedly nil")
return
}
let attachmentStream = currentViewController.galleryItem.attachmentStream
AttachmentSharing.showShareUI(forAttachment: attachmentStream)
}
@objc
public func didPressDelete(_ sender: Any) {
guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
owsFailDebug("currentViewController was unexpectedly nil")
return
}
guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
return
}
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let deleteAction = UIAlertAction(title: NSLocalizedString("TXT_DELETE_TITLE", comment: ""),
style: .destructive) { _ in
let deletedItem = currentViewController.galleryItem
mediaGalleryDataSource.delete(items: [deletedItem], initiatedBy: self)
}
actionSheet.addAction(OWSAlerts.cancelAction)
actionSheet.addAction(deleteAction)
self.presentAlert(actionSheet)
}
// MARK: MediaGalleryDataSourceDelegate
func mediaGalleryDataSource(_ mediaGalleryDataSource: MediaGalleryDataSource, willDelete items: [MediaGalleryItem], initiatedBy: AnyObject) {
Logger.debug("")
guard let currentItem = self.currentItem else {
owsFailDebug("currentItem was unexpectedly nil")
return
}
guard items.contains(currentItem) else {
Logger.debug("irrelevant item")
return
}
// If we setCurrentItem with (animated: true) while this VC is in the background, then
// the next/previous cache isn't expired, and we're able to swipe back to the just-deleted vc.
// So to get the correct behavior, we should only animate these transitions when this
// vc is in the foreground
let isAnimated = initiatedBy === self
if !self.sliderEnabled {
// In message details, which doesn't use the slider, so don't swap pages.
} else if let nextItem = mediaGalleryDataSource.galleryItem(after: currentItem) {
self.setCurrentItem(nextItem, direction: .forward, animated: isAnimated)
} else if let previousItem = mediaGalleryDataSource.galleryItem(before: currentItem) {
self.setCurrentItem(previousItem, direction: .reverse, animated: isAnimated)
} else {
// else we deleted the last piece of media, return to the conversation view
self.dismissSelf(animated: true)
}
}
func mediaGalleryDataSource(_ mediaGalleryDataSource: MediaGalleryDataSource, deletedSections: IndexSet, deletedItems: [IndexPath]) {
// no-op
}
@objc
public func didPressPlayBarButton(_ sender: Any) {
guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
owsFailDebug("currentViewController was unexpectedly nil")
return
}
currentViewController.didPressPlayBarButton(sender)
}
@objc
public func didPressPauseBarButton(_ sender: Any) {
guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
owsFailDebug("currentViewController was unexpectedly nil")
return
}
currentViewController.didPressPauseBarButton(sender)
}
// MARK: UIPageViewControllerDelegate
var pendingViewController: MediaDetailViewController?
public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
Logger.debug("")
assert(pendingViewControllers.count == 1)
pendingViewControllers.forEach { viewController in
guard let pendingViewController = viewController as? MediaDetailViewController else {
owsFailDebug("unexpected mediaDetailViewController: \(viewController)")
return
}
self.pendingViewController = pendingViewController
if let pendingCaptionText = pendingViewController.galleryItem.captionForDisplay, pendingCaptionText.count > 0 {
self.captionContainerView.pendingText = pendingCaptionText
} else {
self.captionContainerView.pendingText = nil
}
// Ensure upcoming page respects current toolbar status
pendingViewController.setShouldHideToolbars(self.shouldHideToolbars)
}
}
public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool) {
Logger.debug("")
assert(previousViewControllers.count == 1)
previousViewControllers.forEach { viewController in
guard let previousPage = viewController as? MediaDetailViewController else {
owsFailDebug("unexpected mediaDetailViewController: \(viewController)")
return
}
// Do any cleanup for the no-longer visible view controller
if transitionCompleted {
pendingViewController = nil
// This can happen when trying to page past the last (or first) view controller
// In that case, we don't want to change the captionView.
if (previousPage != currentViewController) {
captionContainerView.completePagerTransition()
}
updateTitle()
updateMediaRail()
previousPage.zoomOut(animated: false)
previousPage.stopAnyVideo()
updateFooterBarButtonItems(isPlayingVideo: false)
} else {
captionContainerView.pendingText = nil
}
}
}
// MARK: UIPageViewControllerDataSource
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
Logger.debug("")
guard let previousDetailViewController = viewController as? MediaDetailViewController else {
owsFailDebug("unexpected viewController: \(viewController)")
return nil
}
guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
return nil
}
let previousItem = previousDetailViewController.galleryItem
guard let nextItem: MediaGalleryItem = mediaGalleryDataSource.galleryItem(before: previousItem) else {
return nil
}
guard let nextPage: MediaDetailViewController = buildGalleryPage(galleryItem: nextItem) else {
return nil
}
return nextPage
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
Logger.debug("")
guard let previousDetailViewController = viewController as? MediaDetailViewController else {
owsFailDebug("unexpected viewController: \(viewController)")
return nil
}
guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
return nil
}
let previousItem = previousDetailViewController.galleryItem
guard let nextItem = mediaGalleryDataSource.galleryItem(after: previousItem) else {
// no more pages
return nil
}
guard let nextPage: MediaDetailViewController = buildGalleryPage(galleryItem: nextItem) else {
return nil
}
return nextPage
}
private func buildGalleryPage(galleryItem: MediaGalleryItem) -> MediaDetailViewController? {
if let cachedPage = cachedPages[galleryItem] {
Logger.debug("cache hit.")
return cachedPage
}
Logger.debug("cache miss.")
var fetchedItem: ConversationViewItem?
databaseStorage.uiRead { transaction in
let message = galleryItem.message
let thread = message.thread(transaction: transaction)
let conversationStyle = ConversationStyle(thread: thread)
fetchedItem = ConversationInteractionViewItem(interaction: message,
thread: thread,
transaction: transaction,
conversationStyle: conversationStyle)
}
guard let viewItem = fetchedItem else {
owsFailDebug("viewItem was unexpectedly nil")
return nil
}
let viewController = MediaDetailViewController(galleryItemBox: GalleryItemBox(galleryItem), viewItem: viewItem)
viewController.delegate = self
cachedPages[galleryItem] = viewController
return viewController
}
public func dismissSelf(animated isAnimated: Bool, completion: (() -> Void)? = nil) {
// Swapping mediaView for presentationView will be perceptible if we're not zoomed out all the way.
currentViewController.zoomOut(animated: true)
currentViewController.stopAnyVideo()
UIApplication.shared.setStatusBarHidden(false, with: .none)
self.navigationController?.setNavigationBarHidden(false, animated: false)
guard let mediaPageViewDelegate = self.mediaPageViewDelegate else {
owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
self.presentingViewController?.dismiss(animated: true)
return
}
mediaPageViewDelegate.mediaPageViewControllerRequestedDismiss(self,
animated: isAnimated,
completion: completion)
}
// MARK: MediaDetailViewControllerDelegate
@objc
public func mediaDetailViewControllerDidTapMedia(_ mediaDetailViewController: MediaDetailViewController) {
Logger.debug("")
self.shouldHideToolbars = !self.shouldHideToolbars
}
public func mediaDetailViewController(_ mediaDetailViewController: MediaDetailViewController, requestDelete attachment: TSAttachment) {
guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
self.presentingViewController?.dismiss(animated: true)
return
}
guard let galleryItem = self.mediaGalleryDataSource?.galleryItems.first(where: { $0.attachmentStream == attachment }) else {
owsFailDebug("galleryItem was unexpectedly nil")
self.presentingViewController?.dismiss(animated: true)
return
}
dismissSelf(animated: true) {
mediaGalleryDataSource.delete(items: [galleryItem], initiatedBy: self)
}
}
public func mediaDetailViewController(_ mediaDetailViewController: MediaDetailViewController, isPlayingVideo: Bool) {
guard mediaDetailViewController == currentViewController else {
Logger.verbose("ignoring stale delegate.")
return
}
self.shouldHideToolbars = isPlayingVideo
self.updateFooterBarButtonItems(isPlayingVideo: isPlayingVideo)
}
// MARK: Dynamic Header
private var contactsManager: OWSContactsManager {
return Environment.shared.contactsManager
}
private func senderName(message: TSMessage) -> String {
switch message {
case let incomingMessage as TSIncomingMessage:
return self.contactsManager.displayName(for: incomingMessage.authorAddress)
case is TSOutgoingMessage:
return NSLocalizedString("MEDIA_GALLERY_SENDER_NAME_YOU", comment: "Short sender label for media sent by you")
default:
owsFailDebug("Unknown message type: \(type(of: message))")
return ""
}
}
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter
}()
lazy private var portraitHeaderNameLabel: UILabel = {
let label = UILabel()
label.textColor = Theme.darkThemePrimaryColor
label.font = UIFont.ows_regularFont(withSize: 17)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.8
return label
}()
lazy private var portraitHeaderDateLabel: UILabel = {
let label = UILabel()
label.textColor = Theme.darkThemePrimaryColor
label.font = UIFont.ows_regularFont(withSize: 12)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.8
return label
}()
private lazy var portraitHeaderView: UIView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .center
stackView.spacing = 0
stackView.distribution = .fillProportionally
stackView.addArrangedSubview(portraitHeaderNameLabel)
stackView.addArrangedSubview(portraitHeaderDateLabel)
let containerView = UIView()
containerView.layoutMargins = UIEdgeInsets(top: 2, left: 8, bottom: 4, right: 8)
containerView.addSubview(stackView)
stackView.autoPinEdge(toSuperviewMargin: .top, relation: .greaterThanOrEqual)
stackView.autoPinEdge(toSuperviewMargin: .trailing, relation: .greaterThanOrEqual)
stackView.autoPinEdge(toSuperviewMargin: .bottom, relation: .greaterThanOrEqual)
stackView.autoPinEdge(toSuperviewMargin: .leading, relation: .greaterThanOrEqual)
stackView.setContentHuggingHigh()
stackView.autoCenterInSuperview()
return containerView
}()
private func updateTitle() {
guard let currentItem = self.currentItem else {
owsFailDebug("currentItem was unexpectedly nil")
return
}
updateTitle(item: currentItem)
}
private func updateCaption(item: MediaGalleryItem) {
captionContainerView.currentText = item.captionForDisplay
}
private func updateTitle(item: MediaGalleryItem) {
let name = senderName(message: item.message)
portraitHeaderNameLabel.text = name
// use sent date
let date = Date(timeIntervalSince1970: Double(item.message.timestamp) / 1000)
let formattedDate = dateFormatter.string(from: date)
portraitHeaderDateLabel.text = formattedDate
let landscapeHeaderFormat = NSLocalizedString("MEDIA_GALLERY_LANDSCAPE_TITLE_FORMAT", comment: "embeds {{sender name}} and {{sent datetime}}, e.g. 'Sarah on 10/30/18, 3:29'")
let landscapeHeaderText = String(format: landscapeHeaderFormat, name, formattedDate)
self.title = landscapeHeaderText
self.navigationItem.title = landscapeHeaderText
if #available(iOS 11, *) {
// Do nothing, on iOS11+, autolayout grows the stack view as necessary.
} else {
// Size the titleView to be large enough to fit the widest label,
// but no larger. If we go for a "full width" label, our title view
// will not be centered (since the left and right bar buttons have different widths)
portraitHeaderNameLabel.sizeToFit()
portraitHeaderDateLabel.sizeToFit()
let width = max(portraitHeaderNameLabel.frame.width, portraitHeaderDateLabel.frame.width)
let headerFrame: CGRect = CGRect(x: 0, y: 0, width: width, height: 44)
portraitHeaderView.frame = headerFrame
}
}
}
extension MediaGalleryItem: GalleryRailItem {
public func buildRailItemView() -> UIView {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.image = getRailImage()
return imageView
}
public func getRailImage() -> UIImage? {
return self.thumbnailImageSync()
}
}
extension MediaGalleryAlbum: GalleryRailItemProvider {
var railItems: [GalleryRailItem] {
return self.items
}
}
extension MediaPageViewController: GalleryRailViewDelegate {
func galleryRailView(_ galleryRailView: GalleryRailView, didTapItem imageRailItem: GalleryRailItem) {
guard let targetItem = imageRailItem as? MediaGalleryItem else {
owsFailDebug("unexpected imageRailItem: \(imageRailItem)")
return
}
let direction: UIPageViewController.NavigationDirection
direction = currentItem.albumIndex < targetItem.albumIndex ? .forward : .reverse
self.setCurrentItem(targetItem, direction: direction, animated: true)
}
}
extension MediaPageViewController: CaptionContainerViewDelegate {
func captionContainerViewDidUpdateText(_ captionContainerView: CaptionContainerView) {
updateCaptionContainerVisibility()
}
// MARK: Helpers
func updateCaptionContainerVisibility() {
if let currentText = captionContainerView.currentText, currentText.count > 0 {
captionContainerView.isHidden = false
return
}
if let pendingText = captionContainerView.pendingText, pendingText.count > 0 {
captionContainerView.isHidden = false
return
}
captionContainerView.isHidden = true
}
}
extension MediaPageViewController: MediaPresentationContextProvider {
func mediaPresentationContext(galleryItem: MediaGalleryItem, in coordinateSpace: UICoordinateSpace) -> MediaPresentationContext? {
let mediaView = currentViewController.mediaView
guard let mediaSuperview = mediaView.superview else {
owsFailDebug("superview was unexpectedly nil")
return nil
}
let presentationFrame = coordinateSpace.convert(mediaView.frame, from: mediaSuperview)
// TODO better match the corner radius
return MediaPresentationContext(mediaView: mediaView, presentationFrame: presentationFrame, cornerRadius: 0)
}
func snapshotOverlayView(in coordinateSpace: UICoordinateSpace) -> (UIView, CGRect)? {
view.layoutIfNeeded()
guard let snapshot = bottomContainer.snapshotView(afterScreenUpdates: true) else {
owsFailDebug("snapshot was unexpectedly nil")
return nil
}
let presentationFrame = coordinateSpace.convert(bottomContainer.frame,
from: bottomContainer.superview!)
return (snapshot, presentationFrame)
}
}
|
gpl-3.0
|
1c515b21697eba4702d1a4d54b8c32a8
| 37.292824 | 187 | 0.670848 | 5.714162 | false | false | false | false |
xedin/swift
|
test/stdlib/DispatchData.swift
|
2
|
11903
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -swift-version 4 %s %import-libdispatch -o %t/a.out-4 && %target-codesign %t/a.out-4 && %target-run %t/a.out-4
// RUN: %target-build-swift -swift-version 4.2 %s %import-libdispatch -o %t/a.out-4.2 && %target-codesign %t/a.out-4.2 && %target-run %t/a.out-4.2
// REQUIRES: executable_test
// REQUIRES: libdispatch
import Dispatch
import StdlibUnittest
defer { runAllTests() }
var DispatchAPI = TestSuite("DispatchAPI")
DispatchAPI.test("dispatch_data_t enumeration") {
// Ensure we can iterate the empty iterator
for _ in DispatchData.empty {
_ = 1
}
}
DispatchAPI.test("dispatch_data_t deallocator") {
let q = DispatchQueue(label: "dealloc queue")
var t = 0
do {
let size = 1024
let p = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
let _ = DispatchData(bytesNoCopy: UnsafeBufferPointer(start: p, count: size), deallocator: .custom(q, {
t = 1
p.deallocate();
}))
}
q.sync {
expectEqual(1, t)
}
}
DispatchAPI.test("DispatchData.copyBytes") {
let source1: [UInt8] = [0, 1, 2, 3]
let srcPtr1 = UnsafeBufferPointer(start: source1, count: source1.count)
var dest: [UInt8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
let destPtr = UnsafeMutableBufferPointer(start: UnsafeMutablePointer(&dest),
count: dest.count)
var dispatchData = DispatchData(bytes: srcPtr1)
// Copy from offset 0
var count = dispatchData.copyBytes(to: destPtr, from: 0..<2)
expectEqual(count, 2)
expectEqual(destPtr[0], 0)
expectEqual(destPtr[1], 1)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 2
count = dispatchData.copyBytes(to: destPtr, from: 2..<4)
expectEqual(count, 2)
expectEqual(destPtr[0], 2)
expectEqual(destPtr[1], 3)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Add two more regions
let source2: [UInt8] = [0x10, 0x11, 0x12, 0x13]
let srcPtr2 = UnsafeBufferPointer(start: source2, count: source2.count)
dispatchData.append(DispatchData(bytes: srcPtr2))
let source3: [UInt8] = [0x14, 0x15, 0x16]
let srcPtr3 = UnsafeBufferPointer(start: source3, count: source3.count)
dispatchData.append(DispatchData(bytes: srcPtr3))
// Copy from offset 0. Copies across the first two regions
count = dispatchData.copyBytes(to: destPtr, from: 0..<6)
expectEqual(count, 6)
expectEqual(destPtr[0], 0)
expectEqual(destPtr[1], 1)
expectEqual(destPtr[2], 2)
expectEqual(destPtr[3], 3)
expectEqual(destPtr[4], 0x10)
expectEqual(destPtr[5], 0x11)
// Copy from offset 2. Copies across the first two regions
count = dispatchData.copyBytes(to: destPtr, from: 2..<8)
expectEqual(count, 6)
expectEqual(destPtr[0], 2)
expectEqual(destPtr[1], 3)
expectEqual(destPtr[2], 0x10)
expectEqual(destPtr[3], 0x11)
expectEqual(destPtr[4], 0x12)
expectEqual(destPtr[5], 0x13)
// Copy from offset 3. Copies across all three regions
count = dispatchData.copyBytes(to: destPtr, from: 3..<9)
expectEqual(count, 6)
expectEqual(destPtr[0], 3)
expectEqual(destPtr[1], 0x10)
expectEqual(destPtr[2], 0x11)
expectEqual(destPtr[3], 0x12)
expectEqual(destPtr[4], 0x13)
expectEqual(destPtr[5], 0x14)
// Copy from offset 5. Skips the first region and the first byte of the second
count = dispatchData.copyBytes(to: destPtr, from: 5..<11)
expectEqual(count, 6)
expectEqual(destPtr[0], 0x11)
expectEqual(destPtr[1], 0x12)
expectEqual(destPtr[2], 0x13)
expectEqual(destPtr[3], 0x14)
expectEqual(destPtr[4], 0x15)
expectEqual(destPtr[5], 0x16)
// Copy from offset 8. Skips the first two regions
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
count = dispatchData.copyBytes(to: destPtr, from: 8..<11)
expectEqual(count, 3)
expectEqual(destPtr[0], 0x14)
expectEqual(destPtr[1], 0x15)
expectEqual(destPtr[2], 0x16)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 9. Skips the first two regions and the first byte of the third
destPtr[2] = 0xFF
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
count = dispatchData.copyBytes(to: destPtr, from: 9..<11)
expectEqual(count, 2)
expectEqual(destPtr[0], 0x15)
expectEqual(destPtr[1], 0x16)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 9, but only 1 byte. Ends before the end of the data
destPtr[1] = 0xFF
destPtr[2] = 0xFF
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
count = dispatchData.copyBytes(to: destPtr, from: 9..<10)
expectEqual(count, 1)
expectEqual(destPtr[0], 0x15)
expectEqual(destPtr[1], 0xFF)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 2, but only 1 byte. This copy is bounded within the
// first region.
destPtr[1] = 0xFF
destPtr[2] = 0xFF
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
count = dispatchData.copyBytes(to: destPtr, from: 2..<3)
expectEqual(count, 1)
expectEqual(destPtr[0], 2)
expectEqual(destPtr[1], 0xFF)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
}
DispatchAPI.test("DispatchData.copyBytesUnsafeRawBufferPointer") {
let source1: [UInt8] = [0, 1, 2, 3]
let srcPtr1 = UnsafeRawBufferPointer(start: source1, count: source1.count)
var dest: [UInt8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
let destPtr = UnsafeMutableRawBufferPointer(start: UnsafeMutablePointer(&dest),
count: dest.count)
var dispatchData = DispatchData(bytes: srcPtr1)
// Copy from offset 0
dispatchData.copyBytes(to: destPtr, from: 0..<2)
expectEqual(destPtr[0], 0)
expectEqual(destPtr[1], 1)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 2
dispatchData.copyBytes(to: destPtr, from: 2..<4)
expectEqual(destPtr[0], 2)
expectEqual(destPtr[1], 3)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Add two more regions
let source2: [UInt8] = [0x10, 0x11, 0x12, 0x13]
let srcPtr2 = UnsafeRawBufferPointer(start: source2, count: source2.count)
dispatchData.append(DispatchData(bytes: srcPtr2))
let source3: [UInt8] = [0x14, 0x15, 0x16]
let srcPtr3 = UnsafeRawBufferPointer(start: source3, count: source3.count)
dispatchData.append(DispatchData(bytes: srcPtr3))
// Copy from offset 0. Copies across the first two regions
dispatchData.copyBytes(to: destPtr, from: 0..<6)
expectEqual(destPtr[0], 0)
expectEqual(destPtr[1], 1)
expectEqual(destPtr[2], 2)
expectEqual(destPtr[3], 3)
expectEqual(destPtr[4], 0x10)
expectEqual(destPtr[5], 0x11)
// Copy from offset 2. Copies across the first two regions
dispatchData.copyBytes(to: destPtr, from: 2..<8)
expectEqual(destPtr[0], 2)
expectEqual(destPtr[1], 3)
expectEqual(destPtr[2], 0x10)
expectEqual(destPtr[3], 0x11)
expectEqual(destPtr[4], 0x12)
expectEqual(destPtr[5], 0x13)
// Copy from offset 3. Copies across all three regions
dispatchData.copyBytes(to: destPtr, from: 3..<9)
expectEqual(destPtr[0], 3)
expectEqual(destPtr[1], 0x10)
expectEqual(destPtr[2], 0x11)
expectEqual(destPtr[3], 0x12)
expectEqual(destPtr[4], 0x13)
expectEqual(destPtr[5], 0x14)
// Copy from offset 5. Skips the first region and the first byte of the second
dispatchData.copyBytes(to: destPtr, from: 5..<11)
expectEqual(destPtr[0], 0x11)
expectEqual(destPtr[1], 0x12)
expectEqual(destPtr[2], 0x13)
expectEqual(destPtr[3], 0x14)
expectEqual(destPtr[4], 0x15)
expectEqual(destPtr[5], 0x16)
// Copy from offset 8. Skips the first two regions
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
dispatchData.copyBytes(to: destPtr, from: 8..<11)
expectEqual(destPtr[0], 0x14)
expectEqual(destPtr[1], 0x15)
expectEqual(destPtr[2], 0x16)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 9. Skips the first two regions and the first byte of the third
destPtr[2] = 0xFF
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
dispatchData.copyBytes(to: destPtr, from: 9..<11)
expectEqual(destPtr[0], 0x15)
expectEqual(destPtr[1], 0x16)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 9, but only 1 byte. Ends before the end of the data
destPtr[1] = 0xFF
destPtr[2] = 0xFF
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
dispatchData.copyBytes(to: destPtr, from: 9..<10)
expectEqual(destPtr[0], 0x15)
expectEqual(destPtr[1], 0xFF)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
// Copy from offset 2, but only 1 byte. This copy is bounded within the
// first region.
destPtr[1] = 0xFF
destPtr[2] = 0xFF
destPtr[3] = 0xFF
destPtr[4] = 0xFF
destPtr[5] = 0xFF
dispatchData.copyBytes(to: destPtr, from: 2..<3)
expectEqual(destPtr[0], 2)
expectEqual(destPtr[1], 0xFF)
expectEqual(destPtr[2], 0xFF)
expectEqual(destPtr[3], 0xFF)
expectEqual(destPtr[4], 0xFF)
expectEqual(destPtr[5], 0xFF)
}
DispatchAPI.test("DispatchData.buffers") {
let bytes = [UInt8(0), UInt8(1), UInt8(2), UInt8(2)]
var ptr = UnsafeBufferPointer<UInt8>(start: bytes, count: bytes.count)
var data = DispatchData(bytes: ptr)
expectEqual(bytes.count, data.count)
for i in 0..<data.count {
expectEqual(data[i], bytes[i])
}
data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {}))
expectEqual(bytes.count, data.count)
for i in 0..<data.count {
expectEqual(data[i], bytes[i])
}
ptr = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
data = DispatchData(bytes: ptr)
expectEqual(data.count, 0)
data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {}))
expectEqual(data.count, 0)
}
DispatchAPI.test("DispatchData.bufferUnsafeRawBufferPointer") {
let bytes = [UInt8(0), UInt8(1), UInt8(2), UInt8(2)]
var ptr = UnsafeRawBufferPointer(start: bytes, count: bytes.count)
var data = DispatchData(bytes: ptr)
expectEqual(bytes.count, data.count)
for i in 0..<data.count {
expectEqual(data[i], bytes[i])
}
data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {}))
expectEqual(bytes.count, data.count)
for i in 0..<data.count {
expectEqual(data[i], bytes[i])
}
ptr = UnsafeRawBufferPointer(start: nil, count: 0)
data = DispatchData(bytes: ptr)
expectEqual(data.count, 0)
data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {}))
expectEqual(data.count, 0)
}
DispatchAPI.test("DispatchData.enumerateBytes") {
let count = 240
var bytes = [UInt8]()
for i in 0..<count {
bytes.append(UInt8(i))
}
let ptr = UnsafeRawBufferPointer(start: bytes, count: bytes.count)
let data = DispatchData(bytes: ptr)
var nextIndex = 0
#if swift(>=4.2)
data.enumerateBytes({ ptr, offset, stop in
for i in 0..<ptr.count {
expectEqual(ptr[i + offset], UInt8(i + offset))
}
nextIndex = offset + ptr.count
})
#else
data.enumerateBytes(block: { ptr, offset, stop in
for i in 0..<ptr.count {
expectEqual(ptr[i + offset], UInt8(i + offset))
}
nextIndex = offset + ptr.count
})
#endif
expectEqual(nextIndex, data.count)
}
DispatchAPI.test("DispatchData.enumerateBytesTrailingClosure") {
let count = 240
var bytes = [UInt8]()
for i in 0..<count {
bytes.append(UInt8(i))
}
let ptr = UnsafeRawBufferPointer(start: bytes, count: bytes.count)
let data = DispatchData(bytes: ptr)
var nextIndex = 0
data.enumerateBytes() { ptr, offset, stop in
for i in 0..<ptr.count {
expectEqual(ptr[i + offset], UInt8(i + offset))
}
nextIndex = offset + ptr.count
}
expectEqual(nextIndex, data.count)
}
|
apache-2.0
|
f8d3746e30f972f9597668e2e864d869
| 29.134177 | 146 | 0.714106 | 2.959473 | false | false | false | false |
fabiomassimo/eidolon
|
Kiosk/App/Models/Bid.swift
|
2
|
487
|
import Foundation
import SwiftyJSON
public class Bid: JSONAble {
public let id: String
public let amountCents: Int
init(id: String, amountCents: Int) {
self.id = id
self.amountCents = amountCents
}
override public class func fromJSON(json:[String: AnyObject]) -> JSONAble {
let json = JSON(json)
let id = json["id"].stringValue
let amount = json["amount_cents"].int
return Bid(id: id, amountCents: amount!)
}
}
|
mit
|
d97f2be500045bf456ee93de0e0f2ff9
| 23.35 | 79 | 0.628337 | 4.162393 | false | false | false | false |
Palleas/NukeIt
|
NukeIt/AppDelegate.swift
|
1
|
2071
|
//
// AppDelegate.swift
// NukeIt
//
// Created by Romain Pouclet on 2015-10-24.
// Copyright © 2015 Perfectly-Cooked. All rights reserved.
//
import Cocoa
import ORSSerial
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var port: ORSSerialPort!
func applicationDidFinishLaunching(aNotification: NSNotification) {
port = ORSSerialPortManager.sharedSerialPortManager().availablePorts.first
port.delegate = self
port.baudRate = 9600
port.open()
}
}
extension AppDelegate {
func nuke() {
let path = String("/Users/Romain/Library/Developer/Xcode/DerivedData/")
do {
let subdirectories = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
print(subdirectories)
try subdirectories.forEach({ (subdirectory) -> () in
try NSFileManager.defaultManager().removeItemAtPath(path + subdirectory)
})
print("Nuked dd folder")
let notification = NSUserNotification()
notification.title = "DerivedData folder has been nuked! 🔥"
let hub = NSUserNotificationCenter.defaultUserNotificationCenter()
hub.deliverNotification(notification)
} catch {
print("Unable to nuke dd folder \(error)")
}
}
}
extension AppDelegate: ORSSerialPortDelegate {
func serialPortWasOpened(serialPort: ORSSerialPort) {
print("Port \(serialPort) was opened")
}
func serialPortWasClosed(serialPort: ORSSerialPort) {
print("Port \(serialPort) was closed")
}
func serialPortWasRemovedFromSystem(serialPort: ORSSerialPort) {
print("Removed :(")
}
func serialPort(serialPort: ORSSerialPort, didReceiveData data: NSData) {
if let payload = NSString(data: data, encoding: NSUTF8StringEncoding) where payload.rangeOfString("\n").location != NSNotFound {
nuke()
}
}
}
|
mit
|
1ba9dab8486795a92d34a7f1de4d9868
| 29.411765 | 136 | 0.643928 | 5.206549 | false | false | false | false |
shelleyweiss/softsurvey
|
SoftSurvey/SoftButtonsController.swift
|
1
|
1461
|
//
// SoftuttonsController.swift
// SoftSurvey
//
// Created by shelley weiss on 5/26/15.
// Copyright (c) 2015 shelley weiss. All rights reserved.
//
import UIKit
class SoftButtonsController:NSObject
{
private var buttonsArray = [UIButton]()
private weak var currentSelectedButton:UIButton? = nil
override init()
{
}
func addButton(aButton:UIButton)
{
buttonsArray.append(aButton)
aButton.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
aButton.titleLabel!.textAlignment = .Left
}
func setButtonsArray(aButtonsArray:[UIButton])
{
for aButton in aButtonsArray
{
aButton.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
}
buttonsArray = aButtonsArray
}
func pressed(sender:UIButton)
{
if(sender.selected)
{
sender.selected = false
currentSelectedButton = nil
}
else
{
for aButton in buttonsArray
{
if aButton != sender
{
aButton.selected = false
}
}
sender.selected = true
currentSelectedButton = sender
}
}
func selectedButton() ->UIButton?
{
return currentSelectedButton
}
}
|
artistic-2.0
|
f1c643c9a97436d2d2d33db841175f73
| 20.188406 | 104 | 0.557837 | 5.332117 | false | false | false | false |
Oyvindkg/tinysqlite
|
TinySQLiteTests/DatabaseConnectionTests.swift
|
1
|
6930
|
//
// DatabaseConnectionTests.swift
// TinySQLiteTests
//
// Created by Øyvind Grimnes on 13/02/17.
// Copyright © 2017 Øyvind Grimnes. All rights reserved.
//
import XCTest
import Nimble
@testable import TinySQLite
class DatabaseConnectionTests: XCTestCase {
var database: DatabaseConnection!
var databaseLocation: URL {
let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
return documentsDirectory.appendingPathComponent("database").appendingPathExtension("sqlite")
}
override func setUp() {
super.setUp()
try? FileManager.default.removeItem(at: databaseLocation)
database = DatabaseConnection(location: databaseLocation)
}
override func tearDown() {
try? FileManager.default.removeItem(at: databaseLocation)
super.tearDown()
}
func testDatabaseIsClosedByDefault() {
expect(self.database.isOpen) == false
}
func testDatabaseIsClosedAfterClose() {
try! database.open()
try! database.close()
expect(self.database.isOpen) == false
}
func testThrowsNoErrorIfClosedOnClose() {
expect(try self.database.close()).notTo(throwError())
}
func testThrowsNoErrorIfOpenOnOpen() {
try! database.open()
expect(try self.database.open()).notTo(throwError())
}
func testDatabaseIsOpenAfterOpen() {
try! database.open()
expect(self.database.isOpen) == true
}
func testThrowsErrorIfDatabaseIsNotOpenOnPrepare() {
let query = "CREATE TABLE dog (name TEST, age INTEGER)"
expect(try self.database.statement(for: query)).to(throwError())
}
func testThrowsErrorIfDatabaseIsNotOpenOnBeginTransaction() {
expect(try self.database.beginTransaction()).to(throwError())
}
func testThrowsErrorIfTransactionIsEndedWhenNoTransactionIsActive() {
try! database.open()
expect(try self.database.endTransaction()).to(throwError())
}
func testThrowsErrorNoIfTransactionIsEndedWhenATransactionIsActive() {
try! database.open()
try! database.beginTransaction()
expect(try self.database.endTransaction()).notTo(throwError())
}
func testThrowsErrorIfBeginTransactionIsCallenDuringATransaction() {
try! database.open()
try! database.beginTransaction()
expect(try self.database.beginTransaction()).to(throwError())
}
func testThrowsNoErrorIfDatabaseIsOpenOnBeginTransaction() {
try! database.open()
expect(try self.database.beginTransaction()).notTo(throwError())
}
func testTransactionIsNotCommittedIfRollbackIsCalled() {
try! database.open()
try! database.beginTransaction()
try! database.statement(for: "CREATE TABLE dog (name TEXT, age INTEGER)").executeUpdate()
try! database.rollbackTransaction()
expect(try self.database.contains(table: "dog")) == false
}
func testTransactionIsCommitedOnEnd() {
try! database.open()
try! database.beginTransaction()
try! database.statement(for: "CREATE TABLE dog (name TEXT, age INTEGER)").executeUpdate()
try! database.endTransaction()
expect(try self.database.contains(table: "dog")) == true
}
func testNumberOfRowsChangesInLastQueryIsZeroBeforeUpdates() {
try! database.open()
expect(self.database.numberOfChanges) == 0
}
func testTotalNumberOfRowsChangesIsZeroBeforeUpdates() {
try! database.open()
expect(self.database.totalNumberOfChanges) == 0
}
func testNumberOfRowsChangesInLastQueryIsNotZeroAfterAnUpdate() {
try! database.open()
try! database.statement(for: "CREATE TABLE dog (name TEST, age INTEGER)").executeUpdate()
try! database.statement(for: "INSERT INTO dog VALUES (?, ?)").executeUpdate(withParameters: ["fido", 3])
expect(self.database.numberOfChanges) == 1
}
func testTotalNumberOfRowsChangedAccumulatesTheNumberOfRowChanges() {
try! database.open()
try! database.statement(for: "CREATE TABLE dog (name TEST, age INTEGER)").executeUpdate()
try! database.statement(for: "INSERT INTO dog VALUES (?, ?)").executeUpdate(withParameters: ["fido", 3])
try! database.statement(for: "INSERT INTO dog VALUES (?, ?)").executeUpdate(withParameters: ["fido", 3])
expect(self.database.totalNumberOfChanges) == 2
}
func testNumberOfRowsChangesInLastQueryDoesNotAccumulateTheNumberOfRowChanges() {
try! database.open()
try! database.statement(for: "CREATE TABLE dog (name TEST, age INTEGER)").executeUpdate()
try! database.statement(for: "INSERT INTO dog VALUES (?, ?)").executeUpdate(withParameters: ["fido", 3])
try! database.statement(for: "INSERT INTO dog VALUES (?, ?)").executeUpdate(withParameters: ["fido", 3])
expect(self.database.numberOfChanges) == 1
}
func testContainsTableReturnsFalseIfTableDoesNotExist() {
try! database.open()
expect(try! self.database.contains(table: "dog")) == false
}
func testContainsTableReturnsTrueIfTableExists() {
try! database.open()
try! database.statement(for: "CREATE TABLE dog (name TEST, age INTEGER)").executeUpdate()
expect(try! self.database.contains(table: "dog")) == true
}
func testContainsIndexReturnsFalseIfIndexDoesNotExist() {
try! database.open()
expect(try! self.database.contains(index: "dognames")) == false
}
func testContainsIndexReturnsTrueIfIndexExists() {
try! database.open()
try! database.statement(for: "CREATE TABLE dog (name TEST, age INTEGER)").executeUpdate()
try! database.statement(for: "CREATE INDEX dognames ON dog (name)").executeUpdate()
expect(try! self.database.contains(index: "dognames")) == true
}
func testContainsViewReturnsFalseIfViewDoesNotExist() {
try! database.open()
expect(try! self.database.contains(view: "dogview")) == false
}
func testContainsViewReturnsTrueIfViewExists() {
try! database.open()
try! database.statement(for: "CREATE TABLE dog (name TEST, age INTEGER)").executeUpdate()
try! database.statement(for: "CREATE VIEW dogview (name) AS SELECT name FROM dog WHERE name='fido'").executeUpdate()
expect(try! self.database.contains(view: "dogview")) == true
}
}
|
mit
|
5cd6f74b85b8019cfc9a23e436603bb7
| 32.302885 | 143 | 0.639093 | 4.787146 | false | true | false | false |
15cm/AMM
|
AMM/Preferences/ServerProfile.swift
|
1
|
10785
|
//
// ServerProfile.swift
// AMM
//
// Created by Sinkerine on 29/01/2017.
// Copyright © 2017 sinkerine. All rights reserved.
//
fileprivate enum SerializationKeys {
static let uuid = "id"
static let aria2 = "aria2"
static let remark = "remark"
static let globalStatRefreshInterval = "globalStatRefreshInterval"
static let taskStatRefreshInterval = "taskStatRefreshInterval"
static let activeTaskTotal = "activeTaskMaxNum"
static let waitingTaskTotal = "waitingTaskMaxNum"
static let stoppedTaskTotal = "stoppedTaskMaxNum"
static let taskStartNotiEnabled = "taskStartNotiEnabled"
static let taskPauseNotiEnabled = "taskPauseNotiEnabled"
static let taskCompleteNotiEnabled = "taskCompleteNotiEnabled"
static let isDefaultServer = "isDefaultServer"
}
import Foundation
import SwiftyJSON
@objcMembers
class ServerProfile: NSObject, NSCopying, NSCoding, TimerDelegate {
var uuid: String
var aria2: Aria2
var ptclRawValue: String? {
didSet {
aria2.ptcl = Aria2Protocols(rawValue: ptclRawValue!)!
}
}
// Workaournd for enum KVO binding
var remark: String
var globalStatRefreshInterval: Double
var taskStatRefreshInterval: Double
var activeTaskTotal: Int
var waitingTaskTotal: Int
var stoppedTaskTotal: Int
var taskStartNotiEnabled: Bool
var taskPauseNotiEnabled: Bool
var taskCompleteNotiEnabled: Bool
dynamic var isDefaultServer: Bool
var connectCounter: Int = 0
var timer: DispatchSourceTimer?
init?(uuid: String, aria2: Aria2?,
remark: String, globalStatRefreshInterval gsri: Double,
taskStatRefreshInterval tsri: Double, activeTaskTotal atTotal: Int,
waitingTaskTotal wtTotal: Int, stoppedTaskTotal stTotal: Int,
taskStartNotiEnabled startNotiEnabled: Bool, taskPauseNotiEnabled pauseNotiEnabled: Bool,
taskCompleteNotiEnabled completeNotiEnabled: Bool, isDefaultServer isDefault: Bool
) {
guard let aria2 = aria2 else {
return nil
}
self.uuid = uuid
self.aria2 = aria2
self.ptclRawValue = aria2.ptcl.rawValue
self.remark = remark
self.globalStatRefreshInterval = gsri
self.taskStatRefreshInterval = tsri
self.activeTaskTotal = atTotal
self.waitingTaskTotal = wtTotal
self.stoppedTaskTotal = stTotal
self.taskStartNotiEnabled = startNotiEnabled
self.taskPauseNotiEnabled = pauseNotiEnabled
self.taskCompleteNotiEnabled = completeNotiEnabled
self.isDefaultServer = isDefault
}
required init?(coder aDecoder: NSCoder) {
self.uuid = aDecoder.decodeObject(forKey: SerializationKeys.uuid) as! String
self.aria2 = (aDecoder.decodeObject(forKey: SerializationKeys.aria2) as? Aria2)!
self.ptclRawValue = aria2.ptcl.rawValue
self.remark = aDecoder.decodeObject(forKey: SerializationKeys.remark) as! String
self.globalStatRefreshInterval = aDecoder.decodeDouble(forKey: SerializationKeys.globalStatRefreshInterval)
self.taskStatRefreshInterval = Double(aDecoder.decodeDouble(forKey: SerializationKeys.taskStatRefreshInterval))
self.activeTaskTotal = Int(aDecoder.decodeInt64(forKey: SerializationKeys.activeTaskTotal))
self.waitingTaskTotal = Int(aDecoder.decodeInt64(forKey: SerializationKeys.waitingTaskTotal))
self.stoppedTaskTotal = Int(aDecoder.decodeInt64(forKey: SerializationKeys.stoppedTaskTotal))
// Default value for parameters in new versions
self.taskStartNotiEnabled = aDecoder.containsValue(forKey: SerializationKeys.taskStartNotiEnabled) ?
aDecoder.decodeBool(forKey: SerializationKeys.taskStartNotiEnabled) : false
self.taskPauseNotiEnabled = aDecoder.containsValue(forKey: SerializationKeys.taskPauseNotiEnabled) ?
aDecoder.decodeBool(forKey: SerializationKeys.taskPauseNotiEnabled) : false
self.taskCompleteNotiEnabled = aDecoder.containsValue(forKey: SerializationKeys.taskCompleteNotiEnabled) ?
aDecoder.decodeBool(forKey: SerializationKeys.taskCompleteNotiEnabled) : false
self.isDefaultServer = aDecoder.containsValue(forKey: SerializationKeys.isDefaultServer) ?
aDecoder.decodeBool(forKey: SerializationKeys.isDefaultServer) : false
}
func encode(with aCoder: NSCoder) {
aCoder.encode(uuid, forKey: SerializationKeys.uuid)
aCoder.encode(aria2, forKey: SerializationKeys.aria2)
aCoder.encode(remark, forKey: SerializationKeys.remark)
aCoder.encode(globalStatRefreshInterval, forKey: SerializationKeys.globalStatRefreshInterval)
aCoder.encode(taskStatRefreshInterval, forKey: SerializationKeys.taskStatRefreshInterval)
aCoder.encode(activeTaskTotal, forKey: SerializationKeys.activeTaskTotal)
aCoder.encode(waitingTaskTotal, forKey: SerializationKeys.waitingTaskTotal)
aCoder.encode(stoppedTaskTotal, forKey: SerializationKeys.stoppedTaskTotal)
aCoder.encode(taskStartNotiEnabled, forKey: SerializationKeys.taskStartNotiEnabled)
aCoder.encode(taskPauseNotiEnabled, forKey: SerializationKeys.taskPauseNotiEnabled)
aCoder.encode(taskCompleteNotiEnabled, forKey: SerializationKeys.taskCompleteNotiEnabled)
aCoder.encode(isDefaultServer, forKey: SerializationKeys.isDefaultServer)
}
convenience override init() {
self.init(uuid: NSUUID().uuidString,
aria2: Aria2(ptcl: AMMDefault.ptcl, host: AMMDefault.host, port: AMMDefault.port, path: AMMDefault.path),
remark: AMMDefault.remark, globalStatRefreshInterval: AMMDefault.globalStatRefreshInterval,
taskStatRefreshInterval: AMMDefault.taskStatRefreshInterval, activeTaskTotal: AMMDefault.activeTaskTotal,
waitingTaskTotal: AMMDefault.waitingTaskTotal, stoppedTaskTotal: AMMDefault.stoppedTaskTotal,
taskStartNotiEnabled: false, taskPauseNotiEnabled: false, taskCompleteNotiEnabled: false, isDefaultServer: false)!
}
func copy(with zone: NSZone? = nil) -> Any {
return ServerProfile(uuid: uuid, aria2: aria2.copy() as? Aria2, remark: remark,
globalStatRefreshInterval: globalStatRefreshInterval, taskStatRefreshInterval: taskStatRefreshInterval,
activeTaskTotal: activeTaskTotal, waitingTaskTotal: waitingTaskTotal, stoppedTaskTotal: stoppedTaskTotal,
taskStartNotiEnabled: taskStartNotiEnabled, taskPauseNotiEnabled: taskPauseNotiEnabled,
taskCompleteNotiEnabled: taskCompleteNotiEnabled, isDefaultServer: isDefaultServer) as Any
}
func startTimer() {
if timer == nil {
let queue = DispatchQueue.global()
timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
let pref = AMMPreferences.instance
timer?.setEventHandler {
[weak self] in
if let strongSelf = self {
if strongSelf.aria2.status != .connected {
strongSelf.aria2.connect()
if(pref.connectionRetryLimit > 0) {
strongSelf.connectCounter += 1
if(strongSelf.connectCounter >= pref.connectionRetryLimit) {
strongSelf.aria2.disconnect()
strongSelf.timer?.cancel()
}
}
} else {
strongSelf.connectCounter = 0
}
}
}
timer?.schedule(deadline: .now(), repeating: Double(pref.connectionCheckInterval))
if #available(OSX 10.12, *) {
timer?.activate()
} else {
// Fallback on earlier versions
timer?.resume()
}
}
}
func stopTimer() {
timer?.cancel()
timer = nil
}
func getGlobalStat(callback cb: ((Aria2Stat) -> Void)?) {
let wrappedCallback = cb.map({ cb -> Aria2RpcCallback in
{ res in
if let stat = Aria2.getStat(fromResponse: res) {
cb(stat)
}
}
})
aria2.getGlobalStat(callback: wrappedCallback)
}
func tellActive(callback cb: (([Aria2Task]) -> Void)?) {
let wrappedCallback = cb.map({ cb -> Aria2RpcCallback in
{ res in
if let tasks = Aria2.getTasks(fromResponse: res) {
cb(tasks)
}
}
})
aria2.tellActive(callback: wrappedCallback)
}
func tellWaiting(callback cb: (([Aria2Task]) -> Void)?) {
let wrappedCallback = cb.map({ cb -> Aria2RpcCallback in
{ res in
if let tasks = Aria2.getTasks(fromResponse: res) {
cb(tasks)
}
}
})
aria2.tellWaiting(
offset: -1,
num: self.waitingTaskTotal,
callback: wrappedCallback
)
}
func tellStopped(callback cb: (([Aria2Task]) -> Void)?) {
let wrappedCallback = cb.map({ cb -> Aria2RpcCallback in
{ res in
if let tasks = Aria2.getTasks(fromResponse: res) {
cb (tasks)
}
}
})
aria2.tellStopped(
offset: -1,
num: self.stoppedTaskTotal,
callback: wrappedCallback
)
}
func tellStatus(gid: String, callback cb: ((Aria2Task) -> Void)?) {
let wrappedCallback = cb.map({ cb -> Aria2RpcCallback in
{ res in
if let task = Aria2.getTask(fromResponse: res) {
cb (task)
}
}
})
aria2.tellStatus(gid: gid, callback: wrappedCallback)
}
func addUri(url: [String]?, callback cb: ((JSON) -> Void)?) {
if let url = url {
aria2.addUri(url: url, callback: cb)
}
}
func pause(gid: String) {
aria2.pause(gid: gid)
}
func unpause(gid: String) {
aria2.unpause(gid: gid)
}
func stop(gid: String) {
aria2.stop(gid: gid)
}
func remove(gid: String) {
aria2.remove(gid: gid)
}
func registerNotificationDelegate(delegate: Aria2NotificationDelegate) {
self.aria2.notificationDelegate = delegate
}
func isValid() -> Bool {
return true
}
deinit {
stopTimer()
}
}
|
gpl-3.0
|
1f14694b59505de25df7e5796a60a88b
| 40.160305 | 134 | 0.633531 | 4.552132 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Views/Shepard Tab/Shepard Love Interest/ShepardLoveInterestController.swift
|
1
|
4593
|
//
// ShepardLoveInterestController.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/7/15.
// Copyright © 2015 urdnot. All rights reserved.
//
import UIKit
class ShepardLoveInterestController: UITableViewController, Spinnerable {
var persons: [Person] = []
var isUpdating = true
override func viewDidLoad() {
super.viewDidLoad()
setup()
startListeners()
}
// MARK: Setup Page Elements
func setup(reloadData: Bool = false) {
isUpdating = true
tableView.allowsMultipleSelectionDuringEditing = false
setupTableCustomCells()
fetchData()
isUpdating = false
}
func setupTableCustomCells() {
let bundle = Bundle(for: type(of: self))
tableView.register(UINib(nibName: "PersonRow", bundle: bundle), forCellReuseIdentifier: "PersonRow")
}
func fetchData() {
if UIWindow.isInterfaceBuilder {
persons = [Person.getDummy(), Person.getDummy()].compactMap { $0 }
} else {
let shepard = App.current.game?.shepard
let gameVersion = shepard?.gameVersion ?? .game1
persons = Person.getAllLoveOptions(
gameVersion: gameVersion,
isMale: shepard?.gender == .male
).sorted(by: Person.sort)
}
}
func setupRow(_ row: Int, cell: PersonRow) {
guard row < persons.count else { return }
cell.define(
person: persons[row],
isLoveInterest: persons[row].isLoveInterest,
hideDisclosure: true,
onChangeLoveSetting: { _ in
DispatchQueue.global(qos: .background).async {
if let id = self.persons[row].loveInterestDecisionId {
_ = Decision.get(id: id)?.changed(isSelected: cell.isLoveInterest, isSave: true)
}
}
}
)
}
func reloadDataOnChange(_ x: Bool = false) {
guard !isUpdating else { return }
isUpdating = true
fetchData()
tableView.reloadData()
isUpdating = false
}
func startListeners() {
guard !UIWindow.isInterfaceBuilder else { return }
// listen for gender and game version changes
App.onCurrentShepardChange.cancelSubscription(for: self)
_ = App.onCurrentShepardChange.subscribe(with: self) { [weak self] _ in
DispatchQueue.main.async {
self?.reloadDataOnChange()
}
}
// listen for decision changes
Decision.onChange.cancelSubscription(for: self)
_ = Decision.onChange.subscribe(with: self) { [weak self] changed in
DispatchQueue.main.async {
if let index = self?.persons.firstIndex(where: { $0.loveInterestDecisionId == changed.id }) {
let reloadRows: [IndexPath] = [IndexPath(row: index, section: 0)]
self?.reloadRows(reloadRows)
}
}
}
// listen for changes to persons data
Person.onChange.cancelSubscription(for: self)
_ = Person.onChange.subscribe(with: self) { [weak self] changed in
if self?.persons.contains(where: { $0.id == changed.id }) ?? false,
let newPerson = changed.object ?? Person.get(id: changed.id) {
DispatchQueue.main.async {
if let index = self?.persons.firstIndex(where: { $0.id == newPerson.id }) {
self?.persons[index] = newPerson
let reloadRows: [IndexPath] = [IndexPath(row: index, section: 0)]
self?.reloadRows(reloadRows)
}
}
}
}
}
}
extension ShepardLoveInterestController {
// MARK: Protocol - UITableViewDelegate
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return persons.count
}
// override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// return 1
// }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "PersonRow") as? PersonRow {
setupRow((indexPath as NSIndexPath).row, cell: cell)
return cell
}
return super.tableView(tableView, cellForRowAt: indexPath)
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
extension ShepardLoveInterestController: UpdatingTableView {
// public func reloadRows(rows: [NSIndexPath]) // defined in protocol
}
|
mit
|
a363a997ada5c6ca9a0a4bee1e9f3638
| 30.668966 | 109 | 0.662239 | 4.15942 | false | false | false | false |
drewag/agnostic-router
|
Sources/Router.swift
|
1
|
2725
|
//
// Router.swift
// Router
//
// Created by Andrew J Wagner on 4/9/16.
// Copyright © 2016 Drewag. All rights reserved.
//
// The MIT License (MIT)
//
// 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.
public enum RouterResponse<ValueType> {
case Unhandled
case Handled(ValueType)
public var value: ValueType? {
switch self {
case .Unhandled:
return nil
case .Handled(let value):
return value
}
}
}
public protocol Router {
associatedtype InputOutputType: InputOutput
var routes: [Route<InputOutputType>] {get}
}
extension Router {
public func route(input: InputOutputType.InputType, path: String) throws -> RouterResponse<InputOutputType.OutputType> {
let path = self.fix(path: path)
for route in self.routes {
if route.pathComponent.matches(path: path) {
let response = try route.route(input: input, path: path)
switch response {
case .Handled(_):
return response
case .Unhandled:
break
}
}
}
return .Unhandled
}
private func fix(path: String) -> String {
guard path.hasPrefix("/") else {
return path
}
var output = ""
for (index, character) in path.characters.enumerated() {
guard index != 0 else {
continue
}
output.append(character)
}
return output
}
}
struct InPlaceRouter<IO: InputOutput>: Router {
let routes: [Route<IO>]
init(routes: [Route<IO>]) {
self.routes = routes
}
}
|
mit
|
0191a826e72abed1091979c9846eaec1
| 29.954545 | 124 | 0.634361 | 4.601351 | false | false | false | false |
Restofire/Restofire-Gloss
|
Tests/ServiceSpec/BoolService+GETSpec.swift
|
1
|
2257
|
// _____ ____ __.
// / _ \ _____ _______ | |/ _|____ ___.__.
// / /_\ \\__ \\_ __ \ | < \__ \< | |
// / | \/ __ \| | \/ | | \ / __ \\___ |
// \____|__ (____ /__| |____|__ (____ / ____|
// \/ \/ \/ \/\/
//
// Copyright (c) 2016 RahulKatariya. All rights reserved.
//
import Quick
import Nimble
import Alamofire
class BoolGETServiceSpec: ServiceSpec {
override func spec() {
describe("BoolGETService") {
it("executeTask") {
let actual = true
var expected: Bool!
BoolGETService().executeTask() {
if let value = $0.result.value {
expected = value
}
}
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
it("executeRequestOperation") {
let actual = true
var expected: Bool!
let requestOperation = BoolGETService().requestOperation() {
if let value = $0.result.value {
expected = value
}
}
requestOperation.start()
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
it("executeRequestOperation__withoutCompletionHandler") {
let actual = true
var expected: Bool!
let requestOperation = BoolGETService().requestOperation()
requestOperation.start()
requestOperation.completionBlock = {
expected = requestOperation.finished
}
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
}
}
}
|
mit
|
23f77ace09fab0cc693b1c96b6103f99
| 30.788732 | 116 | 0.386354 | 5.545455 | false | false | false | false |
loudnate/xDripG5
|
CGMBLEKit Example/AppDelegate.swift
|
1
|
5141
|
//
// AppDelegate.swift
// xDrip5
//
// Created by Nathan Racklyeft on 10/1/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import UIKit
import CGMBLEKit
import CoreBluetooth
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TransmitterDelegate, TransmitterCommandSource {
var window: UIWindow?
static var sharedDelegate: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
var transmitterID: String? {
didSet {
if let id = transmitterID {
transmitter = Transmitter(
id: id,
passiveModeEnabled: UserDefaults.standard.passiveModeEnabled
)
transmitter?.stayConnected = UserDefaults.standard.stayConnected
transmitter?.delegate = self
transmitter?.commandSource = self
UserDefaults.standard.transmitterID = id
}
glucose = nil
}
}
var transmitter: Transmitter?
let commandQueue = CommandQueue()
var glucose: Glucose?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
transmitterID = UserDefaults.standard.transmitterID
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.
if let transmitter = transmitter, !transmitter.stayConnected {
transmitter.stopScanning()
}
}
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.
transmitter?.resumeScanning()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - TransmitterDelegate
private let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter
}()
func dequeuePendingCommand(for transmitter: Transmitter) -> Command? {
return commandQueue.dequeue()
}
func transmitter(_ transmitter: Transmitter, didFail command: Command, with error: Error) {
// TODO: implement
}
func transmitter(_ transmitter: Transmitter, didComplete command: Command) {
// TODO: implement
}
func transmitter(_ transmitter: Transmitter, didError error: Error) {
DispatchQueue.main.async {
if let vc = self.window?.rootViewController as? TransmitterDelegate {
vc.transmitter(transmitter, didError: error)
}
}
}
func transmitter(_ transmitter: Transmitter, didRead glucose: Glucose) {
self.glucose = glucose
DispatchQueue.main.async {
if let vc = self.window?.rootViewController as? TransmitterDelegate {
vc.transmitter(transmitter, didRead: glucose)
}
}
}
func transmitter(_ transmitter: Transmitter, didReadUnknownData data: Data) {
DispatchQueue.main.async {
if let vc = self.window?.rootViewController as? TransmitterDelegate {
vc.transmitter(transmitter, didReadUnknownData: data)
}
}
}
func transmitter(_ transmitter: Transmitter, didReadBackfill glucose: [Glucose]) {
DispatchQueue.main.async {
if let vc = self.window?.rootViewController as? TransmitterDelegate {
vc.transmitter(transmitter, didReadBackfill: glucose)
}
}
}
func transmitterDidConnect(_ transmitter: Transmitter) {
// Ignore
}
}
|
mit
|
a6215d45499f1ebf06696f95947d9655
| 35.714286 | 285 | 0.67393 | 5.462274 | false | false | false | false |
Nana-Muthuswamy/AadhuEats
|
AadhuEats/Common/Extensions.swift
|
1
|
1878
|
//
// Extensions.swift
// AadhuEats
//
// Created by Nana on 11/4/17.
// Copyright © 2017 Nana. All rights reserved.
//
import Foundation
import UIKit
extension Date {
func startOfDay() -> Date {
let calendar = Calendar.autoupdatingCurrent
var dateComps = calendar.dateComponents([.second,.minute,.hour,.day,.month,.year], from: self)
dateComps.second = 0
dateComps.minute = 0
dateComps.hour = 0
return calendar.date(from: dateComps) ?? self
}
func endOfDay() -> Date {
let calendar = Calendar.autoupdatingCurrent
var dateComps = calendar.dateComponents([.second,.minute,.hour,.day,.month,.year], from: self)
dateComps.second = 59
dateComps.minute = 59
dateComps.hour = 23
return calendar.date(from: dateComps) ?? self
}
func absolute() -> Date {
let calendar = Calendar.autoupdatingCurrent
var dateComps = calendar.dateComponents([.day,.month,.year], from: self)
return calendar.date(from: dateComps) ?? self
}
func previous() -> Date {
let calendar = Calendar.autoupdatingCurrent
var dateComps = calendar.dateComponents([.second,.minute,.hour,.day,.month,.year], from: self)
dateComps.day! -= 1
return calendar.date(from: dateComps) ?? self
}
func next() -> Date {
let calendar = Calendar.autoupdatingCurrent
var dateComps = calendar.dateComponents([.second,.minute,.hour,.day,.month,.year], from: self)
dateComps.day! += 1
return calendar.date(from: dateComps) ?? self
}
}
extension UIViewController {
var contentViewController: UIViewController {
if (self is UINavigationController) {
return (self as! UINavigationController).viewControllers[0]
} else {
return self
}
}
}
|
mit
|
4f3fd186e5ada331f4f64d96870c52f7
| 25.814286 | 102 | 0.625999 | 4.395785 | false | false | false | false |
runtastic/Matrioska
|
Tests/ComponentTests.swift
|
1
|
10798
|
//
// ComponentTests.swift
// MatrioskaTests
//
// Created by Alex Manzella on 09/11/16.
// Copyright © 2016 runtastic. All rights reserved.
//
import XCTest
import Quick
import Nimble
@testable import Matrioska
class ComponentTests: QuickSpec {
override func spec() {
typealias DictMeta = [String: String]
describe("View component") {
it("should build a viewController") {
let component = Component.single(viewBuilder: { _ in UIViewController() }, meta: nil)
expect(component.viewController()).toNot(beNil())
}
it("should pass metadata to the builder") {
var value: ComponentMeta? = nil
_ = Component.single(viewBuilder: { (meta) in
value = meta
return UIViewController()
}, meta: ["foo": "bar"]).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("should have the correct metadata") {
let component = Component.single(viewBuilder: { _ in UIViewController() },
meta: ["foo": "bar"])
expect(component.meta as? DictMeta) == ["foo": "bar"]
}
}
describe("Wrapper component") {
it("should build a viewController") {
let component = Component.wrapper(viewBuilder: { _ in UIViewController() },
child: randComponent(),
meta: nil)
expect(component.viewController()).toNot(beNil())
}
it("should pass the child to the builder") {
var component: Component? = nil
let viewBuilder: Component.WrapperViewBuilder = { (child, _) in
component = child
return UIViewController()
}
_ = Component.wrapper(viewBuilder: viewBuilder,
child: randComponent(),
meta: nil).viewController()
expect(component).toNot(beNil())
}
it("should pass metadata to the builder") {
var value: ComponentMeta? = nil
let viewBuilder: Component.WrapperViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
_ = Component.wrapper(viewBuilder: viewBuilder,
child: randComponent(),
meta: ["foo": "bar"]).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("should have the correct metadata") {
let component = Component.wrapper(viewBuilder: { _ in UIViewController() },
child: randComponent(),
meta: ["foo": "bar"])
expect(component.meta as? DictMeta) == ["foo": "bar"]
}
}
describe("Cluster component") {
it("should build a viewController") {
let component = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: nil)
expect(component.viewController()).toNot(beNil())
}
it("should pass the children to the builder") {
var components: [Component]? = nil
let viewBuilder: Component.ClusterViewBuilder = { (children, _) in
components = children
return UIViewController()
}
_ = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: nil).viewController()
expect(components).toNot(beNil())
}
it("should pass metadata to the builder") {
var value: ComponentMeta? = nil
let viewBuilder: Component.ClusterViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
_ = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: ["foo": "bar"]).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("should have the correct metadata") {
let component = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: ["foo": "bar"])
expect(component.meta as? DictMeta) == ["foo": "bar"]
}
}
describe("Rule component") {
it("builds his child view controller if it evaluates to true") {
let cluster = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: nil)
let rule = Rule.not(rule: Rule.simple(evaluator: { false }))
let component = Component.rule(rule: rule, component: cluster)
expect(component.viewController()).toNot(beNil())
}
it("does not build his child view controller if it evaluates to false") {
let cluster = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: nil)
let rule = Rule.and(rules: [Rule.simple(evaluator: { false }), Rule.simple(evaluator: { true })])
let component = Component.rule(rule: rule, component: cluster)
expect(component.viewController()).to(beNil())
}
it("passes the children to the child's builder if it evaluates to true") {
let rule = Rule.or(rules: [Rule.simple(evaluator: { false }), Rule.simple(evaluator: { true })])
var components: [Component]? = nil
let viewBuilder: Component.ClusterViewBuilder = { (children, _) in
components = children
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: nil)
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(components).toNot(beNil())
}
it("does not pass the children to the child's builder if it evaluates to false") {
let rule = Rule.not(rule: Rule.simple(evaluator: { true }))
var components: [Component]? = nil
let viewBuilder: Component.ClusterViewBuilder = { (children, _) in
components = children
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: nil)
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(components).to(beNil())
}
it("passes metadata to the child's builder if it evaluates to true") {
let rule = Rule.not(rule: Rule.simple(evaluator: { false }))
var value: ComponentMeta? = nil
let viewBuilder: Component.ClusterViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: ["foo": "bar"])
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("does not pass metadata to the child's builder if it evaluates to false") {
let rule = Rule.simple(evaluator: { false })
var value: ComponentMeta? = nil
let viewBuilder: Component.ClusterViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: ["one": "two"])
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(value).to(beNil())
}
it("has the correct child's metadata regardless of evaluating to true/false") {
let rule = Rule.simple(evaluator: { false })
let cluster = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: ["foo": "bar"])
let falseComponent = Component.rule(rule: rule, component: cluster)
let trueComponent = Component.rule(rule: Rule.not(rule: rule), component: cluster)
expect(falseComponent.meta as? DictMeta) == ["foo": "bar"]
expect(trueComponent.meta as? DictMeta) == ["foo": "bar"]
}
}
}
}
private func randComponent() -> Component {
return Component.single(viewBuilder: { _ in UIViewController() }, meta: nil)
}
|
mit
|
2ffc1e2671b47694af11bc3ab3a798f2
| 45.141026 | 113 | 0.445679 | 6.025112 | false | false | false | false |
NikitaAsabin/pdpDecember
|
DayPhoto/ViewController.swift
|
1
|
6874
|
//
// ViewController.swift
// DayPhoto
//
// Created by Kruperfone on 13.02.15.
// Copyright (c) 2015 Flatstack. All rights reserved.
//
import UIKit
import MagicalRecord
import AVFoundation
class ViewController: UIViewController {
private let flipPresentAnimationController = FlipPresentAnimationController()
private let flipDismissAnimationController = FlipDismissAnimationController()
private let swipeInteractionController = SwipeInteractionController()
@IBOutlet weak var label: UILabel!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var fullImageView: UIImageView!
@IBOutlet weak var blurButton: UIButton!
@IBOutlet weak var loginViewContainer: UIView!
var photoSource = Photo.allPhotos()
var collectionViewWidth = CGFloat(0);
var isBlured = false
var fromFrame: CGRect?
override func viewDidLoad() {
super.viewDidLoad()
if let patternImage = UIImage(named: "Pattern") {
view.backgroundColor = UIColor(patternImage: patternImage)
}
if let layout = self.collectionView?.collectionViewLayout as? DayPhotoLayout {
layout.delegate = self
}
self.collectionView!.contentInset = UIEdgeInsets(top: 23, left: 5, bottom: 10, right: 5)
self.collectionViewWidth = self.collectionView.frame.width
self.blurButton.layer.cornerRadius = 70
self.blurButton.clipsToBounds = true
self.setBlurForBlurButton()
self.loginViewContainer.layer.cornerRadius = 10
self.loginViewContainer.clipsToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.collectionView.frame.width != self.collectionViewWidth {
let layout = DayPhotoLayout()
layout.delegate = self
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.reloadData()
self.collectionView.setCollectionViewLayout(layout, animated: false)
self.collectionViewWidth = self.collectionView.frame.width
}
}
func setBlurForBlurButton() {
let blurEffect = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blurEffect)
let vibrancy = UIVibrancyEffect(forBlurEffect:blurEffect)
let vibrancyView = UIVisualEffectView(effect: vibrancy)
blurView.frame = CGRectMake(0, 0, 140, 140)
blurView.userInteractionEnabled = false
vibrancyView.frame = CGRectMake(0, 0, 140, 140)
vibrancyView.userInteractionEnabled = false
self.blurButton.insertSubview(blurView, atIndex: 0)
self.blurButton.insertSubview(vibrancyView, atIndex: 0)
}
@IBAction func blurImage(sender: AnyObject) {
if self.isBlured == false {
let blurEffect = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = self.fullImageView.frame
self.view.insertSubview(blurView, aboveSubview: self.fullImageView)
self.isBlured = true
} else {
for view in self.view.subviews {
if view.isKindOfClass(UIVisualEffectView) {
view.removeFromSuperview()
}
}
self.isBlured = false
}
}
@IBAction func showHideLoginView(sender: AnyObject) {
self.loginViewContainer.hidden = !self.loginViewContainer.hidden
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("AnnotatedPhotoCell", forIndexPath: indexPath) as! AnnotatedPhotoCell
cell.photo = photoSource[indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoSource.count
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if FSIsIPad() == true {
self.fullImageView.image = photoSource[indexPath.row].image
} else {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("PhotoView") as! PhotoViewController
vc.photo = photoSource[indexPath.row]
vc.transitioningDelegate = self
let cell = collectionView.cellForItemAtIndexPath(indexPath)
self.fromFrame = cell?.frame
swipeInteractionController.wireToViewController(vc)
self.showViewController(vc, sender: self)
}
}
}
extension ViewController : DayPhotoLayoutDelegate {
func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:NSIndexPath , withWidth width:CGFloat) -> CGFloat {
let photo = photoSource[indexPath.item]
let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
let rect = AVMakeRectWithAspectRatioInsideRect(photo.image.size , boundingRect)
return rect.size.height
}
func collectionView(collectionView: UICollectionView, heightForAnnotationAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat {
let annotationPadding = CGFloat(4)
let annotationHeaderHeight = CGFloat(17)
let photo = photoSource[indexPath.item]
let font = UIFont(name: "AvenirNext-Regular", size: 10)!
let commentHeight = photo.heightForComment(font, width: width)
let height = annotationPadding + annotationHeaderHeight + commentHeight + annotationPadding
return height
}
}
extension ViewController: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
flipPresentAnimationController.originFrame = self.fromFrame!
return flipPresentAnimationController
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
flipDismissAnimationController.destinationFrame = self.view.frame
return flipDismissAnimationController
}
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return swipeInteractionController.interactionInProgress ? swipeInteractionController : nil
}
}
|
mit
|
fdc334da2a5c0f111df12d9d9f3f23e3
| 41.177914 | 217 | 0.703666 | 5.695112 | false | false | false | false |
kortnee1021/Kortnee
|
04-Application Architecture/Swift 1/05-UIViewController/Demo - presenting/Step-0-StartingCode/BMI/ViewController.swift
|
8
|
3457
|
//
// ViewController.swift
// BMI
//
// Created by Nicholas Outram on 30/12/2014.
// Copyright (c) 2014 Plymouth University. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
let listOfWeightsInKg = Array(80...240).map( { Double($0) * 0.5 } )
let listOfHeightsInM = Array(140...220).map( { Double($0) * 0.01 } )
var weight : Double?
var height : Double?
var bmi : Double? {
get {
if (weight != nil) && (height != nil) {
return weight! / (height! * height!)
} else {
return nil
}
}
}
@IBOutlet weak var bmiLabel: UILabel!
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var weightTextField: UITextField!
@IBOutlet weak var heightPickerView: UIPickerView!
@IBOutlet weak var weightPickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
updateUI()
return true
}
func updateUI() {
if let val = self.bmi {
self.bmiLabel.text = String(format: "%4.1f", val)
}
}
func textFieldDidEndEditing(textField: UITextField) {
let conv = { NSNumberFormatter().numberFromString($0)?.doubleValue }
switch (textField) {
case self.weightTextField:
self.weight = conv(textField.text)
case self.heightTextField:
self.height = conv(textField.text)
default:
println("Error");
}
updateUI()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch (pickerView) {
case self.heightPickerView:
return listOfHeightsInM.count
case self.weightPickerView:
return listOfWeightsInKg.count
default:
return 0
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
switch (pickerView) {
case self.heightPickerView:
return String(format: "%4.2f", listOfHeightsInM[row])
case self.weightPickerView:
return String(format: "%4.1f", listOfWeightsInKg[row])
default:
return ""
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch (pickerView) {
case self.heightPickerView:
let h : Double = self.listOfHeightsInM[row]
self.height = h
case self.weightPickerView:
let w : Double = self.listOfWeightsInKg[row]
self.weight = w
default:
println("Error");
}
updateUI()
}
}
|
mit
|
ea2499b2642699d4dfd8da27a4288c38
| 26.656 | 109 | 0.567255 | 5.032023 | false | false | false | false |
nst/JSONTestSuite
|
parsers/test_Freddy_20170118/test_Freddy/JSONParser.swift
|
1
|
31643
|
//
// JSONParser.swift
// Freddy
//
// Created by John Gallagher on 4/18/15.
// Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//
import Foundation
private struct Literal {
static let BACKSLASH = UInt8(ascii: "\\")
static let BACKSPACE = UInt8(ascii: "\u{0008}")
static let COLON = UInt8(ascii: ":")
static let COMMA = UInt8(ascii: ",")
static let DOUBLE_QUOTE = UInt8(ascii: "\"")
static let FORMFEED = UInt8(ascii: "\u{000c}")
static let LEFT_BRACE = UInt8(ascii: "{")
static let LEFT_BRACKET = UInt8(ascii: "[")
static let MINUS = UInt8(ascii: "-")
static let NEWLINE = UInt8(ascii: "\n")
static let PERIOD = UInt8(ascii: ".")
static let PLUS = UInt8(ascii: "+")
static let RETURN = UInt8(ascii: "\r")
static let RIGHT_BRACE = UInt8(ascii: "}")
static let RIGHT_BRACKET = UInt8(ascii: "]")
static let SLASH = UInt8(ascii: "/")
static let SPACE = UInt8(ascii: " ")
static let TAB = UInt8(ascii: "\t")
static let a = UInt8(ascii: "a")
static let b = UInt8(ascii: "b")
static let c = UInt8(ascii: "c")
static let d = UInt8(ascii: "d")
static let e = UInt8(ascii: "e")
static let f = UInt8(ascii: "f")
static let l = UInt8(ascii: "l")
static let n = UInt8(ascii: "n")
static let r = UInt8(ascii: "r")
static let s = UInt8(ascii: "s")
static let t = UInt8(ascii: "t")
static let u = UInt8(ascii: "u")
static let A = UInt8(ascii: "A")
static let B = UInt8(ascii: "B")
static let C = UInt8(ascii: "C")
static let D = UInt8(ascii: "D")
static let E = UInt8(ascii: "E")
static let F = UInt8(ascii: "F")
static let zero = UInt8(ascii: "0")
static let one = UInt8(ascii: "1")
static let two = UInt8(ascii: "2")
static let three = UInt8(ascii: "3")
static let four = UInt8(ascii: "4")
static let five = UInt8(ascii: "5")
static let six = UInt8(ascii: "6")
static let seven = UInt8(ascii: "7")
static let eight = UInt8(ascii: "8")
static let nine = UInt8(ascii: "9")
}
private let ParserMaximumDepth = 512
/// A pure Swift JSON parser. This parser is much faster than the
/// `NSJSONSerialization`-based parser (due to the overhead of having to
/// dynamically cast the Objective-C objects to determine their type); however,
/// it is much newer and has restrictions that the `NSJSONSerialization` parser
/// does not. Two restrictions in particular are that it requires UTF-8 data as
/// input and it does not allow trailing commas in arrays or dictionaries.
public struct JSONParser {
fileprivate enum Sign: Int {
case positive = 1
case negative = -1
}
private let input: UnsafeBufferPointer<UInt8>
private var loc = 0
private var depth = 0
fileprivate init(input: UnsafeBufferPointer<UInt8>) {
self.input = input
}
/// Decode the root element of the `JSON` stream. This may be any fragment
/// or a structural element, per RFC 7159.
///
/// The beginning bytes are used to determine the stream's encoding.
/// `JSONParser` currently only supports UTF-8 encoding, with or without
/// a byte-order mark.
///
/// - throws: `JSONParser.Error` for any decoding failures, including a
/// source location if needed.
public mutating func parse() throws -> JSON {
try guardAgainstUnsupportedEncodings()
let value = try parseValue()
skipWhitespace()
guard loc == input.count else {
throw Error.endOfStreamGarbage(offset: loc)
}
return value
}
private mutating func parseValue() throws -> JSON {
guard depth <= ParserMaximumDepth else {
throw Error.exceededNestingLimit(offset: loc)
}
guard input.count > 0 else {
throw Error.endOfStreamUnexpected
}
advancing: while loc < input.count {
do {
switch input[loc] {
case Literal.LEFT_BRACKET:
depth += 1
defer { depth -= 1 }
return try decodeArray()
case Literal.LEFT_BRACE:
depth += 1
defer { depth -= 1 }
return try decodeObject()
case Literal.DOUBLE_QUOTE:
return try decodeString()
case Literal.f:
return try decodeFalse()
case Literal.n:
return try decodeNull()
case Literal.t:
return try decodeTrue()
case Literal.MINUS:
return try decodeIntegralValue(NumberParser(loc: loc, input: input, state: .leadingMinus))
case Literal.zero:
return try decodeIntegralValue(NumberParser(loc: loc, input: input, state: .leadingZero))
case Literal.one...Literal.nine:
return try decodeIntegralValue(NumberParser(loc: loc, input: input, state: .preDecimalDigits))
case Literal.SPACE, Literal.TAB, Literal.RETURN, Literal.NEWLINE:
loc = (loc + 1)
default:
break advancing
}
} catch let InternalError.numberOverflow(offset: start) {
return try decodeNumberAsString(from: start)
}
}
if loc < input.count {
throw Error.valueInvalid(offset: loc, character: UnicodeScalar(input[loc]))
} else {
throw Error.endOfStreamUnexpected
}
}
private mutating func skipWhitespace() {
while loc < input.count {
switch input[loc] {
case Literal.SPACE, Literal.TAB, Literal.RETURN, Literal.NEWLINE:
loc = (loc + 1)
default:
return
}
}
}
private mutating func guardAgainstUnsupportedEncodings() throws {
let header = input.prefix(4)
let encodingPrefixInformation = JSONEncodingDetector.detectEncoding(header)
guard JSONEncodingDetector.supportedEncodings.contains(encodingPrefixInformation.encoding) else {
throw Error.invalidUnicodeStreamEncoding(detectedEncoding: encodingPrefixInformation.encoding)
}
loc = loc.advanced(by: encodingPrefixInformation.byteOrderMarkLength)
}
private mutating func decodeNull() throws -> JSON {
guard input.index(loc, offsetBy: 3, limitedBy: input.count) != input.count else {
throw Error.literalNilMisspelled(offset: loc)
}
if input[loc+1] != Literal.u
|| input[loc+2] != Literal.l
|| input[loc+3] != Literal.l {
throw Error.literalNilMisspelled(offset: loc)
}
loc += 4
return .null
}
private mutating func decodeTrue() throws -> JSON {
guard input.index(loc, offsetBy: 3, limitedBy: input.count) != input.count else {
throw Error.literalNilMisspelled(offset: loc)
}
if input[loc+1] != Literal.r
|| input[loc+2] != Literal.u
|| input[loc+3] != Literal.e {
throw Error.literalTrueMisspelled(offset: loc)
}
loc += 4
return .bool(true)
}
private mutating func decodeFalse() throws -> JSON {
guard input.index(loc, offsetBy: 4, limitedBy: input.count) != input.count else {
throw Error.literalNilMisspelled(offset: loc)
}
if input[loc+1] != Literal.a
|| input[loc+2] != Literal.l
|| input[loc+3] != Literal.s
|| input[loc+4] != Literal.e {
throw Error.literalFalseMisspelled(offset: loc)
}
loc += 5
return .bool(false)
}
private var stringDecodingBuffer = [UInt8]()
private mutating func decodeString() throws -> JSON {
loc = (loc + 1)
stringDecodingBuffer.removeAll(keepingCapacity: true)
while loc < input.count {
switch input[loc] {
case Literal.BACKSLASH:
loc = (loc + 1)
guard loc < input.count else { continue }
switch input[loc] {
case Literal.DOUBLE_QUOTE: stringDecodingBuffer.append(Literal.DOUBLE_QUOTE)
case Literal.BACKSLASH: stringDecodingBuffer.append(Literal.BACKSLASH)
case Literal.SLASH: stringDecodingBuffer.append(Literal.SLASH)
case Literal.b: stringDecodingBuffer.append(Literal.BACKSPACE)
case Literal.f: stringDecodingBuffer.append(Literal.FORMFEED)
case Literal.r: stringDecodingBuffer.append(Literal.RETURN)
case Literal.t: stringDecodingBuffer.append(Literal.TAB)
case Literal.n: stringDecodingBuffer.append(Literal.NEWLINE)
case Literal.u:
loc = (loc + 1)
try readUnicodeEscape(start: loc - 2)
// readUnicodeEscape() advances loc on its own, so we'll `continue` now
// to skip the typical "advance past this character" for all the other escapes
continue
default:
throw Error.controlCharacterUnrecognized(offset: loc)
}
loc = (loc + 1)
case Literal.DOUBLE_QUOTE:
loc = (loc + 1)
stringDecodingBuffer.append(0)
let string = stringDecodingBuffer.withUnsafeBufferPointer {
String(cString: UnsafePointer($0.baseAddress!))
}
return .string(string)
case let other:
stringDecodingBuffer.append(other)
loc = (loc + 1)
}
}
throw Error.endOfStreamUnexpected
}
private mutating func readCodeUnit() -> UInt16? {
guard loc + 4 <= input.count else {
return nil
}
var codeUnit: UInt16 = 0
for c in input[loc..<loc+4] {
let nibble: UInt16
switch c {
case Literal.zero...Literal.nine:
nibble = UInt16(c - Literal.zero)
case Literal.a...Literal.f:
nibble = 10 + UInt16(c - Literal.a)
case Literal.A...Literal.F:
nibble = 10 + UInt16(c - Literal.A)
default:
return nil
}
codeUnit = (codeUnit << 4) | nibble
}
loc += 4
return codeUnit
}
private mutating func readUnicodeEscape(start: Int) throws {
guard let codeUnit = readCodeUnit() else {
throw Error.unicodeEscapeInvalid(offset: start)
}
let codeUnits: [UInt16]
if UTF16.isLeadSurrogate(codeUnit) {
// First half of a UTF16 surrogate pair - we must parse another code unit and combine them
// First confirm and skip over that we have another "\u"
guard loc + 6 <= input.count && input[loc] == Literal.BACKSLASH && input[loc+1] == Literal.u else {
throw Error.unicodeEscapeInvalid(offset: start)
}
loc += 2
// Ensure the second code unit is valid for the surrogate pair
guard let secondCodeUnit = readCodeUnit(), UTF16.isTrailSurrogate(secondCodeUnit) else {
throw Error.unicodeEscapeInvalid(offset: start)
}
codeUnits = [codeUnit, secondCodeUnit]
} else {
codeUnits = [codeUnit]
}
let transcodeHadError = transcode(codeUnits.makeIterator(), from: UTF16.self, to: UTF8.self, stoppingOnError: true) { (outputEncodingCodeUnit) in
self.stringDecodingBuffer.append(outputEncodingCodeUnit)
}
if transcodeHadError {
throw Error.unicodeEscapeInvalid(offset: start)
}
}
private mutating func decodeArray() throws -> JSON {
let start = loc
loc = (loc + 1)
var items = [JSON]()
while loc < input.count {
skipWhitespace()
if loc < input.count && input[loc] == Literal.RIGHT_BRACKET {
loc = (loc + 1)
return .array(items)
}
if !items.isEmpty {
guard loc < input.count && input[loc] == Literal.COMMA else {
throw Error.collectionMissingSeparator(offset: start)
}
loc = (loc + 1)
}
items.append(try parseValue())
}
throw Error.endOfStreamUnexpected
}
// Decoding objects can be recursive, so we have to keep more than one
// buffer around for building up key/value pairs (to reduce allocations
// when parsing large JSON documents).
//
// Rough estimate of the difference between this and using a fresh
// [(String,JSON)] for the `pairs` variable in decodeObject() below is
// about 12% on an iPhone 5.
private struct DecodeObjectBuffers {
var buffers = [[(String,JSON)]]()
mutating func getBuffer() -> [(String,JSON)] {
if !buffers.isEmpty {
var buffer = buffers.removeLast()
buffer.removeAll(keepingCapacity: true)
return buffer
}
return [(String,JSON)]()
}
mutating func putBuffer(_ buffer: [(String,JSON)]) {
buffers.append(buffer)
}
}
private var decodeObjectBuffers = DecodeObjectBuffers()
private mutating func decodeObject() throws -> JSON {
let start = loc
loc = (loc + 1)
var pairs = decodeObjectBuffers.getBuffer()
while loc < input.count {
skipWhitespace()
if loc < input.count && input[loc] == Literal.RIGHT_BRACE {
loc = (loc + 1)
var obj = [String:JSON](minimumCapacity: pairs.count)
for (k, v) in pairs {
obj[k] = v
}
decodeObjectBuffers.putBuffer(pairs)
return .dictionary(obj)
}
if !pairs.isEmpty {
guard loc < input.count && input[loc] == Literal.COMMA else {
throw Error.collectionMissingSeparator(offset: start)
}
loc = (loc + 1)
skipWhitespace()
}
guard loc < input.count && input[loc] == Literal.DOUBLE_QUOTE else {
throw Error.dictionaryMissingKey(offset: start)
}
let key = try decodeString().getString()
skipWhitespace()
guard loc < input.count && input[loc] == Literal.COLON else {
throw Error.collectionMissingSeparator(offset: start)
}
loc = (loc + 1)
pairs.append((key, try parseValue()))
}
throw Error.endOfStreamUnexpected
}
private mutating func decodeIntegralValue(_ parser: NumberParser) throws -> JSON {
var sign = Sign.positive
var parser = parser
var value = 0
// This would be more natural as `while true { ... }` with a meaningful .Done case,
// but that causes compile time explosion in Swift 2.2. :-|
while parser.state != .done {
switch parser.state {
case .leadingMinus:
sign = .negative
try parser.parseNegative()
case .leadingZero:
parser.parseLeadingZero()
case .preDecimalDigits:
try parser.parsePreDecimalDigits { c in
guard case let (exponent, false) = Int.multiplyWithOverflow(10, value) else {
throw InternalError.numberOverflow(offset: parser.start)
}
guard case let (newValue, false) = Int.addWithOverflow(exponent, Int(c - Literal.zero)) else {
throw InternalError.numberOverflow(offset: parser.start)
}
value = newValue
}
case .decimal, .exponent:
return try detectingFloatingPointErrors(start: parser.start) {
try decodeFloatingPointValue(parser, sign: sign, value: Double(value))
}
case .postDecimalDigits, .exponentSign, .exponentDigits:
assertionFailure("Invalid internal state while parsing number")
case .done:
fatalError("impossible condition")
}
}
guard case let (signedValue, false) = Int.multiplyWithOverflow(sign.rawValue, value) else {
throw InternalError.numberOverflow(offset: parser.start)
}
loc = parser.loc
return .int(signedValue)
}
private mutating func decodeFloatingPointValue(_ parser: NumberParser, sign: Sign, value: Double) throws -> JSON {
var parser = parser
var value = value
var exponentSign = Sign.positive
var exponent = Double(0)
var position = 0.1
// This would be more natural as `while true { ... }` with a meaningful .Done case,
// but that causes compile time explosion in Swift 2.2. :-|
while parser.state != .done {
switch parser.state {
case .leadingMinus, .leadingZero, .preDecimalDigits:
assertionFailure("Invalid internal state while parsing number")
case .decimal:
try parser.parseDecimal()
case .postDecimalDigits:
parser.parsePostDecimalDigits { c in
value += position * Double(c - Literal.zero)
position /= 10
}
case .exponent:
exponentSign = try parser.parseExponent()
case .exponentSign:
try parser.parseExponentSign()
case .exponentDigits:
parser.parseExponentDigits { c in
exponent = exponent * 10 + Double(c - Literal.zero)
}
case .done:
fatalError("impossible condition")
}
}
loc = parser.loc
return .double(Double(sign.rawValue) * value * pow(10, Double(exponentSign.rawValue) * exponent))
}
private mutating func decodeNumberAsString(from position: Int) throws -> JSON {
var parser: NumberParser = {
let state: NumberParser.State
switch input[position] {
case Literal.MINUS: state = .leadingMinus
case Literal.zero: state = .leadingZero
case Literal.one...Literal.nine: state = .preDecimalDigits
default:
fatalError("Internal error: decodeNumber called on not-a-number")
}
return NumberParser(loc: position, input: input, state: state)
}()
stringDecodingBuffer.removeAll(keepingCapacity: true)
while true {
switch parser.state {
case .leadingMinus:
try parser.parseNegative()
stringDecodingBuffer.append(Literal.MINUS)
case .leadingZero:
parser.parseLeadingZero()
stringDecodingBuffer.append(Literal.zero)
case .preDecimalDigits:
parser.parsePreDecimalDigits { stringDecodingBuffer.append($0) }
case .decimal:
try parser.parseDecimal()
stringDecodingBuffer.append(Literal.PERIOD)
case .postDecimalDigits:
parser.parsePostDecimalDigits { stringDecodingBuffer.append($0) }
case .exponent:
stringDecodingBuffer.append(input[parser.loc])
_ = try parser.parseExponent()
case .exponentSign:
stringDecodingBuffer.append(input[parser.loc])
try parser.parseExponentSign()
case .exponentDigits:
parser.parseExponentDigits { stringDecodingBuffer.append($0) }
case .done:
stringDecodingBuffer.append(0)
let string = stringDecodingBuffer.withUnsafeBufferPointer {
String(cString: UnsafePointer($0.baseAddress!))
}
loc = parser.loc
return .string(string)
}
}
}
private func detectingFloatingPointErrors<T>(start loc: Int, _ f: () throws -> T) throws -> T {
let flags = FE_UNDERFLOW | FE_OVERFLOW
feclearexcept(flags)
let value = try f()
guard fetestexcept(flags) == 0 else {
throw InternalError.numberOverflow(offset: loc)
}
return value
}
}
private struct NumberParser {
enum State {
case leadingMinus
case leadingZero
case preDecimalDigits
case decimal
case postDecimalDigits
case exponent
case exponentSign
case exponentDigits
case done
}
let start: Int
var loc = 0
var state: State
let input: UnsafeBufferPointer<UInt8>
init(loc: Int, input: UnsafeBufferPointer<UInt8>, state: State) {
assert(loc < input.count, "Invalid input to NumberParser")
self.start = loc
self.loc = loc
self.input = input
self.state = state
}
mutating func parseNegative() throws {
assert(state == .leadingMinus, "Unexpected state entering parseNegative")
loc = (loc + 1)
guard loc < input.count else {
throw JSONParser.Error.endOfStreamUnexpected
}
switch input[loc] {
case Literal.zero:
state = .leadingZero
case Literal.one...Literal.nine:
state = .preDecimalDigits
default:
throw JSONParser.Error.numberSymbolMissingDigits(offset: start)
}
}
mutating func parseLeadingZero() {
assert(state == .leadingZero, "Unexpected state entering parseLeadingZero")
loc = (loc + 1)
guard loc < input.count else {
state = .done
return
}
switch input[loc] {
case Literal.PERIOD:
state = .decimal
case Literal.e, Literal.E:
state = .exponent
default:
state = .done
}
}
mutating func parsePreDecimalDigits(f: (UInt8) throws -> Void) rethrows {
assert(state == .preDecimalDigits, "Unexpected state entering parsePreDecimalDigits")
advancing: while loc < input.count {
let c = input[loc]
switch c {
case Literal.zero...Literal.nine:
try f(c)
loc = (loc + 1)
case Literal.PERIOD:
state = .decimal
return
case Literal.e, Literal.E:
state = .exponent
return
default:
break advancing
}
}
state = .done
}
mutating func parseDecimal() throws {
assert(state == .decimal, "Unexpected state entering parseDecimal")
loc = (loc + 1)
guard loc < input.count else {
throw JSONParser.Error.endOfStreamUnexpected
}
switch input[loc] {
case Literal.zero...Literal.nine:
state = .postDecimalDigits
default:
throw JSONParser.Error.numberMissingFractionalDigits(offset: start)
}
}
mutating func parsePostDecimalDigits(f: (UInt8) throws -> Void) rethrows {
assert(state == .postDecimalDigits, "Unexpected state entering parsePostDecimalDigits")
advancing: while loc < input.count {
let c = input[loc]
switch c {
case Literal.zero...Literal.nine:
try f(c)
loc = (loc + 1)
case Literal.e, Literal.E:
state = .exponent
return
default:
break advancing
}
}
state = .done
}
mutating func parseExponent() throws -> JSONParser.Sign {
assert(state == .exponent, "Unexpected state entering parseExponent")
loc = (loc + 1)
guard loc < input.count else {
throw JSONParser.Error.endOfStreamUnexpected
}
switch input[loc] {
case Literal.zero...Literal.nine:
state = .exponentDigits
case Literal.PLUS:
state = .exponentSign
case Literal.MINUS:
state = .exponentSign
return .negative
default:
throw JSONParser.Error.numberSymbolMissingDigits(offset: start)
}
return .positive
}
mutating func parseExponentSign() throws {
assert(state == .exponentSign, "Unexpected state entering parseExponentSign")
loc = (loc + 1)
guard loc < input.count else {
throw JSONParser.Error.endOfStreamUnexpected
}
switch input[loc] {
case Literal.zero...Literal.nine:
state = .exponentDigits
default:
throw JSONParser.Error.numberSymbolMissingDigits(offset: start)
}
}
mutating func parseExponentDigits(f: (UInt8) throws -> Void) rethrows {
assert(state == .exponentDigits, "Unexpected state entering parseExponentDigits")
advancing: while loc < input.count {
let c = input[loc]
switch c {
case Literal.zero...Literal.nine:
try f(c)
loc = (loc + 1)
default:
break advancing
}
}
state = .done
}
}
public extension JSONParser {
/// Creates a `JSONParser` ready to parse UTF-8 encoded `Data`.
///
/// If the data is mutable, it is copied before parsing. The data's lifetime
/// is extended for the duration of parsing.
@available(*, unavailable, message: "Replaced with parse(utf8:)")
init(utf8Data inData: Data) {
fatalError("unavailable code cannot be executed")
}
/// Creates a `JSONParser` from the code units represented by the `string`.
///
/// The synthesized string is lifetime-extended for the duration of parsing.
@available(*, unavailable, message: "Replaced with parse(utf8:)")
init(string: String) {
fatalError("unavailable code cannot be executed")
}
/// Creates an instance of `JSON` from UTF-8 encoded `data`.
static func parse(utf8 data: Data) throws -> JSON {
return try data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> JSON in
let buffer = UnsafeBufferPointer(start: ptr, count: data.count)
var parser = JSONParser(input: buffer)
return try parser.parse()
}
}
/// Creates an instance of `JSON` from `string`.
static func parse(_ string: String) throws -> JSON {
return try string.utf8CString.withUnsafeBufferPointer { (nulTerminatedBuffer) throws -> JSON in
return try nulTerminatedBuffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: nulTerminatedBuffer.count) { (utf8Base) throws -> JSON in
// don't want to include the nul termination in the buffer - trim it off
let buffer = UnsafeBufferPointer(start: utf8Base, count: nulTerminatedBuffer.count - 1)
var parser = JSONParser(input: buffer)
return try parser.parse()
}
}
}
}
extension JSONParser: JSONParserType {
/// Creates an instance of `JSON` from UTF-8 encoded `Data`.
/// - parameter data: An instance of `Data` to parse `JSON` from.
/// - throws: Any `JSONParser.Error` that arises during decoding.
/// - seealso: JSONParser.parse()
public static func createJSON(from data: Data) throws -> JSON {
return try parse(utf8: data)
}
}
// MARK: - Errors
extension JSONParser {
/// Enumeration describing possible errors that occur while parsing a JSON
/// document. Most errors include an associated `offset`, representing the
/// offset into the UTF-8 characters making up the document where the error
/// occurred.
public enum Error: Swift.Error {
/// The parser ran out of data prematurely. This usually means a value
/// was not escaped, such as a string literal not ending with a double
/// quote.
case endOfStreamUnexpected
/// Unexpected non-whitespace data was left around `offset` after
/// parsing all valid JSON.
case endOfStreamGarbage(offset: Int)
/// Too many nested objects or arrays occured at the literal started
/// around `offset`.
case exceededNestingLimit(offset: Int)
/// A `character` was not a valid start of a value around `offset`.
case valueInvalid(offset: Int, character: UnicodeScalar)
/// Badly-formed Unicode escape sequence at `offset`. A Unicode escape
/// uses the text "\u" followed by 4 hex digits, such as "\uF09F\uA684"
/// to represent U+1F984, "UNICORN FACE".
case unicodeEscapeInvalid(offset: Int)
/// Badly-formed control character around `offset`. JSON supports
/// backslash-escaped double quotes, slashes, whitespace control codes,
/// and Unicode escape sequences.
case controlCharacterUnrecognized(offset: Int)
/// Invalid token, expected `null` around `offset`
case literalNilMisspelled(offset: Int)
/// Invalid token, expected `true` around `offset`
case literalTrueMisspelled(offset: Int)
/// Invalid token, expected `false` around `offset`
case literalFalseMisspelled(offset: Int)
/// Badly-formed collection at given `offset`, expected `,` or `:`
case collectionMissingSeparator(offset: Int)
/// While parsing an object literal, a value was found without a key
/// around `offset`. The start of a string literal was expected.
case dictionaryMissingKey(offset: Int)
/// Badly-formed number with no digits around `offset`. After a decimal
/// point, a number must include some number of digits.
case numberMissingFractionalDigits(offset: Int)
/// Badly-formed number with symbols ("-" or "e") but no following
/// digits around `offset`.
case numberSymbolMissingDigits(offset: Int)
/// Supplied data is encoded in an unsupported format.
case invalidUnicodeStreamEncoding(detectedEncoding: JSONEncodingDetector.Encoding)
}
fileprivate enum InternalError: Swift.Error {
/// Attempted to parse an integer outside the range of [Int.min, Int.max]
/// or a double outside the range of representable doubles. Note that
/// for doubles, this could be an overflow or an underflow - we don't
/// get enough information from Swift here to know which it is. The number
/// causing the overflow/underflow began at `offset`.
case numberOverflow(offset: Int)
}
}
|
mit
|
841e8b92fb8b0d09227acb48fa1d240d
| 33.430903 | 157 | 0.566873 | 4.755335 | false | false | false | false |
malaonline/iOS
|
mala-ios/Common/Handler/MalaRemoteNotificationHandler.swift
|
1
|
5363
|
//
// MalaRemoteNotificationHandler.swift
// mala-ios
//
// Created by 王新宇 on 3/24/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
open class MalaRemoteNotificationHandler: NSObject {
/// 通知类型键
open let kNotificationType = "type"
/// 附带参数键(暂时仅当type为2时,附带code为订单号)
open let kNotificationCode = "code"
// MARK: - Property
/// 远程推送通知处理对象
private var remoteNotificationTypeHandler: RemoteNotificationType? {
willSet {
processNotification(withType: newValue)
}
}
/// 通知信息字典
private var notificationInfo: [AnyHashable: Any] = [AnyHashable: Any]()
/// 附带参数(订单号)
private var code: Int = 0 {
didSet {
println("code - \(code)")
}
}
// MARK: - Method
/// 处理APNs
///
/// - parameter userInfo: 通知信息字典
open func handleRemoteNotification(_ userInfo: [AnyHashable: Any]) -> Bool {
guard let type = Int(userInfo[kNotificationType] as? String ?? "0") else { return false }
guard let remoteNotificationType = RemoteNotificationType(rawValue: type) else { return false }
if let code = Int(userInfo[kNotificationCode] as? String ?? "0") {
self.code = code
}
notificationInfo = userInfo
remoteNotificationTypeHandler = remoteNotificationType
return true
}
/// 处理通知信息
open func processNotification(withType type: RemoteNotificationType?) {
guard let type = type else { return }
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
guard let apsInfo = notificationInfo["aps"] as? [AnyHashable: Any] else { return }
// 提示确认闭包
var action: ()->() = {
appDelegate.switchTabBarControllerWithIndex(1)
}
// 消息内容
var title: String? = L10n.notifyMessage
// var subTitle: String? = ""
var body: String? = L10n.youHaveANewMessage
// 获取通知消息 [标题]、[副标题]、[消息内容]
if let alert = apsInfo["alert"] as? String {
body = alert
}else if let alert = apsInfo["alert"] as? [AnyHashable: Any] {
title = alert["title"] as? String
// subTitle = alert["subtitle"] as? String
body = alert["body"] as? String
}
// 匹配消息类型
switch type {
case .changed:
setIfNeed(&title, bak: L10n.courseChanged)
case .refunds:
setIfNeed(&title, bak: L10n.refundSuccess)
action = {
// 订单详情页
guard let viewController = getActivityViewController() else { return }
let orderFormViewController = OrderFormInfoViewController()
orderFormViewController.id = self.code
orderFormViewController.hidesBottomBarWhenPushed = true
viewController.navigationController?.pushViewController(orderFormViewController, animated: true)
}
case .finished:
setIfNeed(&title, bak: L10n.ableToComment)
action = {
// 我的评价
guard let viewController = getActivityViewController() else { return }
let commentViewController = CommentViewController()
commentViewController.hidesBottomBarWhenPushed = true
viewController.navigationController?.pushViewController(commentViewController, animated: true)
}
case .starting:
setIfNeed(&title, bak: L10n.courseRemind)
case .maturity:
setIfNeed(&title, bak: L10n.couponWillExpire)
action = {
// 我的奖学金
guard let viewController = getActivityViewController() else { return }
let couponViewController = CouponViewController()
couponViewController.hidesBottomBarWhenPushed = true
viewController.navigationController?.pushViewController(couponViewController, animated: true)
}
case .livecourse:
setIfNeed(&title, bak: L10n.liveActivities)
action = {
// 课表页
appDelegate.switchTabBarControllerWithIndex(0)
guard let viewController = getActivityViewController() as? RootViewController else { return }
viewController.handleRemoteNotification()
}
}
// 若当前在前台,弹出提示
if MalaIsForeground {
// 获取当前控制器
if let viewController = getActivityViewController() {
MalaAlert.confirmOrCancel(
title: title!,
message: body!,
confirmTitle: L10n.check,
cancelTitle: L10n.later,
inViewController: viewController,
withConfirmAction: action, cancelAction: {})
}
}
}
}
|
mit
|
d0b1e2369dce689e7fb2e83574a55b5f
| 33.405405 | 112 | 0.56304 | 5.190622 | false | false | false | false |
DSanzh/GuideMe-iOS
|
GuideMe/Controller/SignUpVC.swift
|
1
|
11387
|
//
// SignUpVC.swift
// GuideMe
//
// Created by Sanzhar on 7/22/17.
// Copyright © 2017 Sanzhar Dauylov. All rights reserved.
//
import UIKit
import EasyPeasy
class SignUpVC: UIViewController, UIScrollViewDelegate {
// MARK: Properties
lazy var mainScrollView: UIScrollView = {
let _scrollview = UIScrollView()
_scrollview.frame = ScreenConstant.frame
_scrollview.delegate = self
return _scrollview
}()
lazy var facebookButton: UIButton = {
let _button = UIButton()
_button.backgroundColor = ColorConstants.fb_color
_button.setTitle("Facebook", for: .normal)
_button.setTitleColor(.white, for: .normal)
return _button
}()
lazy var vkButton: UIButton = {
let _button = UIButton()
_button.backgroundColor = ColorConstants.vk_color
_button.setTitle("VK", for: .normal)
_button.setTitleColor(.white, for: .normal)
return _button
}()
lazy var ggButton: UIButton = {
let _button = UIButton()
_button.backgroundColor = ColorConstants.gg_color
_button.setTitle("Sign in with Google", for: .normal)
_button.titleLabel?.font = FontContant.fontWith(16, type: .bold)
_button.setTitleColor(.white, for: .normal)
return _button
}()
lazy var seperatorLineView: UIView = {
let _view = UIView()
_view.backgroundColor = .lightGray
return _view
}()
lazy var seperatorLabel: UILabel = {
let _label = UILabel()
_label.text = "or"
_label.font = FontContant.fontWith(16, type: .regular)
_label.textAlignment = .center
_label.backgroundColor = .white
_label.textColor = .lightGray
return _label
}()
lazy var loginHeaderLabel: UILabel = {
let _label = UILabel()
_label.text = "Sign Up for GuideMe account"
_label.font = FontContant.fontWith(16, type: .regular)
_label.textColor = .lightGray
return _label
}()
lazy var firstnameTField: UITextField = {
let _textfield = UITextField()
_textfield.placeholder = "First name"
_textfield.font = FontContant.fontWith(16, type: .regular)
_textfield.layer.cornerRadius = 22
_textfield.layer.borderWidth = 1.0
_textfield.layer.borderColor = UIColor.lightGray.cgColor
_textfield.layer.masksToBounds = true
_textfield.textAlignment = .center
_textfield.tag = 0
_textfield.delegate = self
_textfield.returnKeyType = .next
return _textfield
}()
lazy var lastnameTField: UITextField = {
let _textfield = UITextField()
_textfield.placeholder = "Last name"
_textfield.font = FontContant.fontWith(16, type: .regular)
_textfield.layer.cornerRadius = 22
_textfield.layer.borderWidth = 1.0
_textfield.layer.borderColor = UIColor.lightGray.cgColor
_textfield.layer.masksToBounds = true
_textfield.textAlignment = .center
_textfield.tag = 1
_textfield.delegate = self
_textfield.returnKeyType = .next
return _textfield
}()
lazy var emailTField: UITextField = {
let _textfield = UITextField()
_textfield.placeholder = "E-mail"
_textfield.font = FontContant.fontWith(16, type: .regular)
_textfield.layer.cornerRadius = 22
_textfield.layer.borderWidth = 1.0
_textfield.layer.borderColor = UIColor.lightGray.cgColor
_textfield.layer.masksToBounds = true
_textfield.textAlignment = .center
_textfield.tag = 2
_textfield.delegate = self
_textfield.returnKeyType = .next
return _textfield
}()
lazy var passwordTField: UITextField = {
let _textfield = UITextField()
_textfield.placeholder = "Password"
_textfield.font = FontContant.fontWith(16, type: .regular)
_textfield.layer.cornerRadius = 22
_textfield.layer.borderWidth = 1.0
_textfield.layer.borderColor = UIColor.lightGray.cgColor
_textfield.layer.masksToBounds = true
_textfield.textAlignment = .center
_textfield.tag = 3
_textfield.delegate = self
_textfield.returnKeyType = .done
return _textfield
}()
lazy var signUpButton: UIButton = {
let _button = UIButton()
_button.setTitle("Sign Up", for: .normal)
_button.backgroundColor = ColorConstants.register_color
_button.setTitleColor(.white, for: .normal)
_button.layer.cornerRadius = 28
return _button
}()
lazy var privacyLabel: UILabel = {
let _label = UILabel()
_label.text = "Explore the world searching Term Of Service and Privacy Polocy by location, interests and more on the go."
_label.font = FontContant.fontWith(12, type: .regular)
_label.textColor = .lightGray
_label.textAlignment = .center
_label.numberOfLines = 0
return _label
}()
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupConstraints()
setupScrollView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = false
}
func setupScrollView() {
NotificationCenter.default.addObserver(self, selector: #selector(SignUpVC.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SignUpVC.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(SignUpVC.dismissKeyboard))
mainScrollView.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
mainScrollView.contentSize = .zero
}
func setupView() {
navigationController?.isNavigationBarHidden = false
title = "Quick registration with"
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = ColorConstants.steel
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font : FontContant.fontWith(16, type: .regular)]
replaceBackButton()
navigationController?.interactivePopGestureRecognizer?.isEnabled = true
navigationController?.interactivePopGestureRecognizer?.delegate = self as? UIGestureRecognizerDelegate
view.backgroundColor = .white
view.addSubview(mainScrollView)
[facebookButton, vkButton, ggButton, seperatorLineView, seperatorLabel, loginHeaderLabel, firstnameTField, lastnameTField, emailTField, passwordTField, signUpButton, privacyLabel].forEach{
mainScrollView.addSubview($0)
}
}
func setupConstraints() {
let width = (ScreenConstant.width - 80.widthProportion())
mainScrollView.easy.layout([
Top().to(view),
Left().to(view),
Right().to(view),
Bottom().to(view)
])
// quickLabel.easy.layout([
// Top(40.heightProportion()).to(mainScrollView),
// CenterX().to(mainScrollView)
// ])
facebookButton.easy.layout([
Top(15.heightProportion()).to(mainScrollView),
Left(40.widthProportion()).to(mainScrollView),
Width(view.frame.width/2 - 25),
Height(56.heightProportion()),
])
vkButton.easy.layout([
Top(15.heightProportion()).to(mainScrollView),
Left(10.widthProportion()).to(facebookButton),
Width(view.frame.width/2 - 25),
Height(56.heightProportion())
])
ggButton.easy.layout([
Top(10.heightProportion()).to(vkButton),
Left(40.widthProportion()).to(mainScrollView),
Width(width),
Height(56.heightProportion())
])
seperatorLabel.easy.layout([
Top(20.heightProportion()).to(ggButton),
CenterX().to(mainScrollView),
Width(40.widthProportion())
])
seperatorLineView.easy.layout([
CenterX().to(seperatorLabel),
CenterY().to(seperatorLabel),
Height(1),
Left(40.widthProportion()),
Width(width)
])
loginHeaderLabel.easy.layout([
Top(20.heightProportion()).to(seperatorLabel),
CenterX().to(mainScrollView)
])
firstnameTField.easy.layout([
Top(20.heightProportion()).to(loginHeaderLabel),
Left(40.widthProportion()).to(mainScrollView),
Width(width),
Height(44.heightProportion())
])
lastnameTField.easy.layout([
Top(10.heightProportion()).to(firstnameTField),
Left(40.widthProportion()).to(mainScrollView),
Width(width),
Height(44.heightProportion())
])
emailTField.easy.layout([
Top(10.heightProportion()).to(lastnameTField),
Left(40.widthProportion()).to(mainScrollView),
Width(width),
Height(44.heightProportion())
])
passwordTField.easy.layout([
Top(10.heightProportion()).to(emailTField),
Left(40.widthProportion()).to(mainScrollView),
Width(width),
Height(44.heightProportion())
])
signUpButton.easy.layout([
Top(20.heightProportion()).to(passwordTField),
Left(40.widthProportion()).to(mainScrollView),
Width(width),
Height(56.heightProportion())
])
privacyLabel.easy.layout([
Top(20.heightProportion()).to(signUpButton),
Left(40.widthProportion()).to(mainScrollView),
Width(width)
])
}
// MARK: Methods
func signUpBAction() {
}
// MARK: NotificationCenter
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if view.frame.origin.y == 0 {
mainScrollView.contentSize.height = ScreenConstant.height - 64 + keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
mainScrollView.contentSize.height = ScreenConstant.height - 64
}
}
extension SignUpVC: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let y = textField.frame.minY
let point = CGPoint(x: 0.0, y: y - 350.heightProportion())
mainScrollView.setContentOffset(point, animated: true)
}
}
|
mit
|
a164f53cc9f7a92ebb0243c56471c9f9
| 36.953333 | 196 | 0.621377 | 4.786045 | false | false | false | false |
mtransitapps/mtransit-for-ios
|
MonTransit/Source/UI/ViewController/BusTableViewController.swift
|
1
|
6103
|
//
// NewsTableViewController.swift
// SidebarMenu
//
//
import UIKit
import SQLite
import GoogleMobileAds
class BusTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var menuButton:UIBarButtonItem!
@IBOutlet var tableView: UITableView!
@IBOutlet weak var marginConstraint: NSLayoutConstraint!
private var listOfRoute:AnySequence<Row>!
private var mBusProvider:BusDataProviderHelper!
private var mTripProvider:TripDataProviderHelper!
private var mSelectedTripList:[TripObject]!
private var mSelectedBus:BusObject!
override func viewDidLoad() {
navigationController?.navigationBar.barStyle = .Black;
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
if revealViewController() != nil {
revealViewController().delegate = self
revealViewController().rearViewRevealWidth = 180
menuButton.target = revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
revealViewController().draggableBorderWidth = 100
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
}
mSelectedTripList = [TripObject]()
mTripProvider = TripDataProviderHelper()
mBusProvider = BusDataProviderHelper()
mBusProvider.retrieveRouteName(AgencyManager.getAgency().getAgencyId())
self.addIAdBanner()
}
var adRecieved:Bool = false
override func adViewDidReceiveAd(bannerView: GADBannerView!) {
super.adViewDidReceiveAd(bannerView)
if (!self.adRecieved)
{
marginConstraint.constant = -CGRectGetHeight(bannerView.frame)
self.adRecieved = true;
}
}
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = AgencyManager.getAgency().mAgencyName
self.navigationController!.navigationBar.barTintColor = ColorUtils.hexStringToUIColor(AgencyManager.getAgency().getAgencyDefaultColor())
//check data outdated
if self.checkDateLimits(AgencyManager.getAgency().getAgencyId()){
switch AgencyManager.getAgency().mAgencyType {
case SQLProvider.DatabaseType.eBus:
self.displayDataOutdatedPopup("BusDataOutDated")
case SQLProvider.DatabaseType.eSubway:
self.displayDataOutdatedPopup("SubwayDataOutDated")
case SQLProvider.DatabaseType.eTrain:
self.displayDataOutdatedPopup("TrainDataOutDated")
}
}
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = AgencyManager.getAgency().mAgencyName
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return mBusProvider.totalRoutes()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BusTableViewCell
if mBusProvider.totalRoutes() > indexPath.row{
let route = mBusProvider.retrieveLongName(indexPath.row)
cell.postTitleLabel.text = route.wlongName
cell.addBusNumber(route.wshortName, iColor: (route.iColor == "" ? AgencyManager.getAgency().getAgencyDefaultColor() : route.iColor))
}
return cell
}
// Override to support conditional rearranging of the table view.
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
// selectedCell.contentView.backgroundColor = UIColor.redColor()
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow;
let wSelectedBus = mBusProvider.retrieveBusAtIndex((indexPath?.row)!)
mSelectedTripList.removeAll()
mSelectedTripList = mTripProvider.retrieveTrip(wSelectedBus.getBusId(), iId:AgencyManager.getAgency().getAgencyId())
mSelectedBus = wSelectedBus
performSegueWithIdentifier("StationIdentifier", sender: self)
let deselectedCell = tableView.cellForRowAtIndexPath(indexPath!)!
deselectedCell.setSelected(false, animated: true)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if (segue.identifier == "StationIdentifier") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destinationViewController as! DirectionViewController
viewController.mTripList = mSelectedTripList
viewController.mSelectedBus = mSelectedBus
}
}
}
|
apache-2.0
|
dd0832e7241e9c152f9ddcd8e231a1d1
| 37.383648 | 144 | 0.673603 | 5.812381 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/Authentication/Event Handlers/Flow Start/AuthenticationStartCompanyLoginLinkEventHandler.swift
|
1
|
1690
|
//
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireSyncEngine
/**
* Handles the case where the app is opened from an SSO link.
*/
class AuthenticationStartCompanyLoginLinkEventHandler: AuthenticationEventHandler {
weak var statusProvider: AuthenticationStatusProvider?
func handleEvent(currentStep: AuthenticationFlowStep, context: (NSError?, Int)) -> [AuthenticationCoordinatorAction]? {
let error = context.0
// Only handle "add account" request errors
guard case .addAccountRequested? = error?.userSessionErrorCode else {
return nil
}
// Only handle this case if there is an SSO code in the error.
guard let code = error?.userInfo[SessionManager.companyLoginCodeKey] as? UUID else {
return nil
}
if currentStep == .start {
return [.transition(.landingScreen, mode: .reset), .startCompanyLogin(code: code)]
} else {
return [.startCompanyLogin(code: code)]
}
}
}
|
gpl-3.0
|
7a349428aadd713290136f6e90a3ea36
| 32.8 | 123 | 0.695858 | 4.604905 | false | false | false | false |
steelwheels/KiwiControls
|
Source/Window/KCViewControlEvent.swift
|
1
|
770
|
/**
* @file KCViewControlEvent.swift
* @brief Define KCViewControlEvent class
* @par Copyright
* Copyright (C) 2020 Steel Wheels Project
*/
#if os(iOS)
import UIKit
#else
import Cocoa
#endif
import CoconutData
public enum KCViewControlEvent {
case none
case updateSize(KCView)
case switchFirstResponder(KCViewBase)
}
public protocol KCViewControlEventReceiver {
func notifyControlEvent(viewControlEvent event: KCViewControlEvent)
}
extension KCResponder {
func notify(viewControlEvent event: KCViewControlEvent) {
var responder: KCResponder? = self
while responder != nil {
if let receiver = responder as? KCViewControlEventReceiver {
let _ = receiver.notifyControlEvent(viewControlEvent: event)
}
responder = responder?.next
}
}
}
|
lgpl-2.1
|
70bfd9cb29a0747457f5969aeb140f57
| 21 | 68 | 0.761039 | 3.737864 | false | false | false | false |
the-hypermedia-project/representor-swift
|
Sources/RepresentorBuilder.swift
|
1
|
3074
|
//
// RepresentorBuilder.swift
// Representor
//
// Created by Kyle Fuller on 05/11/2014.
// Copyright (c) 2014 Apiary. All rights reserved.
//
import Foundation
/// A class used to build a representor using a builder pattern
public class RepresentorBuilder<Transition : TransitionType> {
/// The added transitions
fileprivate(set) public var transitions = [String:[Transition]]()
/// The added representors
fileprivate(set) public var representors = [String:[Representor<Transition>]]()
/// The added attributes
fileprivate(set) public var attributes = [String:AnyObject]()
/// The added metadata
fileprivate(set) public var metadata = [String:String]()
/// Adds an attribute
///
/// - parameter name: The name of the attribute
/// - parameter value: The value of the attribute
public func addAttribute(_ name:String, value:AnyObject) {
attributes[name] = value
}
// MARK: Representors
/// Adds an embedded representor
///
/// - parameter name: The name of the representor
/// - parameter representor: The representor
public func addRepresentor(_ name:String, representor:Representor<Transition>) {
if var representorSet = representors[name] {
representorSet.append(representor)
representors[name] = representorSet
} else{
representors[name] = [representor]
}
}
/// Adds an embedded representor using the builder pattern
///
/// - parameter name: The name of the representor
/// - parameter builder: A builder to build the representor
public func addRepresentor(_ name:String, block:((_ builder:RepresentorBuilder<Transition>) -> ())) {
addRepresentor(name, representor:Representor<Transition>(block))
}
// MARK: Transition
/// Adds a transition
///
/// - parameter name: The name (or relation) for the transition
/// - parameter transition: The transition
public func addTransition(_ name:String, _ transition:Transition) {
var transitions = self.transitions[name] ?? []
transitions.append(transition)
self.transitions[name] = transitions
}
/// Adds a transition with a URI
///
/// - parameter name: The name (or relation) for the transition
/// - parameter uri: The URI of the transition
public func addTransition(_ name:String, uri:String) {
let transition = Transition(uri: uri, attributes:[:], parameters:[:])
addTransition(name, transition)
}
/// Adds a transition with a URI using a builder
///
/// - parameter name: The name (or relation) for the transition
/// - parameter uri: The URI of the transition
/// - parameter builder: The builder used to create the transition
public func addTransition(_ name:String, uri:String, builder:((Transition.Builder) -> ())) {
let transition = Transition(uri: uri, builder)
addTransition(name, transition)
}
// MARK: Metadata
/// Adds an piece of metadata
///
/// - parameter key: The key for the metadata
/// - parameter value: The value of the key
public func addMetaData(_ key:String, value:String) {
metadata[key] = value
}
}
|
mit
|
69af9d999344a97104ab93b526641da2
| 31.020833 | 103 | 0.690306 | 4.275382 | false | false | false | false |
fhchina/firefox-ios
|
Client/Frontend/Browser/Browser.swift
|
1
|
12787
|
/* 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 Foundation
import WebKit
import Storage
import Shared
protocol BrowserHelper {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol BrowserDelegate {
func browser(browser: Browser, didAddSnackbar bar: SnackBar)
func browser(browser: Browser, didRemoveSnackbar bar: SnackBar)
optional func browser(browser: Browser, didCreateWebView webView: WKWebView)
optional func browser(browser: Browser, willDeleteWebView webView: WKWebView)
}
class Browser: NSObject {
var webView: WKWebView? = nil
var browserDelegate: BrowserDelegate? = nil
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
var lastRequest: NSURLRequest? = nil
var restoring: Bool = false
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
private(set) var screenshot: UIImage?
var screenshotUUID: NSUUID?
private var helperManager: HelperManager? = nil
private var configuration: WKWebViewConfiguration? = nil
init(configuration: WKWebViewConfiguration) {
self.configuration = configuration
}
class func toTab(browser: Browser) -> RemoteTab? {
if let displayURL = browser.displayURL {
let history = browser.historyList.filter(RemoteTab.shouldIncludeURL).reverse()
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: browser.displayTitle,
history: history,
lastUsed: NSDate.now(),
icon: nil)
} else if let sessionData = browser.sessionData where !sessionData.urls.isEmpty {
let history = sessionData.urls.reverse()
return RemoteTab(clientGUID: nil,
URL: history[0],
title: browser.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
assert(configuration != nil, "Create webview can only be called once")
configuration!.userContentController = WKUserContentController()
configuration!.preferences = WKPreferences()
configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false
let webView = WKWebView(frame: CGRectZero, configuration: configuration!)
configuration = nil
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
webView.backgroundColor = UIColor.lightGrayColor()
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
helperManager = HelperManager(webView: webView)
// Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var updatedURLs = [String]()
for url in sessionData.urls {
let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString!
updatedURLs.append(updatedURL)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = updatedURLs
jsonDict["currentPage"] = currentPage
let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)")
webView.loadRequest(NSURLRequest(URL: restoreURL!))
} else if let request = lastRequest {
webView.loadRequest(request)
}
self.webView = webView
browserDelegate?.browser?(self, didCreateWebView: webView)
// lastTitle is used only when showing zombie tabs after a session restore.
// Since we now have a web view, lastTitle is no longer useful.
lastTitle = nil
}
}
deinit {
if let webView = webView {
browserDelegate?.browser?(self, willDeleteWebView: webView)
}
}
var loading: Bool {
return webView?.loading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList as? [WKBackForwardListItem]
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList as? [WKBackForwardListItem]
}
var historyList: [NSURL] {
func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL }
var tabs = self.backList?.map(listToUrl) ?? [NSURL]()
tabs.append(self.url!)
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title {
if !title.isEmpty {
return title
}
}
return displayURL?.absoluteString ?? lastTitle ?? ""
}
var displayFavicon: Favicon? {
var width = 0
var largest: Favicon?
for icon in favicons {
if icon.width > width {
width = icon.width!
largest = icon
}
}
return largest
}
var url: NSURL? {
return webView?.URL ?? lastRequest?.URL
}
var displayURL: NSURL? {
if let url = url {
if ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
if ErrorPageHelper.isErrorPageURL(url) {
let decodedURL = ErrorPageHelper.decodeURL(url)
if !AboutUtils.isAboutURL(decodedURL) {
return decodedURL
} else {
return nil
}
}
if !AboutUtils.isAboutURL(url) {
return url
}
}
return nil
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
webView?.goBack()
}
func goForward() {
webView?.goForward()
}
func goToBackForwardListItem(item: WKBackForwardListItem) {
webView?.goToBackForwardListItem(item)
}
func loadRequest(request: NSURLRequest) -> WKNavigation? {
lastRequest = request
if let webView = webView {
return webView.loadRequest(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
webView?.reload()
}
func addHelper(helper: BrowserHelper, name: String) {
helperManager!.addHelper(helper, name: name)
}
func getHelper(#name: String) -> BrowserHelper? {
return helperManager?.getHelper(name: name)
}
func hideContent(animated: Bool = false) {
webView?.userInteractionEnabled = false
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(animated: Bool = false) {
webView?.userInteractionEnabled = true
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(bar: SnackBar) {
bars.append(bar)
browserDelegate?.browser(self, didAddSnackbar: bar)
}
func removeSnackbar(bar: SnackBar) {
if let index = find(bars, bar) {
bars.removeAtIndex(index)
browserDelegate?.browser(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
removeSnackbar(bar)
}
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
if !bar.shouldPersist(self) {
removeSnackbar(bar)
}
}
}
func setScreenshot(screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = NSUUID()
}
}
}
private class HelperManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: BrowserHelper]()
private weak var webView: WKWebView?
init(webView: WKWebView) {
self.webView = webView
}
@objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
if scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
}
func addHelper(helper: BrowserHelper, name: String) {
if let existingHelper = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right BrowserHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName)
}
}
func getHelper(#name: String) -> BrowserHelper? {
return helpers[name]
}
}
extension WKWebView {
func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) {
if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in
if let err = err {
println("Error injecting \(err)")
return
}
self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in
self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in })
if let err = err {
println("Error running \(err)")
return
}
callback(obj)
})
})
}
}
}
}
|
mpl-2.0
|
b4ce43961fae1661780f28821dac2d68
| 33.281501 | 171 | 0.597951 | 5.487983 | false | false | false | false |
Nyx0uf/MPDRemote
|
src/common/misc/Settings.swift
|
1
|
6295
|
// Settings.swift
// Copyright (c) 2017 Nyx0uf
//
// 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 let kNYXPrefCoversDirectory = "app-covers-directory"
public let kNYXPrefCoversSize = "app-covers-size"
public let kNYXPrefCoversSizeTVOS = "app-covers-size-tvos"
public let kNYXPrefDisplayType = "app-display-type"
public let kNYXPrefFuzzySearch = "app-search-fuzzy"
public let kNYXPrefShakeToPlayRandomAlbum = "app-shake-to-play"
public let kNYXPrefMPDServer = "mpd-server2"
public let kNYXPrefMPDShuffle = "mpd-shuffle"
public let kNYXPrefMPDRepeat = "mpd-repeat"
public let kNYXPrefWEBServer = "web-server2"
public let kNYXPrefEnableLogging = "app-enable-logging"
public let kNYXPrefLastKnownVersion = "app-last-version"
public let kNYXPrefLayoutLibraryCollection = "app-layout-library-collection"
public let kNYXPrefLayoutArtistsCollection = "app-layout-artists-collection"
public let kNYXPrefLayoutAlbumsCollection = "app-layout-albums-collection"
final class Settings
{
// Singletion instance
static let shared = Settings()
//
private var defaults: UserDefaults
// MARK: - Initializers
init()
{
self.defaults = UserDefaults(suiteName: "group.mpdremote.settings")!
}
// MARK: - Public
func initialize()
{
_registerDefaultPreferences()
_iCloudInit()
}
func synchronize()
{
defaults.synchronize()
NSUbiquitousKeyValueStore.default.synchronize()
}
func bool(forKey: String) -> Bool
{
return defaults.bool(forKey: forKey)
}
func data(forKey: String) -> Data?
{
return defaults.data(forKey: forKey)
}
func integer(forKey: String) -> Int
{
return defaults.integer(forKey: forKey)
}
func string(forKey: String) -> String?
{
return defaults.string(forKey: forKey)
}
func set(_ value: Bool, forKey: String)
{
defaults.set(value, forKey: forKey)
NSUbiquitousKeyValueStore.default.set(value, forKey: forKey)
}
func set(_ value: Data, forKey: String)
{
defaults.set(value, forKey: forKey)
NSUbiquitousKeyValueStore.default.set(value, forKey: forKey)
}
func set(_ value: Int, forKey: String)
{
defaults.set(value, forKey: forKey)
NSUbiquitousKeyValueStore.default.set(value, forKey: forKey)
}
func removeObject(forKey: String)
{
defaults.removeObject(forKey: forKey)
NSUbiquitousKeyValueStore.default.removeObject(forKey: forKey)
}
// MARK: - Private
private func _registerDefaultPreferences()
{
let coversDirectoryPath = "covers"
let columns_ios = CGFloat(3)
let width_ios = ceil((UIScreen.main.bounds.width / columns_ios) - (2 * 10))
let columns_tvos = CGFloat(5)
let width_tvos = ceil(((UIScreen.main.bounds.width * (2.0 / 3.0)) / columns_tvos) - (2 * 50))
let defaultsValues: [String: Any] = [
kNYXPrefCoversDirectory : coversDirectoryPath,
kNYXPrefCoversSize : NSKeyedArchiver.archivedData(withRootObject: NSValue(cgSize: CGSize(width_ios, width_ios))),
kNYXPrefCoversSizeTVOS : NSKeyedArchiver.archivedData(withRootObject: NSValue(cgSize: CGSize(width_tvos, width_tvos))),
kNYXPrefFuzzySearch : false,
kNYXPrefMPDShuffle : false,
kNYXPrefMPDRepeat : false,
kNYXPrefDisplayType : DisplayType.albums.rawValue,
kNYXPrefShakeToPlayRandomAlbum : false,
kNYXPrefEnableLogging : false,
kNYXPrefLayoutLibraryCollection : true,
kNYXPrefLayoutAlbumsCollection : false,
kNYXPrefLayoutArtistsCollection : false,
kNYXPrefLastKnownVersion : Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? ""
]
let cachesDirectoryURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).last!
do
{
try FileManager.default.createDirectory(at: cachesDirectoryURL.appendingPathComponent(coversDirectoryPath), withIntermediateDirectories: true, attributes: nil)
}
catch let error
{
Logger.shared.log(error: error)
fatalError("Failed to create covers directory")
}
defaults.register(defaults: defaultsValues)
defaults.synchronize()
}
private func _iCloudInit()
{
let store = NSUbiquitousKeyValueStore.default
NotificationCenter.default.addObserver(self, selector: #selector(_updateKVStoreItems(_:)), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: store)
store.synchronize()
_checkIntegrity()
}
private func _checkIntegrity()
{
let keys = defaults.dictionaryRepresentation().keys
for key in keys
{
let localValue = defaults.object(forKey: key)
if NSUbiquitousKeyValueStore.default.object(forKey: key) == nil
{
NSUbiquitousKeyValueStore.default.set(localValue, forKey: key)
}
}
}
// MARK: - Notifications
@objc private func _updateKVStoreItems(_ aNotification: Notification)
{
guard let userInfo = aNotification.userInfo else
{
return
}
guard let reason = userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] as! Int? else
{
return
}
if reason == NSUbiquitousKeyValueStoreServerChange || reason == NSUbiquitousKeyValueStoreInitialSyncChange
{
guard let changedKeys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as! [String]? else
{
return
}
for key in changedKeys
{
guard let value = NSUbiquitousKeyValueStore.default.object(forKey: key) else
{
continue
}
defaults.set(value, forKey: key);
}
defaults.synchronize()
}
}
}
|
mit
|
19bb5084028a375daec3fa5cdebd5a5a
| 29.264423 | 172 | 0.750913 | 3.727057 | false | false | false | false |
ianyh/Amethyst
|
Amethyst/Layout/Layouts/RowLayout.swift
|
1
|
3975
|
//
// RowLayout.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 12/14/15.
// Copyright © 2015 Ian Ynda-Hummel. All rights reserved.
//
import Silica
class RowLayout<Window: WindowType>: Layout<Window>, PanedLayout {
override static var layoutName: String { return "Row" }
override static var layoutKey: String { return "row" }
enum CodingKeys: String, CodingKey {
case mainPaneCount
case mainPaneRatio
}
private(set) var mainPaneCount: Int = 1
private(set) var mainPaneRatio: CGFloat = 0.5
required init() {
super.init()
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.mainPaneCount = try values.decode(Int.self, forKey: .mainPaneCount)
self.mainPaneRatio = try values.decode(CGFloat.self, forKey: .mainPaneRatio)
super.init()
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(mainPaneCount, forKey: .mainPaneCount)
try container.encode(mainPaneRatio, forKey: .mainPaneRatio)
}
func recommendMainPaneRawRatio(rawRatio: CGFloat) {
mainPaneRatio = rawRatio
}
func increaseMainPaneCount() {
mainPaneCount += 1
}
func decreaseMainPaneCount() {
mainPaneCount = max(1, mainPaneCount - 1)
}
override func frameAssignments(_ windowSet: WindowSet<Window>, on screen: Screen) -> [FrameAssignmentOperation<Window>]? {
let windows = windowSet.windows
guard !windows.isEmpty else {
return []
}
let mainPaneCount = min(windows.count, self.mainPaneCount)
let secondaryPaneCount = windows.count - mainPaneCount
let hasSecondaryPane = secondaryPaneCount > 0
let screenFrame = screen.adjustedFrame()
let mainPaneHeight = floor(screenFrame.size.height * (hasSecondaryPane ? CGFloat(mainPaneRatio) : 1.0))
let mainPaneWindowHeight = floor(mainPaneHeight / CGFloat(mainPaneCount))
let secondaryPaneWindowHeight = hasSecondaryPane ? floor((screenFrame.size.height - mainPaneHeight) / CGFloat(secondaryPaneCount)) : 0.0
return windows.reduce([]) { frameAssignments, window -> [FrameAssignmentOperation<Window>] in
var assignments = frameAssignments
var windowFrame: CGRect = .zero
let isMain = frameAssignments.count < mainPaneCount
var scaleFactor: CGFloat
if isMain {
scaleFactor = screenFrame.size.height / mainPaneWindowHeight
windowFrame.origin.x = screenFrame.origin.x
windowFrame.origin.y = screenFrame.origin.y + (mainPaneWindowHeight * CGFloat(frameAssignments.count))
windowFrame.size.width = screenFrame.width
windowFrame.size.height = mainPaneWindowHeight
} else {
scaleFactor = screenFrame.size.height / secondaryPaneWindowHeight / CGFloat(secondaryPaneCount)
windowFrame.origin.x = screenFrame.origin.x
windowFrame.origin.y = screenFrame.origin.y + (mainPaneWindowHeight * CGFloat(mainPaneCount)) + (secondaryPaneWindowHeight * CGFloat(frameAssignments.count - mainPaneCount))
windowFrame.size.width = screenFrame.width
windowFrame.size.height = secondaryPaneWindowHeight
}
let resizeRules = ResizeRules(isMain: isMain, unconstrainedDimension: .vertical, scaleFactor: scaleFactor)
let frameAssignment = FrameAssignment<Window>(
frame: windowFrame,
window: window,
screenFrame: screenFrame,
resizeRules: resizeRules
)
assignments.append(FrameAssignmentOperation(frameAssignment: frameAssignment, windowSet: windowSet))
return assignments
}
}
}
|
mit
|
35aa310f82e3d6bb263b6513db101b60
| 37.960784 | 189 | 0.660544 | 4.62093 | false | false | false | false |
iWeslie/Ant
|
Ant/Ant/Main/ChoseCityVC.swift
|
1
|
5195
|
//
// ViewController.swift
// CitiesSelectorDemo
//
// Created by Weslie on 2017/7/24.
// Copyright © 2017年 Weslie. All rights reserved.
//
import UIKit
let skyblue: UIColor = UIColor.init(red: 102 / 255, green: 204 / 255, blue: 255 / 255, alpha: 1)
typealias cityClouseType = (String?) -> ()
class ChoseCityVC: UIViewController {
let app = UIApplication.shared.delegate as? AppDelegate
let scroll = UIScrollView(frame: UIScreen.main.bounds)
//定义传值闭包
var cityClouse : cityClouseType?
var cities: [[String: [Any]]] = [
["": ["圣诞红", UIColor.red]],
["": ["梦想蓝", skyblue]],
["": ["草坪绿", UIColor.green]],
["": ["酸橙黄", UIColor.yellow]],
["": ["橘子橙", UIColor.orange]],
["": ["香水紫", UIColor.purple]]
]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.view.addSubview(scroll)
scroll.showsVerticalScrollIndicator = false
scroll.showsHorizontalScrollIndicator = false
setupCitiesVC()
//添加导航栏
initNav()
}
//初始化导航栏
func initNav() {
let bgView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 64))
bgView.backgroundColor = UIColor.init(red: 241/255.0, green: 241/255.0, blue: 241/255.0, alpha: 1.0)
self.view.addSubview(bgView)
//标题
let titleLabel = UILabel(frame: CGRect.init(x: screenWidth/2 - 50, y: 30, width: 100, height: 25))
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.font = UIFont.systemFont(ofSize: 18)
titleLabel.text = "选择皮肤"
bgView.addSubview(titleLabel)
//取消按钮
let closeBtn = UIButton(type: .custom)
closeBtn.frame = CGRect.init(x: 20, y: 30, width: 20, height: 20)
closeBtn.setImage(UIImage.init(named: "icon_nav_quxiao_normal"), for: .normal)
closeBtn.addTarget(self, action:#selector(ChoseCityVC.closeBtn1), for: .touchUpInside)
bgView.addSubview(closeBtn)
}
func closeBtn1() -> () {
self.dismiss(animated: true, completion: nil)
}
func getTitleColor(sender: UIButton) {
app?.theme = (sender.titleLabel?.textColor)!
if self.cityClouse != nil {
self.cityClouse!(sender.titleLabel?.text!)
self.dismiss(animated: true, completion: nil)
}
}
func setupCitiesVC() {
let lableHeight: CGFloat = 50
let lableWidth: CGFloat = 150
let buttonWidth = (UIScreen.main.bounds.width - 20 - 3 * 5) / 4
let buttonHeight: CGFloat = 30
let buttonSpacing: CGFloat = 10
var buttonY: CGFloat = 60
var buttonX: CGFloat = 10
var lableY: CGFloat = 64{
willSet {
buttonY = lableY + lableHeight
}
}
for i in 0..<cities.count {
let locality = cities[i]
let localityLable = UILabel(frame: CGRect(x: 10, y: lableY, width: lableWidth, height: lableHeight))
localityLable.text = locality.keys.first
localityLable.font = UIFont.systemFont(ofSize: 15)
localityLable.textColor = UIColor.darkGray
self.scroll.addSubview(localityLable)
lableY = lableY + lableHeight
for j in 0..<(locality.first?.value)!.count - 1 {
let lines: Int = ((locality.first?.value.count)! - 2) / 4 + 1
let city = locality.first?.value
let cityButton = UIButton(frame: CGRect(x: buttonX + (CGFloat)(j % 4) * (buttonWidth + 5), y: (CGFloat(j / 4) * (buttonHeight + buttonSpacing) + lableY) , width: buttonWidth, height: buttonHeight))
cityButton.setTitle((city![j] as! String), for: .normal)
cityButton.setTitleColor(UIColor.darkGray, for: .normal)
// cityButton.setAttributedTitle(NSAttributedString(string : (cityButton.titleLabel?.text)! , attributes : [NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue, NSForegroundColorAttributeName: UIColor.red] ), for: .normal)
cityButton.setTitleColor((locality.first?.value.last! as! UIColor), for: .highlighted)
cityButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
cityButton.layer.borderWidth = 0.3
cityButton.layer.borderColor = UIColor.init(white: 0.7, alpha: 0.5).cgColor
cityButton.addTarget(self, action: #selector(getTitleColor(sender:)), for: .touchUpInside)
self.scroll.addSubview(cityButton)
if j == ((locality.first?.value.count)! - 2) {
lableY += CGFloat(lines) * (buttonHeight + buttonSpacing)
}
}
}
}
}
|
apache-2.0
|
fe36170375199ad8ee0fe580d7b6e47a
| 34.186207 | 255 | 0.570561 | 4.360684 | false | false | false | false |
SoneeJohn/WWDC
|
WWDC/PreferencesWindowController.swift
|
1
|
1349
|
//
// PreferencesWindowController.swift
// WWDC
//
// Created by Guilherme Rambo on 20/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
class PreferencesWindowController: NSWindowController {
static var defaultRect: NSRect {
return NSRect(x: 0, y: 0, width: 650, height: 500)
}
init() {
let mask: NSWindow.StyleMask = [NSWindow.StyleMask.titled, NSWindow.StyleMask.closable]
let window = WWDCWindow(contentRect: PreferencesWindowController.defaultRect, styleMask: mask, backing: .buffered, defer: false)
super.init(window: window)
window.title = "Preferences"
window.appearance = WWDCAppearance.appearance()
window.center()
window.titleVisibility = .hidden
window.toolbar = NSToolbar(identifier: NSToolbar.Identifier(rawValue: "WWDCPreferences"))
window.identifier = NSUserInterfaceItemIdentifier(rawValue: "preferences")
window.minSize = PreferencesWindowController.defaultRect.size
window.animationBehavior = .alertPanel
window.backgroundColor = .auxWindowBackground
windowDidLoad()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func windowDidLoad() {
super.windowDidLoad()
}
}
|
bsd-2-clause
|
9c5638cca3d3a6cc735fa52144b03dde
| 25.96 | 136 | 0.683234 | 4.780142 | false | false | false | false |
lllyyy/LY
|
U17-master/U17/Pods/EmptyDataSet-Swift/EmptyDataSet-Swift/EmptyDataSet/EmptyDataSetView.swift
|
1
|
10486
|
//
// EmptyDataSetView.swift
// EmptyDataSet-Swift
//
// Created by YZF on 28/6/17.
// Copyright © 2017年 Xiaoye. All rights reserved.
//
import Foundation
import UIKit
public class EmptyDataSetView: UIView {
internal lazy var contentView: UIView = {
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.backgroundColor = UIColor.clear
contentView.isUserInteractionEnabled = true
contentView.alpha = 0
return contentView
}()
internal lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = UIColor.clear
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = false
imageView.accessibilityIdentifier = "empty set background image"
self.contentView.addSubview(imageView)
return imageView
}()
internal lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.backgroundColor = UIColor.clear
titleLabel.font = UIFont.systemFont(ofSize: 27.0)
titleLabel.textColor = UIColor(white: 0.6, alpha: 1.0)
titleLabel.textAlignment = .center
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.numberOfLines = 0
titleLabel.accessibilityIdentifier = "empty set title"
self.contentView.addSubview(titleLabel)
return titleLabel
}()
internal lazy var detailLabel: UILabel = {
let detailLabel = UILabel()
detailLabel.translatesAutoresizingMaskIntoConstraints = false
detailLabel.backgroundColor = UIColor.clear
detailLabel.font = UIFont.systemFont(ofSize: 17.0)
detailLabel.textColor = UIColor(white: 0.6, alpha: 1.0)
detailLabel.textAlignment = .center
detailLabel.lineBreakMode = .byWordWrapping
detailLabel.numberOfLines = 0
detailLabel.accessibilityIdentifier = "empty set detail label"
self.contentView.addSubview(detailLabel)
return detailLabel
}()
internal lazy var button: UIButton = {
let button = UIButton.init(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.clear
button.contentHorizontalAlignment = .center
button.contentVerticalAlignment = .center
button.accessibilityIdentifier = "empty set button"
self.contentView.addSubview(button)
return button
}()
private var canShowImage: Bool {
return imageView.image != nil
}
private var canShowTitle: Bool {
if let attributedText = titleLabel.attributedText {
return attributedText.length > 0
}
return false
}
private var canShowDetail: Bool {
if let attributedText = detailLabel.attributedText {
return attributedText.length > 0
}
return false
}
private var canShowButton: Bool {
if let attributedTitle = button.attributedTitle(for: .normal) {
return attributedTitle.length > 0
} else if let _ = button.image(for: .normal) {
return true
}
return false
}
internal var customView: UIView? {
willSet {
if let customView = customView {
customView.removeFromSuperview()
}
}
didSet {
if let customView = customView {
customView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(customView)
}
}
}
internal var fadeInOnDisplay = false
internal var verticalOffset: CGFloat = 0
internal var verticalSpace: CGFloat = 11
internal var didTapContentViewHandle: (() -> Void)?
internal var didTapDataButtonHandle: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(contentView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func didMoveToSuperview() {
if let superviewBounds = superview?.bounds {
frame = CGRect(x: 0, y: 0, width: superviewBounds.width, height: superviewBounds.height)
}
if fadeInOnDisplay {
UIView.animate(withDuration: 0.25) {
self.contentView.alpha = 1
}
} else {
contentView.alpha = 1
}
}
// MARK: - Action Methods
internal func removeAllConstraints() {
removeConstraints(constraints)
contentView.removeConstraints(contentView.constraints)
}
internal func prepareForReuse() {
titleLabel.text = nil
detailLabel.text = nil
imageView.image = nil
button.setImage(nil, for: .normal)
button.setImage(nil, for: .highlighted)
button.setAttributedTitle(nil, for: .normal)
button.setAttributedTitle(nil, for: .highlighted)
button.setBackgroundImage(nil, for: .normal)
button.setBackgroundImage(nil, for: .highlighted)
customView = nil
removeAllConstraints()
}
// MARK: - Auto-Layout Configuration
internal func setupConstraints() {
// First, configure the content view constaints
// The content view must alway be centered to its superview
let centerXConstraint = NSLayoutConstraint.init(item: contentView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0)
let centerYConstraint = NSLayoutConstraint.init(item: contentView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)
addConstraints([centerXConstraint, centerYConstraint])
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[contentView]|", options: [], metrics: nil, views: ["contentView": contentView]))
// When a custom offset is available, we adjust the vertical constraints' constants
if (verticalOffset != 0 && constraints.count > 0) {
centerYConstraint.constant = verticalOffset
}
if let _ = customView {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[contentView]|", options: [], metrics: nil, views: ["contentView": contentView]))
// contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[customView]|", options: [], metrics: nil, views: ["customView": customView]))
// contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[customView]|", options: [], metrics: nil, views: ["customView": customView]))
} else {
let width = frame.width > 0 ? frame.width : UIScreen.main.bounds.width
let padding = roundf(Float(width/16.0))
let verticalSpace = self.verticalSpace // Default is 11 pts
var subviewStrings: [String] = []
var views: [String: UIView] = [:]
let metrics = ["padding": padding]
// Assign the image view's horizontal constraints
if canShowImage {
imageView.isHidden = false
subviewStrings.append("imageView")
views[subviewStrings.last!] = imageView
contentView.addConstraint(NSLayoutConstraint.init(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1.0, constant: 0.0))
} else {
imageView.isHidden = true
}
// Assign the title label's horizontal constraints
if (canShowTitle) {
titleLabel.isHidden = false
subviewStrings.append("titleLabel")
views[subviewStrings.last!] = titleLabel
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(padding@750)-[titleLabel(>=0)]-(padding@750)-|", options: [], metrics: metrics, views: views))
} else {
titleLabel.isHidden = true
}
// Assign the detail label's horizontal constraints
if (canShowDetail) {
detailLabel.isHidden = false
subviewStrings.append("detailLabel")
views[subviewStrings.last!] = detailLabel
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(padding@750)-[detailLabel(>=0)]-(padding@750)-|", options: [], metrics: metrics, views: views))
} else {
detailLabel.isHidden = true
}
// Assign the button's horizontal constraints
if (canShowButton) {
button.isHidden = false
subviewStrings.append("button")
views[subviewStrings.last!] = button
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(padding@750)-[button(>=0)]-(padding@750)-|", options: [], metrics: metrics, views: views))
} else {
button.isHidden = true
}
var verticalFormat = String()
// Build a dynamic string format for the vertical constraints, adding a margin between each element. Default is 11 pts.
for i in 0 ..< subviewStrings.count {
let string = subviewStrings[i]
verticalFormat += "[\(string)]"
if i < subviewStrings.count - 1 {
verticalFormat += "-(\(verticalSpace)@750)-"
}
}
// Assign the vertical constraints to the content view
if !verticalFormat.isEmpty {
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|\(verticalFormat)|", options: [], metrics: metrics, views: views))
}
}
}
}
|
mit
|
74aa252108f1136a862e761b94ebd1d4
| 37.540441 | 197 | 0.606697 | 5.629968 | false | false | false | false |
TifaTsubasa/TTReflect
|
Example/ViewController.swift
|
1
|
3058
|
//
// ViewController.swift
// TTReflect
//
// Created by 谢许峰 on 16/1/10.
// Copyright © 2016年 tifatsubasa. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import AFNetworking
class ViewController: UIViewController {
func injected() {
self.viewDidLoad()
}
override func viewDidLoad() {
super.viewDidLoad()
// Swift JSONDecoder test
let bookUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "book", ofType: nil)!)
let bookData = try? Data(contentsOf: bookUrl)
let book: BookStruct? = try? JSONDecoder().decode(BookStruct.self, from: bookData!)
}
func testReflect() {
// let home = Reflect<Item>.mapObjects("Home")
// debugPrint(home)
let bookUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "book", ofType: nil)!)
let bookData = try? Data(contentsOf: bookUrl)
let json = try! JSONSerialization.jsonObject(with: bookData!, options: JSONSerialization.ReadingOptions.allowFragments)
let book = Reflect<Book>.mapObject(data: bookData)
// let bookJsonString = book.toJSONString() ?? ""
// let d = bookJsonString.data(using: .utf8)
// let newBook = Reflect<Book>.mapObject(data: d)
debugPrint(book)
// debugPrint(book, newBook)
// debugPrint(TTNull().toJSONString())
let b = Reflect<Book>.mapObject(json: json, override: book)
// let books = Reflect2<[Book]>.mapping(json: json)
// let books = Reflect<Book>.mapObjects(json: json)
// let tag = book.tags.first
// debugPrint(book)
let castUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "casts", ofType: nil)!)
let castsData = try? Data(contentsOf: castUrl)
let castsJson = try! JSONSerialization.jsonObject(with: castsData!, options: .allowFragments)
let castsJ = JSON(data: castsData!)
let casts = Reflect<Cast>.mapObjects(json: castsJ.rawValue as AnyObject)
let cast = casts.first
debugPrint(casts)
// self.useAFNetworking()
useAlamofire()
}
func useAFNetworking() {
let manager = AFHTTPRequestOperationManager()
manager.get("https://api.douban.com/v2/movie/subject/1764796", parameters: nil, success: { (operation, responseData) -> Void in
let movie = Reflect<Movie>.mapObjects(json: responseData as AnyObject)
print(movie)
}, failure: nil)
}
func useAlamofire() {
Alamofire.request("https://api.douban.com/v2/movie/subject/1764796", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).response { response in
let data = response.data
let j = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)
let json = JSON(data: data!)
// debugPrint(json)
let movie = Reflect<Movie>.mapObject(json: json.rawValue)
debugPrint(movie)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
b3c34d984b56a762fe1aab57b044c15f
| 31.43617 | 171 | 0.66448 | 4.049137 | false | false | false | false |
ali-zahedi/AZViewer
|
AZViewer/AZColor.swift
|
1
|
2747
|
//
// UIColor+hex.swift
// AZViewer
//
// Created by Ali Zahedi on 1/15/1396 AP.
// Copyright © 1396 AP Ali Zahedi. All rights reserved.
//
import Foundation
public class AZColor: UIColor{
public convenience init(hex: String) {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
public convenience init?(hSS: String) {
let r, g, b, a: CGFloat!
let colorArray = ["#607D8Bff" ,"#FF5722ff" ,"#9E9E9Eff","#FFEA00ff","#FF9100ff","#8BC34Aff","#4CAF50ff","#CDDC39ff","#00BCD4ff","#009688ff","#673AB7ff","#3F51B5ff","#2196F3ff","#F44336ff","#E91E63ff","#9C27B0ff","#E91E63ff","#E91E63ff","#26A69Aff","#546E7Aff"]
let cStrings = hSS.unicodeScalars.map { $0.value }
var log:Int64 = 1
for cs in cStrings {
log = Int(cs) != 32 ? log * Int64(cs) : log ;
}
var val = 0
if (log > 100 ){
let logString = String(log)
// range
let start = logString.index(logString.endIndex, offsetBy: -3)
let range = start..<logString.endIndex
val = Int(logString[range])!
}else {
val = Int(log)
}
let tochar = val < 20 ? val : val % 19 ;
let hexString: String = colorArray[tochar < 1 ? 0 : tochar - 1 ]
if hexString.hasPrefix("#") {
let start = hexString.index(hexString.startIndex, offsetBy: 1)
let hexColor = hexString.substring(from: start)
if hexColor.characters.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
}
|
apache-2.0
|
0652248a30196c22ebea5bf5839ecc33
| 30.563218 | 268 | 0.497087 | 3.889518 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne
|
CustomTableViewCellStoryboard/CustomTableViewCellStoryboard/ViewController.swift
|
1
|
2569
|
//
// ViewController.swift
// CustomTableViewCellStoryboard
//
// Created by bingoogol on 14/8/20.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource {
var dataList:NSMutableArray!
override func viewDidLoad() {
super.viewDidLoad()
dataList = NSMutableArray(capacity: 30)
for index in 0 ... 30 {
var book = Book()
book.bookName = NSString.localizedStringWithFormat("IOS开发系列(%d)",index)
book.price = 59.98
dataList.addObject(book)
}
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
// 1.创建一个静态表格标示字符串,定义静态变量时,变量首字母要大写
let CellInentifier = "bookCell"
// 2.从缓存池查找是否有可重用的表格行对象 //其实加上forIndexPath的方法内部已经实现了第3步
/*
如果使用storyboard,并且在storyboard中指定了单元格的可重用标示符,那么
dequeueReusableCellWithIdentifier
dequeueReusableCellWithIdentifier:forIndexPath(此方法的indexpath本身没有任何用处,加上这个参数的目的是提醒程序员必须在storyboard中指定单元格的可重用标示符,一旦注册,两个查找可重用单元格的方法等效)
是等效的
*/
// var bookCell:BookCell! = tableView.dequeueReusableCellWithIdentifier(CellInentifier,forIndexPath:indexPath) as BookCell
var bookCell:BookCell! = tableView.dequeueReusableCellWithIdentifier(CellInentifier) as BookCell
// 注意:在ios6及以上版本系统才接管重用单元格优化
// 3.如果没有找到可重用单元格对象,实例化新的单元格
// if bookCell == nil {
// println("新创建单元格")
// bookCell = BookCell(style: .Default, reuseIdentifier: CellInentifier)
// }
// 4.设置单元格内容
// TODO:设置单元格内容
var book:Book! = dataList.objectAtIndex(indexPath.row) as Book
bookCell.bookNameLabel.text = book.bookName
bookCell.bookPriceLabel.text = NSString.localizedStringWithFormat("%.2f",book.price)
return bookCell
}
}
|
apache-2.0
|
070a18ca9b73b55738584af218cd88e0
| 35.413793 | 140 | 0.657035 | 4.308163 | false | false | false | false |
Limon-O-O/KingfisherExtension
|
KingfisherExtension/UIButton+Kingfisher.swift
|
1
|
4427
|
//
// UIButton+Kingfisher.swift
// KingfisherExtension
//
// Created by Limon on 7/6/16.
// Copyright © 2016 KingfisherExtension. All rights reserved.
//
import Kingfisher
extension UIButton {
public func kfe_setBackgroundImageWithURLString(_ URLString: String?,
forState state: UIControlState,
placeholderImage: UIImage? = nil,
optionsInfo: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask?
{
return kfe_setImageWithURLString(URLString, forState: state, isSetingBackgroundImage: true, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
}
public func kfe_setImageWithURLString(_ URLString: String?,
forState state: UIControlState,
placeholderImage: UIImage? = nil,
optionsInfo: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask?
{
return kfe_setImageWithURLString(URLString, forState: state, isSetingBackgroundImage: false, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
}
private func kfe_setImageWithURLString(_ URLString: String?,
forState state: UIControlState,
isSetingBackgroundImage: Bool,
placeholderImage: UIImage? = nil,
optionsInfo: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask?
{
guard let URLString = URLString, let URL = URL(string: URLString), !URLString.isEmpty else {
print("[KingfisherExtension] \((#file as NSString).lastPathComponent)[\(#line)], \(#function): Image Downlaod error: URL Error")
isSetingBackgroundImage ? setBackgroundImage(nil, for: state) : setImage(nil, for: state)
return nil
}
guard let image = KingfisherManager.shared.cache.retrieveImageInMemoryCache(forKey: URLString) ?? KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: URLString) else {
let optionInfoBuffer: KingfisherOptionsInfo = [
.backgroundDecode,
.transition(ImageTransition.fade(0.35))
]
return kf.setImage(with: URL,
for: state,
placeholder: placeholderImage,
options: optionsInfo ?? optionInfoBuffer,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
DispatchQueue.main.async {
UIView.performWithoutAnimation {
isSetingBackgroundImage ? self.setBackgroundImage(image, for: state) : self.setImage(image, for: state)
}
}
return nil
}
}
extension UIButton {
public func kfe_setImage(byTransformer transformer: ImageResizable, forState state: UIControlState = UIControlState(), toDisk: Bool = true, completionHandler: ((_ image: UIImage?) -> Void)? = nil) {
kfe_setImage(byTransformer: transformer, action: { [weak self] image in
self?.setImage(image, for: state)
}, toDisk: toDisk, completionHandler: completionHandler)
}
public func kfe_setBackgroundImage(byTransformer transformer: ImageResizable, forState state: UIControlState = UIControlState(), toDisk: Bool = true, completionHandler: ((_ image: UIImage?) -> Void)? = nil) {
kfe_setImage(byTransformer: transformer, action: { [weak self] image in
self?.setBackgroundImage(image, for: state)
}, toDisk: toDisk, completionHandler: completionHandler)
}
}
|
mit
|
f00bcf1436cdc82dacdffe655fb6e60d
| 44.628866 | 230 | 0.592634 | 6.207574 | false | false | false | false |
JoeLago/MHGDB-iOS
|
MHGDB/Model/Quest.swift
|
1
|
8270
|
//
// MIT License
// Copyright (c) Gathering Hall Studios
//
import Foundation
import GRDB
class Quest: RowConvertible {
var id: Int!
var name: String?
var hub: String? // Switch to enum
var icon: String?
var goal: String?
var goalType: Quest.Goal?
var progression: Quest.Progression?
var stars: Int
var subQuest: String?
var reward: Int?
var hrp: Int?
var description: String?
var subReward: Int?
var subHrp: Int?
var fee: Int?
var hasSubQuest = false
enum Rank: String {
case low = "LR"
case high = "HR"
case g = "G"
}
enum Hub: String {
case village = "Village"
case arena = "Arena"
case event = "Event"
case guild = "Guild"
case permit = "Permit"
}
enum Progression {
case normal, key, urgent
init?(_ type: Int?) {
if type == nil {
return nil
}
switch type! {
case 0: self = .normal
case 1: self = .key
case 2: self = .urgent
default: return nil
}
}
var text: String {
get {
switch self {
case .normal: return "Normal"
case .key: return "Key"
case .urgent: return "Urgent"
}
}
}
}
enum Goal {
case hunt, slay, capture, deliver, huntathon, marathon
init?(_ type: Int?) {
if type == nil {
return nil
}
switch type! {
case 0: self = .hunt
case 1: self = .slay
case 2: self = .capture
case 3: self = .deliver
case 4: self = .huntathon
case 5: self = .marathon
default: return nil
}
}
var text: String? {
get {
switch self {
case .hunt: return "Hunt"
case .slay: return "Slay"
case .capture: return "Capture"
case .deliver: return "Deliver"
case .huntathon: return "Huntathon"
case .marathon: return "Marathon"
}
}
}
}
class func titleForStars(count: Int) -> String {
if count == 0 {
return "Training"
}
var title = "\(count) "
for _ in 0 ... count - 1 {
title += String.star
}
return title
}
lazy var rewards: [QuestReward] = {
return Database.shared.rewards(questId: self.id)
}()
lazy var prereqQuests: [Quest] = {
return Database.shared.prereqQuests(questId: self.id)
}()
lazy var rewardsBySlot: [String: [QuestReward]] = {
let allRewards = Database.shared.rewards(questId: self.id)
var rewardsBySlot = [String: [QuestReward]]()
for reward in allRewards {
var slot = rewardsBySlot[reward.slot] ?? [QuestReward]()
slot.append(reward)
rewardsBySlot[reward.slot] = slot
}
return rewardsBySlot
}()
lazy var monsters: [QuestMonster] = {
return Database.shared.monsters(questId: self.id)
}()
required init(row: Row) {
id = row["_id"]
name = row["name"]
icon = row["icon_name"]
goal = row["goal"]
goalType = Quest.Goal(row["goal_type"]) // TODO enum inferrence
hub = row["hub"]
progression = Quest.Progression(Int(row["type"] as String)) // TODO enum inferrence
stars = row["stars"]
reward = row["reward"]
hrp = row["hrp"]
subQuest = row["sub_goal"]
subReward = row["sub_reward"]
subHrp = row["sub_hrp"]
description = row["flavor"]
fee = row["fee"]
hasSubQuest = subQuest != "None"
}
}
class QuestReward: RowConvertible {
let itemId: Int
var name: String
var icon: String?
var quantity: Int
var chance: Int
var slot: String
required init(row: Row) {
itemId = row["itemid"]
name = row["itemname"]
icon = row["itemicon"]
quantity = row["quantity"] ?? 0
chance = row["percentage"] ?? 0
slot = row["reward_slot"]
}
}
class QuestMonster: RowConvertible {
let monsterId: Int
let name: String
var startArea: String?
var moveArea: String?
var restArea: String?
var locations: String {
return [startArea, moveArea, restArea].compactMap{ $0 }.joined(separator: " > ")
}
let icon: String?
required init(row: Row) {
monsterId = row["monsterid"]
name = row["monstername"]
icon = row["monstericon"]
startArea = row["start_area"]
moveArea = row["move_area"]
restArea = row["rest_area"]
}
}
extension Database {
func quest(id: Int) -> Quest {
let query = "SELECT * FROM quests WHERE _id = \(id)"
return fetch(query)!
}
func quests(_ search: String? = nil, keyOnly: Bool = false, hub: String? = nil,
stars: Int? = nil) -> [[Quest]] {
let query = "SELECT * FROM quests"
let order = "ORDER BY stars"
var filters = [String]()
if let hub = hub {
filters.append("hub == '\(hub)'")
}
if let stars = stars {
filters.append("stars == \(stars)")
}
if (keyOnly) {
filters.append("type != 0")
}
let filter = filters.joined(separator: " AND ")
let quests = fetch(select: query, order: order, filter: filter, search: search) as [Quest]
if search != nil {
return [quests]
}
// Meh
var questGroups = [[Quest]]()
var questsPerStar = [Quest]()
for quest in quests {
if questsPerStar.count > 0 && quest.stars != questsPerStar.first!.stars {
questGroups.append(questsPerStar)
questsPerStar = [quest]
} else {
questsPerStar.append(quest)
}
}
questGroups.append(questsPerStar)
return questGroups
}
func questHubs() -> [String] {
return getStrings("SELECT hub as value FROM quests GROUP BY hub")
}
var rewardsQuery: String {
return "SELECT *,"
+ " items._id AS itemid,"
+ " items.name AS itemname,"
+ " items._id AS itemid,"
+ " items.icon_name AS itemicon,"
+ " quests.name AS questname,"
+ " quests._id AS questid"
+ " FROM quest_rewards"
+ " LEFT JOIN items on quest_rewards.item_id = items._id"
+ " LEFT JOIN quests on quest_rewards.quest_id = quests._id "
}
func rewards(questId: Int) -> [QuestReward] {
let query = rewardsQuery + "WHERE quests._id == \(questId)"
return fetch(query)
}
func monsters(questId: Int) -> [QuestMonster] {
// The monster_habitat night locations use day counterpart id 100 off
let query = "SELECT *,"
+ " monsters._id AS monsterid,"
+ " monsters.name AS monstername,"
+ " monsters.icon_name as monstericon"
+ " FROM monster_to_quest"
+ " LEFT JOIN quests on monster_to_quest.quest_id = quests._id"
+ " LEFT JOIN monsters on monster_to_quest.monster_id = monsters._id"
+ " LEFT JOIN monster_habitat on monster_habitat.monster_id = monsters._id"
+ " AND (monster_habitat.location_id = quests.location_id OR monster_habitat.location_id = quests.location_id - 100)"
+ " WHERE quests._id == \(questId)"
return fetch(query)
}
func prereqQuests(questId: Int) -> [Quest] {
let query = "SELECT *, quest_prereqs.prereq_id as _id FROM quest_prereqs"
+ " LEFT JOIN quests ON quests._id = quest_prereqs.prereq_id"
+ " WHERE quest_id == \(questId)"
return fetch(query)
}
}
|
mit
|
e2b23abde87d2a10526221c147f12ad8
| 27.615917 | 129 | 0.506046 | 4.151606 | false | false | false | false |
yuxiuyu/TrendBet
|
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift
|
5
|
20049
|
//
// ChartData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class ChartData: NSObject
{
internal var _yMax: Double = -Double.greatestFiniteMagnitude
internal var _yMin: Double = Double.greatestFiniteMagnitude
internal var _xMax: Double = -Double.greatestFiniteMagnitude
internal var _xMin: Double = Double.greatestFiniteMagnitude
internal var _leftAxisMax: Double = -Double.greatestFiniteMagnitude
internal var _leftAxisMin: Double = Double.greatestFiniteMagnitude
internal var _rightAxisMax: Double = -Double.greatestFiniteMagnitude
internal var _rightAxisMin: Double = Double.greatestFiniteMagnitude
internal var _dataSets = [IChartDataSet]()
public override init()
{
super.init()
_dataSets = [IChartDataSet]()
}
@objc public init(dataSets: [IChartDataSet]?)
{
super.init()
_dataSets = dataSets ?? [IChartDataSet]()
self.initialize(dataSets: _dataSets)
}
@objc public convenience init(dataSet: IChartDataSet?)
{
self.init(dataSets: dataSet === nil ? nil : [dataSet!])
}
internal func initialize(dataSets: [IChartDataSet])
{
notifyDataChanged()
}
/// Call this method to let the ChartData know that the underlying data has changed.
/// Calling this performs all necessary recalculations needed when the contained data has changed.
@objc open func notifyDataChanged()
{
calcMinMax()
}
@objc open func calcMinMaxY(fromX: Double, toX: Double)
{
for set in _dataSets
{
set.calcMinMaxY(fromX: fromX, toX: toX)
}
// apply the new data
calcMinMax()
}
/// calc minimum and maximum y value over all datasets
@objc open func calcMinMax()
{
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
for set in _dataSets
{
calcMinMax(dataSet: set)
}
_leftAxisMax = -Double.greatestFiniteMagnitude
_leftAxisMin = Double.greatestFiniteMagnitude
_rightAxisMax = -Double.greatestFiniteMagnitude
_rightAxisMin = Double.greatestFiniteMagnitude
// left axis
let firstLeft = getFirstLeft(dataSets: dataSets)
if firstLeft !== nil
{
_leftAxisMax = firstLeft!.yMax
_leftAxisMin = firstLeft!.yMin
for dataSet in _dataSets
{
if dataSet.axisDependency == .left
{
if dataSet.yMin < _leftAxisMin
{
_leftAxisMin = dataSet.yMin
}
if dataSet.yMax > _leftAxisMax
{
_leftAxisMax = dataSet.yMax
}
}
}
}
// right axis
let firstRight = getFirstRight(dataSets: dataSets)
if firstRight !== nil
{
_rightAxisMax = firstRight!.yMax
_rightAxisMin = firstRight!.yMin
for dataSet in _dataSets
{
if dataSet.axisDependency == .right
{
if dataSet.yMin < _rightAxisMin
{
_rightAxisMin = dataSet.yMin
}
if dataSet.yMax > _rightAxisMax
{
_rightAxisMax = dataSet.yMax
}
}
}
}
}
/// Adjusts the current minimum and maximum values based on the provided Entry object.
@objc open func calcMinMax(entry e: ChartDataEntry, axis: YAxis.AxisDependency)
{
if _yMax < e.y
{
_yMax = e.y
}
if _yMin > e.y
{
_yMin = e.y
}
if _xMax < e.x
{
_xMax = e.x
}
if _xMin > e.x
{
_xMin = e.x
}
if axis == .left
{
if _leftAxisMax < e.y
{
_leftAxisMax = e.y
}
if _leftAxisMin > e.y
{
_leftAxisMin = e.y
}
}
else
{
if _rightAxisMax < e.y
{
_rightAxisMax = e.y
}
if _rightAxisMin > e.y
{
_rightAxisMin = e.y
}
}
}
/// Adjusts the minimum and maximum values based on the given DataSet.
@objc open func calcMinMax(dataSet d: IChartDataSet)
{
if _yMax < d.yMax
{
_yMax = d.yMax
}
if _yMin > d.yMin
{
_yMin = d.yMin
}
if _xMax < d.xMax
{
_xMax = d.xMax
}
if _xMin > d.xMin
{
_xMin = d.xMin
}
if d.axisDependency == .left
{
if _leftAxisMax < d.yMax
{
_leftAxisMax = d.yMax
}
if _leftAxisMin > d.yMin
{
_leftAxisMin = d.yMin
}
}
else
{
if _rightAxisMax < d.yMax
{
_rightAxisMax = d.yMax
}
if _rightAxisMin > d.yMin
{
_rightAxisMin = d.yMin
}
}
}
/// - returns: The number of LineDataSets this object contains
@objc open var dataSetCount: Int
{
return _dataSets.count
}
/// - returns: The smallest y-value the data object contains.
@objc open var yMin: Double
{
return _yMin
}
@nonobjc
open func getYMin() -> Double
{
return _yMin
}
@objc open func getYMin(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
if _leftAxisMin == Double.greatestFiniteMagnitude
{
return _rightAxisMin
}
else
{
return _leftAxisMin
}
}
else
{
if _rightAxisMin == Double.greatestFiniteMagnitude
{
return _leftAxisMin
}
else
{
return _rightAxisMin
}
}
}
/// - returns: The greatest y-value the data object contains.
@objc open var yMax: Double
{
return _yMax
}
@nonobjc
open func getYMax() -> Double
{
return _yMax
}
@objc open func getYMax(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
if _leftAxisMax == -Double.greatestFiniteMagnitude
{
return _rightAxisMax
}
else
{
return _leftAxisMax
}
}
else
{
if _rightAxisMax == -Double.greatestFiniteMagnitude
{
return _leftAxisMax
}
else
{
return _rightAxisMax
}
}
}
/// - returns: The minimum x-value the data object contains.
@objc open var xMin: Double
{
return _xMin
}
/// - returns: The maximum x-value the data object contains.
@objc open var xMax: Double
{
return _xMax
}
/// - returns: All DataSet objects this ChartData object holds.
@objc open var dataSets: [IChartDataSet]
{
get
{
return _dataSets
}
set
{
_dataSets = newValue
notifyDataChanged()
}
}
/// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not.
///
/// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.**
///
/// - parameter dataSets: the DataSet array to search
/// - parameter type:
/// - parameter ignorecase: if true, the search is not case-sensitive
/// - returns: The index of the DataSet Object with the given label. Sensitive or not.
internal func getDataSetIndexByLabel(_ label: String, ignorecase: Bool) -> Int
{
if ignorecase
{
for i in 0 ..< dataSets.count
{
if dataSets[i].label == nil
{
continue
}
if (label.caseInsensitiveCompare(dataSets[i].label!) == ComparisonResult.orderedSame)
{
return i
}
}
}
else
{
for i in 0 ..< dataSets.count
{
if label == dataSets[i].label
{
return i
}
}
}
return -1
}
/// - returns: The labels of all DataSets as a string array.
internal func dataSetLabels() -> [String]
{
var types = [String]()
for i in 0 ..< _dataSets.count
{
if dataSets[i].label == nil
{
continue
}
types[i] = _dataSets[i].label!
}
return types
}
/// Get the Entry for a corresponding highlight object
///
/// - parameter highlight:
/// - returns: The entry that is highlighted
@objc open func entryForHighlight(_ highlight: Highlight) -> ChartDataEntry?
{
if highlight.dataSetIndex >= dataSets.count
{
return nil
}
else
{
return dataSets[highlight.dataSetIndex].entryForXValue(highlight.x, closestToY: highlight.y)
}
}
/// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.**
///
/// - parameter label:
/// - parameter ignorecase:
/// - returns: The DataSet Object with the given label. Sensitive or not.
@objc open func getDataSetByLabel(_ label: String, ignorecase: Bool) -> IChartDataSet?
{
let index = getDataSetIndexByLabel(label, ignorecase: ignorecase)
if index < 0 || index >= _dataSets.count
{
return nil
}
else
{
return _dataSets[index]
}
}
@objc open func getDataSetByIndex(_ index: Int) -> IChartDataSet!
{
if index < 0 || index >= _dataSets.count
{
return nil
}
return _dataSets[index]
}
@objc open func addDataSet(_ dataSet: IChartDataSet!)
{
calcMinMax(dataSet: dataSet)
_dataSets.append(dataSet)
}
/// Removes the given DataSet from this data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed.
@objc @discardableResult open func removeDataSet(_ dataSet: IChartDataSet!) -> Bool
{
if dataSet === nil
{
return false
}
for i in 0 ..< _dataSets.count
{
if _dataSets[i] === dataSet
{
return removeDataSetByIndex(i)
}
}
return false
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed.
@objc @discardableResult open func removeDataSetByIndex(_ index: Int) -> Bool
{
if index >= _dataSets.count || index < 0
{
return false
}
_dataSets.remove(at: index)
calcMinMax()
return true
}
/// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list.
@objc open func addEntry(_ e: ChartDataEntry, dataSetIndex: Int)
{
if _dataSets.count > dataSetIndex && dataSetIndex >= 0
{
let set = _dataSets[dataSetIndex]
if !set.addEntry(e) { return }
calcMinMax(entry: e, axis: set.axisDependency)
}
else
{
print("ChartData.addEntry() - Cannot add Entry because dataSetIndex too high or too low.", terminator: "\n")
}
}
/// Removes the given Entry object from the DataSet at the specified index.
@objc @discardableResult open func removeEntry(_ entry: ChartDataEntry, dataSetIndex: Int) -> Bool
{
// entry outofbounds
if dataSetIndex >= _dataSets.count
{
return false
}
// remove the entry from the dataset
let removed = _dataSets[dataSetIndex].removeEntry(entry)
if removed
{
calcMinMax()
}
return removed
}
/// Removes the Entry object closest to the given xIndex from the ChartDataSet at the
/// specified index.
/// - returns: `true` if an entry was removed, `false` ifno Entry was found that meets the specified requirements.
@objc @discardableResult open func removeEntry(xValue: Double, dataSetIndex: Int) -> Bool
{
if dataSetIndex >= _dataSets.count
{
return false
}
if let entry = _dataSets[dataSetIndex].entryForXValue(xValue, closestToY: Double.nan)
{
return removeEntry(entry, dataSetIndex: dataSetIndex)
}
return false
}
/// - returns: The DataSet that contains the provided Entry, or null, if no DataSet contains this entry.
@objc open func getDataSetForEntry(_ e: ChartDataEntry!) -> IChartDataSet?
{
if e == nil
{
return nil
}
for i in 0 ..< _dataSets.count
{
let set = _dataSets[i]
if e === set.entryForXValue(e.x, closestToY: e.y)
{
return set
}
}
return nil
}
/// - returns: The index of the provided DataSet in the DataSet array of this data object, or -1 if it does not exist.
@objc open func indexOfDataSet(_ dataSet: IChartDataSet) -> Int
{
for i in 0 ..< _dataSets.count
{
if _dataSets[i] === dataSet
{
return i
}
}
return -1
}
/// - returns: The first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found.
@objc open func getFirstLeft(dataSets: [IChartDataSet]) -> IChartDataSet?
{
for dataSet in dataSets
{
if dataSet.axisDependency == .left
{
return dataSet
}
}
return nil
}
/// - returns: The first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found.
@objc open func getFirstRight(dataSets: [IChartDataSet]) -> IChartDataSet?
{
for dataSet in _dataSets
{
if dataSet.axisDependency == .right
{
return dataSet
}
}
return nil
}
/// - returns: All colors used across all DataSet objects this object represents.
@objc open func getColors() -> [NSUIColor]?
{
var clrcnt = 0
for i in 0 ..< _dataSets.count
{
clrcnt += _dataSets[i].colors.count
}
var colors = [NSUIColor]()
for i in 0 ..< _dataSets.count
{
let clrs = _dataSets[i].colors
for clr in clrs
{
colors.append(clr)
}
}
return colors
}
/// Sets a custom IValueFormatter for all DataSets this data object contains.
@objc open func setValueFormatter(_ formatter: IValueFormatter?)
{
guard let formatter = formatter
else { return }
for set in dataSets
{
set.valueFormatter = formatter
}
}
/// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains.
@objc open func setValueTextColor(_ color: NSUIColor!)
{
for set in dataSets
{
set.valueTextColor = color ?? set.valueTextColor
}
}
/// Sets the font for all value-labels for all DataSets this data object contains.
@objc open func setValueFont(_ font: NSUIFont!)
{
for set in dataSets
{
set.valueFont = font ?? set.valueFont
}
}
/// Enables / disables drawing values (value-text) for all DataSets this data object contains.
@objc open func setDrawValues(_ enabled: Bool)
{
for set in dataSets
{
set.drawValuesEnabled = enabled
}
}
/// Enables / disables highlighting values for all DataSets this data object contains.
/// If set to true, this means that values can be highlighted programmatically or by touch gesture.
@objc open var highlightEnabled: Bool
{
get
{
for set in dataSets
{
if !set.highlightEnabled
{
return false
}
}
return true
}
set
{
for set in dataSets
{
set.highlightEnabled = newValue
}
}
}
/// if true, value highlightning is enabled
@objc open var isHighlightEnabled: Bool { return highlightEnabled }
/// Clears this data object from all DataSets and removes all Entries.
/// Don't forget to invalidate the chart after this.
@objc open func clearValues()
{
dataSets.removeAll(keepingCapacity: false)
notifyDataChanged()
}
/// Checks if this data object contains the specified DataSet.
/// - returns: `true` if so, `false` ifnot.
@objc open func contains(dataSet: IChartDataSet) -> Bool
{
for set in dataSets
{
if set === dataSet
{
return true
}
}
return false
}
/// - returns: The total entry count across all DataSet objects this data object contains.
@objc open var entryCount: Int
{
var count = 0
for set in _dataSets
{
count += set.entryCount
}
return count
}
/// - returns: The DataSet object with the maximum number of entries or null if there are no DataSets.
@objc open var maxEntryCountSet: IChartDataSet?
{
if _dataSets.count == 0
{
return nil
}
var max = _dataSets[0]
for set in _dataSets
{
if set.entryCount > max.entryCount
{
max = set
}
}
return max
}
}
|
apache-2.0
|
5e8acb21a28af1bbc166de316f3c9543
| 25.41502 | 169 | 0.501671 | 5.369309 | false | false | false | false |
emilstahl/swift
|
test/Parse/init_deinit.swift
|
12
|
2853
|
// RUN: %target-parse-verify-swift
struct FooStructConstructorA {
init // expected-error {{expected '('}}
}
struct FooStructConstructorB {
init() // expected-error {{initializer requires a body}}
}
struct FooStructConstructorC {
init {} // expected-error {{expected '('}}{{8-8=() }}
}
struct FooStructDeinitializerA {
deinit // expected-error {{expected '{' for deinitializer}}
}
struct FooStructDeinitializerB {
deinit // expected-error {{expected '{' for deinitializer}}
}
struct FooStructDeinitializerC {
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
class FooClassDeinitializerA {
deinit(a : Int) {} // expected-error{{no parameter clause allowed on deinitializer}}{{9-18=}}
}
class FooClassDeinitializerB {
deinit { }
}
init {} // expected-error {{initializers may only be declared within a type}} expected-error {{expected '('}} {{6-6=() }}
init() // expected-error {{initializers may only be declared within a type}}
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
deinit // expected-error {{expected '{' for deinitializer}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
struct BarStruct {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarStruct {
init(x : Int) {}
// When/if we allow 'var' in extensions, then we should also allow dtors
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
enum BarUnion {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarUnion {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
class BarClass {
init() {}
deinit {}
}
extension BarClass {
convenience init(x : Int) { self.init() }
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
protocol BarProtocol {
init() {} // expected-error {{protocol initializers may not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarProtocol {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
func fooFunc() {
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
func barFunc() {
var x : () = { () -> () in
init() {} // expected-error {{initializers may only be declared within a type}}
return
} ()
var y : () = { () -> () in
deinit {} // expected-error {{deinitializers may only be declared within a class}}
return
} ()
}
|
apache-2.0
|
1095514500fa03774298abecdf57d259
| 26.970588 | 121 | 0.681739 | 4.146802 | false | false | false | false |
LedgerHQ/ledger-wallet-ios
|
ledger-wallet-ios/Helpers/Allures/VisualTheme.swift
|
1
|
14889
|
//
// VisualTheme.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 12/01/2015.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import UIKit
final class VisualTheme {
static let allureBlocks: [String: ViewStylist.AllureBlock] = [
// MARK: - View allures
"view.background": ViewStylist.wrapAllureBlock({ (view: UIView) in
view.backgroundColor = VisualFactory.Colors.BackgroundColor
}),
"view.nightBlue": ViewStylist.wrapAllureBlock({ (view: UIView) in
view.backgroundColor = VisualFactory.Colors.NightBlue
}),
"view.transparent": ViewStylist.wrapAllureBlock({ (view: UIView) in
view.backgroundColor = VisualFactory.Colors.Transparent
view.opaque = false
}),
"actionBarView.grey": ViewStylist.wrapAllureBlock({ (actionBarView: ActionBarView) in
actionBarView.backgroundColor = VisualFactory.Colors.ExtraLightGrey
actionBarView.borderColor = VisualFactory.Colors.VeryLightGrey
}),
"tableView.transparent": ViewStylist.wrapAllureBlock({ (tableView: TableView) in
tableView.backgroundColor = VisualFactory.Colors.Transparent
tableView.separatorColor = VisualFactory.Colors.LightGrey
tableView.separatorInset = UIEdgeInsetsMake(0, VisualFactory.Metrics.Padding.Small, 0, VisualFactory.Metrics.Padding.Small)
}),
"tableViewCell.transparent": ViewStylist.wrapAllureBlock({ (tableViewCell: TableViewCell) in
tableViewCell.contentView.backgroundColor = VisualFactory.Colors.Transparent
tableViewCell.backgroundColor = VisualFactory.Colors.Transparent
}),
"navigationBar.nightBlue": ViewStylist.wrapAllureBlock({ (navigationBar: NavigationBar) in
navigationBar.translucent = false
navigationBar.shadowImage = UIImage()
navigationBar.barTintColor = VisualFactory.Colors.NightBlue
navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
}),
"pinCodeView.grey": ViewStylist.wrapAllureBlock({ (pinCodeView: PinCodeView) in
pinCodeView.boxSize = CGSizeMake(55.0, 75.0)
pinCodeView.highlightedColor = VisualFactory.Colors.InvalidRed
pinCodeView.filledColor = VisualFactory.Colors.DarkGrey
pinCodeView.boxSpacing = VisualFactory.Metrics.Padding.VerySmall
pinCodeView.boxColor = VisualFactory.Colors.White
pinCodeView.borderWidth = 1.0
pinCodeView.dotRadius = 15.0
}),
"loadingIndicator.grey": ViewStylist.wrapAllureBlock({ (loadingIndicator: LoadingIndicator) in
loadingIndicator.dotsHighlightedColor = VisualFactory.Colors.DarkGreyBlue
loadingIndicator.dotsNormalColor = VisualFactory.Colors.LightGrey
loadingIndicator.animationDuration = VisualFactory.Durations.Animation.VeryShort
loadingIndicator.dotsSize = 3.5
loadingIndicator.preferredWidth = 44.0
loadingIndicator.dotsCount = 9
}),
// MARK: - Label allures
"label.navigationBar.title": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.PageTitle)
}),
"label.navigationBar.largeTitle": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.LargePageTitle)
}),
"label.navigationBar.text": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.NavigationBarText)
}),
"label.medium": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.Medium)
}),
"label.medium.centered": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.MediumCentered)
}),
"label.medium.grey": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.MediumGrey)
}),
"label.medium.softGrey": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.MediumSoftGrey)
}),
"label.small": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.Small)
}),
"label.small.centered": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.SmallCentered)
}),
"label.small.grey": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.SmallGrey)
}),
"label.small.grey.centered": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.SmallGreyCentered)
}),
"label.small.softGrey": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.SmallSoftGrey)
}),
"label.small.softGrey.centered": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.SmallSoftGreyCentered)
}),
"label.largeIndication": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.LargeIndication)
}),
"label.largeIndication.grey": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.LargeIndicationGrey)
}),
"label.largeIndication.grey.centered": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.LargeIndicationGreyCentered)
}),
"label.largeTitle": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.LargeTitle)
}),
"label.hugeNumber.grey": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.HugeNumberGrey)
}),
"label.sectionTitle": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.SectionTitle)
}),
"label.huge": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.Huge)
}),
"label.huge.light": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.HugeLight)
}),
"label.huge.light.centered": ViewStylist.wrapAllureBlock({ (label: UILabel) in
label.attributedText = NSAttributedString(string: label.readableText(), attributes: VisualFactory.TextAttributes.HugeLightCentered)
}),
// MARK: - Button allures
"button.navigationBar.grey": ViewStylist.wrapAllureBlock({ (button: UIButton) in
var highlightedStyle = VisualFactory.TextAttributes.NavigationBarText
highlightedStyle.updateValue((highlightedStyle[NSForegroundColorAttributeName] as! UIColor).darkerColor(factor: VisualFactory.Factors.Darken.UltraStrong), forKey: NSForegroundColorAttributeName)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Normal), attributes: VisualFactory.TextAttributes.NavigationBarText), forState: UIControlState.Normal)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Normal), attributes: highlightedStyle), forState: UIControlState.Highlighted)
}),
"button.navigationBar.white": ViewStylist.wrapAllureBlock({ (button: UIButton) in
var highlightedStyle = VisualFactory.TextAttributes.NavigationBarWhiteText
highlightedStyle.updateValue((highlightedStyle[NSForegroundColorAttributeName] as! UIColor).darkerColor(factor: VisualFactory.Factors.Darken.UltraStrong), forKey: NSForegroundColorAttributeName)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Normal), attributes: VisualFactory.TextAttributes.NavigationBarWhiteText), forState: UIControlState.Normal)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Normal), attributes: highlightedStyle), forState: UIControlState.Highlighted)
}),
"button.small.softGrey": ViewStylist.wrapAllureBlock({ (button: UIButton) in
var highlightedStyle = VisualFactory.TextAttributes.SmallSoftGrey
highlightedStyle.updateValue((highlightedStyle[NSForegroundColorAttributeName] as! UIColor).darkerColor(factor: VisualFactory.Factors.Darken.ExtraStrong), forKey: NSForegroundColorAttributeName)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Normal), attributes: VisualFactory.TextAttributes.SmallSoftGrey), forState: UIControlState.Normal)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Highlighted), attributes: highlightedStyle), forState: UIControlState.Highlighted)
}),
"roundedButton": ViewStylist.wrapAllureBlock({ (roundedButton: RoundedButton) in
roundedButton.adjustsImageWhenHighlighted = false
roundedButton.borderRadius = VisualFactory.Metrics.BordersRadius.Infinite
roundedButton.setAttributedTitle(NSAttributedString(string: roundedButton.readableTitleForState(UIControlState.Normal), attributes: VisualFactory.TextAttributes.RoundedButtonText), forState: UIControlState.Normal)
roundedButton.contentEdgeInsets = UIEdgeInsets(top: VisualFactory.Metrics.Padding.VerySmall, left: VisualFactory.Metrics.Padding.Small, bottom: VisualFactory.Metrics.Padding.VerySmall, right: VisualFactory.Metrics.Padding.Small)
if (roundedButton.imageForState(UIControlState.Normal) != nil) {
roundedButton.setImage(roundedButton.imageForState(UIControlState.Normal)!.imageWithColor(VisualFactory.Colors.White), forState: UIControlState.Normal)
roundedButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: VisualFactory.Metrics.Padding.VerySmall)
}
}),
"roundedButton.green": ViewStylist.wrapAllureBlock({ (roundedButton: RoundedButton) in
VisualTheme.allureBlocks["roundedButton"]?(roundedButton)
roundedButton.setFillColor(VisualFactory.Colors.ActionGreen, forState: UIControlState.Normal)
roundedButton.setFillColor(VisualFactory.Colors.ActionGreen.darkerColor(), forState: UIControlState.Highlighted)
}),
"roundedButton.grey": ViewStylist.wrapAllureBlock({ (roundedButton: RoundedButton) in
VisualTheme.allureBlocks["roundedButton"]?(roundedButton)
roundedButton.setFillColor(VisualFactory.Colors.LightGrey, forState: UIControlState.Normal)
roundedButton.setFillColor(VisualFactory.Colors.LightGrey.darkerColor(), forState: UIControlState.Highlighted)
}),
"roundedButton.red": ViewStylist.wrapAllureBlock({ (roundedButton: RoundedButton) in
VisualTheme.allureBlocks["roundedButton"]?(roundedButton)
roundedButton.setFillColor(VisualFactory.Colors.InvalidRed, forState: UIControlState.Normal)
roundedButton.setFillColor(VisualFactory.Colors.InvalidRed.darkerColor(), forState: UIControlState.Highlighted)
}),
"button.icon": ViewStylist.wrapAllureBlock({ (button: UIButton) in
button.adjustsImageWhenHighlighted = false
}),
"button.icon.large.grey": ViewStylist.wrapAllureBlock({ (button: UIButton) in
VisualTheme.allureBlocks["button.icon"]?(button)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Normal), attributes: VisualFactory.TextAttributes.LargeIconGrey), forState: UIControlState.Normal)
var highlightedStyle = VisualFactory.TextAttributes.LargeIconGrey
highlightedStyle.updateValue((highlightedStyle[NSForegroundColorAttributeName] as! UIColor).darkerColor(factor: VisualFactory.Factors.Darken.VeryStrong), forKey: NSForegroundColorAttributeName)
button.setAttributedTitle(NSAttributedString(string: button.readableTitleForState(UIControlState.Normal), attributes: highlightedStyle), forState: UIControlState.Highlighted)
}),
// MARK: - TextField allures
"textField.huge.light": ViewStylist.wrapAllureBlock({ (textField: UITextField) in
var placeholderAttributes = VisualFactory.TextAttributes.HugeLight
placeholderAttributes.updateValue(VisualFactory.Colors.LightGrey, forKey: NSForegroundColorAttributeName)
textField.attributedText = NSAttributedString(string: textField.readableText(), attributes: VisualFactory.TextAttributes.HugeLight)
textField.attributedPlaceholder = NSAttributedString(string: textField.readablePlaceholder(), attributes: placeholderAttributes)
textField.tintColor = VisualFactory.Colors.Black
textField.borderStyle = UITextBorderStyle.None
textField.adjustsFontSizeToFitWidth = false
})
]
}
|
mit
|
648dd66c086bff473dbfd5df0ab1cefa
| 72.707921 | 240 | 0.731547 | 5.211411 | false | false | false | false |
gmoral/SwiftTraining2016
|
Pods/SlideMenuControllerSwift/Source/SlideMenuController.swift
|
1
|
38508
|
//
// SlideMenuController.swift
//
// Created by Yuji Hato on 12/3/14.
//
import Foundation
import UIKit
public struct SlideMenuOptions
{
public static var leftViewWidth: CGFloat = 270.0
public static var leftBezelWidth: CGFloat = 16.0
public static var contentViewScale: CGFloat = 0.96
public static var contentViewOpacity: CGFloat = 0.5
public static var shadowOpacity: CGFloat = 0.0
public static var shadowRadius: CGFloat = 0.0
public static var shadowOffset: CGSize = CGSizeMake(0,0)
public static var panFromBezel: Bool = true
public static var animationDuration: CGFloat = 0.4
public static var rightViewWidth: CGFloat = 270.0
public static var rightBezelWidth: CGFloat = 16.0
public static var rightPanFromBezel: Bool = true
public static var hideStatusBar: Bool = true
public static var pointOfNoReturnWidth: CGFloat = 44.0
public static var opacityViewBackgroundColor: UIColor = UIColor.blackColor()
}
public class SlideMenuController: UIViewController, UIGestureRecognizerDelegate
{
public enum SlideAction
{
case Open
case Close
}
public enum TrackAction
{
case TapOpen
case TapClose
case FlickOpen
case FlickClose
}
struct PanInfo
{
var action: SlideAction
var shouldBounce: Bool
var velocity: CGFloat
}
public var opacityView = UIView()
public var mainContainerView = UIView()
public var leftContainerView = UIView()
public var rightContainerView = UIView()
public var mainViewController: UIViewController?
public var leftViewController: UIViewController?
public var leftPanGesture: UIPanGestureRecognizer?
public var leftTapGesture: UITapGestureRecognizer?
public var rightViewController: UIViewController?
public var rightPanGesture: UIPanGestureRecognizer?
public var rightTapGesture: UITapGestureRecognizer?
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController)
{
self.init()
self.mainViewController = mainViewController
leftViewController = leftMenuViewController
initView()
}
public convenience init(mainViewController: UIViewController, rightMenuViewController: UIViewController)
{
self.init()
self.mainViewController = mainViewController
rightViewController = rightMenuViewController
initView()
}
public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController)
{
self.init()
self.mainViewController = mainViewController
leftViewController = leftMenuViewController
rightViewController = rightMenuViewController
initView()
}
public override func awakeFromNib()
{
initView()
}
deinit { }
public func initView()
{
mainContainerView = UIView(frame: view.bounds)
mainContainerView.backgroundColor = UIColor.clearColor()
mainContainerView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
view.insertSubview(mainContainerView, atIndex: 0)
var opacityframe: CGRect = view.bounds
let opacityOffset: CGFloat = 0
opacityframe.origin.y = opacityframe.origin.y + opacityOffset
opacityframe.size.height = opacityframe.size.height - opacityOffset
opacityView = UIView(frame: opacityframe)
opacityView.backgroundColor = SlideMenuOptions.opacityViewBackgroundColor
opacityView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
opacityView.layer.opacity = 0.0
view.insertSubview(opacityView, atIndex: 1)
var leftFrame: CGRect = view.bounds
leftFrame.size.width = SlideMenuOptions.leftViewWidth
leftFrame.origin.x = leftMinOrigin();
let leftOffset: CGFloat = 0
leftFrame.origin.y = leftFrame.origin.y + leftOffset
leftFrame.size.height = leftFrame.size.height - leftOffset
leftContainerView = UIView(frame: leftFrame)
leftContainerView.backgroundColor = UIColor.clearColor()
leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
view.insertSubview(leftContainerView, atIndex: 2)
var rightFrame: CGRect = view.bounds
rightFrame.size.width = SlideMenuOptions.rightViewWidth
rightFrame.origin.x = rightMinOrigin()
let rightOffset: CGFloat = 0
rightFrame.origin.y = rightFrame.origin.y + rightOffset;
rightFrame.size.height = rightFrame.size.height - rightOffset
rightContainerView = UIView(frame: rightFrame)
rightContainerView.backgroundColor = UIColor.clearColor()
rightContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
view.insertSubview(rightContainerView, atIndex: 3)
addLeftGestures()
addRightGestures()
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
{
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
leftContainerView.hidden = true
rightContainerView.hidden = true
coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.closeLeftNonAnimation()
self.closeRightNonAnimation()
self.leftContainerView.hidden = false
self.rightContainerView.hidden = false
if self.leftPanGesture != nil && self.leftPanGesture != nil {
self.removeLeftGestures()
self.addLeftGestures()
}
if self.rightPanGesture != nil && self.rightPanGesture != nil {
self.removeRightGestures()
self.addRightGestures()
}
})
}
public override func viewDidLoad()
{
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge.None
}
public override func viewWillLayoutSubviews()
{
// topLayoutGuide
setUpViewController(mainContainerView, targetViewController: mainViewController)
setUpViewController(leftContainerView, targetViewController: leftViewController)
setUpViewController(rightContainerView, targetViewController: rightViewController)
}
public override func openLeft()
{
setOpenWindowLevel()
//leftViewControllerのviewWillAppearを呼ぶため
leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true)
openLeftWithVelocity(0.0)
track(.TapOpen)
}
public override func openRight()
{
setOpenWindowLevel()
//menuViewControllerのviewWillAppearを呼ぶため
rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true)
openRightWithVelocity(0.0)
}
public override func closeLeft()
{
leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true)
closeLeftWithVelocity(0.0)
setCloseWindowLebel()
}
public override func closeRight()
{
rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true)
closeRightWithVelocity(0.0)
setCloseWindowLebel()
}
public func addLeftGestures()
{
if (leftViewController != nil)
{
if leftPanGesture == nil
{
leftPanGesture = UIPanGestureRecognizer(target: self, action: "handleLeftPanGesture:")
leftPanGesture!.delegate = self
view.addGestureRecognizer(leftPanGesture!)
}
if leftTapGesture == nil
{
leftTapGesture = UITapGestureRecognizer(target: self, action: "toggleLeft")
leftTapGesture!.delegate = self
view.addGestureRecognizer(leftTapGesture!)
}
}
}
public func addRightGestures()
{
if (rightViewController != nil)
{
if rightPanGesture == nil
{
rightPanGesture = UIPanGestureRecognizer(target: self, action: "handleRightPanGesture:")
rightPanGesture!.delegate = self
view.addGestureRecognizer(rightPanGesture!)
}
if rightTapGesture == nil
{
rightTapGesture = UITapGestureRecognizer(target: self, action: "toggleRight")
rightTapGesture!.delegate = self
view.addGestureRecognizer(rightTapGesture!)
}
}
}
public func removeLeftGestures()
{
if leftPanGesture != nil
{
view.removeGestureRecognizer(leftPanGesture!)
leftPanGesture = nil
}
if leftTapGesture != nil
{
view.removeGestureRecognizer(leftTapGesture!)
leftTapGesture = nil
}
}
public func removeRightGestures()
{
if rightPanGesture != nil
{
view.removeGestureRecognizer(rightPanGesture!)
rightPanGesture = nil
}
if rightTapGesture != nil
{
view.removeGestureRecognizer(rightTapGesture!)
rightTapGesture = nil
}
}
public func isTagetViewController() -> Bool
{
// Function to determine the target ViewController
// Please to override it if necessary
return true
}
public func track(trackAction: TrackAction)
{
// function is for tracking
// Please to override it if necessary
}
struct LeftPanState {
static var frameAtStartOfPan: CGRect = CGRectZero
static var startPointOfPan: CGPoint = CGPointZero
static var wasOpenAtStartOfPan: Bool = false
static var wasHiddenAtStartOfPan: Bool = false
}
func handleLeftPanGesture(panGesture: UIPanGestureRecognizer)
{
if !isTagetViewController()
{
return
}
if isRightOpen()
{
return
}
switch panGesture.state
{
case UIGestureRecognizerState.Began:
LeftPanState.frameAtStartOfPan = leftContainerView.frame
LeftPanState.startPointOfPan = panGesture.locationInView(view)
LeftPanState.wasOpenAtStartOfPan = isLeftOpen()
LeftPanState.wasHiddenAtStartOfPan = isLeftHidden()
leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true)
addShadowToView(leftContainerView)
setOpenWindowLevel()
case UIGestureRecognizerState.Changed:
let translation: CGPoint = panGesture.translationInView(panGesture.view!)
leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan)
applyLeftOpacity()
applyLeftContentViewScale()
case UIGestureRecognizerState.Ended:
let velocity:CGPoint = panGesture.velocityInView(panGesture.view)
let panInfo: PanInfo = panLeftResultInfoForVelocity(velocity)
if panInfo.action == .Open
{
if !LeftPanState.wasHiddenAtStartOfPan
{
leftViewController?.beginAppearanceTransition(true, animated: true)
}
openLeftWithVelocity(panInfo.velocity)
track(.FlickOpen)
} else
{
if LeftPanState.wasHiddenAtStartOfPan
{
leftViewController?.beginAppearanceTransition(false, animated: true)
}
closeLeftWithVelocity(panInfo.velocity)
setCloseWindowLebel()
track(.FlickClose)
}
default:
break
}
}
struct RightPanState {
static var frameAtStartOfPan: CGRect = CGRectZero
static var startPointOfPan: CGPoint = CGPointZero
static var wasOpenAtStartOfPan: Bool = false
static var wasHiddenAtStartOfPan: Bool = false
}
func handleRightPanGesture(panGesture: UIPanGestureRecognizer)
{
if !isTagetViewController()
{
return
}
if isLeftOpen()
{
return
}
switch panGesture.state {
case UIGestureRecognizerState.Began:
RightPanState.frameAtStartOfPan = rightContainerView.frame
RightPanState.startPointOfPan = panGesture.locationInView(view)
RightPanState.wasOpenAtStartOfPan = isRightOpen()
RightPanState.wasHiddenAtStartOfPan = isRightHidden()
rightViewController?.beginAppearanceTransition(RightPanState.wasHiddenAtStartOfPan, animated: true)
addShadowToView(rightContainerView)
setOpenWindowLevel()
case UIGestureRecognizerState.Changed:
let translation: CGPoint = panGesture.translationInView(panGesture.view!)
rightContainerView.frame = applyRightTranslation(translation, toFrame: RightPanState.frameAtStartOfPan)
applyRightOpacity()
applyRightContentViewScale()
case UIGestureRecognizerState.Ended:
let velocity: CGPoint = panGesture.velocityInView(panGesture.view)
let panInfo: PanInfo = panRightResultInfoForVelocity(velocity)
if panInfo.action == .Open {
if !RightPanState.wasHiddenAtStartOfPan
{
rightViewController?.beginAppearanceTransition(true, animated: true)
}
openRightWithVelocity(panInfo.velocity)
} else {
if RightPanState.wasHiddenAtStartOfPan
{
rightViewController?.beginAppearanceTransition(false, animated: true)
}
closeRightWithVelocity(panInfo.velocity)
setCloseWindowLebel()
}
default:
break
}
}
public func openLeftWithVelocity(velocity: CGFloat)
{
let xOrigin: CGFloat = leftContainerView.frame.origin.x
let finalXOrigin: CGFloat = 0.0
var frame = leftContainerView.frame;
frame.origin.x = finalXOrigin;
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0
{
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
addShadowToView(leftContainerView)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations:
{ [weak self]() -> Void in
if let strongSelf = self
{
strongSelf.leftContainerView.frame = frame
strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity)
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self
{
strongSelf.disableContentInteraction()
strongSelf.leftViewController?.endAppearanceTransition()
}
}
}
public func openRightWithVelocity(velocity: CGFloat)
{
let xOrigin: CGFloat = rightContainerView.frame.origin.x
// CGFloat finalXOrigin = SlideMenuOptions.rightViewOverlapWidth;
let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width
var frame = rightContainerView.frame
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
addShadowToView(rightContainerView)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self
{
strongSelf.rightContainerView.frame = frame
strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity)
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self
{
strongSelf.disableContentInteraction()
strongSelf.rightViewController?.endAppearanceTransition()
}
}
}
public func closeLeftWithVelocity(velocity: CGFloat)
{
let xOrigin: CGFloat = leftContainerView.frame.origin.x
let finalXOrigin: CGFloat = leftMinOrigin()
var frame: CGRect = leftContainerView.frame;
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0
{
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations:
{ [weak self]() -> Void in
if let strongSelf = self
{
strongSelf.leftContainerView.frame = frame
strongSelf.opacityView.layer.opacity = 0.0
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.removeShadow(strongSelf.leftContainerView)
strongSelf.enableContentInteraction()
strongSelf.leftViewController?.endAppearanceTransition()
}
}
}
public func closeRightWithVelocity(velocity: CGFloat)
{
let xOrigin: CGFloat = rightContainerView.frame.origin.x
let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds)
var frame: CGRect = rightContainerView.frame
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0
{
duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self
{
strongSelf.rightContainerView.frame = frame
strongSelf.opacityView.layer.opacity = 0.0
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self
{
strongSelf.removeShadow(strongSelf.rightContainerView)
strongSelf.enableContentInteraction()
strongSelf.rightViewController?.endAppearanceTransition()
}
}
}
public override func toggleLeft()
{
if isLeftOpen()
{
closeLeft()
setCloseWindowLebel()
// closeMenuはメニュータップ時にも呼ばれるため、closeタップのトラッキングはここに入れる
track(.TapClose)
} else
{
openLeft()
}
}
public func isLeftOpen() -> Bool
{
return leftContainerView.frame.origin.x == 0.0
}
public func isLeftHidden() -> Bool
{
return leftContainerView.frame.origin.x <= leftMinOrigin()
}
public override func toggleRight()
{
if isRightOpen()
{
closeRight()
setCloseWindowLebel()
} else
{
openRight()
}
}
public func isRightOpen() -> Bool
{
return rightContainerView.frame.origin.x == CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width
}
public func isRightHidden() -> Bool
{
return rightContainerView.frame.origin.x >= CGRectGetWidth(view.bounds)
}
public func changeMainViewController(mainViewController: UIViewController, close: Bool)
{
removeViewController(self.mainViewController)
self.mainViewController = mainViewController
setUpViewController(mainContainerView, targetViewController: mainViewController)
if (close)
{
closeLeft()
closeRight()
}
}
public func changeLeftViewWidth(width: CGFloat)
{
SlideMenuOptions.leftViewWidth = width;
var leftFrame: CGRect = view.bounds
leftFrame.size.width = width
leftFrame.origin.x = leftMinOrigin();
let leftOffset: CGFloat = 0
leftFrame.origin.y = leftFrame.origin.y + leftOffset
leftFrame.size.height = leftFrame.size.height - leftOffset
leftContainerView.frame = leftFrame;
}
public func changeRightViewWidth(width: CGFloat)
{
SlideMenuOptions.rightBezelWidth = width;
var rightFrame: CGRect = view.bounds
rightFrame.size.width = width
rightFrame.origin.x = rightMinOrigin()
let rightOffset: CGFloat = 0
rightFrame.origin.y = rightFrame.origin.y + rightOffset;
rightFrame.size.height = rightFrame.size.height - rightOffset
rightContainerView.frame = rightFrame;
}
public func changeLeftViewController(leftViewController: UIViewController, closeLeft:Bool)
{
removeViewController(self.leftViewController)
self.leftViewController = leftViewController
setUpViewController(leftContainerView, targetViewController: leftViewController)
if closeLeft
{
self.closeLeft()
}
}
public func changeRightViewController(rightViewController: UIViewController, closeRight:Bool)
{
removeViewController(self.rightViewController)
self.rightViewController = rightViewController;
setUpViewController(rightContainerView, targetViewController: rightViewController)
if closeRight {
self.closeRight()
}
}
private func leftMinOrigin() -> CGFloat
{
return -SlideMenuOptions.leftViewWidth
}
private func rightMinOrigin() -> CGFloat
{
return CGRectGetWidth(view.bounds)
}
private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo
{
let thresholdVelocity: CGFloat = 1000.0
let pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + SlideMenuOptions.pointOfNoReturnWidth
let leftOrigin: CGFloat = leftContainerView.frame.origin.x
var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0)
panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open;
if velocity.x >= thresholdVelocity
{
panInfo.action = .Open
panInfo.velocity = velocity.x
} else if velocity.x <= (-1.0 * thresholdVelocity)
{
panInfo.action = .Close
panInfo.velocity = velocity.x
}
return panInfo
}
private func panRightResultInfoForVelocity(velocity: CGPoint) -> PanInfo
{
let thresholdVelocity: CGFloat = -1000.0
let pointOfNoReturn: CGFloat = CGFloat(floor(CGRectGetWidth(view.bounds)) - SlideMenuOptions.pointOfNoReturnWidth)
let rightOrigin: CGFloat = rightContainerView.frame.origin.x
var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0)
panInfo.action = rightOrigin >= pointOfNoReturn ? .Close : .Open
if velocity.x <= thresholdVelocity
{
panInfo.action = .Open
panInfo.velocity = velocity.x
} else if (velocity.x >= (-1.0 * thresholdVelocity))
{
panInfo.action = .Close
panInfo.velocity = velocity.x
}
return panInfo
}
private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect
{
var newOrigin: CGFloat = toFrame.origin.x
newOrigin += translation.x
let minOrigin: CGFloat = leftMinOrigin()
let maxOrigin: CGFloat = 0.0
var newFrame: CGRect = toFrame
if newOrigin < minOrigin
{
newOrigin = minOrigin
} else if newOrigin > maxOrigin
{
newOrigin = maxOrigin
}
newFrame.origin.x = newOrigin
return newFrame
}
private func applyRightTranslation(translation: CGPoint, toFrame: CGRect) -> CGRect
{
var newOrigin: CGFloat = toFrame.origin.x
newOrigin += translation.x
let minOrigin: CGFloat = rightMinOrigin()
let maxOrigin: CGFloat = rightMinOrigin() - rightContainerView.frame.size.width
var newFrame: CGRect = toFrame
if newOrigin > minOrigin
{
newOrigin = minOrigin
} else if newOrigin < maxOrigin
{
newOrigin = maxOrigin
}
newFrame.origin.x = newOrigin
return newFrame
}
private func getOpenedLeftRatio() -> CGFloat
{
let width: CGFloat = leftContainerView.frame.size.width
let currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin()
return currentPosition / width
}
private func getOpenedRightRatio() -> CGFloat
{
let width: CGFloat = rightContainerView.frame.size.width
let currentPosition: CGFloat = rightContainerView.frame.origin.x
return -(currentPosition - CGRectGetWidth(view.bounds)) / width
}
private func applyLeftOpacity()
{
let openedLeftRatio: CGFloat = getOpenedLeftRatio()
let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedLeftRatio
opacityView.layer.opacity = Float(opacity)
}
private func applyRightOpacity()
{
let openedRightRatio: CGFloat = getOpenedRightRatio()
let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedRightRatio
opacityView.layer.opacity = Float(opacity)
}
private func applyLeftContentViewScale()
{
let openedLeftRatio: CGFloat = getOpenedLeftRatio()
let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedLeftRatio);
mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)
}
private func applyRightContentViewScale()
{
let openedRightRatio: CGFloat = getOpenedRightRatio()
let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedRightRatio)
mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)
}
private func addShadowToView(targetContainerView: UIView)
{
targetContainerView.layer.masksToBounds = false
targetContainerView.layer.shadowOffset = SlideMenuOptions.shadowOffset
targetContainerView.layer.shadowOpacity = Float(SlideMenuOptions.shadowOpacity)
targetContainerView.layer.shadowRadius = SlideMenuOptions.shadowRadius
targetContainerView.layer.shadowPath = UIBezierPath(rect: targetContainerView.bounds).CGPath
}
private func removeShadow(targetContainerView: UIView)
{
targetContainerView.layer.masksToBounds = true
mainContainerView.layer.opacity = 1.0
}
private func removeContentOpacity()
{
opacityView.layer.opacity = 0.0
}
private func addContentOpacity() {
opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity)
}
private func disableContentInteraction()
{
mainContainerView.userInteractionEnabled = false
}
private func enableContentInteraction()
{
mainContainerView.userInteractionEnabled = true
}
private func setOpenWindowLevel()
{
if (SlideMenuOptions.hideStatusBar)
{
dispatch_async(dispatch_get_main_queue(),
{
if let window = UIApplication.sharedApplication().keyWindow
{
window.windowLevel = UIWindowLevelStatusBar + 1
}
})
}
}
private func setCloseWindowLebel()
{
if (SlideMenuOptions.hideStatusBar)
{
dispatch_async(dispatch_get_main_queue(),
{
if let window = UIApplication.sharedApplication().keyWindow
{
window.windowLevel = UIWindowLevelNormal
}
})
}
}
private func setUpViewController(targetView: UIView, targetViewController: UIViewController?)
{
if let viewController = targetViewController
{
addChildViewController(viewController)
viewController.view.frame = targetView.bounds
targetView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
}
}
private func removeViewController(viewController: UIViewController?)
{
if let _viewController = viewController
{
_viewController.view.layer.removeAllAnimations()
_viewController.willMoveToParentViewController(nil)
_viewController.view.removeFromSuperview()
_viewController.removeFromParentViewController()
}
}
public func closeLeftNonAnimation()
{
setCloseWindowLebel()
let finalXOrigin: CGFloat = leftMinOrigin()
var frame: CGRect = leftContainerView.frame;
frame.origin.x = finalXOrigin
leftContainerView.frame = frame
opacityView.layer.opacity = 0.0
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
removeShadow(leftContainerView)
enableContentInteraction()
}
public func closeRightNonAnimation()
{
setCloseWindowLebel()
let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds)
var frame: CGRect = rightContainerView.frame
frame.origin.x = finalXOrigin
rightContainerView.frame = frame
opacityView.layer.opacity = 0.0
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
removeShadow(rightContainerView)
enableContentInteraction()
}
// MARK: UIGestureRecognizerDelegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool
{
let point: CGPoint = touch.locationInView(view)
if gestureRecognizer == leftPanGesture
{
return slideLeftForGestureRecognizer(gestureRecognizer, point: point)
} else if gestureRecognizer == rightPanGesture
{
return slideRightViewForGestureRecognizer(gestureRecognizer, withTouchPoint: point)
} else if gestureRecognizer == leftTapGesture
{
return isLeftOpen() && !isPointContainedWithinLeftRect(point)
} else if gestureRecognizer == rightTapGesture
{
return isRightOpen() && !isPointContainedWithinRightRect(point)
}
return true
}
// returning true here helps if the main view is fullwidth with a scrollview
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
return true
}
private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool
{
return isLeftOpen() || SlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point)
}
private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool
{
var leftBezelRect: CGRect = CGRectZero
var tempRect: CGRect = CGRectZero
let bezelWidth: CGFloat = SlideMenuOptions.leftBezelWidth
CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge)
return CGRectContainsPoint(leftBezelRect, point)
}
private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool
{
return CGRectContainsPoint(leftContainerView.frame, point)
}
private func slideRightViewForGestureRecognizer(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool
{
return isRightOpen() || SlideMenuOptions.rightPanFromBezel && isRightPointContainedWithinBezelRect(point)
}
private func isRightPointContainedWithinBezelRect(point: CGPoint) -> Bool
{
var rightBezelRect: CGRect = CGRectZero
var tempRect: CGRect = CGRectZero
let bezelWidth: CGFloat = CGRectGetWidth(view.bounds) - SlideMenuOptions.rightBezelWidth
CGRectDivide(view.bounds, &tempRect, &rightBezelRect, bezelWidth, CGRectEdge.MinXEdge)
return CGRectContainsPoint(rightBezelRect, point)
}
private func isPointContainedWithinRightRect(point: CGPoint) -> Bool
{
return CGRectContainsPoint(rightContainerView.frame, point)
}
}
extension UIViewController
{
public func slideMenuController() -> SlideMenuController?
{
var viewController: UIViewController? = self
while viewController != nil {
if viewController is SlideMenuController
{
return viewController as? SlideMenuController
}
viewController = viewController?.parentViewController
}
return nil;
}
public func addLeftBarButtonWithImage(buttonImage: UIImage)
{
let leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleLeft")
navigationItem.leftBarButtonItem = leftButton;
}
public func addLeftBackBarButtonWithImage(buttonImage: UIImage)
{
let leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "backLeft")
navigationItem.leftBarButtonItem = leftButton;
}
public func addRightSaveBarButtonWithImage(buttonImage: UIImage)
{
let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "saveRight")
navigationItem.rightBarButtonItem = rightButton;
}
public func addRightBarButtonWithImage(buttonImage: UIImage)
{
let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleRight")
navigationItem.rightBarButtonItem = rightButton;
}
public func addSaveRightBarButtonWithImage(buttonImage: UIImage)
{
let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "SaveRight")
navigationItem.rightBarButtonItem = rightButton;
}
public func toggleLeft()
{
slideMenuController()?.toggleLeft()
}
public func backLeft()
{
// You will need to override this method
}
public func saveRight()
{
// You will need to override this method
}
public func toggleRight()
{
slideMenuController()?.toggleRight()
}
public func openLeft()
{
slideMenuController()?.openLeft()
}
public func openRight()
{
slideMenuController()?.openRight() }
public func closeLeft()
{
slideMenuController()?.closeLeft()
}
public func closeRight()
{
slideMenuController()?.closeRight()
}
// Please specify if you want menu gesuture give priority to than targetScrollView
public func addPriorityToMenuGesuture(targetScrollView: UIScrollView)
{
guard let slideController = slideMenuController(), let recognizers = slideController.view.gestureRecognizers else
{
return
}
for recognizer in recognizers where recognizer is UIPanGestureRecognizer
{
targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer)
}
}
}
|
mit
|
a44301bc59c236559229ffc7f532f8ed
| 33.298214 | 177 | 0.629796 | 6.196806 | false | false | false | false |
indragiek/DominantColor
|
DominantColor/Mac/DragAndDropImageView.swift
|
1
|
1851
|
//
// DragAndDropImageView.swift
// DominantColor
//
// Created by Indragie on 12/19/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
import Cocoa
@objc protocol DragAndDropImageViewDelegate {
func dragAndDropImageView(imageView: DragAndDropImageView, droppedImage image: NSImage?)
}
class DragAndDropImageView: NSImageView {
@IBOutlet weak var delegate: DragAndDropImageViewDelegate?
private let filenameType = NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")
required init?(coder: NSCoder) {
super.init(coder: coder)
registerForDraggedTypes([filenameType])
}
private func fileURL(for pasteboard: NSPasteboard) -> URL? {
if let files = pasteboard.propertyList(forType: filenameType) as? [String] {
guard let filename = files.first else { return nil }
return URL(fileURLWithPath: filename)
}
return nil
}
// MARK: NSDraggingDestination
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
let pasteboard = sender.draggingPasteboard
if let fileURL = fileURL(for: pasteboard) {
let pathExtension = fileURL.pathExtension as CFString
guard let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue() else { return [] }
return (UTTypeConformsTo(UTI, kUTTypeImage) == true) ? .copy : []
}
return []
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
let pasteboard = sender.draggingPasteboard
if let fileURL = fileURL(for: pasteboard) {
self.delegate?.dragAndDropImageView(imageView: self, droppedImage: NSImage(contentsOf: fileURL))
return true
}
return false
}
}
|
mit
|
9e0413ce4063d1c8201e2bfb704b823c
| 33.277778 | 155 | 0.684495 | 5.170391 | false | false | false | false |
dimitris-c/Omicron
|
Tests/RxAPIServiceSpec.swift
|
1
|
8483
|
//
// RxAPIServiceSpec.swift
// Omicron
//
// Created by Dimitris C. on 24/06/2017.
// Copyright © 2017 Decimal. All rights reserved.
//
import Quick
import Nimble
import Alamofire
import SwiftyJSON
import OHHTTPStubs
import RxSwift
@testable import Omicron
@testable import RxOmicron
class RxAPIServiceSpec: QuickSpec {
override func spec() {
describe("RxAPIServiceSpec") {
it("emits a JSON object and a completion when using callJSON") {
let service = RxAPIService<HTTPBin>()
var called = false
var completed = false
waitUntil(timeout: 30.0, action: { (done) in
_ = service.callJSON(with: .get).subscribe(onNext: { _ in
called = true
}, onCompleted: {
completed = true
done()
})
})
expect(called).to(beTrue())
expect(completed).to(beTrue())
}
it("emits a JSON Object when using call<Model>(with parse:)") {
let service = RxAPIService<HTTPBin>()
var expectedJSON: JSON?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.call(with: .get, parse: JSONResponse()).subscribe(onNext: { json in
expectedJSON = json
done()
})
})
expect(expectedJSON).toNot(beNil())
}
context("reactive methods emit Error") {
it("emits Error when calling a wrong url when using callJSON") {
let service = RxAPIService<HTTPBin>()
var expectedError: Error?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.callJSON(with: .nonExistingPath).subscribe(onError: { error in
expectedError = error
done()
})
})
expect(expectedError).toNot(beNil())
}
it("emits Error when calling a wrong url when using callString") {
let service = RxAPIService<HTTPBin>()
var expectedError: Error?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.callString(with: .nonExistingPath).subscribe(onError: { error in
expectedError = error
done()
})
})
expect(expectedError).toNot(beNil())
}
it("emits Error when calling a wrong url when using callData") {
let service = RxAPIService<HTTPBin>()
var expectedError: Error?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.callData(with: .nonExistingPath).subscribe(onError: { error in
expectedError = error
done()
})
})
expect(expectedError).toNot(beNil())
}
it("emits Error when calling a wrong url when using call") {
let service = RxAPIService<HTTPBin>()
var expectedError: Error?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.call(with: .nonExistingPath, parse: JSONResponse()).subscribe(onError: { error in
expectedError = error
done()
})
})
expect(expectedError).toNot(beNil())
}
}
context("Stubs") {
beforeEach {
OHHTTPStubs.setEnabled(true)
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("emits a String when using callString") {
stub(condition: isHost("httpbin.org"), response: { _ -> OHHTTPStubsResponse in
let stubPath = OHPathForFile("text.txt", type(of: self))
return fixture(filePath: stubPath!, headers: ["Content-Type":"application/text"])
})
let service = RxAPIService<HTTPBin>()
var string: String?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.callString(with: .get).subscribe(onNext: { value in
string = value
done()
})
})
expect(string).toNot(beNil())
}
it("emits data when using callData") {
stub(condition: isHost("httpbin.org"), response: { _ -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(data: "Test".data(using: .utf8)!,
statusCode: 200,
headers: ["Content-Type":"application/text"])
})
let service = RxAPIService<HTTPBin>()
var expectedData: Data?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.callData(with: .get).subscribe(onNext: { data in
expectedData = data
done()
})
})
expect(expectedData).toNot(beNil())
}
it("emits a User object when using call with custom parse object") {
stub(condition: isHost("httpbin.org"), response: { _ -> OHHTTPStubsResponse in
let stubPath = OHPathForFile("user.json", type(of: self))
return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"])
})
let service = RxAPIService<HTTPBin>()
var expectedUser: User?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.call(with: .get, parse: UserReponse()).subscribe(onNext: { user in
expectedUser = user
done()
})
})
expect(expectedUser).toNot(beNil())
expect(expectedUser?.name).to(equal("Dimitris"))
}
}
}
describe("RxAPIServiceTyped") {
it("returns JSON response") {
let service = RxAPIService<GithubService>()
var userJSON: JSON?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.callJSON(with: .user(name: "dimitris-c")).subscribe(onNext: { json in
userJSON = json
done()
})
})
expect(userJSON).toNot(beNil())
}
it("returns an appropriate model response") {
let service = RxAPIService<GithubService>()
var expectedUser: GithubUser?
waitUntil(timeout: 30.0, action: { (done) in
_ = service.call(with: .user(name: "dimitris-c"), parse: GithubUserResponse()).subscribe(onNext: { user in
expectedUser = user
done()
})
})
expect(expectedUser).toNot(beNil())
}
}
}
}
|
mit
|
b0b04ef4fac417540f6aa9746cb7c906
| 39.009434 | 126 | 0.408276 | 6.241354 | false | false | false | false |
liuguya/TestKitchen_1606
|
TestKitchen/TestKitchen/classes/cookbook/foodMaterial/view/CBMaterialCell.swift
|
1
|
4744
|
//
// CBMaterialCell.swift
// TestKitchen
//
// Created by 阳阳 on 16/8/24.
// Copyright © 2016年 liuguyang. All rights reserved.
//
import UIKit
class CBMaterialCell: UITableViewCell {
var model:CBMaterialTypeModel?{
didSet{
if model != nil{
showData()
}
}
}
func showData(){
//1.删除之前的子视图
for oldSub in contentView.subviews {
oldSub.removeFromSuperview()
}
//2.添加子视图
//2.1 标题
let titleLabel = UILabel.createLabel(model!.text, font: UIFont.systemFontOfSize(20), textAlignment: .Left, textColor: UIColor.blackColor())
titleLabel.frame = CGRectMake(20, 0, kSreenWith-20*2, 40)
contentView.addSubview(titleLabel)
//横向间距
let spaceX: CGFloat = 10
//纵向间距
let spaceY: CGFloat = 10
//一共几列
let colNum = 5
//按钮高度
let h: CGFloat = 40
//按钮的宽度
let w = (kSreenWith-spaceX*CGFloat(colNum+1))/CGFloat(colNum)
//y的偏移量
let offsetY: CGFloat = 40
//2.2 图片
let imageFrame = CGRectMake(spaceX, offsetY, w*2+spaceX, h*2+spaceY)
let imageView = UIImageView.createImageView(nil)
imageView.frame = imageFrame
let url = NSURL(string: (model?.image)!)
imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
contentView.addSubview(imageView)
//2.3 循环创建按钮
if model?.data?.count > 0 {
for i in 0..<(model?.data?.count)! {
var btnFrame = CGRectZero
if i < 6 {
//前两行的按钮
//行和列
let row = i/3
let col = i%3
btnFrame = CGRectMake(w*2+spaceX*3+CGFloat(col)*(w+spaceX), offsetY+CGFloat(row)*(h+spaceY), w, h)
}else{
//后面几行的按钮
//行和列
let row = (i-6)/5
let col = (i-6)%5
btnFrame = CGRectMake(spaceX+CGFloat(col)*(w+spaceX), offsetY+2*(h+spaceY)+CGFloat(row)*(h+spaceY), w, h)
}
//按钮
let btn = CBMaterialBtn(frame: btnFrame)
let subModel = model?.data![i]
btn.model = subModel
contentView.addSubview(btn)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
//计算cell的高度
class func heightWithModel(model: CBMaterialTypeModel) -> CGFloat {
var h: CGFloat = 0
//标题高度
let offsetY: CGFloat = 40
//纵向间距
let spaceY: CGFloat = 10
//按钮的高度
let btnH: CGFloat = 40
if model.data?.count > 0 {
if model.data?.count < 6 {
h = offsetY+(btnH+spaceY)*2
}else{
h = offsetY+(btnH+spaceY)*2
//除去前面两行,计算还有多少行
var rowNum = ((model.data?.count)!-6)/5
if ((model.data?.count)!-6)%5 > 0 {
rowNum += 1
}
h += CGFloat(rowNum)*(btnH+spaceY)
}
}
return h
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
class CBMaterialBtn: UIControl {
private var titleLabel: UILabel?
//数据
var model: CBMaterialSubtypeModel? {
didSet{
titleLabel?.text = model?.text
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.8, alpha: 1.0)
//文字
titleLabel = UILabel.createLabel(nil, font: UIFont.systemFontOfSize(17), textAlignment: .Center, textColor: UIColor.blackColor())
titleLabel?.frame = bounds
titleLabel?.adjustsFontSizeToFitWidth = true
addSubview(titleLabel!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
3d426c30b6a4ac375f49cd868c626cc5
| 25.179191 | 154 | 0.47781 | 4.59797 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015
|
04-App Architecture/Swift 4/Breadcrumbs/Breadcrumbs-9/BCOptions.swift
|
12
|
1910
|
//
// BCOptions.swift
// Breadcrumbs
//
// Created by Nicholas Outram on 25/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import Foundation
import CoreLocation
import MapKit
struct BCOptions {
static let defaultsDictionary : [String : AnyObject] = {
let fp = Bundle.main.path(forResource: "factoryDefaults", ofType: "plist")
return NSDictionary(contentsOfFile: fp!) as! [String : AnyObject]
}()
static let defaults : UserDefaults = {
let ud = UserDefaults.standard
ud.register(defaults: BCOptions.defaultsDictionary)
ud.synchronize()
return ud
}()
lazy var backgroundUpdates : Bool = BCOptions.defaults.bool(forKey: "backgroundUpdates")
lazy var headingAvailable : Bool = CLLocationManager.headingAvailable()
lazy var headingUP : Bool = {
return self.headingAvailable && BCOptions.defaults.bool(forKey: "headingUP")
}()
var userTrackingMode : MKUserTrackingMode {
mutating get {
return self.headingUP ? .followWithHeading : .follow
}
}
lazy var showTraffic : Bool = BCOptions.defaults.bool(forKey: "showTraffic")
lazy var distanceBetweenMeasurements : Double = BCOptions.defaults.double(forKey: "distanceBetweekMeasurements")
lazy var gpsPrecision : Double = BCOptions.defaults.double(forKey: "gpsPrecision")
mutating func updateDefaults() {
BCOptions.defaults.set(backgroundUpdates, forKey: "backgroundUpdates")
BCOptions.defaults.set(headingUP, forKey: "headingUP")
BCOptions.defaults.set(showTraffic, forKey: "showTraffic")
BCOptions.defaults.set(distanceBetweenMeasurements, forKey: "distanceBetweenMeasurements")
BCOptions.defaults.set(gpsPrecision, forKey: "gpsPrecision")
}
static func commit() {
BCOptions.defaults.synchronize()
}
}
|
mit
|
d867d6b660ded788e00e5a2a5ccb2839
| 35.711538 | 116 | 0.688318 | 4.656098 | false | false | false | false |
ArchonGum/AKDrawer
|
AKDrawer/Controller/MainCenterViewController.swift
|
1
|
2199
|
//
// MainCenterViewController.swift
// AKDrawer
//
// Created by Archon.K on 15/8/23.
// Copyright (c) 2015年 ArchonK. All rights reserved.
//
import UIKit
class MainCenterViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("mainCenterViewCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = "Main View Cell: \(indexPath.row)"
return cell
}
@IBAction func barButtonClick(sender: UIBarButtonItem) {
switch sender.tag {
// Left bar button action
case 101:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.toggleLeftDrawer(sender, animated: false)
// Right bar button action
case 102:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.toggleRightDrawer(sender, animated: true)
default:
break
}
}
@IBAction func swipeGestureAction(sender: UISwipeGestureRecognizer) {
switch sender.direction {
case UISwipeGestureRecognizerDirection.Left:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.toggleRightDrawer(sender, animated: false)
case UISwipeGestureRecognizerDirection.Right:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.toggleLeftDrawer(sender, animated: true)
default:
return
}
}
}
|
mit
|
3dd4119f027fe766ced261bc4262d909
| 29.513889 | 129 | 0.654074 | 5.796834 | false | false | false | false |
aamays/Twitter
|
Twitter/Utilities/MenuOptions.swift
|
1
|
3004
|
//
// MenuOptions.swift
// Twitter
//
// Created by Amay Singhal on 10/9/15.
// Copyright © 2015 ple. All rights reserved.
//
import Foundation
import UIKit
protocol MenuOption: class {
var title: String { get }
var iconType: FontasticIconType { get }
var isSelected: Bool { get set }
var viewController: UIViewController { get set }
}
class HomeMenuOption: MenuOption {
private let _title = "Home"
var title: String {
get {
return _title
}
}
private let _iconType = FontasticIconType.Home
var iconType: FontasticIconType {
get {
return _iconType
}
}
var selected: Bool!
var isSelected: Bool {
get {
return selected
}
set(newValue) {
selected = newValue
}
}
var homeViewController: UIViewController!
var viewController: UIViewController {
get {
return homeViewController
}
set(newViewController) {
homeViewController = newViewController
}
}
init(selected: Bool, viewController: UIViewController) {
self.selected = selected
self.viewController = viewController
}
}
class ProfileMenuOption: MenuOption {
private var _title = "Me"
var title: String {
get {
return _title
}
}
private var _iconType = FontasticIconType.UserFilled
var iconType: FontasticIconType {
get {
return _iconType
}
}
var selected: Bool!
var isSelected: Bool {
get {
return selected
}
set(newValue) {
selected = newValue
}
}
var profileViewController: UIViewController!
var viewController: UIViewController {
get {
return profileViewController
}
set(newViewController) {
profileViewController = newViewController
}
}
init(selected: Bool, viewController: UIViewController) {
self.selected = selected
self.viewController = viewController
}
}
class MentionsMenuOption: MenuOption {
private let _title = "Mentions"
var title: String {
get {
return _title
}
}
private let _iconType = FontasticIconType.AtSign
var iconType: FontasticIconType {
get {
return _iconType
}
}
var selected: Bool!
var isSelected: Bool {
get {
return selected
}
set(newValue) {
selected = newValue
}
}
var homeViewController: UIViewController!
var viewController: UIViewController {
get {
return homeViewController
}
set(newViewController) {
homeViewController = newViewController
}
}
init(selected: Bool, viewController: UIViewController) {
self.selected = selected
self.viewController = viewController
}
}
|
mit
|
8ef3bb0f3de642d42398ea36c7b5a399
| 20.304965 | 60 | 0.575092 | 5.098472 | false | false | false | false |
icecrystal23/ios-charts
|
ChartsDemo-macOS/ChartsDemo-macOS/Demos/PieDemoViewController.swift
|
1
|
2334
|
//
// PieDemoViewController.swift
// ChartsDemo-OSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Foundation
import Cocoa
import Charts
open class PieDemoViewController: NSViewController
{
@IBOutlet var pieChartView: PieChartView!
override open func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) * 100.0 }
let yse1 = ys1.enumerated().map { x, y in return PieChartDataEntry(value: y, label: String(x)) }
let data = PieChartData()
let ds1 = PieChartDataSet(values: yse1, label: "Hello")
ds1.colors = ChartColorTemplates.vordiplom()
data.addDataSet(ds1)
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
let centerText: NSMutableAttributedString = NSMutableAttributedString(string: "Charts\nby Daniel Cohen Gindi")
centerText.setAttributes([NSAttributedString.Key.font: NSFont(name: "HelveticaNeue-Light", size: 15.0)!, NSAttributedString.Key.paragraphStyle: paragraphStyle], range: NSMakeRange(0, centerText.length))
centerText.addAttributes([NSAttributedString.Key.font: NSFont(name: "HelveticaNeue-Light", size: 13.0)!, NSAttributedString.Key.foregroundColor: NSColor.gray], range: NSMakeRange(10, centerText.length - 10))
centerText.addAttributes([NSAttributedString.Key.font: NSFont(name: "HelveticaNeue-LightItalic", size: 13.0)!, NSAttributedString.Key.foregroundColor: NSColor(red: 51 / 255.0, green: 181 / 255.0, blue: 229 / 255.0, alpha: 1.0)], range: NSMakeRange(centerText.length - 19, 19))
self.pieChartView.centerAttributedText = centerText
self.pieChartView.data = data
self.pieChartView.chartDescription?.text = "Piechart Demo"
}
override open func viewWillAppear()
{
self.pieChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0)
}
}
|
apache-2.0
|
e9e2898dfb431f527bcb4523ca30eb4c
| 42.222222 | 284 | 0.688089 | 4.567515 | false | false | false | false |
DungFu/TrafficSweetSpot
|
TrafficSweetSpot/TravelTimeChartView.swift
|
1
|
1280
|
//
// TravelTimeChartView.swift
// TrafficSweetSpot
//
// Created by Freddie Meyer on 7/19/16.
// Copyright © 2016 Freddie Meyer. All rights reserved.
//
import Cocoa
import Charts
class TravelTimeChartView: NSView {
@IBOutlet weak var lineChartView: LineChartView!
func update() {
DispatchQueue.main.async {
if (self.lineChartView != nil) {
self.lineChartView.notifyDataSetChanged()
}
}
}
func initData(_ data: LineChartData) {
DispatchQueue.main.async {
if (self.lineChartView != nil) {
self.lineChartView.leftAxis.axisMinimum = 0
self.lineChartView.leftAxis.setLabelCount(5, force: true)
self.lineChartView.rightAxis.axisMinimum = 0
self.lineChartView.rightAxis.setLabelCount(5, force: true)
self.lineChartView.chartDescription?.text = ""
self.lineChartView.noDataText = "No data yet"
self.lineChartView.xAxis.valueFormatter = TravelTimeChartFormatter()
self.lineChartView.xAxis.setLabelCount(5, force: true)
self.lineChartView.xAxis.yOffset = 10.0
self.lineChartView.data = data
}
}
}
}
|
mit
|
bc519703af0da85be9ec6a5624afbe3e
| 31.794872 | 84 | 0.605942 | 4.754647 | false | false | false | false |
GYLibrary/GYNetWorking
|
GYNetWorking/NetWork/GYNetWork.swift
|
1
|
5111
|
//
// GYNetWork.swift
// GYNetWorkING
//
// Created by zhuguangyang on 16/10/26.
// Copyright © 2016年 Giant. All rights reserved.
//
import UIKit
// MARK: - Data Request
@discardableResult
public func request(str:String) {
return GYNetWork.request()
}
public class GYNetWork{
public class func request() {
let session = URLSession.shared
var request = URLRequest(url: URL(string:"http://baidu.com")!)
//超时时间设置
request.timeoutInterval = 0.1
let task = session.dataTask(with: request) { (data, response, error) in
print("waif for 5 seconds!")
sleep(5)
let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
Print(string)
}
//开始执行
task.resume()
}
/// 网络请求
///
/// - parameter method: 请求方式
/// - parameter url: URL
open class func request(method:String, url: String) {
let session = URLSession.shared
var request = URLRequest.init(url: URL(string: url)!)
request.httpMethod = method
request.httpShouldHandleCookies = false
let task = session.dataTask(with: request) { (data, response, error) in
print("稍等一下!")
sleep(5)
let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(string)
}
task.resume()
}
/// 网络请求(带返回结果)
///
/// - parameter method: GET、post
/// - parameter url: url description
/// - parameter callback: callback description
open class func request(method: String, url: String,callback: @escaping (_ data:Data?,_ response:URLResponse?,_ error: Error?) -> Void) {
let session = URLSession.shared
var request = URLRequest.init(url: URL(string: url)!)
request.httpMethod = method
request.httpShouldHandleCookies = false
let task = session.dataTask(with: request) { (data, response, error) in
callback(data, response, error)
}
task.resume()
}
/// 网络请求参数以字典的形式传入
///
/// - parameter method: 请求方式
/// - parameter url: url
/// - parameter params: 请求参数
/// - parameter callBack: 返回请求结果
open class func request(method: GYNetWorkMethod, url:String,params: [String: Any],callBack: @escaping RequestCompletion) {
let session = URLSession.shared
var newURl = url
switch method {
case .GET:
//如何转化编码的...未知的世界
//password=Optional%28%22666666%22%29&phone=Optional%28%2215026981614%22%29
// newURl += "?" + GYParameterEncoding.convertParams(params).replacingOccurrences(of: "Optional", with: "")
newURl += "?" + GYParameterEncoding.convertSimpleParams(params)
case .POST:
break
default:
break
}
print(newURl)
print(GYParameterEncoding.convertParams(params))
var request = URLRequest.init(url: URL(string: newURl)!)
request.httpMethod = method.rawValue
if method == .POST {
request.addValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = GYParameterEncoding.convertSimpleParams(params).data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
}
let task = session.dataTask(with: request) { (data, response, error) in
callBack(data, response, error)
}
task.resume()
}
/// 参数以String的方式传入
///
/// - parameter method: 请求方式
/// - parameter url: url
/// - parameter params: 参数
/// - parameter callBack: 回调
open class func request(method: GYNetWorkMethod, url:String,params: String,callBack: @escaping RequestCompletion) {
let session = URLSession.shared
var newURl = url
switch method {
case .GET:
newURl += "?" + params
case .POST:
break
default:
break
}
print(newURl)
var request = URLRequest.init(url: URL(string: newURl)!)
request.httpMethod = method.rawValue
if method == .POST {
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = params.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
}
let task = session.dataTask(with: request) { (data, response, error) in
callBack(data, response, error)
}
task.resume()
}
}
|
mit
|
7c38f480be9d7b21ba5cb7c7758af057
| 28.321429 | 148 | 0.556435 | 4.565338 | false | false | false | false |
hGhostD/SwiftLearning
|
Swift设计模式/Swift设计模式/18 备忘录模式/18.playground/Contents.swift
|
1
|
2300
|
import Cocoa
/*:
> 备忘录模式可以捕获一个对象的完整状态,并将其保存到一个备忘录对象中,以后可以根据备忘录重置对象的状态
备忘录模式中有两个参与者,即原发器和管理者。原发器为需要回退状态的对象,管理者则告诉原发器将状态会退到哪一刻的状态。
*/
class LedgerEntry {
let id: Int
let counterParty: String
let amount: Float
init(id:Int, counterParty: String, amount: Float) {
self.id = id
self.counterParty = counterParty
self.amount = amount
}
}
class Ledger {
private var entries = [Int: LedgerEntry]()
private var nextId = 1
var total: Float = 0
func addEntry(counterParty: String, amount: Float) -> LedgerCommand {
nextId += 1
let entry = LedgerEntry(id: nextId, counterParty: counterParty, amount: amount)
entries[entry.id] = entry
total += amount
return createUndoCommand(entry: entry)
}
private func createUndoCommand(entry: LedgerEntry) -> LedgerCommand {
return LedgerCommand(instruction: { (targer) in
let removed = targer.entries.removeValue(forKey: entry.id)
if removed != nil {
targer.total -= removed!.amount
}
}, receiver: self)
}
func printEntries() {
for id in entries.keys.sorted() {
if let entry = entries[id] {
print("#\(id): \(entry.counterParty) \(entry.amount)")
}
}
print("Total:\(total)")
print("--------")
}
}
class LedgerCommand {
private let instructons: (Ledger) -> Void
private let receiver: Ledger
init(instruction: @escaping (Ledger) -> Void, receiver: Ledger) {
self.instructons = instruction
self.receiver = receiver
}
func execute() {
self.instructons(self.receiver)
}
}
let ledger = Ledger()
ledger.addEntry(counterParty: "Bob", amount: 100.43)
ledger.addEntry(counterParty: "Joe", amount: 200.20)
let undoCommand = ledger.addEntry(counterParty: "Alice", amount: 500)
ledger.addEntry(counterParty: "Tony", amount: 20)
ledger.printEntries()
undoCommand.execute()
ledger.printEntries()
|
apache-2.0
|
38ed01e37da56a9db74fc2487512d589
| 26.421053 | 87 | 0.609885 | 3.675485 | false | false | false | false |
xiaohu557/TinyPlayer
|
Examples/Demo/Tests/TinyPlayerFunctionalTests.swift
|
2
|
20269
|
//
// TinyPlayerFunctionalTests.swift
// TinyPlayerDemo
//
// Created by Kevin Chen on 13/02/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
import Quick
import Nimble
import AVFoundation
@testable import TinyPlayer
class TinyPlayerFunctionalSpecs: QuickSpec {
override func spec() {
Nimble.AsyncDefaults.Timeout = 10.0 * tm
describe("TinyVideoPlayer") {
let urlPath = Bundle(for: type(of: self)).path(forResource: "unittest_video", ofType: "mp4")
let targetUrl = urlPath.flatMap { URL(fileURLWithPath: $0) }
guard let url = targetUrl else {
XCTFail("Error encountered at loading test video.")
return
}
describe("can be initialized") {
it("with empty parameters") {
let videoPlayer = TinyVideoPlayer()
expect(videoPlayer.playbackState).to(equal(TinyPlayerState.unknown))
expect(videoPlayer.player).toNot(beNil())
expect(videoPlayer.playerItem).to(beNil())
expect(videoPlayer.mediaContext).to(beNil())
expect(videoPlayer.videoDuration).to(beNil())
expect(videoPlayer.playbackPosition).to(beNil())
expect(videoPlayer.startPosition) == 0.0
expect(videoPlayer.endPosition) == 0.0
expect(videoPlayer.playbackProgress).to(beNil())
expect(videoPlayer.playerItemVideoOutput).to(beNil())
expect(videoPlayer.hidden).to(beFalse())
}
it("with a url") {
let videoPlayer = TinyVideoPlayer(resourceUrl: url)
expect(videoPlayer.playbackState).to(equal(TinyPlayerState.unknown))
expect(videoPlayer.player).toNot(beNil())
expect(videoPlayer.mediaContext).to(beNil())
/* The video which the url points to should be eventually loaded. */
expect(videoPlayer.playbackState).toEventually(equal(TinyPlayerState.ready), timeout: 3.0 * tm)
expect(videoPlayer.playerItem).toEventuallyNot(beNil())
/* PlaybackPosition and the duration should be correctly initialized. */
expect(videoPlayer.videoDuration).toEventually(beGreaterThan(59.99))
expect(videoPlayer.playbackPosition).toEventually(beCloseTo(0.0, within: 0.2), timeout: 3.0 * tm)
expect(videoPlayer.playbackProgress).toEventually(equal(0.0))
expect(videoPlayer.startPosition).toEventually(equal(0.0))
expect(videoPlayer.playerItemVideoOutput).toEventuallyNot(beNil())
/* The endPosition should be set to the whole video length if it's not previously set. */
expect(videoPlayer.endPosition).toEventually(equal(videoPlayer.videoDuration))
expect(videoPlayer.hidden).to(beFalse())
}
}
describe("can unload a loaded media item") {
it("when unload") {
let videoPlayer = TinyVideoPlayer(resourceUrl: url)
let spy = PlayerTestObserver(player: videoPlayer)
/* Wait until the player is ready. */
waitUntilPlayerIsReady(withSpy: spy)
/* Initiate closing procedure and wait until the unloading process is done. */
waitUntil(timeout: 5.0 * tm) { done -> Void in
spy.onPlayerStateChanged = { state in
if state == TinyPlayerState.closed {
done()
}
}
videoPlayer.closeCurrentItem()
}
expect(videoPlayer.videoDuration).to(beNil())
expect(videoPlayer.startPosition).to(equal(0.0))
expect(videoPlayer.endPosition).to(equal(0.0))
expect(videoPlayer.playbackPosition).toEventually(beNil())
expect(videoPlayer.playbackProgress).toEventually(beNil())
expect(videoPlayer.playerItemVideoOutput).toEventually(beNil())
expect(videoPlayer.player).toNot(beNil())
expect(videoPlayer.player.currentItem).toEventually(beNil())
expect(videoPlayer.playerItem).to(beNil())
expect(videoPlayer.mediaContext).to(beNil())
}
}
describe("can load mediaContext correctly") {
let mediaContext = MediaContext(videoTitle: "Test Video with start and end settings",
artistName: "TinyPlayer Tester",
startPosition: 9.0,
endPosition: 15.0,
thumbnailImage: UIImage())
it("when specify start and end properties in mediaContext") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
var secondsRecorded = Set<Float>()
/* Wait until the player receives the ready signal and play. */
waitUntil(timeout: 10.0 * tm) { done -> Void in
spy.onPlayerReady = {
videoPlayer.play()
}
/* Record secs updated by the player delegate method. */
spy.onPlaybackPositionUpdated = { secs, _ in
secondsRecorded.insert(floor(secs))
}
spy.onPlaybackFinished = {
done()
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url, mediaContext: mediaContext)
}
/* Test if the player start at the 0.0 (absolute: 9.0) position,
and ends at the 6.0 (absolute: 15.0) position;. */
expect(secondsRecorded).to(contain(0.0))
expect(secondsRecorded).to(contain(6.0))
/* Test the player ends before the 7.0 position. */
expect(secondsRecorded).toNot(contain(7.0))
expect(videoPlayer.playbackState).toEventually(equal(TinyPlayerState.finished), timeout: 8.0 * tm)
/* Start and End should be correctly set. */
expect(videoPlayer.startPosition).toEventually(equal(9.0), timeout: 2.0 * tm)
expect(videoPlayer.endPosition).toEventually(equal(15.0), timeout: 2.0 * tm)
}
}
describe("can create and recycle projection views") {
it("at creation") {
let videoPlayer = TinyVideoPlayer()
let projectionView = videoPlayer.generateVideoProjectionView()
expect(projectionView.hashId).toNot(beNil())
}
it("at recycling") {
}
}
describe("can hide all projection views") {
it("when hide") {
let videoPlayer = TinyVideoPlayer()
let projectionViewBeforeHide = videoPlayer.generateVideoProjectionView()
videoPlayer.hidden = true
let projectionViewAfterHide = videoPlayer.generateVideoProjectionView()
expect(projectionViewBeforeHide.isHidden) == true
expect(projectionViewAfterHide.isHidden) == true
}
it("when unhide") {
let videoPlayer = TinyVideoPlayer()
let projectionViewBeforeUnhide = videoPlayer.generateVideoProjectionView()
videoPlayer.hidden = false
let projectionViewAfterUnhide = videoPlayer.generateVideoProjectionView()
expect(projectionViewBeforeUnhide.isHidden) == false
expect(projectionViewAfterUnhide.isHidden) == false
}
}
describe("can set content fill mode") {
it("when switch between fill modes") {
let videoPlayer = TinyVideoPlayer()
let projectionView = videoPlayer.generateVideoProjectionView()
projectionView.fillMode = .resizeFill
expect(projectionView.playerLayer.videoGravity) == AVLayerVideoGravityResize
projectionView.fillMode = .resizeAspect
expect(projectionView.playerLayer.videoGravity) == AVLayerVideoGravityResizeAspect
projectionView.fillMode = .resizeAspectFill
expect(projectionView.playerLayer.videoGravity)
== AVLayerVideoGravityResizeAspectFill
}
}
describe("can call it's delegate at a proper time") {
it("can call delegate when playerState changed") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
var delegateCalled = false
waitUntil(timeout: 10.0 * tm) { done -> Void in
var onceToken = 0x1
spy.onPlayerStateChanged = { _ in
if onceToken > 0x0 {
delegateCalled = true
onceToken = 0x0
done()
}
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
expect(delegateCalled) == true
}
it("can call delegate when playback position updated") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
var delegateCalled = false
waitUntil(timeout: 10.0 * tm) { done -> Void in
spy.onPlayerReady = {
videoPlayer.play()
}
/* We will use the helper method to test the delegate hit.*/
let playbackPositionChangeAction = {
delegateCalled = true
done()
}
spy.registerAction(action: playbackPositionChangeAction, onTimepoint: 3.0)
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
expect(delegateCalled) == true
}
it("can call delegate when seekable range updated") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
var delegateCalled = false
waitUntil(timeout: 10.0 * tm) { done -> Void in
spy.onSeekableRangeUpdated = { _ in
delegateCalled = true
done()
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
expect(delegateCalled) == true
}
it("can call delegate when player is ready") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
var delegateCalled = false
waitUntil(timeout: 10.0 * tm) { done -> Void in
spy.onPlayerReady = {
delegateCalled = true
done()
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
expect(delegateCalled) == true
}
it("can call delegate when playback finished") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
var delegateCalled = false
waitUntil(timeout: 10.0 * tm) { done -> Void in
spy.onPlaybackFinished = {
delegateCalled = true
done()
}
spy.onPlayerReady = {
videoPlayer.play()
/* Seek to the near ending position. */
videoPlayer.seekTo(position: 58.0)
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
expect(delegateCalled) == true
}
}
describe("can capture still images from video") {
/*
Unfortunately AVPlayerItemVideoOutput is not supported on Simulators.
Enable these tests only for devices.
*/
#if !(arch(i386) || arch(x86_64))
it("can capture one image at a specific timepoint") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
waitUntil(timeout: 10 * tm) { done -> Void in
spy.onPlayerReady = {
videoPlayer.play()
videoPlayer.captureStillImageForHLSMediaItem(atTime: 10.0) { aTime, aImage in
expect(aTime).toNot(beNil())
expect(aImage).toNot(beNil())
done()
}
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
}
it("can capture one image without specifing a timepoint") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
waitUntil(timeout: 10 * tm) { done -> Void in
spy.onPlayerReady = {
videoPlayer.play()
videoPlayer.captureStillImageForHLSMediaItem { aTime, aImage in
expect(aTime).toNot(beNil())
expect(aImage).toNot(beNil())
done()
}
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
}
it("can capture one image outside of valid video duration") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
waitUntil(timeout: 10 * tm) { done -> Void in
spy.onPlayerReady = {
videoPlayer.play()
videoPlayer.captureStillImageForHLSMediaItem(atTime: 120.0) { aTime, aImage in
expect(aTime).toNot(beNil())
expect(aImage).toNot(beNil())
done()
}
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
}
#endif
it("can capture several images with a single call") {
let videoPlayer = TinyVideoPlayer()
let spy = PlayerTestObserver(player: videoPlayer)
waitUntil(timeout: 10 * tm) { done -> Void in
spy.onPlayerReady = {
videoPlayer.play()
done()
}
/* Start player initialization now. */
videoPlayer.switchResourceUrl(url)
}
let timepoints: [Float] = [-15.0, 20.0, 30.0, 120.0]
waitUntil(timeout: 16 * tm) { done -> Void in
var executionRegister = 0
expect{
try videoPlayer.captureStillImageFromCurrentVideoAssets(forTimes: timepoints) { aTime, aImage in
expect(aTime).toNot(beNil())
expect(aImage).toNot(beNil())
executionRegister = executionRegister + 1
if executionRegister == timepoints.count {
done()
}
}
}.toNot(throwError())
}
}
}
}
}
}
|
mit
|
10eb7dfc5ab590c053f41fb92b969084
| 42.681034 | 124 | 0.416371 | 7.104101 | false | false | false | false |
tylyo/APLineChart
|
APLineChart/APChartView/APChartView.swift
|
1
|
22255
|
//
// APChartView.swift
// linechart
//
// Created by Attilio Patania on 20/03/15.
// Copyright (c) 2015 zemirco. All rights reserved.
//
import UIKit
import QuartzCore
// delegate method
protocol APChartViewDelegate {
func didSelectNearDataPoint(_ selectedDots:[String:APChartPoint])
}
@IBDesignable class APChartView:UIView,UIScrollViewDelegate{
var collectionLines:[APChartLine] = []
var collectionMarkers:[APChartMarkerLine] = []
var delegate: APChartViewDelegate!
let labelAxesSize:CGSize = CGSize(width: 35.0, height: 20.0)
var lineLayerStore: [CALayer] = []
@IBInspectable var showAxes:Bool = true
@IBInspectable var titleForX:String = "x axis"
@IBInspectable var titleForY:String = "y axis"
@IBInspectable var axesColor = UIColor(red: 96/255.0, green: 125/255.0, blue: 139/255.0, alpha: 1)
// @IBInspectable var positiveAreaColor = UIColor(red: 246/255.0, green: 153/255.0, blue: 136/255.0, alpha: 1)
// @IBInspectable var negativeAreaColor = UIColor(red: 114/255.0, green: 213/255.0, blue: 114/255.0, alpha: 1)
@IBInspectable var showGrid:Bool = false
@IBInspectable var gridColor = UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1)
@IBInspectable var gridLinesX: CGFloat = 5.0
@IBInspectable var gridLinesY: CGFloat = 5.0
@IBInspectable var showLabelsX:Bool = false
@IBInspectable var showLabelsY:Bool = false
@IBInspectable var showDots:Bool = false
@IBInspectable var dotsBackgroundColor:UIColor = UIColor.white
@IBInspectable var areaUnderLinesVisible:Bool = true
var animationEnabled = true
@IBInspectable var showMean:Bool = false
@IBInspectable var showMeanProgressive:Bool = false
@IBInspectable var showMax:Bool = false
@IBInspectable var showMin:Bool = false
var marginBottom:CGFloat = 50.0
lazy var marginLeft:CGFloat = {
return self.labelAxesSize.width + self.labelAxesSize.height
}()
var marginTop:CGFloat = 25
var marginRight:CGFloat = 25
var animationDuration: CFTimeInterval = 1
let colors: [UIColor] = [
UIColor.fromHex(0x1f77b4),
UIColor.fromHex(0xff7f0e),
UIColor.fromHex(0x2ca02c),
UIColor.fromHex(0xd62728),
UIColor.fromHex(0x9467bd),
UIColor.fromHex(0x8c564b),
UIColor.fromHex(0xe377c2),
UIColor.fromHex(0x7f7f7f),
UIColor.fromHex(0xbcbd22),
UIColor.fromHex(0x17becf)
]
var offsetX: Offset = Offset(min:0.0, max:1.0)
var offsetY: Offset = Offset(min:0.0, max:1.0)
var drawingArea:CGRect = CGRect.zero
var pointBase:CGPoint = CGPoint.zero
var pointZero:CGPoint {
return drawingArea.origin
}
var selectetedXlayer:CAShapeLayer? = nil
var lineMax :APChartMarkerLine?
var lineMin :APChartMarkerLine?
var removeAll: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
let line = APChartLine(chartView: self, title: "mio", lineWidth: 2.0, lineColor: self.colors[1])
line.addPoint( CGPoint(x: 23.0, y: 159.0))
line.addPoint( CGPoint(x: 34.0, y: 137.0))
line.addPoint(CGPoint(x: 36.0, y: 160.0))
line.addPoint(CGPoint(x: 49.0, y: 125.0))
line.addPoint(CGPoint(x: 61.0, y: 140.0))
line.addPoint(CGPoint(x: 72.0, y: 132.0))
line.addPoint(CGPoint(x: 78.0, y: 138.0))
line.addPoint(CGPoint(x: 95.0, y: 138.0))
line.addPoint(CGPoint(x: 98.0, y: 175.0))
line.addPoint(CGPoint(x: 101.0, y: 102.0))
line.addPoint(CGPoint(x: 102.0, y: 92.0))
line.addPoint(CGPoint(x: 115.0, y: 88.0))
self.addLine(line)
_ = APChartMarkerLine(chartView: self, title: "x marker", x: 85.0, lineColor: UIColor.red )
self.addMarkerLine("x marker", x: 85.0 )
self.addMarkerLine("y marker", y: 120.0 )
self.setNeedsDisplay()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func addLine(_ line:APChartLine){
collectionLines.append(line)
}
func addMarkerLine(_ title:String, x:CGFloat) {
let line = APChartMarkerLine(chartView: self, title: title, x: x, lineColor: UIColor.red)
collectionMarkers.append(line)
}
func addMarkerLine(_ title:String, y:CGFloat){
let line = APChartMarkerLine(chartView: self, title: title, y: y, lineColor: UIColor.blue)
collectionMarkers.append(line)
}
override func draw(_ rect: CGRect) {
if removeAll {
let context = UIGraphicsGetCurrentContext()
context?.clear(rect)
return
}
// remove all labels
for view: AnyObject in self.subviews {
view.removeFromSuperview()
}
// remove all lines on device rotation
for lineLayer in lineLayerStore {
lineLayer.removeFromSuperlayer()
}
lineLayerStore.removeAll()
selectetedXlayer?.removeFromSuperlayer()
updateDrawingArea()
drawGrid()
drawAxes()
calculateOffsets()
lineMax = nil
lineMin = nil
if showMax {
lineMax = APChartMarkerLine(chartView: self, title: "Max", y: offsetY.maxValue, lineColor: UIColor.blue)
}
if showMin {
lineMin = APChartMarkerLine(chartView: self, title: "Min", y: offsetY.minValue, lineColor: UIColor.blue)
}
updateLinesDataStoreScaled()
drawXLabels()
drawYLabels()
var _:CAShapeLayer? = nil
for lineData in collectionLines {
lineData.showMeanValue = showMean
lineData.showMeanValueProgressive = showMeanProgressive
if let layer = lineData.drawLine() {
self.layer.addSublayer(layer)
self.lineLayerStore.append(layer)
}
lineData.drawMeanValue()
lineData.drawMeanProgressive()
// draw dots
if showDots {
if let dotsLayer = lineData.drawDots(dotsBackgroundColor) {
for ll in dotsLayer {
self.layer.addSublayer(ll)
self.lineLayerStore.append(ll)
}
}
}
// draw area under line chart
if areaUnderLinesVisible { lineData.drawAreaBeneathLineChart() }
}
if let markerLine = lineMax {
if let layer = markerLine.drawLine() {
self.layer.addSublayer(layer)
self.lineLayerStore.append(layer)
}
}
if let markerLine = lineMin {
if let layer = markerLine.drawLine() {
self.layer.addSublayer(layer)
self.lineLayerStore.append(layer)
}
}
for markerLine in collectionMarkers {
if let layer = markerLine.drawLine() {
self.layer.addSublayer(layer)
self.lineLayerStore.append(layer)
}
}
}
func updateDrawingArea(){
drawingArea = CGRect(x: marginLeft, y: self.bounds.height-marginBottom, width: self.bounds.width - marginLeft - marginRight, height: self.bounds.height - marginTop - marginBottom)
if !showLabelsX {
drawingArea.origin.y = self.bounds.height-self.labelAxesSize.height
drawingArea.size.height = self.bounds.height - self.labelAxesSize.height - marginTop
}
if !showLabelsY {
drawingArea.origin.x = self.labelAxesSize.height
drawingArea.size.width = self.bounds.width - self.labelAxesSize.height - marginRight
}
}
/**
* Draw grid.
*/
func drawGrid() {
if !showGrid {
return
}
drawXGrid()
drawYGrid()
}
/**
* Draw x grid.
*/
func drawXGrid() {
_ = self.bounds.height
_ = self.bounds.width
let space = drawingArea.width / gridLinesX
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(gridColor.cgColor)
var x:CGFloat = drawingArea.origin.x;
var step:CGFloat = 0.0
while step < gridLinesX {
x += space
context?.move(to: CGPoint(x: x, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: x, y: drawingArea.origin.y - drawingArea.height))
step += 1
}
context?.strokePath()
}
/**
* Draw y grid.
*/
func drawYGrid() {
let delta_h = drawingArea.height / gridLinesY
let context = UIGraphicsGetCurrentContext()
var y:CGFloat = drawingArea.origin.y
var step:CGFloat = 0.0
while step < gridLinesY {
y -= delta_h
context?.move(to: CGPoint(x: drawingArea.origin.x, y: y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width, y: y))
step += 1
}
context?.strokePath()
}
/**
* Draw x and y axis.
*/
func drawAxes() {
if (!showAxes){
return
}
let height = self.bounds.height
_ = self.bounds.width
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(axesColor.cgColor)
// draw x-axis
context?.move(to: CGPoint(x: drawingArea.origin.x, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y-4))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5+10, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y+4))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y-4))
context?.strokePath()
// draw y-axis
context?.move(to: CGPoint(x: drawingArea.origin.x, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x, y: marginTop - 5.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x-4.0, y: marginTop - 5.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x, y: marginTop - 5.0 - 10.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x+4.0, y: marginTop - 5.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x-4.0, y: marginTop - 5.0))
context?.strokePath()
let xAxeTitle = UILabel(frame: CGRect(x: pointZero.x, y: height - labelAxesSize.height, width: drawingArea.width, height: labelAxesSize.height))
xAxeTitle.font = UIFont.italicSystemFont(ofSize: 12.0)
xAxeTitle.textAlignment = .right
xAxeTitle.backgroundColor = UIColor.clear
xAxeTitle.text = titleForX
self.addSubview(xAxeTitle)
let yAxeTitle = UILabel(frame: CGRect(x: -labelAxesSize.height, y: pointZero.y, width: drawingArea.height, height: labelAxesSize.height))
yAxeTitle.font = UIFont.italicSystemFont(ofSize: 12.0)
yAxeTitle.textAlignment = .right
yAxeTitle.text = titleForY
yAxeTitle.backgroundColor = UIColor.clear
let yframe = yAxeTitle.frame
yAxeTitle.layer.anchorPoint = CGPoint(x:(yframe.size.height / yframe.size.width * 0.5), y: -0.5) // Anchor points are in unit space
yAxeTitle.frame = yframe; // Moving the anchor point moves the layer's position, this is a simple way to re-set
yAxeTitle.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2)
self.addSubview(yAxeTitle)
}
func drawMarkers() {
if (!showAxes){
return
}
let height = self.bounds.height
_ = self.bounds.width
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(axesColor.cgColor)
// draw x-axis
context?.move(to: CGPoint(x: drawingArea.origin.x, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y-4))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5+10, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y+4))
context?.addLine(to: CGPoint(x: drawingArea.origin.x + drawingArea.width+5, y: drawingArea.origin.y-4))
context?.strokePath()
// draw y-axis
context?.move(to: CGPoint(x: drawingArea.origin.x, y: drawingArea.origin.y))
context?.addLine(to: CGPoint(x: drawingArea.origin.x, y: marginTop - 5.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x-4.0, y: marginTop - 5.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x, y: marginTop - 5.0 - 10.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x+4.0, y: marginTop - 5.0))
context?.addLine(to: CGPoint(x: drawingArea.origin.x-4.0, y: marginTop - 5.0))
context?.strokePath()
let xAxeTitle = UILabel(frame: CGRect(x: pointZero.x, y: height - labelAxesSize.height, width: drawingArea.width, height: labelAxesSize.height))
xAxeTitle.font = UIFont.italicSystemFont(ofSize: 12.0)
xAxeTitle.textAlignment = .right
xAxeTitle.backgroundColor = UIColor.clear
xAxeTitle.text = titleForX
self.addSubview(xAxeTitle)
let yAxeTitle = UILabel(frame: CGRect(x: -labelAxesSize.height, y: pointZero.y, width: drawingArea.height, height: labelAxesSize.height))
yAxeTitle.font = UIFont.italicSystemFont(ofSize: 12.0)
yAxeTitle.textAlignment = .right
yAxeTitle.text = titleForY
yAxeTitle.backgroundColor = UIColor.clear
let yframe = yAxeTitle.frame
yAxeTitle.layer.anchorPoint = CGPoint(x:(yframe.size.height / yframe.size.width * 0.5), y: -0.5) // Anchor points are in unit space
yAxeTitle.frame = yframe; // Moving the anchor point moves the layer's position, this is a simple way to re-set
yAxeTitle.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2)
self.addSubview(yAxeTitle)
}
func calculateOffsets() {
offsetX = Offset(min:0.0, max:1.0)
offsetY = Offset(min:0.0, max:1.0)
if collectionLines.count == 0 {
return
}
if collectionLines[0].dots.count == 0 {
return
}
let p = collectionLines[0].dots[0]
offsetX = Offset(min:p.dot.x, max:p.dot.x )
offsetY = Offset(min:p.dot.y, max:p.dot.y )
for line in collectionLines {
for curr:APChartPoint in line.dots {
offsetX.updateMinMax(curr.dot.x)
offsetY.updateMinMax(curr.dot.y)
}
}
let x = offsetX.delta()/10
offsetX.min -= x
offsetX.max += x
let y = offsetY.delta()/10
offsetY.min -= y
offsetY.max += y
if x > 0.0 && x < offsetX.min {
offsetX.min -= 2*y
}
if y > 0.0 && y < offsetY.min {
offsetY.min -= 2*y
}
}
func updateLinesDataStoreScaled() {
let x_factor = drawingArea.width / ( offsetX.delta()) // - pointZero.x )
let y_factor = drawingArea.height / offsetY.delta()
let factorPoint = CGPoint(x: x_factor, y: y_factor)
pointBase = CGPoint(x: pointZero.x-offsetX.min*x_factor , y: pointZero.y+offsetY.min*y_factor)
for line in collectionLines {
line.updatePoints( factorPoint, offset: pointBase )
}
for line in collectionMarkers {
line.updatePoints( factorPoint, offset: pointBase )
}
lineMin?.updatePoints(factorPoint, offset: pointBase)
lineMax?.updatePoints(factorPoint, offset: pointBase)
}
/**
* Draw x labels.
*/
func drawXLabels() {
if !showLabelsX {
return
}
if (offsetX.min > 0 ){
let label = UILabel(frame: CGRect(x: pointZero.x-6.0, y: pointZero.y+12.0, width: pointZero.x-4.0-16.0, height: 16.0))
label.backgroundColor = UIColor.clear
label.font = UIFont.boldSystemFont(ofSize: 10)
label.textAlignment = NSTextAlignment.left
label.transform = CGAffineTransform(rotationAngle: CGFloat.pi * 7 / 18)
label.sizeToFit()
label.text = "\(offsetX.min.round2dec())"
self.addSubview(label)
}
let delta = drawingArea.width / gridLinesX
let xValue_delta = offsetX.delta() / gridLinesX
var x:CGFloat = pointZero.x
var step:CGFloat = 0.0
while step < gridLinesX {
x += delta
let label = UILabel(frame: CGRect(x: x-12.0, y: pointZero.y+12.0, width: pointZero.x-4.0-16.0, height: 16.0))
label.font = UIFont.boldSystemFont(ofSize: 10)
label.textAlignment = NSTextAlignment.left
label.transform = CGAffineTransform(rotationAngle: CGFloat.pi * 7 / 18)
var textX = offsetX.min + xValue_delta*step
label.text = "\(textX.round2dec())"
label.sizeToFit()
self.addSubview(label)
step += 1
}
}
/**
* Draw y labels.
*/
func drawYLabels() {
if !showLabelsY{
return
}
if (offsetY.min > 0 ) {
let label = UILabel(frame: CGRect(x: 18.0, y: pointZero.y-16.0, width: pointZero.x-4.0-16.0, height: 16.0))
label.font = UIFont.systemFont(ofSize: 10)
label.textAlignment = NSTextAlignment.right
label.text = "\(offsetY.min.round2dec())"
label.sizeToFit()
self.addSubview(label)
}
let delta_h = drawingArea.height / gridLinesY
let yValue_delta = offsetY.delta() / gridLinesY
var y:CGFloat = pointZero.y
var step:CGFloat = 0.0
while step < gridLinesY {
y -= delta_h
let label = UILabel(frame: CGRect(x: 18.0, y: y-8.0, width: pointZero.x-4.0-16.0, height: 16.0))
label.font = UIFont.systemFont(ofSize: 10)
label.textAlignment = NSTextAlignment.right
var textY = yValue_delta*step+offsetY.min
label.text = "\(textY.round2dec())"
label.sizeToFit()
self.addSubview(label)
step += 1
}
}
func getClosetLineDot(_ selectedPoint:CGPoint) -> [String:APChartPoint]?{
var delta:CGFloat = 100000.0
var diff:CGFloat = 0.0
var selectedDot:[String:APChartPoint] = [:]
for line in collectionLines {
delta = 5.0
for (_,dot) in line.dots.enumerated(){
dot.backgroundColor = dotsBackgroundColor
diff = selectedPoint.distanceXFrom(dot.point)
if delta > diff
{
selectedDot[line.title] = dot
delta = diff
}
}
}
for (_, dot) in selectedDot {
dot.backgroundColor = dotsBackgroundColor.lighterColorForColor()
}
return selectedDot
}
/**
* Handle touch events.
*/
func handleTouchEvents(_ touches: Set<NSObject>, withEvent event: UIEvent) {
if (self.collectionLines.isEmpty) { return }
let point: AnyObject! = touches.first
let selectedPoint = point.location(in: self)
let bpath = UIBezierPath()
bpath.move(to: CGPoint(x: selectedPoint.x, y: marginTop))
bpath.addLine(to: CGPoint(x: selectedPoint.x, y: pointZero.y))
selectetedXlayer?.removeFromSuperlayer()
selectetedXlayer = CAShapeLayer()
selectetedXlayer!.frame = self.bounds
selectetedXlayer!.path = bpath.cgPath
selectetedXlayer!.strokeColor = UIColor.purple.cgColor //colors[lineIndex].CGColor
selectetedXlayer!.fillColor = nil
selectetedXlayer!.lineWidth = 1.0
self.layer.addSublayer(selectetedXlayer!)
if let closestDots = getClosetLineDot(selectedPoint) {
delegate?.didSelectNearDataPoint(closestDots)
}
}
/**
* Listen on touch end event.
*/
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if (event != nil) {
handleTouchEvents(touches, withEvent: event!)
}
}
/**
* Listen on touch move event
*/
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if (event != nil) {
handleTouchEvents(touches, withEvent: event!)
}
}
}
class Offset {
var min:CGFloat = 0.0
var max:CGFloat = 1.0
var maxValue:CGFloat = 1.0
var minValue:CGFloat = 0.0
init(min:CGFloat, max:CGFloat){
self.min = min
self.max = max
}
func updateMinMax(_ value:CGFloat){
if self.min > value {
self.min = value
}
if self.max < value {
self.max = value
}
self.maxValue = self.max
self.minValue = self.min
}
func delta() -> CGFloat {
return (self.max - self.min)
}
}
|
mit
|
2c31daec921a61a3ba164979ff844521
| 33.882445 | 189 | 0.581982 | 4.020777 | false | false | false | false |
kylef/CLIKit
|
Tests/CommanderTests/ArgumentParserSpec.swift
|
2
|
5164
|
import Spectre
import Commander
let testArgumentParser: ((ContextType) -> Void) = {
var parser: ArgumentParser!
$0.before {
parser = ArgumentParser(arguments: ["first", "-f", "--verbose", "middle", "end", "--varOption", "varValue1", "--varOption", "varValue2"])
}
$0.after {
parser = nil
}
$0.describe("isEmpty") {
$0.it("returns when not empty") {
parser = ArgumentParser(arguments: [])
try expect(parser.isEmpty).to.beTrue()
}
$0.it("returns when not empty") {
try expect(parser.isEmpty).to.beFalse()
}
$0.it("returns empty when containing empty arguments") {
parser = ArgumentParser(arguments: [""])
try expect(parser.isEmpty).to.beTrue()
}
}
$0.describe("shifting") {
$0.it("provides first positional argument") {
try expect(parser.shift()) == "first"
}
$0.it("removes the shifted positional argument") {
_ = parser.shift()
try expect(parser.shift()) == "middle"
}
}
$0.describe("options") {
$0.it("returns when an option is found") {
try expect(parser.hasOption("verbose")).to.beTrue()
try expect(parser.hasOption("verbose")).to.beFalse()
}
$0.it("returns when an option is not found") {
try expect(parser.hasOption("f")).to.beFalse()
}
}
$0.describe("flags") {
$0.it("returns when a flag is found") {
try expect(parser.hasFlag("f")).to.beTrue()
try expect(parser.hasFlag("f")).to.beFalse()
}
$0.it("returns when a flag is not found") {
try expect(parser.hasFlag("v")).to.beFalse()
}
}
$0.describe("when shifting a flag") {
$0.it("returns the flag value when found") {
parser = ArgumentParser(arguments: ["-o", "value"])
let value = try parser.shiftValue(for: "o" as ArgumentParser.Flag)
try expect(value) == "value"
}
$0.it("removes the flag and it's value") {
parser = ArgumentParser(arguments: ["-o", "value"])
_ = try parser.shiftValue(for: "o" as ArgumentParser.Flag)
try expect(parser.description) == ""
}
}
$0.describe("when shifting an option") {
$0.it("should return the options value") {
let value = try parser.shiftValue(for: "verbose")
try expect(value) == "middle"
}
$0.it("should return nil when option is unknown") {
let value = try parser.shiftValue(for: "unknown")
try expect(value).to.beNil()
}
$0.it("should thrown an error when options value is not positional") {
let parser = ArgumentParser(arguments: ["--verbose", "-t"])
try expect(try parser.shiftValue(for: "verbose")).toThrow(ArgumentParserError("Unexpected flag `-t` as a value for `--verbose`"))
}
$0.it("should throw when value is missing") {
let parser = ArgumentParser(arguments: ["--verbose"])
try expect(try parser.shiftValue(for: "verbose")).toThrow(ArgumentError.missingValue(argument: "--verbose"))
}
$0.it("should return arguments for option") {
let value = try parser.shiftValues(for: "verbose", count: 2)
try expect(value?.count) == 2
try expect(value?.first) == "middle"
try expect(value?.last) == "end"
}
}
$0.describe("variadic options") {
$0.it("should return arguments for option") {
let option = VariadicOption<String>("varOption")
let values = try option.parse(parser)
try expect(values.count) == 2
try expect(values.first) == "varValue1"
try expect(values.last) == "varValue2"
}
$0.it("should return empty array when option is unknown") {
let option = VariadicOption<String>("unknown")
let values = try option.parse(parser)
try expect(values.count) == 0
}
}
$0.describe("positional arguments") {
$0.before {
parser = ArgumentParser(arguments: ["-a", "value1", "--", "-b", "value2"])
}
$0.it("should not count double dash into the arguments") {
try expect(parser.remainder.count) == 4
_ = try parser.shiftValue(for: "a" as ArgumentParser.Flag)
try expect(parser.remainder.count) == 2
}
$0.it("should not parse parameters as flags after the double dash") {
try expect(parser.hasFlag("a" as ArgumentParser.Flag)).to.beTrue()
try expect(parser.hasFlag("b" as ArgumentParser.Flag)).to.beFalse()
_ = try parser.shiftValue(for: "a" as ArgumentParser.Flag)
let value = try parser.shiftValue(for: "b" as ArgumentParser.Flag)
try expect(value).to.beNil()
}
$0.it("should return parameters after the double dash as arguments") {
_ = try parser.shiftValue(for: "a" as ArgumentParser.Flag)
let value1 = parser.shift()
let value2 = parser.shift()
try expect(value1) == "-b"
try expect(value2) == "value2"
}
}
$0.describe("#description") {
$0.it("should maintain flag ordering") {
let parser = ArgumentParser(arguments: ["-user", "-one"])
try expect(parser.description) == "-user -one"
}
}
$0.describe("clear") {
$0.it("clears arguments") {
try expect(parser.isEmpty).to.beFalse()
parser.clear()
try expect(parser.isEmpty).to.beTrue()
}
}
}
|
bsd-3-clause
|
472c053acbfb8aad55f7c0e6f85dd2de
| 29.376471 | 141 | 0.614253 | 3.701792 | false | false | false | false |
radvansky-tomas/NutriFacts
|
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Renderers/RadarChartRenderer.swift
|
6
|
9579
|
//
// RadarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIFont
public class RadarChartRenderer: ChartDataRendererBase
{
internal weak var _chart: RadarChartView!;
public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler);
_chart = chart;
}
public override func drawData(#context: CGContext)
{
if (_chart !== nil)
{
var radarData = _chart.data;
if (radarData != nil)
{
for set in radarData!.dataSets as! [RadarChartDataSet]
{
if (set.isVisible)
{
drawDataSet(context: context, dataSet: set);
}
}
}
}
}
internal func drawDataSet(#context: CGContext, dataSet: RadarChartDataSet)
{
CGContextSaveGState(context);
var sliceangle = _chart.sliceAngle;
// calculate the factor that is needed for transforming the value to pixels
var factor = _chart.factor;
var center = _chart.centerOffsets;
var entries = dataSet.yVals;
var path = CGPathCreateMutable();
for (var j = 0; j < entries.count; j++)
{
var e = entries[j];
var p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value - _chart.chartYMin) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle);
if (j == 0)
{
CGPathMoveToPoint(path, nil, p.x, p.y);
}
else
{
CGPathAddLineToPoint(path, nil, p.x, p.y);
}
}
CGPathCloseSubpath(path);
// draw filled
if (dataSet.isDrawFilledEnabled)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(0).CGColor);
CGContextSetAlpha(context, dataSet.fillAlpha);
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextFillPath(context);
}
// draw the line (only if filled is disabled or alpha is below 255)
if (!dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0)
{
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextSetLineWidth(context, dataSet.lineWidth);
CGContextSetAlpha(context, 1.0);
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextStrokePath(context);
}
CGContextRestoreGState(context);
}
public override func drawValues(#context: CGContext)
{
if (_chart.data === nil)
{
return;
}
var data = _chart.data!;
var defaultValueFormatter = _chart.valueFormatter;
var sliceangle = _chart.sliceAngle;
// calculate the factor that is needed for transforming the value to pixels
var factor = _chart.factor;
var center = _chart.centerOffsets;
var yoffset = CGFloat(5.0);
for (var i = 0, count = data.dataSetCount; i < count; i++)
{
var dataSet = data.getDataSetByIndex(i) as! RadarChartDataSet;
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var entries = dataSet.yVals;
for (var j = 0; j < entries.count; j++)
{
var e = entries[j];
var p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle);
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(e.value)!, point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]);
}
}
}
public override func drawExtras(#context: CGContext)
{
drawWeb(context: context);
}
private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
internal func drawWeb(#context: CGContext)
{
var sliceangle = _chart.sliceAngle;
CGContextSaveGState(context);
// calculate the factor that is needed for transforming the value to
// pixels
var factor = _chart.factor;
var rotationangle = _chart.rotationAngle;
var center = _chart.centerOffsets;
// draw the web lines that come from the center
CGContextSetLineWidth(context, _chart.webLineWidth);
CGContextSetStrokeColorWithColor(context, _chart.webColor.CGColor);
CGContextSetAlpha(context, _chart.webAlpha);
for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++)
{
var p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor, angle: sliceangle * CGFloat(i) + rotationangle);
_webLineSegmentsBuffer[0].x = center.x;
_webLineSegmentsBuffer[0].y = center.y;
_webLineSegmentsBuffer[1].x = p.x;
_webLineSegmentsBuffer[1].y = p.y;
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2);
}
// draw the inner-web
CGContextSetLineWidth(context, _chart.innerWebLineWidth);
CGContextSetStrokeColorWithColor(context, _chart.innerWebColor.CGColor);
CGContextSetAlpha(context, _chart.webAlpha);
var labelCount = _chart.yAxis.entryCount;
for (var j = 0; j < labelCount; j++)
{
for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++)
{
var r = CGFloat(_chart.yAxis.entries[j] - _chart.chartYMin) * factor;
var p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle);
var p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle);
_webLineSegmentsBuffer[0].x = p1.x;
_webLineSegmentsBuffer[0].y = p1.y;
_webLineSegmentsBuffer[1].x = p2.x;
_webLineSegmentsBuffer[1].y = p2.y;
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2);
}
}
CGContextRestoreGState(context);
}
private var _lineSegments = [CGPoint](count: 4, repeatedValue: CGPoint());
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
if (_chart.data === nil)
{
return;
}
var data = _chart.data as! RadarChartData;
CGContextSaveGState(context);
CGContextSetLineWidth(context, data.highlightLineWidth);
if (data.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var sliceangle = _chart.sliceAngle;
var factor = _chart.factor;
var center = _chart.centerOffsets;
for (var i = 0; i < indices.count; i++)
{
var set = _chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as! RadarChartDataSet!;
if (set === nil)
{
continue;
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor);
// get the index to highlight
var xIndex = indices[i].xIndex;
var e = set.entryForXIndex(xIndex);
var j = set.entryIndex(entry: e, isEqual: true);
var y = (e.value - _chart.chartYMin);
var p = ChartUtils.getPosition(center: center, dist: CGFloat(y) * factor,
angle: sliceangle * CGFloat(j) + _chart.rotationAngle);
_lineSegments[0] = CGPoint(x: p.x, y: 0.0)
_lineSegments[1] = CGPoint(x: p.x, y: viewPortHandler.chartHeight)
_lineSegments[2] = CGPoint(x: 0.0, y: p.y)
_lineSegments[3] = CGPoint(x: viewPortHandler.chartWidth, y: p.y)
CGContextStrokeLineSegments(context, _lineSegments, 4);
}
CGContextRestoreGState(context);
}
}
|
gpl-2.0
|
8580a039bf6ee04d6dd382032254989a
| 33.214286 | 274 | 0.550579 | 5.21448 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.