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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aestesis/Aether
|
Project/sources/Media/FlacPicture.swift
|
1
|
2855
|
//
// FlacPicture.swift
// Alib
//
// Created by renan jegouzo on 16/07/2016.
// Copyright © 2016 aestesis. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
// format: https://xiph.org/flac/format.html#metadata_block_picture
public class FlacPicture : NodeUI {
public static func get(parent:NodeUI, base64 b64:String) -> Bitmap? {
var base64 = b64
let n = base64.length & 3
if n != 0 {
base64 += "===="[n...3]
}
if let data = Data(base64Encoded: base64) {
let s = DataReader(data: data)
let r = UTF8Reader(bigEndian: true)
s.pipe(to: r)
let type = PictureType(rawValue: r.readUInt32()!)!
let ml = r.readUInt32()!
let mt = r.read(Int(ml))!
let mime = String(bytes: mt, encoding: .ascii)!
let dl = r.readUInt32()!
var desc = ""
if dl>0 {
let dt = r.read(Int(dl))!
desc = String(bytes: dt, encoding: .ascii)!
}
let _ = Int(r.readUInt32()!) // width or 0
let _ = Int(r.readUInt32()!) // height or 0
let depth = r.readUInt32()!
let cidx = r.readUInt32()!
let pictsize = r.readUInt32()!
let d = r.read(Int(pictsize))!
let b = Bitmap(parent: parent, data: d)
b["mime"] = mime
b["description"] = desc
b["depth"] = depth
b["idx"] = cidx
b["type"] = type
return Bitmap(parent: parent, data: d)
} else {
Debug.error("not a base64 string",#file,#line)
}
return nil
}
public enum PictureType : UInt32
{
case other = 0
case pngIcon = 1
case otherIcon = 2
case coverFront = 3
case coverBack = 4
case leaflet = 5
case media = 6
case leadArtist = 7
case artist = 8
case conductor = 9
case band = 10
case composer = 11
case lyricist = 12
case recordingLocation = 13
case recording = 14
case performance = 15
case screenCapture = 16
case fish = 17
case illustration = 18
case logo = 19
case publisher = 20
}
}
|
apache-2.0
|
667d3ae56375b0cc33725a44a1e40e40
| 31.431818 | 76 | 0.547302 | 3.952909 | false | false | false | false |
Onix-Systems/RainyRefreshControl
|
Sources/RainyRefreshControl.swift
|
2
|
2804
|
//
// RainyRefreshControl.swift
// RainyRefreshControl
//
// Created by Anton Dolzhenko on 14.11.16.
// Copyright © 2016 Onix Systems. All rights reserved.
//
import UIKit
import SpriteKit
public final class RainyRefreshControl: ONXRefreshControl {
private var backgroundView: SKView!
var bgColor = UIColor(red: 85.0/255.0, green: 74.0/255.0, blue: 99.0/255.0, alpha: 1)
private var scene: RainScene?
private var umbrellaView: UmbrellaView!
private var thresholdValue: CGFloat = 100.0
override public func setup() {
delayBeforeEnd = 0.2
backgroundView = SKView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
backgroundView.backgroundColor = bgColor
addSubview(backgroundView)
backgroundView.showsFPS = false
backgroundView.showsNodeCount = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
backgroundView.ignoresSiblingOrder = true
scene = RainScene(size: backgroundView.bounds.size)
// Configure the view.
scene?.backgroundColor = bgColor
/* Set the scale mode to scale to fit the window */
scene?.scaleMode = .aspectFill
scene?.particles.particleBirthRate = 0
backgroundView.presentScene(scene)
let width = backgroundView.frame.height*0.6
umbrellaView = UmbrellaView(frame: CGRect(x: 0, y: 0, width: width, height: width))
umbrellaView.strokeColor = UIColor.white
umbrellaView.lineWidth = 1
umbrellaView.backgroundColor = UIColor.clear
addSubview(umbrellaView)
}
override public func layout() {
backgroundView.frame = bounds
scene?.size = bounds.size
scene?.layout()
let width = thresholdValue*0.36
umbrellaView.frame = CGRect(x: 0, y: 0, width: width, height: width)
umbrellaView.center = CGPoint(x: center.x, y: backgroundView.frame.height-thresholdValue/2)
}
override public func didBeginRefresh() {
scene?.particles.particleBirthRate = 766
scene?.particles.resetSimulation()
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
CATransaction.commit()
self.umbrellaView.setButtonState(state: .opened, animated: true)
}
override public func willEndRefresh() {
scene?.particles.particleBirthRate = 0
scene?.particles.resetSimulation()
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
CATransaction.commit()
self.umbrellaView.setButtonState(state: .closed, animated: true)
}
}
|
mit
|
499f3f25165c3271ae9f02c43c4fd0d5
| 34.935897 | 100 | 0.662504 | 4.758913 | false | false | false | false |
GraphKit/MaterialKit
|
Sources/iOS/StatusBarController.swift
|
3
|
3984
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
extension UIViewController {
/**
A convenience property that provides access to the StatusBarController.
This is the recommended method of accessing the StatusBarController
through child UIViewControllers.
*/
public var statusBarController: StatusBarController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is StatusBarController {
return viewController as? StatusBarController
}
viewController = viewController?.parent
}
return nil
}
}
open class StatusBarController: RootController {
/// Device status bar style.
open var statusBarStyle: UIStatusBarStyle {
get {
return Application.statusBarStyle
}
set(value) {
Application.statusBarStyle = value
}
}
/// Device visibility state.
open var isStatusBarHidden: Bool {
get {
return Application.isStatusBarHidden
}
set(value) {
Application.isStatusBarHidden = value
statusBar.isHidden = isStatusBarHidden
}
}
/// A boolean that indicates to hide the statusBar on rotation.
open var shouldHideStatusBarOnRotation = true
/// A reference to the statusBar.
open let statusBar = UIView()
/**
To execute in the order of the layout chain, override this
method. LayoutSubviews should be called immediately, unless you
have a certain need.
*/
open override func layoutSubviews() {
super.layoutSubviews()
if shouldHideStatusBarOnRotation {
statusBar.isHidden = Application.shouldStatusBarBeHidden
}
statusBar.width = view.width
rootViewController.view.frame = view.bounds
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
prepareStatusBar()
}
}
extension StatusBarController {
/// Prepares the statusBar.
fileprivate func prepareStatusBar() {
statusBar.backgroundColor = .white
statusBar.height = 20
view.addSubview(statusBar)
}
}
|
agpl-3.0
|
c314e1ae451bce7ab5ceee6f34073db3
| 33.947368 | 88 | 0.711345 | 5.005025 | false | false | false | false |
ming1016/smck
|
smck/Lib/RxSwift/Observable+Creation.swift
|
16
|
9910
|
//
// Observable+Creation.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension Observable {
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
// MARK: empty
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> Observable<E> {
return Empty<E>()
}
// MARK: never
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> Observable<E> {
return Never()
}
// MARK: just
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: E) -> Observable<E> {
return Just(element: element)
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return JustScheduled(element: element, scheduler: scheduler)
}
// MARK: fail
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> Observable<E> {
return Error(error: error)
}
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: elements, scheduler: scheduler)
}
// MARK: defer
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> Observable<E>)
-> Observable<E> {
return Deferred(observableFactory: observableFactory)
}
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html)
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
public static func repeatElement(_ element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
public static func using<R: Disposable>(_ resourceFactory: @escaping () throws -> R, observableFactory: @escaping (R) throws -> Observable<E>) -> Observable<E> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
}
extension Observable where Element : SignedInteger {
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RangeProducer<E>(start: start, count: count, scheduler: scheduler)
}
}
extension Observable {
/**
Converts an array to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: array, scheduler: scheduler)
}
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<S: Sequence>(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> where S.Iterator.Element == E {
return ObservableSequence(elements: sequence, scheduler: scheduler)
}
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
public static func from(_ optional: E?) -> Observable<E> {
return ObservableOptional(optional: optional)
}
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- parameter: Scheduler to send the optional element on.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
public static func from(_ optional: E?, scheduler: ImmediateSchedulerType) -> Observable<E> {
return ObservableOptionalScheduled(optional: optional, scheduler: scheduler)
}
}
|
apache-2.0
|
7d47bd82c406ff253b9380a06203b171
| 42.845133 | 213 | 0.721062 | 4.996974 | false | false | false | false |
victorchee/CustomTransition
|
CustomTransition/CustomTransition/DetailViewController.swift
|
1
|
2020
|
//
// DetailViewController.swift
// CustomTransition
//
// Created by qihaijun on 11/4/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UINavigationControllerDelegate {
@IBOutlet weak var label: UILabel!
private var percentDrivenTransition: UIPercentDrivenInteractiveTransition?
@IBAction func edgePan(_ sender: UIScreenEdgePanGestureRecognizer) {
let progress = sender.translation(in: view).x / view.bounds.width
if sender.state == .began {
percentDrivenTransition = UIPercentDrivenInteractiveTransition()
navigationController?.popViewController(animated: true)
} else if sender.state == .changed {
percentDrivenTransition?.update(progress)
} else if sender.state == .cancelled || sender.state == .ended {
if progress > 0.5 {
percentDrivenTransition?.finish()
} else {
percentDrivenTransition?.cancel()
}
percentDrivenTransition = nil
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.delegate = self
}
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .pop {
return CustomPopTransition()
} else {
return nil
}
}
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if animationController is CustomPopTransition {
return percentDrivenTransition
} else {
return nil
}
}
}
|
mit
|
735f2e01fb37fc9199b10f9147c9723c
| 36.388889 | 246 | 0.677563 | 6.533981 | false | false | false | false |
esttorhe/RxSwift
|
RxSwift/RxSwift/Observables/Implementations/Debug.swift
|
1
|
1641
|
//
// Debug.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Debug_<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.Element
typealias Parent = Debug<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
let maxEventTextLength = 40
let eventText = "\(event)"
let eventNormalized = eventText.characters.count > maxEventTextLength
? String(prefix(eventText.characters, maxEventTextLength / 2)) + "..." + String(suffix(eventText.characters, maxEventTextLength / 2))
: eventText
print("Event \(eventNormalized) @ observer \(self) [\(parent.identifier)]")
trySend(observer, event)
}
override func dispose() {
print("Disposing observer \(self) [\(parent.identifier)]")
super.dispose()
}
}
class Debug<Element> : Producer<Element> {
let identifier: String
let source: Observable<Element>
init(identifier: String, source: Observable<Element>) {
self.identifier = identifier
self.source = source
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = Debug_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return self.source.subscribeSafe(sink)
}
}
|
mit
|
31532b861840be3e584eb037483ab4e3
| 29.981132 | 145 | 0.635588 | 4.295812 | false | false | false | false |
leotao2014/RTPhotoBrowser
|
RTPhotoBrowser/PhotoSelectVC.swift
|
1
|
6237
|
//
// PhotoSelectVC.swift
// RTPhotoBrowser
//
// Created by leotao on 2017/2/26.
// Copyright © 2017年 leotao. All rights reserved.
//
import UIKit
import Kingfisher
class PhotoSelectVC: UIViewController {
var photos = [PhotoModel]();
var collectionView:UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
setup();
}
func setup() {
let layout = UICollectionViewFlowLayout();
collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout);
collectionView.delegate = self;
collectionView.dataSource = self;
collectionView.register(ImageCell.self, forCellWithReuseIdentifier: "image");
self.view.addSubview(collectionView);
collectionView.backgroundColor = UIColor.white;
let urls: [Dictionary<String, String>] = [
[
"thumbnail": "https://wx3.sinaimg.cn/orj360/a17004b2gy1gehlhsjj61j20u01hc120.jp",
"large": "https://photo.weibo.com/2708473010/wbphotos/large/mid/4501241004504614/pid/a17004b2gy1gehlhsjj61j20u01hc120"],
[
"thumbnail": "https://wx3.sinaimg.cn/mw690/bc52b9dfly1gehbgbfdhwj20j60qvq8j.jpg",
"large": "https://wx3.sinaimg.cn/large/bc52b9dfly1gehbgbfdhwj20j60qvq8j.jpg"],
[
"thumbnail": "https://wx2.sinaimg.cn/mw690/bc52b9dfly1gehbgbz3ptj20j60sswl2.jpg",
"large": "https://wx2.sinaimg.cn/large/bc52b9dfly1gehbgbz3ptj20j60sswl2.jpg"],
[
"thumbnail": "https://wx4.sinaimg.cn/mw690/bc52b9dfly1gehbgd5xsoj20j60rmq9v.jpg",
"large": "https://wx4.sinaimg.cn/large/bc52b9dfly1gehbgd5xsoj20j60rmq9v.jpg"],
[
"thumbnail": "https://wx3.sinaimg.cn/mw690/bc52b9dfly1gehbgdubwsj20j60tdn3r.jpg",
"large": "https://wx3.sinaimg.cn/large/bc52b9dfly1gehbgdubwsj20j60tdn3r.jpg"],
[
"thumbnail": "https://wx4.sinaimg.cn/mw690/bc52b9dfly1gehbgetb6nj20j60s6gsg.jpg",
"large": "https://wx4.sinaimg.cn/large/bc52b9dfly1gehbgetb6nj20j60s6gsg.jpg"],
[
"thumbnail": "https://wx3.sinaimg.cn/mw690/bc52b9dfly1gehbgftkfhj20j60srq5x.jpg",
"large": "https://wx3.sinaimg.cn/large/bc52b9dfly1gehbgftkfhj20j60srq5x.jpg"],
[
"thumbnail": "https://wx4.sinaimg.cn/mw690/bc52b9dfly1gegps3uujgj20rs0rs0u7.jpg",
"large": "https://wx4.sinaimg.cn/large/bc52b9dfly1gegps3uujgj20rs0rs0u7.jpg"],
[
"thumbnail": "https://wx1.sinaimg.cn/mw690/94d9c01fly1gehgoot8uaj20h808maan.jpg",
"large": "https://wx1.sinaimg.cn/mw1024/94d9c01fly1gehgoot8uaj20h808maan.jpg"]
];
photos = urls.map({ (dict) -> PhotoModel in
let model = PhotoModel()
model.picUrl = dict["thumbnail", default: ""]
model.highQualityUrl = dict["large", default: ""]
return model
})
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
self.collectionView.frame = self.view.bounds;
self.collectionView.reloadData();
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default;
}
deinit {
ImageCache.default.clearMemoryCache();
print("dealloc - PhotoSelectVC");
}
}
extension PhotoSelectVC: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let _ = RTPhotoBrowser.show(initialIndex: indexPath.item, delegate: self, prsentedVC: self);
}
}
extension PhotoSelectVC: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos.count;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "image", for: indexPath) as! ImageCell;
let photo = self.photos[indexPath.item];
cell.imageUrl = photo.picUrl;
return cell;
}
}
let margin:CGFloat = 10.0;
extension PhotoSelectVC: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let col = 3;
let width = (UIScreen.main.bounds.width - margin * (CGFloat(col) + 1.0)) / CGFloat(col);
let size = CGSize(width: floor(width) , height: floor(width));
return size;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10.0;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 10, left: 10, bottom: 0, right: 10);
}
}
extension PhotoSelectVC: RTPhotoBrowserDelegate {
func rt_numberOfPhotosForBrowser(browser: RTPhotoBrowser) -> Int {
return self.photos.count;
}
func rt_picUrlsForIndex(index: Int, browser: RTPhotoBrowser) -> (picUrl: String, originalPicUrl: String?) {
let photo = self.photos[index];
return (photo.picUrl, photo.highQualityUrl);
}
func rt_thumnailView(atIndex index: Int, browser: RTPhotoBrowser) -> UIView? {
let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) as? ImageCell;
return cell?.imageView;
}
func rt_previewImage(atIndex index: Int, browser: RTPhotoBrowser) -> UIImage? {
let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) as? ImageCell;
return cell?.imageView.image;
}
func rt_heightForFooterView(atIndex index: Int, browser: RTPhotoBrowser) -> CGFloat {
if index % 2 == 0 {
return 88;
} else {
return 150;
}
}
}
|
apache-2.0
|
b621337139a97aae1e13f917701d9d1e
| 38.961538 | 170 | 0.657042 | 3.819853 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/Swiftz/Sources/Swiftz/State.swift
|
3
|
6276
|
//
// State.swift
// Swiftz
//
// Created by Robert Widmann on 2/21/15.
// Copyright (c) 2015-2016 TypeLift. All rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
/// The State Monad represents a computation that threads a piece of state
/// through each step.
public struct State<S, A> {
public let runState : (S) -> (A, S)
/// Creates a new State Monad given a function from a piece of state to a
/// value and an updated state.
public init(_ runState : @escaping (S) -> (A, S)) {
self.runState = runState
}
/// Evaluates the computation given an initial state then returns a final
/// value after running each step.
public func eval(_ s : S) -> A {
return self.runState(s).0
}
/// Evaluates the computation given an initial state then returns the final
/// state after running each step.
public func exec(_ s : S) -> S {
return self.runState(s).1
}
/// Executes an action that can modify the inner state.
public func withState(_ f : @escaping (S) -> S) -> State<S, A> {
return State(self.runState • f)
}
}
/// Fetches the current value of the state.
public func get<S>() -> State<S, S> {
return State<S, S> { ($0, $0) }
}
/// Sets the state.
public func put<S>(s : S) -> State<S, ()> {
return State<S, ()> { _ in ((), s) }
}
/// Gets a specific component of the state using a projection function.
public func gets<S, A>(_ f : @escaping (S) -> A) -> State<S, A> {
return State { s in (f(s), s) }
}
/// Updates the state with the result of executing the given function.
public func modify<S>(_ f : @escaping (S) -> S) -> State<S, ()> {
return State<S, ()> { s in ((), f(s)) }
}
extension State /*: Functor*/ {
public typealias B = Any
public typealias FB = State<S, B>
public func fmap<B>(_ f : @escaping (A) -> B) -> State<S, B> {
return State<S, B> { s in
let (val, st2) = self.runState(s)
return (f(val), st2)
}
}
}
public func <^> <S, A, B>(_ f : @escaping (A) -> B, s : State<S, A>) -> State<S, B> {
return s.fmap(f)
}
extension State /*: Pointed*/ {
public static func pure(_ x : A) -> State<S, A> {
return State { s in (x, s) }
}
}
extension State /*: Applicative*/ {
public typealias FAB = State<S, (A) -> B>
public func ap<B>(_ stfn : State<S, (A) -> B>) -> State<S, B> {
return stfn.bind { f in
return self.bind { a in
return State<S, B>.pure(f(a))
}
}
}
}
public func <*> <S, A, B>(_ f : State<S, (A) -> B> , s : State<S, A>) -> State<S, B> {
return s.ap(f)
}
extension State /*: Cartesian*/ {
public typealias FTOP = State<S, ()>
public typealias FTAB = State<S, (A, B)>
public typealias FTABC = State<S, (A, B, C)>
public typealias FTABCD = State<S, (A, B, C, D)>
public static var unit : State<S, ()> { return State<S, ()> { s in ((), s) } }
public func product<B>(r : State<S, B>) -> State<S, (A, B)> {
return State<S, (A, B)> { c in
let (d, _) = r.runState(c)
let (e, f) = self.runState(c)
return ((e, d), f)
}
}
public func product<B, C>(r : State<S, B>, _ s : State<S, C>) -> State<S, (A, B, C)> {
return State<S, (A, B, C)> { c in
let (d, _) = s.runState(c)
let (e, _) = r.runState(c)
let (f, g) = self.runState(c)
return ((f, e, d), g)
}
}
public func product<B, C, D>(r : State<S, B>, _ s : State<S, C>, _ t : State<S, D>) -> State<S, (A, B, C, D)> {
return State<S, (A, B, C, D)> { c in
let (d, _) = t.runState(c)
let (e, _) = s.runState(c)
let (f, _) = r.runState(c)
let (g, h) = self.runState(c)
return ((g, f, e, d), h)
}
}
}
extension State /*: ApplicativeOps*/ {
public typealias C = Any
public typealias FC = State<S, C>
public typealias D = Any
public typealias FD = State<S, D>
public static func liftA<B>(_ f : @escaping (A) -> B) -> (State<S, A>) -> State<S, B> {
return { (a : State<S, A>) -> State<S, B> in State<S, (A) -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (State<S, A>) -> (State<S, B>) -> State<S, C> {
return { (a : State<S, A>) -> (State<S, B>) -> State<S, C> in { (b : State<S, B>) -> State<S, C> in f <^> a <*> b } }
}
public static func liftA3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (State<S, A>) -> (State<S, B>) -> (State<S, C>) -> State<S, D> {
return { (a : State<S, A>) -> (State<S, B>) -> (State<S, C>) -> State<S, D> in { (b : State<S, B>) -> (State<S, C>) -> State<S, D> in { (c : State<S, C>) -> State<S, D> in f <^> a <*> b <*> c } } }
}
}
extension State /*: Monad*/ {
public func bind<B>(_ f : @escaping (A) -> State<S, B>) -> State<S, B> {
return State<S, B> { s in
let (a, s2) = self.runState(s)
return f(a).runState(s2)
}
}
}
public func >>- <S, A, B>(xs : State<S, A>, f : @escaping (A) -> State<S, B>) -> State<S, B> {
return xs.bind(f)
}
extension State /*: MonadOps*/ {
public static func liftM<B>(_ f : @escaping (A) -> B) -> (State<S, A>) -> State<S, B> {
return { (m1 : State<S, A>) -> State<S, B> in m1 >>- { (x1 : A) in State<S, B>.pure(f(x1)) } }
}
public static func liftM2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (State<S, A>) -> (State<S, B>) -> State<S, C> {
return { (m1 : State<S, A>) -> (State<S, B>) -> State<S, C> in { (m2 : State<S, B>) -> State<S, C> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in State<S, C>.pure(f(x1)(x2)) } } } }
}
public static func liftM3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (State<S, A>) -> (State<S, B>) -> (State<S, C>) -> State<S, D> {
return { (m1 : State<S, A>) -> (State<S, B>) -> (State<S, C>) -> State<S, D> in { (m2 : State<S, B>) -> (State<S, C>) -> State<S, D> in { (m3 : State<S, C>) -> State<S, D> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in m3 >>- { (x3 : C) in State<S, D>.pure(f(x1)(x2)(x3)) } } } } } }
}
}
public func >>->> <S, A, B, C>(_ f : @escaping (A) -> State<S, B>, g : @escaping (B) -> State<S, C>) -> ((A) -> State<S, C>) {
return { x in f(x) >>- g }
}
public func <<-<< <S, A, B, C>(g : @escaping (B) -> State<S, C>, f : @escaping (A) -> State<S, B>) -> ((A) -> State<S, C>) {
return f >>->> g
}
public func sequence<S, A>(_ ms : [State<S, A>]) -> State<S, [A]> {
return ms.reduce(State<S, [A]>.pure([]), { n, m in
return n.bind { xs in
return m.bind { x in
return State<S, [A]>.pure(xs + [x])
}
}
})
}
|
apache-2.0
|
f21bda2e5847dae42571e2045f43800d
| 30.527638 | 283 | 0.53124 | 2.457501 | false | false | false | false |
gabrielPeart/SimpleChat
|
SimpleChat/LGSimpleChat/LGSimpleChat.swift
|
4
|
33100
|
//
// SimpleChatController.swift
// SimpleChat
//
// Created by Logan Wright on 10/16/14.
// Copyright (c) 2014 Logan Wright. All rights reserved.
//
/*
Mozilla Public License
Version 2.0
https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)
*/
import UIKit
// MARK: Message
class LGChatMessage : NSObject {
enum SentBy : String {
case User = "LGChatMessageSentByUser"
case Opponent = "LGChatMessageSentByOpponent"
}
// MARK: ObjC Compatibility
/*
ObjC can't interact w/ enums properly, so this is used for converting compatible values.
*/
class func SentByUserString() -> String {
return LGChatMessage.SentBy.User.rawValue
}
class func SentByOpponentString() -> String {
return LGChatMessage.SentBy.Opponent.rawValue
}
var sentByString: String {
get {
return sentBy.rawValue
}
set {
if let sentBy = SentBy(rawValue: newValue) {
self.sentBy = sentBy
} else {
println("LGChatMessage.FatalError : Property Set : Incompatible string set to SentByString!")
}
}
}
// MARK: Public Properties
var sentBy: SentBy
var content: String
var timeStamp: NSTimeInterval?
required init (content: String, sentBy: SentBy, timeStamp: NSTimeInterval? = nil){
self.sentBy = sentBy
self.timeStamp = timeStamp
self.content = content
}
// MARK: ObjC Compatibility
convenience init (content: String, sentByString: String) {
if let sentBy = SentBy(rawValue: sentByString) {
self.init(content: content, sentBy: sentBy, timeStamp: nil)
} else {
fatalError("LGChatMessage.FatalError : Initialization : Incompatible string set to SentByString!")
}
}
convenience init (content: String, sentByString: String, timeStamp: NSTimeInterval) {
if let sentBy = SentBy(rawValue: sentByString) {
self.init(content: content, sentBy: sentBy, timeStamp: timeStamp)
} else {
fatalError("LGChatMessage.FatalError : Initialization : Incompatible string set to SentByString!")
}
}
}
// MARK: Message Cell
class LGChatMessageCell : UITableViewCell {
// MARK: Global MessageCell Appearance Modifier
struct Appearance {
static var opponentColor = UIColor(red: 0.142954, green: 0.60323, blue: 0.862548, alpha: 0.88)
static var userColor = UIColor(red: 0.14726, green: 0.838161, blue: 0.533935, alpha: 1)
static var font: UIFont = UIFont.systemFontOfSize(17.0)
}
/*
These methods are included for ObjC compatibility. If using Swift, you can set the Appearance variables directly.
*/
class func setAppearanceOpponentColor(opponentColor: UIColor) {
Appearance.opponentColor = opponentColor
}
class func setAppearanceUserColor(userColor: UIColor) {
Appearance.userColor = userColor
}
class func setAppearanceFont(font: UIFont) {
Appearance.font = font
}
// MARK: Message Bubble TextView
private lazy var textView: MessageBubbleTextView = {
let textView = MessageBubbleTextView(frame: CGRectZero, textContainer: nil)
self.contentView.addSubview(textView)
return textView
}()
private class MessageBubbleTextView : UITextView {
override init(frame: CGRect = CGRectZero, textContainer: NSTextContainer? = nil) {
super.init(frame: frame, textContainer: textContainer)
self.font = Appearance.font
self.scrollEnabled = false
self.editable = false
self.textContainerInset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7)
self.layer.cornerRadius = 15
self.layer.borderWidth = 2.0
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: ImageView
private lazy var opponentImageView: UIImageView = {
let opponentImageView = UIImageView()
opponentImageView.hidden = true
opponentImageView.bounds.size = CGSize(width: self.minimumHeight, height: self.minimumHeight)
let halfWidth = CGRectGetWidth(opponentImageView.bounds) / 2.0
let halfHeight = CGRectGetHeight(opponentImageView.bounds) / 2.0
// Center the imageview vertically to the textView when it is singleLine
let textViewSingleLineCenter = self.textView.textContainerInset.top + (Appearance.font.lineHeight / 2.0)
opponentImageView.center = CGPointMake(self.padding + halfWidth, textViewSingleLineCenter)
opponentImageView.backgroundColor = UIColor.lightTextColor()
opponentImageView.layer.rasterizationScale = UIScreen.mainScreen().scale
opponentImageView.layer.shouldRasterize = true
opponentImageView.layer.cornerRadius = halfHeight
opponentImageView.layer.masksToBounds = true
self.contentView.addSubview(opponentImageView)
return opponentImageView
}()
// MARK: Sizing
private let padding: CGFloat = 5.0
private let minimumHeight: CGFloat = 30.0 // arbitrary minimum height
private var size = CGSizeZero
private var maxSize: CGSize {
get {
let maxWidth = CGRectGetWidth(self.bounds) * 0.75 // Cells can take up to 3/4 of screen
let maxHeight = CGFloat.max
return CGSize(width: maxWidth, height: maxHeight)
}
}
// MARK: Setup Call
/*!
Use this in cellForRowAtIndexPath to setup the cell.
*/
func setupWithMessage(message: LGChatMessage) -> CGSize {
textView.text = message.content
size = textView.sizeThatFits(maxSize)
if size.height < minimumHeight {
size.height = minimumHeight
}
textView.bounds.size = size
self.styleTextViewForSentBy(message.sentBy)
return size
}
// MARK: TextBubble Styling
private func styleTextViewForSentBy(sentBy: LGChatMessage.SentBy) {
let halfTextViewWidth = CGRectGetWidth(self.textView.bounds) / 2.0
let targetX = halfTextViewWidth + padding
let halfTextViewHeight = CGRectGetHeight(self.textView.bounds) / 2.0
switch sentBy {
case .Opponent:
self.textView.center.x = targetX
self.textView.center.y = halfTextViewHeight
self.textView.layer.borderColor = Appearance.opponentColor.CGColor
if self.opponentImageView.image != nil {
self.opponentImageView.hidden = false
self.textView.center.x += CGRectGetWidth(self.opponentImageView.bounds) + padding
}
case .User:
self.opponentImageView.hidden = true
self.textView.center.x = CGRectGetWidth(self.bounds) - targetX
self.textView.center.y = halfTextViewHeight
self.textView.layer.borderColor = Appearance.userColor.CGColor
}
}
}
// MARK: Chat Controller
@objc protocol LGChatControllerDelegate {
optional func shouldChatController(chatController: LGChatController, addMessage message: LGChatMessage) -> Bool
optional func chatController(chatController: LGChatController, didAddNewMessage message: LGChatMessage)
}
class LGChatController : UIViewController, UITableViewDelegate, UITableViewDataSource, LGChatInputDelegate {
// MARK: Constants
private struct Constants {
static let MessagesSection: Int = 0;
static let MessageCellIdentifier: String = "LGChatController.Constants.MessageCellIdentifier"
}
// MARK: Public Properties
/*!
Use this to set the messages to be displayed
*/
var messages: [LGChatMessage] = []
var opponentImage: UIImage?
weak var delegate: LGChatControllerDelegate?
// MARK: Private Properties
private let sizingCell = LGChatMessageCell()
private let tableView: UITableView = UITableView()
private let chatInput = LGChatInput(frame: CGRectZero)
private var bottomChatInputConstraint: NSLayoutConstraint!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.listenForKeyboardChanges()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.scrollToBottom()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.unregisterKeyboardObservers()
}
deinit {
/*
Need to remove delegate and datasource or they will try to send scrollView messages.
*/
self.tableView.delegate = nil
self.tableView.dataSource = nil
}
// MARK: Setup
private func setup() {
self.setupTableView()
self.setupChatInput()
self.setupLayoutConstraints()
}
private func setupTableView() {
tableView.allowsSelection = false
tableView.separatorStyle = .None
tableView.frame = self.view.bounds
tableView.registerClass(LGChatMessageCell.classForCoder(), forCellReuseIdentifier: "identifier")
tableView.delegate = self
tableView.dataSource = self
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
self.view.addSubview(tableView)
}
private func setupChatInput() {
chatInput.delegate = self
self.view.addSubview(chatInput)
}
private func setupLayoutConstraints() {
chatInput.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addConstraints(self.chatInputConstraints())
self.view.addConstraints(self.tableViewConstraints())
}
private func chatInputConstraints() -> [NSLayoutConstraint] {
self.bottomChatInputConstraint = NSLayoutConstraint(item: chatInput, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
let leftConstraint = NSLayoutConstraint(item: chatInput, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: chatInput, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0)
return [leftConstraint, self.bottomChatInputConstraint, rightConstraint]
}
private func tableViewConstraints() -> [NSLayoutConstraint] {
let leftConstraint = NSLayoutConstraint(item: tableView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: tableView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0)
let topConstraint = NSLayoutConstraint(item: tableView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: chatInput, attribute: .Top, multiplier: 1.0, constant: 0)
return [rightConstraint, leftConstraint, topConstraint, bottomConstraint]//, rightConstraint, bottomConstraint]
}
// MARK: Keyboard Notifications
private func listenForKeyboardChanges() {
let defaultCenter = NSNotificationCenter.defaultCenter()
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
defaultCenter.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
defaultCenter.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
} else {
defaultCenter.addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
}
private func unregisterKeyboardObservers() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: iOS 8 Keyboard Animations
func keyboardWillChangeFrame(note: NSNotification) {
/*
NOTE: For iOS 8 Only, will cause autolayout issues in iOS 7
*/
let keyboardAnimationDetail = note.userInfo!
let duration = keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
var keyboardFrame = (keyboardAnimationDetail[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
if let window = self.view.window {
keyboardFrame = window.convertRect(keyboardFrame, toView: self.view)
}
let animationCurve = keyboardAnimationDetail[UIKeyboardAnimationCurveUserInfoKey] as! UInt
self.tableView.scrollEnabled = false
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.view.layoutIfNeeded()
var chatInputOffset = -(CGRectGetHeight(self.view.bounds) - CGRectGetMinY(keyboardFrame))
if chatInputOffset > 0 {
chatInputOffset = 0
}
self.bottomChatInputConstraint.constant = chatInputOffset
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(animationCurve), animations: { () -> Void in
self.view.layoutIfNeeded()
self.scrollToBottom()
}, completion: {(finished) -> () in
self.tableView.scrollEnabled = true
self.tableView.decelerationRate = UIScrollViewDecelerationRateNormal
})
}
// MARK: iOS 7 Compatibility Keyboard Animations
func keyboardWillShow(note: NSNotification) {
let keyboardAnimationDetail = note.userInfo!
let duration = keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
let keyboardFrame = (keyboardAnimationDetail[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let animationCurve = keyboardAnimationDetail[UIKeyboardAnimationCurveUserInfoKey] as! UInt
let keyboardHeight = UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) ? CGRectGetHeight(keyboardFrame) : CGRectGetWidth(keyboardFrame)
self.tableView.scrollEnabled = false
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.view.layoutIfNeeded()
self.bottomChatInputConstraint.constant = -keyboardHeight
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(animationCurve), animations: { () -> Void in
self.view.layoutIfNeeded()
self.scrollToBottom()
}, completion: {(finished) -> () in
self.tableView.scrollEnabled = true
self.tableView.decelerationRate = UIScrollViewDecelerationRateNormal
})
}
func keyboardWillHide(note: NSNotification) {
let keyboardAnimationDetail = note.userInfo!
let duration = keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
let animationCurve = keyboardAnimationDetail[UIKeyboardAnimationCurveUserInfoKey] as! UInt
self.tableView.scrollEnabled = false
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.view.layoutIfNeeded()
self.bottomChatInputConstraint.constant = 0.0
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(animationCurve), animations: { () -> Void in
self.view.layoutIfNeeded()
self.scrollToBottom()
}, completion: {(finished) -> () in
self.tableView.scrollEnabled = true
self.tableView.decelerationRate = UIScrollViewDecelerationRateNormal
})
}
// MARK: Rotation
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
super.willAnimateRotationToInterfaceOrientation(toInterfaceOrientation, duration: duration)
self.tableView.reloadData()
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
super.didRotateFromInterfaceOrientation(fromInterfaceOrientation)
UIView.animateWithDuration(0.25, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.scrollToBottom()
}, completion: nil)
}
// MARK: Scrolling
private func scrollToBottom() {
if messages.count > 0 {
var lastItemIdx = self.tableView.numberOfRowsInSection(Constants.MessagesSection) - 1
if lastItemIdx < 0 {
lastItemIdx = 0
}
let lastIndexPath = NSIndexPath(forRow: lastItemIdx, inSection: Constants.MessagesSection)
self.tableView.scrollToRowAtIndexPath(lastIndexPath, atScrollPosition: .Bottom, animated: false)
}
}
// MARK: New messages
func addNewMessage(message: LGChatMessage) {
messages += [message]
tableView.reloadData()
self.scrollToBottom()
self.delegate?.chatController?(self, didAddNewMessage: message)
}
// MARK: SwiftChatInputDelegate
func chatInputDidResize(chatInput: LGChatInput) {
self.scrollToBottom()
}
func chatInput(chatInput: LGChatInput, didSendMessage message: String) {
let newMessage = LGChatMessage(content: message, sentBy: .User)
var shouldSendMessage = true
if let value = self.delegate?.shouldChatController?(self, addMessage: newMessage) {
shouldSendMessage = value
}
if shouldSendMessage {
self.addNewMessage(newMessage)
}
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let padding: CGFloat = 10.0
sizingCell.bounds.size.width = CGRectGetWidth(self.view.bounds)
let height = self.sizingCell.setupWithMessage(messages[indexPath.row]).height + padding;
return height
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.dragging {
self.chatInput.textView.resignFirstResponder()
}
}
// MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messages.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as! LGChatMessageCell
let message = self.messages[indexPath.row]
cell.opponentImageView.image = message.sentBy == .Opponent ? self.opponentImage : nil
cell.setupWithMessage(message)
return cell;
}
}
// MARK: Chat Input
protocol LGChatInputDelegate : class {
func chatInputDidResize(chatInput: LGChatInput)
func chatInput(chatInput: LGChatInput, didSendMessage message: String)
}
class LGChatInput : UIView, LGStretchyTextViewDelegate {
// MARK: Styling
struct Appearance {
static var includeBlur = true
static var tintColor = UIColor(red: 0.0, green: 120 / 255.0, blue: 255 / 255.0, alpha: 1.0)
static var backgroundColor = UIColor.whiteColor()
static var textViewFont = UIFont.systemFontOfSize(17.0)
static var textViewTextColor = UIColor.darkTextColor()
static var textViewBackgroundColor = UIColor.whiteColor()
}
/*
These methods are included for ObjC compatibility. If using Swift, you can set the Appearance variables directly.
*/
class func setAppearanceIncludeBlur(includeBlur: Bool) {
Appearance.includeBlur = includeBlur
}
class func setAppearanceTintColor(color: UIColor) {
Appearance.tintColor = color
}
class func setAppearanceBackgroundColor(color: UIColor) {
Appearance.backgroundColor = color
}
class func setAppearanceTextViewFont(textViewFont: UIFont) {
Appearance.textViewFont = textViewFont
}
class func setAppearanceTextViewTextColor(textColor: UIColor) {
Appearance.textViewTextColor = textColor
}
class func setAppearanceTextViewBackgroundColor(color: UIColor) {
Appearance.textViewBackgroundColor = color
}
// MARK: Public Properties
var textViewInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
weak var delegate: LGChatInputDelegate?
// MARK: Private Properties
private let textView = LGStretchyTextView(frame: CGRectZero, textContainer: nil)
private let sendButton = UIButton.buttonWithType(.System) as! UIButton
private let blurredBackgroundView: UIToolbar = UIToolbar()
private var heightConstraint: NSLayoutConstraint!
private var sendButtonHeightConstraint: NSLayoutConstraint!
// MARK: Initialization
override init(frame: CGRect = CGRectZero) {
super.init(frame: frame)
self.setup()
self.stylize()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Setup
func setup() {
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.setupSendButton()
self.setupSendButtonConstraints()
self.setupTextView()
self.setupTextViewConstraints()
self.setupBlurredBackgroundView()
self.setupBlurredBackgroundViewConstraints()
}
func setupTextView() {
textView.bounds = UIEdgeInsetsInsetRect(self.bounds, self.textViewInsets)
textView.stretchyTextViewDelegate = self
textView.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
self.styleTextView()
self.addSubview(textView)
}
func styleTextView() {
textView.layer.rasterizationScale = UIScreen.mainScreen().scale
textView.layer.shouldRasterize = true
textView.layer.cornerRadius = 5.0
textView.layer.borderWidth = 1.0
textView.layer.borderColor = UIColor(white: 0.0, alpha: 0.2).CGColor
}
func setupSendButton() {
self.sendButton.enabled = false
self.sendButton.setTitle("Send", forState: .Normal)
self.sendButton.addTarget(self, action: "sendButtonPressed:", forControlEvents: .TouchUpInside)
self.sendButton.bounds = CGRect(x: 0, y: 0, width: 40, height: 1)
self.addSubview(sendButton)
}
func setupSendButtonConstraints() {
self.sendButton.setTranslatesAutoresizingMaskIntoConstraints(false)
self.sendButton.removeConstraints(self.sendButton.constraints())
// TODO: Fix so that button height doesn't change on first newLine
let rightConstraint = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: self.sendButton, attribute: .Right, multiplier: 1.0, constant: textViewInsets.right)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.sendButton, attribute: .Bottom, multiplier: 1.0, constant: textViewInsets.bottom)
let widthConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 40)
sendButtonHeightConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 30)
self.addConstraints([sendButtonHeightConstraint, widthConstraint, rightConstraint, bottomConstraint])
}
func setupTextViewConstraints() {
self.textView.setTranslatesAutoresizingMaskIntoConstraints(false)
let topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: self.textView, attribute: .Top, multiplier: 1.0, constant: -textViewInsets.top)
let leftConstraint = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: self.textView, attribute: .Left, multiplier: 1, constant: -textViewInsets.left)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.textView, attribute: .Bottom, multiplier: 1, constant: textViewInsets.bottom)
let rightConstraint = NSLayoutConstraint(item: self.textView, attribute: .Right, relatedBy: .Equal, toItem: self.sendButton, attribute: .Left, multiplier: 1, constant: -textViewInsets.right)
heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.00, constant: 40)
self.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint, heightConstraint])
}
func setupBlurredBackgroundView() {
self.addSubview(self.blurredBackgroundView)
self.sendSubviewToBack(self.blurredBackgroundView)
}
func setupBlurredBackgroundViewConstraints() {
self.blurredBackgroundView.setTranslatesAutoresizingMaskIntoConstraints(false)
let topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Top, multiplier: 1.0, constant: 0)
let leftConstraint = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Left, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Bottom, multiplier: 1.0, constant: 0)
let rightConstraint = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Right, multiplier: 1.0, constant: 0)
self.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint])
}
// MARK: Styling
func stylize() {
self.textView.backgroundColor = Appearance.textViewBackgroundColor
self.sendButton.tintColor = Appearance.tintColor
self.textView.tintColor = Appearance.tintColor
self.textView.font = Appearance.textViewFont
self.textView.textColor = Appearance.textViewTextColor
self.blurredBackgroundView.hidden = !Appearance.includeBlur
self.backgroundColor = Appearance.backgroundColor
}
// MARK: StretchyTextViewDelegate
func stretchyTextViewDidChangeSize(textView: LGStretchyTextView) {
let textViewHeight = CGRectGetHeight(textView.bounds)
if count(textView.text) == 0 {
self.sendButtonHeightConstraint.constant = textViewHeight
}
let targetConstant = textViewHeight + textViewInsets.top + textViewInsets.bottom
self.heightConstraint.constant = targetConstant
self.delegate?.chatInputDidResize(self)
}
func stretchyTextView(textView: LGStretchyTextView, validityDidChange isValid: Bool) {
self.sendButton.enabled = isValid
}
// MARK: Button Presses
func sendButtonPressed(sender: UIButton) {
if count(self.textView.text) > 0 {
self.delegate?.chatInput(self, didSendMessage: self.textView.text)
self.textView.text = ""
}
}
}
// MARK: Text View
@objc protocol LGStretchyTextViewDelegate {
func stretchyTextViewDidChangeSize(chatInput: LGStretchyTextView)
optional func stretchyTextView(textView: LGStretchyTextView, validityDidChange isValid: Bool)
}
class LGStretchyTextView : UITextView, UITextViewDelegate {
// MARK: Delegate
weak var stretchyTextViewDelegate: LGStretchyTextViewDelegate?
// MARK: Public Properties
var maxHeightPortrait: CGFloat = 160
var maxHeightLandScape: CGFloat = 60
var maxHeight: CGFloat {
get {
return UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) ? maxHeightPortrait : maxHeightLandScape
}
}
// MARK: Private Properties
private var maxSize: CGSize {
get {
return CGSize(width: CGRectGetWidth(self.bounds), height: self.maxHeightPortrait)
}
}
private var _isValid = false
private var isValid: Bool {
get {
return _isValid
}
set {
if _isValid != newValue {
_isValid = newValue
self.stretchyTextViewDelegate?.stretchyTextView?(self, validityDidChange: _isValid)
}
}
}
private let sizingTextView = UITextView()
// MARK: Property Overrides
override var contentSize: CGSize {
didSet {
self.resizeAndAlign()
}
}
override var font: UIFont! {
didSet {
sizingTextView.font = font
}
}
override var textContainerInset: UIEdgeInsets {
didSet {
sizingTextView.textContainerInset = textContainerInset
}
}
// MARK: Initializers
override init(frame: CGRect = CGRectZero, textContainer: NSTextContainer? = nil) {
super.init(frame: frame, textContainer: textContainer);
self.setup()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Setup
func setup() {
self.font = UIFont.systemFontOfSize(17.0)
self.textContainerInset = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
self.delegate = self
}
// MARK: Resize & Align
func resizeAndAlign() {
self.resize()
self.align()
}
// MARK: Sizing
func resize() {
self.bounds.size.height = self.targetHeight()
self.stretchyTextViewDelegate?.stretchyTextViewDidChangeSize(self)
}
func targetHeight() -> CGFloat {
/*
There is an issue when calling `sizeThatFits` on self that results in really weird drawing issues with aligning line breaks ("\n"). For that reason, we have a textView whose job it is to size the textView. It's excess, but apparently necessary. If there's been an update to the system and this is no longer necessary, or if you find a better solution. Please remove it and submit a pull request as I'd rather not have it.
*/
sizingTextView.text = self.text
let targetSize = sizingTextView.sizeThatFits(maxSize)
var targetHeight = targetSize.height
let maxHeight = self.maxHeight
return targetHeight < maxHeight ? targetHeight : maxHeight
}
// MARK: Alignment
func align() {
let caretRect: CGRect = self.caretRectForPosition(self.selectedTextRange?.end)
let topOfLine = CGRectGetMinY(caretRect)
let bottomOfLine = CGRectGetMaxY(caretRect)
let contentOffsetTop = self.contentOffset.y
let bottomOfVisibleTextArea = contentOffsetTop + CGRectGetHeight(self.bounds)
/*
If the caretHeight and the inset padding is greater than the total bounds then we are on the first line and aligning will cause bouncing.
*/
let caretHeightPlusInsets = CGRectGetHeight(caretRect) + self.textContainerInset.top + self.textContainerInset.bottom
if caretHeightPlusInsets < CGRectGetHeight(self.bounds) {
var overflow: CGFloat = 0.0
if topOfLine < contentOffsetTop + self.textContainerInset.top {
overflow = topOfLine - contentOffsetTop - self.textContainerInset.top
} else if bottomOfLine > bottomOfVisibleTextArea - self.textContainerInset.bottom {
overflow = (bottomOfLine - bottomOfVisibleTextArea) + self.textContainerInset.bottom
}
self.contentOffset.y += overflow
}
}
// MARK: UITextViewDelegate
func textViewDidChangeSelection(textView: UITextView) {
self.align()
}
func textViewDidChange(textView: UITextView) {
// TODO: Possibly filter spaces and newlines
self.isValid = count(textView.text) > 0
}
}
|
mpl-2.0
|
92cac4a7c3ed6fb00851713924fc8edc
| 38.640719 | 431 | 0.67435 | 5.168645 | false | false | false | false |
samburnstone/SwiftSnake
|
SwiftSnake/ViewController.swift
|
1
|
4349
|
//
// ViewController.swift
// SwiftSnake
//
// Created by Sam Burnstone on 02/11/2014.
// Copyright (c) 2014 Sam Burnstone. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SnakeCollisionDelegate, UIAlertViewDelegate {
var snake: Snake!
var gameLoopTimer: NSTimer!
var collisionDetector: CollisionDetector!
var foodSpawner: FoodSpawner!
@IBOutlet weak var scoreLabel: UILabel!
var updateInterval: NSTimeInterval = 0.2
var timeElapsedSinceLastSpeedIncrease: NSTimeInterval = 0.0
let timeIntervalUntilSpeedIncrease: NSTimeInterval = 10.0
let minUpdateInterval: NSTimeInterval = 0.1
/// Store the user's current score (incremented when collects food items)
var score: Int = 0 {
didSet {
// Update score label when score updated
scoreLabel.text = "\(score)"
}
}
/// The amount added on to user's score when a food item is picked up
let foodItemPickupScore = 10
override func viewDidLoad() {
super.viewDidLoad()
// Create food spawner
foodSpawner = FoodSpawner(viewFrame: view.frame)
// Initalize collision detector
collisionDetector = CollisionDetector(viewFrame: view.frame, foodSpawner: foodSpawner)
collisionDetector.delegate = self
startGame()
}
func startGame() {
// Reset game variables
score = 0
timeElapsedSinceLastSpeedIncrease = 0.0
updateInterval = 0.2
// Create snake
snake = Snake(gameView: view, startPoint: CGPoint(x: 100, y: 100))
// Add first food item to view
view.insertSubview(foodSpawner.newFoodItem(), belowSubview: snake.headBodyPart())
// Create the timer
gameLoopTimer = NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func update() {
collisionDetector.checkForCollision(snake)
snake.moveBodyParts()
// Increase speed if necessary
timeElapsedSinceLastSpeedIncrease += updateInterval
if timeIntervalUntilSpeedIncrease - timeElapsedSinceLastSpeedIncrease <= 0.0 {
if updateInterval >= minUpdateInterval {
updateInterval -= 0.01
timeElapsedSinceLastSpeedIncrease = 0.0;
gameLoopTimer.invalidate()
gameLoopTimer = NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
}
}
// MARK:- Change of movement button selection methods
@IBAction func moveRight(sender: AnyObject) {
snake.addNewMovement(BodyPart.MovementDirection.Right)
}
@IBAction func moveLeft(sender: AnyObject) {
snake.addNewMovement(BodyPart.MovementDirection.Left)
}
@IBAction func moveUp(sender: AnyObject) {
snake.addNewMovement(BodyPart.MovementDirection.Up)
}
@IBAction func moveDown(sender: AnyObject) {
snake.addNewMovement(BodyPart.MovementDirection.Down)
}
// MARK:- CollisionDetector Delegate Methods
func snakeDidCollideWithWall() {
// Stop the timer
gameLoopTimer.invalidate()
// Alert the player by showing an alert view for now
UIAlertView(title: "You crashed into the wall!", message: "Better luck next time", delegate: self, cancelButtonTitle: "Whoops!").show()
}
func snakeDidCollideWithFoodItem() {
foodSpawner.foodItemView.removeFromSuperview()
// Make sure snake appears above food item
view.insertSubview(foodSpawner.newFoodItem(), belowSubview: snake.headBodyPart())
// Increment score
score += foodItemPickupScore
}
// MARK:- UIAlertView Delegate Methods
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
// Remove snake from view
snake.removeFromView()
// Start new game
startGame()
}
}
|
mit
|
4d387d92dbdc1bec616af4accde328b7
| 31.954545 | 160 | 0.645206 | 5.08655 | false | false | false | false |
sonsongithub/reddift
|
application/SubredditListItem.swift
|
1
|
6637
|
//
// SubredditListItem.swift
// reddift
//
// Created by sonson on 2015/12/28.
// Copyright © 2015年 sonson. All rights reserved.
//
import Foundation
/**
Subreddit object which is used by subredditlist.com
*/
struct SubredditListItem {
/// Subreddit subpath, such as windows in /r/windows
let subreddit: String
/// Subreddit's title
let title: String
/// Subreddit's content type, sfw or nsfw.
let type: String
/// Description of subreddit.
let description: String
/// Rank of subreddit.
let ranking: String
/// Score of subreddit, is that subscriptors, growth rate and recent activity.
let score: String
/**
Initialize SubredditListItem.
- parameter subreddit: Subreddit subpath, such as windows in /r/windows
- parameter title: Subreddit's title
- parameter type: Subreddit's content type, sfw or nsfw.
- parameter description: Description of subreddit.
- parameter ranking: Rank of subreddit.
- parameter score: Score of subreddit, is that subscriptors, growth rate and recent activity.
- returns: SubredditListItem objects.
*/
init(subreddit: String, title: String, type: String, description: String, ranking: String, score: String) {
self.subreddit = subreddit
self.title = title
self.type = type
self.description = description
self.ranking = ranking
self.score = score
}
/**
Create SubredditListItem with dictionary object which is obtained from api.reddift.net.
- parameter dict: Dictinay, that is [String:AnyObject], which is extracted from JSON at api.reddift.net.
- parameter showsNSFW: Filters NSFW contents. Returns nil when the dict's type is "nsfw" and this argument is false. Default is true.
- returns: SubredditListItem object.
*/
static func objectFromDictionary(dict: [String: AnyObject], showsNSFW: Bool = true) -> SubredditListItem? {
let subreddit = dict["subreddit"] as? String ?? ""
let title = dict["title"] as? String ?? ""
let type = dict["type"] as? String ?? ""
let description = dict["description"] as? String ?? ""
let ranking = dict["ranking"] as? String ?? ""
let score = dict["score"] as? String ?? ""
if type == "nsfw" && !showsNSFW { return nil }
return SubredditListItem(subreddit: subreddit, title: title, type: type, description: description, ranking: ranking, score: score)
}
/**
Extracted arrays of SubredditListItem from https://api.reddift.net/all_ranking.json, nsfw_ranking.json, sfw_ranking.json.
- parameter data: Binary data of JSON object.
- returns: Tuple object which includes three lists and NSDate which shows last update date. The three lists are ranking of all subreddits, nswf and sfw.
*/
static func SubredditListJSON2List(data: NSData) -> ([SubredditListItem], [SubredditListItem], [SubredditListItem], NSDate) {
do {
let json = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions())
if let dictionary = json as? [String: AnyObject] {
guard let data_root = dictionary["data"] as? [String: AnyObject]
else { throw NSError(domain: "com.sonson.reddift", code: 0, userInfo: nil) }
guard let lastUpdateDate = dictionary["lastUpdateDate"] as? Double
else { throw NSError(domain: "com.sonson.reddift", code: 0, userInfo: nil) }
guard let subscribers_json = data_root["Subscribers"] as? [[String: AnyObject]]
else { throw NSError(domain: "com.sonson.reddift", code: 0, userInfo: nil) }
guard let growth_json = data_root["Growth (24Hrs)"] as? [[String: AnyObject]]
else { throw NSError(domain: "com.sonson.reddift", code: 0, userInfo: nil) }
guard let recent_json = data_root["Recent Activity"] as? [[String: AnyObject]]
else { throw NSError(domain: "com.sonson.reddift", code: 0, userInfo: nil) }
let subscribersRankingList = subscribers_json.compactMap({SubredditListItem.objectFromDictionary(dict: $0)})
let growthRankingList = growth_json.compactMap({SubredditListItem.objectFromDictionary(dict: $0)})
let recentActivityList = recent_json.compactMap({SubredditListItem.objectFromDictionary(dict: $0)})
let date = NSDate(timeIntervalSince1970: lastUpdateDate)
return (subscribersRankingList, growthRankingList, recentActivityList, date)
}
return ([], [], [], NSDate())
} catch {
return ([], [], [], NSDate())
}
}
/**
Extracted arrays of SubredditListItem from https://api.reddift.net/newsokur.json.
- parameter data: Binary data of JSON object.
- parameter showsNSFW: Set true when you do not want filter nsfw contents.
- returns: Tuple object which includes dictionary, list of category titles and NSDate which shows last update date. The dictionay is with category title keys and SubredditListItem list.
*/
static func ReddiftJSON2List(data: NSData, showsNSFW: Bool = true) -> ([String: [SubredditListItem]], [String], NSDate) {
do {
let json = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions())
guard let dictionary = json as? [String: AnyObject]
else { throw NSError(domain: "com.sonson.reddift", code: 0, userInfo: nil) }
guard let lastUpdateDate = dictionary["lastUpdateDate"] as? Double
else { throw NSError(domain: "com.sonson.reddift", code: 0, userInfo: nil) }
guard let categories = dictionary["data"] as? [String: AnyObject]
else { throw NSError(domain: "", code: 0, userInfo: nil) }
var categoryLists: [String: [SubredditListItem]] = [:]
categories.keys.forEach({
if let list = categories[$0] as? [[String: AnyObject]] {
let temp = list.compactMap({SubredditListItem.objectFromDictionary(dict: $0, showsNSFW: showsNSFW)})
if temp.count > 0 {
categoryLists[$0] = temp
}
}
})
let date = NSDate(timeIntervalSince1970: lastUpdateDate)
let categoryTitles = Array(categoryLists.keys)
return (categoryLists, categoryTitles, date)
} catch {
return ([:], [], NSDate())
}
}
}
|
mit
|
5ac1d2dc854d68728fd75e330238afac
| 51.650794 | 190 | 0.634007 | 4.550069 | false | false | false | false |
AndyWoJ/DouYuLive
|
DouYuLive/DouYuLive/Classes/Main/PageContentView.swift
|
1
|
4778
|
//
// PageContentView.swift
// DouYuLive
//
// Created by wujian on 2017/1/6.
// Copyright © 2017年 wujian. All rights reserved.
//
import UIKit
private let ContentCellID = "ContentCellID"
protocol PageContentViewDelegate : class{
func pageContentView(_ contentView:PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
class PageContentView: UIView {
var childVCs :[UIViewController]
weak var parentVC : UIViewController?
var beginOffsetX : CGFloat = 0
var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
lazy var collectionView : UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
collectionView.dataSource = self
collectionView.delegate = self
return collectionView
}()
//MARK : 自定义构造函数
init(frame: CGRect, childVCs: [UIViewController], parentVC: UIViewController?) {
self.childVCs = childVCs
self.parentVC = parentVC
super.init(frame: frame)
// 设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK : 设置UI界面
extension PageContentView {
func setupUI(){
//1.将所有子控制器添加到父控制器中
for childVC in childVCs {
parentVC?.addChildViewController(childVC)
}
//2.添加UICollectionView
addSubview(collectionView)
collectionView.frame = bounds
}
}
//MARK : 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
for view in cell.contentView.subviews{
view.removeFromSuperview()
}
let childVC = childVCs[indexPath.item]
childVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVC.view)
return cell
}
}
//MARK : 遵守UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false // 滚动需要执行代理方法
beginOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isForbidScrollDelegate {return}
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > 0 {
progress = (currentOffsetX / scrollViewW) - floor(currentOffsetX / scrollViewW)
sourceIndex = Int(floor(currentOffsetX / scrollViewW))
targetIndex = Int(ceil(currentOffsetX / scrollViewW))
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
if sourceIndex == targetIndex{
progress = 1
}
}
else{
progress = ceil(currentOffsetX / scrollViewW) - (currentOffsetX / scrollViewW)
sourceIndex = Int(ceil(currentOffsetX / scrollViewW))
targetIndex = Int(floor(currentOffsetX / scrollViewW))
if sourceIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
}
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK : 对外暴露的方法
extension PageContentView{
func setCurrentIndex(_ currentIndex : Int){
isForbidScrollDelegate = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: false)
}
}
|
mit
|
8d31a3f02dc4925e967f8dc12abb59fe
| 33.109489 | 124 | 0.659319 | 5.719706 | false | false | false | false |
tekezo/Karabiner-Elements
|
src/apps/EventViewer/src/DevicesController.swift
|
1
|
1286
|
import Cocoa
private func callback(_ filePath: UnsafePointer<Int8>?, _ context: UnsafeMutableRawPointer?) {
if filePath == nil { return }
let path = String(cString: filePath!)
let obj: DevicesController! = unsafeBitCast(context, to: DevicesController.self)
guard let message = try? String(contentsOfFile: path, encoding: .utf8) else { return }
DispatchQueue.main.async { [weak obj] in
guard let obj = obj else { return }
guard let textStorage = obj.textView.textStorage else { return }
guard let font = NSFont(name: "Menlo", size: 11) else { return }
let attributedString = NSAttributedString(string: message, attributes: [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: NSColor.textColor,
])
textStorage.beginEditing()
textStorage.setAttributedString(attributedString)
textStorage.endEditing()
}
}
public class DevicesController: NSObject {
@IBOutlet var textView: NSTextView!
deinit {
libkrbn_disable_device_details_json_file_monitor()
}
public func setup() {
let obj = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
libkrbn_enable_device_details_json_file_monitor(callback, obj)
}
}
|
unlicense
|
1caf5227816001fe50b54c78f9f9efce
| 32.842105 | 94 | 0.679627 | 4.625899 | false | false | false | false |
edx/edx-app-ios
|
Source/UIAlertController+OEXBlockActions.swift
|
1
|
9274
|
//
// UIAlertController+OEXBlockActions.swift
// edX
//
// Created by Danial Zahid on 8/30/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
private let UIAlertControllerBlocksCancelButtonIndex = 0
private let UIAlertControllerBlocksDestructiveButtonIndex = 1
private let UIAlertControllerBlocksFirstOtherButtonIndex = 2
extension UIAlertController {
//MARK:- Init Methods
@objc @discardableResult func showAlert(with title: String?,
message: String?,
preferredStyle: UIAlertController.Style,
cancelButtonTitle: String?,
destructiveButtonTitle: String?,
otherButtonsTitle: [String]?,
tapBlock: ((_ controller: UIAlertController, _ action: UIAlertAction, _ buttonIndex: Int) -> ())?, textFieldWithConfigurationHandler: ((_ textField: UITextField) -> Void)? = nil) -> UIAlertController?{
guard let controller = UIApplication.shared.topMostController() else { return nil }
return showIn(viewController: controller, title: title, message: message, preferredStyle: preferredStyle, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle, otherButtonsTitle: otherButtonsTitle, tapBlock: tapBlock)
}
@objc @discardableResult func showIn(viewController pController: UIViewController,
title: String?,
message: String?,
preferredStyle: UIAlertController.Style,
cancelButtonTitle: String?,
destructiveButtonTitle: String?,
otherButtonsTitle: [String]?,
tapBlock: ((_ controller: UIAlertController, _ action: UIAlertAction, _ buttonIndex: Int) -> ())?, textFieldWithConfigurationHandler: ((_ textField: UITextField) -> Void)? = nil) -> UIAlertController{
let controller = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
if let textFieldHandler = textFieldWithConfigurationHandler {
controller.addTextField() { textField in
textFieldHandler(textField)
}
}
if let cancelText = cancelButtonTitle {
let cancelAction = UIAlertAction(title: cancelText, style: UIAlertAction.Style.cancel, handler: { (action) in
if let tap = tapBlock {
tap(controller, action, UIAlertControllerBlocksCancelButtonIndex)
}
})
controller.addAction(cancelAction)
}
if let destructiveText = destructiveButtonTitle {
let destructiveAction = UIAlertAction(title: destructiveText, style: UIAlertAction.Style.destructive, handler: { (action) in
if let tap = tapBlock {
tap(controller, action, UIAlertControllerBlocksDestructiveButtonIndex)
}
})
controller.addAction(destructiveAction)
}
if let otherButtonsText = otherButtonsTitle {
for otherTitle in otherButtonsText {
let otherAction = UIAlertAction(title: otherTitle, style: UIAlertAction.Style.default, handler: { (action) in
if let tap = tapBlock {
tap(controller, action, UIAlertControllerBlocksDestructiveButtonIndex)
}
})
controller.addAction(otherAction)
}
}
controller.view.tintColor = .systemBlue
pController.present(controller, animated: true, completion: nil)
return controller
}
@objc @discardableResult func showAlert(withTitle title: String?,
message: String?,
cancelButtonTitle: String?,
onViewController viewController: UIViewController) -> UIAlertController{
return self.showIn(viewController: viewController,
title: title,
message: message,
preferredStyle: UIAlertController.Style.alert,
cancelButtonTitle: cancelButtonTitle,
destructiveButtonTitle: nil,
otherButtonsTitle: nil,
tapBlock: nil)
}
@objc @discardableResult func showAlert(withTitle title: String?,
message: String?,
onViewController viewController: UIViewController) -> UIAlertController{
return self.showAlert(withTitle: title,
message: message,
cancelButtonTitle: Strings.ok,
onViewController: viewController)
}
@objc @discardableResult func showAlert(withTitle title: String?,
message: String?,
cancelButtonTitle: String?,
onViewController viewController: UIViewController,
tapBlock:((_ controller: UIAlertController, _ action: UIAlertAction, _ buttonIndex: Int) -> ())?) -> UIAlertController{
return showIn(viewController: viewController,
title: title,
message: message,
preferredStyle: UIAlertController.Style.alert,
cancelButtonTitle: cancelButtonTitle,
destructiveButtonTitle: nil,
otherButtonsTitle: nil,
tapBlock: tapBlock)
}
//MARK:- Add Action Methods
func addButton(withTitle title: String,
style: UIAlertAction.Style,
actionBlock: ((_ action: UIAlertAction) -> ())?) {
let alertAction = UIAlertAction(title: title, style: style, handler: { (action) in
if let tap = actionBlock {
tap(action)
}
})
self.addAction(alertAction)
}
@objc func addButton(withTitle title: String,
actionBlock: ((_ action: UIAlertAction) -> ())?) {
let alertAction = UIAlertAction(title: title, style: UIAlertAction.Style.default, handler: { (action) in
if let tap = actionBlock {
tap(action)
}
})
self.addAction(alertAction)
}
//MARK:- Helper Variables
var visible : Bool {
return self.view != nil;
}
var cancelButtonIndex : Int {
return UIAlertControllerBlocksCancelButtonIndex;
}
var firstOtherButtonIndex : Int {
return UIAlertControllerBlocksFirstOtherButtonIndex;
}
var destructiveButtonIndex : Int{
return UIAlertControllerBlocksDestructiveButtonIndex;
}
}
extension UIAlertController {
convenience init(style: UIAlertController.Style, childController: UIViewController, title: String? = nil, message: String? = nil) {
self.init(title: title, message: message, preferredStyle: style)
setValue(childController, forKey: "contentViewController")
}
}
extension UIAlertController {
@discardableResult
func showProgressDialogAlert(viewController parentController: UIViewController,
message: String,
textColor: UIColor = OEXStyles.shared().neutralBlackT(),
activityIndicatorColor: UIColor = OEXStyles.shared().neutralBlackT(),
completion: (() -> Void)? = nil) -> UIAlertController {
let alertController = UIAlertController(title: message, message: "", preferredStyle: .alert)
let activityIndicator = UIActivityIndicatorView()
activityIndicator.color = activityIndicatorColor
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.isUserInteractionEnabled = false
activityIndicator.startAnimating()
activityIndicator.scaleIndicator(factor: 1.5)
alertController.view.addSubview(activityIndicator)
alertController.view.snp.makeConstraints { make in
make.height.equalTo(StandardVerticalMargin * 17)
}
activityIndicator.snp.makeConstraints { make in
make.centerX.equalTo(alertController.view)
make.bottom.equalTo(alertController.view).inset(StandardVerticalMargin * 5)
}
parentController.present(alertController, animated: true, completion: completion)
return alertController
}
}
fileprivate extension UIActivityIndicatorView {
func scaleIndicator(factor: CGFloat) {
transform = CGAffineTransform(scaleX: factor, y: factor)
}
}
|
apache-2.0
|
846bc5f8b04de641cd3fed3b57cf94f5
| 41.732719 | 257 | 0.575218 | 6.666427 | false | false | false | false |
robertwtucker/kfinder-ios
|
KFinder/SettingsTabCoordinator.swift
|
1
|
1397
|
/**
* Copyright 2017 Robert Tucker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
final class SettingsTabCoordinator: TabCoordinator {
let tabBarItem: UITabBarItem
var viewController: UIViewController
init(tabBarController: UITabBarController, title: String, image: UIImage?) {
self.tabBarItem = UITabBarItem(title: title, image: image, selectedImage: nil)
self.viewController = UIViewController()
}
func start() {
let viewController: SettingsViewController = UIStoryboard.storyboard(.settings).instantiateViewController()
viewController.tabBarItem = tabBarItem
viewController.viewModel = SettingsViewModel(realm: RealmProvider.appRealm)
let navigationController = UINavigationController(rootViewController: viewController)
self.viewController = navigationController
}
}
|
apache-2.0
|
67a18e72c953585ae6968ca7b6642985
| 37.805556 | 115 | 0.73801 | 5.136029 | false | false | false | false |
JanGorman/Zoetrope
|
Zoetrope/UIImageView+Zoetrope.swift
|
1
|
3961
|
//
// Copyright © 2018 Schnaub. All rights reserved.
//
import UIKit
extension UIImageView {
private static var animationPropertiesKey: UInt8 = 0
private static var currentFrameKey: UInt8 = 1
private static var animatedImageKey: UInt8 = 2
private static var displayLinkKey: UInt8 = 3
open override func didMoveToWindow() {
super.didMoveToWindow()
if window == nil {
displayLink?.invalidate()
displayLink = nil
} else if displayLink == nil {
displayLink = makeDisplayLink()
displayLink?.isPaused = false
}
}
open override func display(_ layer: CALayer) {
guard let image = currentFrame else {
return
}
layer.contents = image.cgImage
}
public func displayGif(_ image: UIImage) {
guard let zoetrope = image.zoetrope else {
return
}
self.zoetrope = zoetrope
currentFrame = zoetrope.posterImage
animationProperties = AnimationProperties()
animationProperties?.loopCountDown = zoetrope.loopCount > 0 ? zoetrope.loopCount : .max
displayLink = makeDisplayLink()
displayLink?.isPaused = false
}
private func makeDisplayLink() -> CADisplayLink {
let displayLink = CADisplayLink(target: self, selector: #selector(refreshDisplay))
displayLink.add(to: .main, forMode: .common)
return displayLink
}
private var animationProperties: AnimationProperties? {
get {
return objc_getAssociatedObject(self, &UIImageView.animationPropertiesKey) as? AnimationProperties
}
set {
objc_setAssociatedObject(self, &UIImageView.animationPropertiesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private var displayLink: CADisplayLink? {
get {
return objc_getAssociatedObject(self, &UIImageView.displayLinkKey) as? CADisplayLink
}
set {
objc_setAssociatedObject(self, &UIImageView.displayLinkKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private var currentFrame: UIImage? {
get {
return objc_getAssociatedObject(self, &UIImageView.currentFrameKey) as? UIImage
}
set {
objc_setAssociatedObject(self, &UIImageView.currentFrameKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var zoetrope: Zoetrope? {
get {
return objc_getAssociatedObject(self, &UIImageView.animatedImageKey) as? Zoetrope
}
set {
objc_setAssociatedObject(self, &UIImageView.animatedImageKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
@objc
private func refreshDisplay(_ displayLink: CADisplayLink) {
guard var animationProperties = animationProperties,
let zoetrope = zoetrope,
let image = zoetrope[imageAtIndex: animationProperties.currentFrameIndex],
let delayTime = zoetrope[delayAtIndex: animationProperties.currentFrameIndex] else {
return
}
currentFrame = image
if animationProperties.needsDisplayWhenImageBecomesAvailable {
layer.setNeedsDisplay()
animationProperties.needsDisplayWhenImageBecomesAvailable = false
}
animationProperties.accumulator += displayLink.duration
while animationProperties.accumulator >= delayTime {
animationProperties.accumulator -= delayTime
animationProperties.currentFrameIndex += 1
if animationProperties.currentFrameIndex >= zoetrope.frameCount {
animationProperties.loopCountDown -= 1
guard animationProperties.loopCountDown > 0 else {
stopDisplayLink()
return
}
animationProperties.currentFrameIndex = 0
}
animationProperties.needsDisplayWhenImageBecomesAvailable = true
}
self.animationProperties = animationProperties
}
private func stopDisplayLink() {
displayLink?.isPaused = true
}
}
private struct AnimationProperties {
var currentFrameIndex = 0
var loopCountDown = 0
var accumulator = 0.0
var needsDisplayWhenImageBecomesAvailable = false
}
|
mit
|
789619213070205d4aef47d60f96531e
| 28.774436 | 119 | 0.708586 | 4.811665 | false | false | false | false |
cvillaseca/CVLoggerSwift
|
CVLoggerSwift/Classes/CVLoggerViewController.swift
|
1
|
10111
|
//
// CVLoggerViewController.swift
// Pods
//
// Created by Cristian Villaseca on 6/5/16.
//
//
import UIKit
protocol CVLoggerDelegate: class {
func didCloseCVLogger()
}
class CVLoggerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
var selectedCell = -1
let maxLength = 1500
var collapseHeight:CGFloat = 150
let cellIdentifier = "logCell"
weak var delegate:CVLoggerDelegate?
var logs:[String]?
var searchLogs:[String]?
let tableView:UITableView = UITableView(frame: CGRectZero, style: .Plain)
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
selectedCell = -1
let bundlePath = NSBundle(forClass: CVLoggerViewController.self).pathForResource("CVLoggerSwift", ofType: "bundle")
let bundle = NSBundle(path: bundlePath!)
let close = UIImage(named: "close", inBundle: bundle, compatibleWithTraitCollection: nil)
let share = UIImage(named: "share", inBundle: bundle, compatibleWithTraitCollection: nil)
let delete = UIImage(named: "delete", inBundle: bundle, compatibleWithTraitCollection: nil)
let shareButton = UIBarButtonItem(image: share, style: .Plain, target: self, action: #selector(CVLoggerViewController.share(_:)))
let closeButton = UIBarButtonItem(image: close, style: .Plain, target: self, action: #selector(CVLoggerViewController.close(_:)))
let deleteButton = UIBarButtonItem(image: delete, style: .Plain, target: self, action: #selector(CVLoggerViewController.clearLogs(_:)))
self.navigationController?.navigationBar.barTintColor = UINavigationBar.appearance().tintColor
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationItem.rightBarButtonItems = [closeButton,shareButton]
self.navigationItem.leftBarButtonItem = deleteButton
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.logs = CVLogManager.sharedManager.getLogs().reverse()
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
//MARK: UITableViewDelegate methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.resultSearchController.active {
guard self.searchLogs != nil else {
return 0
}
return self.searchLogs!.count
}
else {
guard self.logs != nil else {
return 0
}
return self.logs!.count
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var text:String
if self.resultSearchController.active {
text = self.searchLogs![indexPath.row]
} else {
text = self.logs![indexPath.row]
}
if (indexPath.row == self.selectedCell) {
return self.heightForText(text)
}else {
return min(self.collapseHeight, self.heightForText(text));
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! CVLoggerCell?
if (cell == nil) {
cell = CVLoggerCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
}
if indexPath.row % 2 == 1 {
cell!.backgroundColor = UINavigationBar.appearance().tintColor.colorWithAlphaComponent(0.5)
} else {
cell!.backgroundColor = UIColor.whiteColor()
}
var recipe:NSString
if self.resultSearchController.active {
recipe = self.searchLogs![indexPath.row]
let range = (recipe.lowercaseString as NSString).rangeOfString(self.resultSearchController.searchBar.text!.lowercaseString)
let attributedRecipe = NSMutableAttributedString(string: recipe as String)
let attributes = [NSBackgroundColorAttributeName:UIColor(colorLiteralRed: 245.0/255.0, green: 228.0/255.0, blue: 55.0/255.0, alpha: 1)]
attributedRecipe.addAttributes(attributes, range: range)
cell!.logLabel.attributedText = attributedRecipe;
return cell!;
} else {
recipe = self.logs![indexPath.row]
}
if recipe.length > maxLength {
recipe = recipe.substringToIndex(maxLength)
}
cell!.logLabel.text = recipe as String
return cell!;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedCell = indexPath.row
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.separatorInset = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
}
//MARK: SearchDisplayController
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchLogs?.removeAll(keepCapacity: false)
self.searchLogs = self.logs?.filter({ (str:String) -> Bool in
return str == searchController.searchBar.text
})
self.tableView.reloadData()
}
//MARK: Private methods
func configureView() {
self.tableView.frame = self.view.frame
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.tableView)
let views = ["tableView":self.tableView]
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: views)
self.view.addConstraints(constraints)
constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[tableView]|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: views)
self.view.addConstraints(constraints)
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
controller.searchBar.barTintColor = UINavigationBar.appearance().tintColor
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
}
//MARK: Action senders
func close (sender: AnyObject) {
self.dismissViewControllerAnimated(true) {
self.delegate?.didCloseCVLogger();
}
}
func share (sender: AnyObject) {
guard (self.logs != nil) else {
return;
}
var logs = String()
for log in self.logs! {
logs.appendContentsOf(log)
}
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths.first
let path = documentsDirectory?.stringByAppendingString("logs.txt")
do {
try logs.writeToFile(path!, atomically: true, encoding: NSUTF8StringEncoding)
let fileURL = NSURL(fileURLWithPath: path!)
let activityVC = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)
} catch {
}
}
func clearLogs (sender: AnyObject) {
CVLogManager.sharedManager.removeLogs()
self.logs?.removeAll()
self.tableView.reloadData()
}
func heightForText(text:String) -> CGFloat {
let str = text as NSString
let marginHeight:CGFloat = 8.0
let marginWidth:CGFloat = 4.0
let aLabelFont = UIFont(name: "HelveticaNeue", size: 14.0)
let aLabelSizeWidth = self.view.bounds.size.width - (2*marginWidth);
let options : NSStringDrawingOptions = [.UsesLineFragmentOrigin , .UsesFontLeading]
var textHeight = str.boundingRectWithSize(CGSizeMake(aLabelSizeWidth, CGFloat.max), options: options, attributes: [NSFontAttributeName:aLabelFont!], context: nil).size.height
if str.containsString("\n") {
textHeight += 20.0
}
textHeight += (2*marginHeight);
return textHeight;
}
}
|
mit
|
17038d5e95eedad769e6f1711d7c2fb1
| 33.508532 | 182 | 0.599051 | 5.814261 | false | false | false | false |
benlangmuir/swift
|
test/TypeRoundTrip/Inputs/testcases/typealiases.swift
|
11
|
806
|
import RoundTrip
typealias Alias = Int
struct Outer {
typealias Alias = Int
struct Inner {
typealias Alias = Int
}
}
struct GenericOuter<T> {
typealias Alias = Int
struct Inner {
typealias Alias = Int
}
}
protocol Proto {
typealias Alias = Int
}
extension Proto {
typealias OtherAlias = Int
}
extension GenericOuter where T : Proto {
typealias ConditionalAlias = Int
}
struct Conforms : Proto {}
public func test() {
roundTripType(Alias.self)
roundTripType(Outer.Alias.self)
roundTripType(Outer.Inner.Alias.self)
roundTripType(GenericOuter<Int>.Alias.self)
roundTripType(GenericOuter<Int>.Inner.Alias.self)
roundTripType(Proto.Alias.self)
roundTripType(Proto.OtherAlias.self)
roundTripType(GenericOuter<Conforms>.ConditionalAlias.self)
}
|
apache-2.0
|
9b6c9fb998fab79cf304c792d00a8b69
| 17.318182 | 63 | 0.723325 | 3.912621 | false | false | false | false |
crepashok/The-Complete-Watch-OS2-Developer-Course
|
Section-15/Roman Numeral/Roman Numeral WatchKit Extension/InterfaceController.swift
|
1
|
3827
|
//
// InterfaceController.swift
// Roman Numeral WatchKit Extension
//
// Created by Pavlo Cretsu on 4/20/16.
// Copyright © 2016 Pasha Cretsu. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet var lblRomanNumber: WKInterfaceLabel!
@IBOutlet var lblCorrect: WKInterfaceLabel!
@IBOutlet var btnAnswer0: WKInterfaceButton!
@IBOutlet var btnAnswer1: WKInterfaceButton!
var buttonCorrect : Int = 0
var totalCorrect : Int = 0
var romanNumeralArray = ["I", "V", "X", "L", "C", "D", "M"]
var randomArrayNumber : Int = 0
var correctAnswerArray = ["1", "5", "10", "15", "100", "500", "1000"]
var colorChange : Int = 0
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
reset()
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func btnAnswer0Action() {
button0Correct()
}
@IBAction func btnAnswer1Action() {
button1Correct()
}
func randomizeNumbers() {
randomArrayNumber = Int(arc4random_uniform(UInt32(romanNumeralArray.count)))
buttonCorrect = Int(arc4random_uniform(2))
printRomanNumeral()
printButtons()
}
func printRomanNumeral() {
lblRomanNumber.setText("\(romanNumeralArray[randomArrayNumber])")
}
func printButtons() {
var incorrectAnswer : Int = 0
incorrectAnswer = randomArrayNumber
if buttonCorrect == 0 {
btnAnswer0.setTitle("\(correctAnswerArray[randomArrayNumber])")
if randomArrayNumber == (romanNumeralArray.count - 1) {
incorrectAnswer = 0
}
btnAnswer1.setTitle("\(correctAnswerArray[(incorrectAnswer + 1)])")
}
if buttonCorrect == 1 {
btnAnswer1.setTitle("\(correctAnswerArray[randomArrayNumber])")
if randomArrayNumber == (romanNumeralArray.count - 1) {
incorrectAnswer = 0
}
btnAnswer0.setTitle("\(correctAnswerArray[(incorrectAnswer + 1)])")
}
//addScore()
}
func addScore() {
totalCorrect += 1
printScore()
}
func printScore() {
lblCorrect.setText("Correct: \(totalCorrect)")
}
func button0Correct() {
if buttonCorrect == 0 {
addScore()
}
reset()
}
func button1Correct() {
if buttonCorrect == 1 {
addScore()
}
reset()
}
func reset() {
randomizeNumbers()
changeTheColorOfRomanNumeral()
}
func changeTheColorOfRomanNumeral() {
var labelsColor = UIColor.lightGrayColor()
if colorChange == 0 {
labelsColor = UIColor.whiteColor()
} else if colorChange == 1 {
labelsColor = UIColor.orangeColor()
} else if colorChange == 2 {
labelsColor = UIColor.purpleColor()
} else if colorChange == 3 {
labelsColor = UIColor.greenColor()
} else if colorChange == 4 {
labelsColor = UIColor.redColor()
} else if colorChange == 5 {
labelsColor = UIColor.blueColor()
} else if colorChange == 6 {
labelsColor = UIColor.magentaColor()
}
lblRomanNumber.setTextColor(labelsColor)
lblCorrect.setTextColor(labelsColor)
colorChange += 1
if colorChange > 6 {
colorChange = 0
}
}
}
|
gpl-3.0
|
9473fbe91085ed52c55dd9425cc38f53
| 24.337748 | 84 | 0.555672 | 4.930412 | false | false | false | false |
dsay/POPDataSources
|
Sources/POPDataSources/Extensions/DataSource+Array.swift
|
1
|
1011
|
import UIKit
public extension Array where Element: Equatable {
func changes(to other: [Element]) -> (removed: [Int], inserted: [Int]) {
let otherEnumerated = other.enumerated()
let selfEnumerated = enumerated()
let leftCombinations = selfEnumerated.compactMap({ item in
return (item, otherEnumerated.first(where: { $0.element == item.element }))
})
let removedIndexes = leftCombinations.filter { combination -> Bool in
combination.1 == nil
}.compactMap { combination in
combination.0.offset
}
let rightCombinations = other.enumerated().compactMap({ item in
(selfEnumerated.first(where: { $0.element == item.element }), item)
})
let insertedIndexes = rightCombinations.filter { combination -> Bool in
combination.0 == nil
}.compactMap { combination in
combination.1.offset
}
return (removedIndexes, insertedIndexes)
}
}
|
mit
|
cdc4db35e6119197c9de98ddfabc50a1
| 37.884615 | 87 | 0.613254 | 4.931707 | false | false | false | false |
obrichak/discounts
|
discounts/Classes/BarCodeGenerator/RSFocusMarkLayer.swift
|
1
|
2730
|
//
// RSFocusMarkLayer.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
import QuartzCore
class RSFocusMarkLayer: CALayer {
var size = CGSizeMake(76, 76) // Use camera.app's focus mark size
var sight: CGFloat = 6 // Use camera.app's focus mark sight
var strokeColor = UIColor(rgba: "#ffcc00").CGColor // Use camera.app's focus mark color
var strokeWidth: CGFloat = 1
var delay: CFTimeInterval = 1
var canDraw = false
var point : CGPoint = CGPointMake(0, 0) {
didSet {
dispatch_async(dispatch_get_main_queue(), {
self.canDraw = true
self.setNeedsDisplay()
})
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(self.delay * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue(), {
self.canDraw = false
self.setNeedsDisplay()
})
}
}
override func drawInContext(ctx: CGContext!) {
if !canDraw {
return
}
CGContextSaveGState(ctx)
CGContextSetShouldAntialias(ctx, true)
CGContextSetAllowsAntialiasing(ctx, true)
CGContextSetFillColorWithColor(ctx, UIColor.clearColor().CGColor)
CGContextSetStrokeColorWithColor(ctx, strokeColor)
CGContextSetLineWidth(ctx, strokeWidth)
// Rect
CGContextStrokeRect(ctx, CGRectMake(point.x - size.width / 2.0, point.y - size.height / 2.0, size.width, size.height))
// Focus
for i in 0..<4 {
var endPoint: CGPoint
switch i {
case 0:
CGContextMoveToPoint(ctx, point.x, point.y - size.height / 2.0)
endPoint = CGPointMake(point.x, point.y - size.height / 2.0 + sight)
case 1:
CGContextMoveToPoint(ctx, point.x, point.y + size.height / 2.0);
endPoint = CGPointMake(point.x, point.y + size.height / 2.0 - sight);
case 2:
CGContextMoveToPoint(ctx, point.x - size.width / 2.0, point.y);
endPoint = CGPointMake(point.x - size.width / 2.0 + sight, point.y);
case 3:
CGContextMoveToPoint(ctx, point.x + size.width / 2.0, point.y);
endPoint = CGPointMake(point.x + size.width / 2.0 - sight, point.y);
default:
endPoint = CGPointMake(0, 0)
}
CGContextAddLineToPoint(ctx, endPoint.x, endPoint.y);
}
CGContextDrawPath(ctx, kCGPathFillStroke);
CGContextRestoreGState(ctx);
}
}
|
gpl-3.0
|
eabfb9fc7021c66ee9712ed9360904aa
| 34.454545 | 126 | 0.565201 | 4.389068 | false | false | false | false |
SafeCar/iOS
|
CarEasyApp/FeatureViewModel.swift
|
1
|
3127
|
//
// FeatureViewModel.swift
// CarEasyApp
//
// Created by Remi Robert on 25/06/16.
// Copyright © 2016 王笛iOS.Inc. All rights reserved.
//
import UIKit
import RxSwift
import RealmSwift
import Starscream
protocol FeatureViewModelDelegate {
func showAddFeature()
}
class FeatureViewModel: FeatureViewModelProtocol {
var models = Variable([FeatureCellViewModel]())
var events = Variable([EventCellViewModel]())
var delegate: FeatureViewModelDelegate?
private let disposeBag = DisposeBag()
private let socket = WebSocket(url: NSURL(string: "ws://192.168.128.245:4567/event")!)
func addFeature() {
self.delegate?.showAddFeature()
}
func fetchFeatures() {
let realm = try! Realm()
let filter = "selected = true"
let results = Array(realm.objects(Feature).filter(filter))
self.models.value = results.map({ feature -> FeatureCellViewModel in
return FeatureCellViewModel(feature: feature)
})
}
func permission() {
CarEasyAPI.permission().subscribeNext { (response: [String : AnyObject]?) in
guard let response = response else { return }
print("response \(response)")
}.addDisposableTo(self.disposeBag)
}
func removeFeature(atIndex: Int) {
let feature = self.models.value[atIndex].feature
let realm = try! Realm()
try! realm.write({
feature.selected = true
self.fetchFeatures()
})
}
func startScoket() {
self.socket.delegate = self
self.socket.connect()
}
func stopSocket() {
self.socket.disconnect()
}
}
extension FeatureViewModel: WebSocketDelegate {
func websocketDidConnect(socket: WebSocket) {
let parameters = [
"driver_id": "remi",
"secret_id": "yo",
"filters": [
["name": "seatbelt", "range": [0, 1, 2, 3]],
["name": "inhibited", "range": ["airbag", "ESC"]],
["name": "location", "range": [41.8383355, -88.2616092]],
["name": "speed", "limit": 120],
["name": "crash"]
]
]
let data = try! NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted)
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)! as String
socket.writeString(jsonString)
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
print("web socket disconnected: \(error)")
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
print("text : \(text)")
let value = text.componentsSeparatedByString(":").last?.componentsSeparatedByString("\"")[1]
let event = Event(message: value!)
self.events.value.append(EventCellViewModel(event: event))
print("web socket get message : \(text)")
}
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
print("web socket get data : \(data)")
}
}
|
mit
|
36dd3b9b55e969f9bf3430022d0d769c
| 30.22 | 119 | 0.601217 | 4.564327 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
WordPress/Classes/ViewRelated/Reader/ReaderListStreamHeader.swift
|
2
|
1256
|
import Foundation
import WordPressShared.WPStyleGuide
@objc open class ReaderListStreamHeader: UIView, ReaderStreamHeader {
@IBOutlet fileprivate weak var borderedView: UIView!
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var detailLabel: UILabel!
// Required by ReaderStreamHeader protocol.
open var delegate: ReaderStreamHeaderDelegate?
// MARK: - Lifecycle Methods
open override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
func applyStyles() {
backgroundColor = WPStyleGuide.greyLighten30()
borderedView.layer.borderColor = WPStyleGuide.readerCardCellBorderColor().cgColor
borderedView.layer.borderWidth = 1.0
WPStyleGuide.applyReaderStreamHeaderTitleStyle(titleLabel)
WPStyleGuide.applyReaderStreamHeaderDetailStyle(detailLabel)
}
// MARK: - Configuration
open func configureHeader(_ topic: ReaderAbstractTopic) {
assert(topic.isKind(of: ReaderListTopic.self))
let listTopic = topic as! ReaderListTopic
titleLabel.text = topic.title
detailLabel.text = listTopic.owner
}
open func enableLoggedInFeatures(_ enable: Bool) {
// noop
}
}
|
gpl-2.0
|
eeb8091f6c289ec80a12b13aeab7fbf1
| 26.911111 | 89 | 0.711783 | 5.168724 | false | false | false | false |
santosli/100-Days-of-Swift-3
|
Project 11/Project 11/SLTableViewController.swift
|
1
|
3467
|
//
// SLTableViewController.swift
// Project 11
//
// Created by Santos on 02/11/2016.
// Copyright © 2016 santos. All rights reserved.
//
import UIKit
class SLTableViewController: UITableViewController {
var heroes : [String] = ["EARTHSHAKER", "TINY", "SVEN", "JUGGERNAUT"]
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
//add navigationItems
self.navigationItem.leftBarButtonItem = self.editButtonItem
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: nil, action: nil)
self.navigationItem.title = "DOTA"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return heroes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = heroes[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
heroes.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let temp = heroes[fromIndexPath.row]
heroes[fromIndexPath.row] = heroes[to.row]
heroes[to.row] = temp
}
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
b9cb2c43b95ecb1f17753791b1f455bc
| 33.316832 | 136 | 0.668205 | 5.127219 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/General/Extensions.swift
|
1
|
24022
|
//
// Extensions.swift
//
// Created by Josh Doman on 12/13/16.
// Copyright © 2016 Josh Doman. All rights reserved.
//
import UIKit
extension UIApplication {
public static var isRunningFastlaneTest: Bool {
return ProcessInfo().arguments.contains("FASTLANE")
}
}
class Padding {
static let pad: CGFloat = 14.0
}
extension UIView {
var pad: CGFloat { return Padding.pad }
}
extension UIViewController {
var pad: CGFloat { return Padding.pad }
}
extension UIView {
func anchorToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil) {
anchorWithConstantsToTop(top, left: left, bottom: bottom, right: right, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
}
func anchorWithConstantsToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0) {
_ = anchor(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant)
}
func
anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
}
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: 1)
}
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
}
extension UIFont {
static let avenirMedium = UIFont.systemFont(ofSize: 21, weight: .regular)
static let primaryTitleFont = UIFont.systemFont(ofSize: 21, weight: .semibold)
static let secondaryTitleFont = UIFont.systemFont(ofSize: 11, weight: .medium)
static let interiorTitleFont = UIFont.systemFont(ofSize: 17, weight: .medium)
static let pollsTitleFont = UIFont.systemFont(ofSize: 17, weight: .semibold)
static let primaryInformationFont = UIFont.systemFont(ofSize: 14, weight: .semibold)
static let secondaryInformationFont = UIFont.systemFont(ofSize: 14, weight: .regular)
static let footerDescriptionFont = UIFont.systemFont(ofSize: 10, weight: .regular)
static let footerTransitionFont = UIFont.systemFont(ofSize: 10, weight: .semibold)
static let gsrTimeIncrementFont = UIFont.systemFont(ofSize: 20, weight: .semibold)
static let alertSettingsWarningFont = UIFont.systemFont(ofSize: 30, weight: .bold)
}
extension UIBarButtonItem {
static func itemWith(colorfulImage: UIImage?, color: UIColor, target: AnyObject, action: Selector) -> UIBarButtonItem {
let button = UIButton(type: .custom)
button.setImage(colorfulImage?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate), for: .normal)
button.tintColor = color
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
button.addTarget(target, action: action, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
}
extension Date {
func minutesFrom(date: Date) -> Int {
let difference = Calendar.current.dateComponents([.hour, .minute], from: self, to: date)
if let hour = difference.hour, let minute = difference.minute {
return hour*60 + minute
}
return 0
}
func hoursFrom(date: Date) -> Int {
let difference = Calendar.current.dateComponents([.hour], from: self, to: date)
return difference.hour ?? 0
}
func humanReadableDistanceFrom(_ date: Date) -> String {
// Opens in 55m
// Opens at 6pm
let minutes = minutesFrom(date: date) % 60
let hours = hoursFrom(date: date)
var result = ""
if hours != 0 {
result += "at \(date.strFormat())"
} else {
result += "in \(minutes)m"
}
return result
}
// returns date in local time
static var currentLocalDate: Date {
return Date().localTime
}
func convert(to timezone: String) -> Date {
var nowComponents = DateComponents()
let calendar = Calendar.current
nowComponents.year = Calendar.current.component(.year, from: self)
nowComponents.month = Calendar.current.component(.month, from: self)
nowComponents.day = Calendar.current.component(.day, from: self)
nowComponents.hour = Calendar.current.component(.hour, from: self)
nowComponents.minute = Calendar.current.component(.minute, from: self)
nowComponents.second = Calendar.current.component(.second, from: self)
nowComponents.timeZone = TimeZone(abbreviation: timezone)!
return calendar.date(from: nowComponents)! as Date
}
// Formats individual dates to be similar to those used on the Dining Screen
func strFormat() -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(abbreviation: "EST")
formatter.dateFormat = "h:mma"
formatter.amSymbol = "am"
formatter.pmSymbol = "pm"
var timesString = ""
if self.minutes == 0 {
formatter.dateFormat = "ha"
} else {
formatter.dateFormat = "h:mma"
}
let open = formatter.string(from: self)
timesString += open
return timesString
}
var localTime: Date {
return self.convert(to: "GMT")
}
var minutes: Int {
let calendar = Calendar.current
let minutes = calendar.component(.minute, from: self)
return minutes
}
var hour: Int {
let calendar = Calendar.current
let minutes = calendar.component(.hour, from: self)
return minutes
}
func add(minutes: Int) -> Date {
return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
}
func add(months: Int) -> Date {
return Calendar.current.date(byAdding: .month, value: months, to: self)!
}
func add(seconds: Int) -> Date {
return Calendar.current.date(byAdding: .second, value: seconds, to: self)!
}
func add(milliseconds: Int) -> Date {
let millisecondsSince1970 = Int((self.timeIntervalSince1970 * 1000.0).rounded())
return Date(timeIntervalSince1970: TimeInterval((milliseconds + millisecondsSince1970) / 1000))
}
var roundedDownToHour: Date {
let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour], from: self)
return Calendar.current.date(from: comp)!
// return self.add(minutes: -self.minutes)
}
var month: Int {
let values = Calendar.current.dateComponents([Calendar.Component.month], from: self)
return values.month!
}
var year: Int {
let values = Calendar.current.dateComponents([Calendar.Component.year], from: self)
return values.year!
}
var roundedDownToHalfHour: Date {
let roundedDownToHour = self.roundedDownToHour
if roundedDownToHour.minutesFrom(date: self) >= 30 {
return roundedDownToHour.add(minutes: 30)
} else {
return roundedDownToHour
}
}
var roundUpToHourIfNeeded: Date {
if minutes > 0 {
return self.add(minutes: 60 - self.minutes)
} else {
return self
}
}
static var currentDayOfWeek: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE" // Monday, Friday, etc.
return dateFormatter.string(from: Date())
}
static let weekdayArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
var dayOfWeek: String {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
myCalendar.timeZone = TimeZone(abbreviation: "EST")!
let myComponents = myCalendar.components(.weekday, from: self)
let weekDay = myComponents.weekday!
return Date.weekdayArray[weekDay-1]
}
var integerDayOfWeek: Int {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let myComponents = myCalendar.components(.weekday, from: self)
return myComponents.weekday! - 1
}
static let dayOfMonthFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
df.timeZone = TimeZone(abbreviation: "EST")
return df
}()
var dateStringsForCurrentWeek: [String] {
var dateStrings = [String]()
let formatter = Date.dayOfMonthFormatter
let currentDayOfWeek = Date().integerDayOfWeek
for day in 0 ..< 7 {
dateStrings.append(formatter.string(from: Date().add(minutes: 1440 * (day - currentDayOfWeek))))
}
return dateStrings
}
var adjustedFor11_59: Date {
if self.minutes == 59 {
return self.add(minutes: 1)
}
return self
}
func dateIn(days: Int) -> Date {
let start = Calendar.current.startOfDay(for: self)
return Calendar.current.date(byAdding: .day, value: days, to: start)!
}
var tomorrow: Date {
return self.dateIn(days: 1)
}
var isToday: Bool {
return Calendar.current.isDateInToday(self)
}
static func midnight(for dateStr: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.date(from: dateStr)!
}
static var midnightYesterday: Date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
let dateStr = formatter.string(from: Date())
return formatter.date(from: dateStr)!
}
static var midnightToday: Date {
return midnightYesterday.tomorrow
}
static var todayString: String {
return Date.dayOfMonthFormatter.string(from: Date())
}
static var startOfSemester: Date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: "2022-08-30")!
}
static var endOfSemester: Date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: "2022-12-22")!
}
}
extension LazyMapCollection {
func toArray() -> [Element] {
return Array(self)
}
}
extension UIViewController {
var isVisible: Bool {
return self.isViewLoaded && self.view.window != nil
}
}
extension DateFormatter {
static var yyyyMMdd: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter
}
static var iso8601Full: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}
}
public extension Collection {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Iterator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
var random: Iterator.Element? {
return shuffle().first
}
}
public extension MutableCollection where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in startIndex ..< endIndex - 1 {
let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i
guard i != j else { continue }
self.swapAt(i, j)
}
}
}
extension Optional {
func nullUnwrap() -> Any {
return self == nil ? "null" : self!
}
/// Unwraps an optional and throws an error if it is nil.
///
/// https://www.avanderlee.com/swift/unwrap-or-throw/
func unwrap(orThrow error: Error) throws -> Wrapped {
if let self {
return self
} else {
throw error
}
}
}
extension UILabel {
func shrinkUntilFits() {
self.allowsDefaultTighteningForTruncation = true
self.adjustsFontSizeToFitWidth = true
self.minimumScaleFactor = 0.3
self.numberOfLines = 1
}
}
extension Sequence {
/// Maps an array to an array of transformed values, fetched asynchronously in parallel.
func asyncMap<T>(_ transform: @escaping (Element) async throws -> T) async rethrows -> [T] {
try await withThrowingTaskGroup(of: T.self) { group in
forEach { element in
group.addTask {
try await transform(element)
}
}
return try await group.reduce(into: []) { $0.append($1) }
}
}
}
extension Dictionary where Key == String, Value == String {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// - returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = map { key, value -> String in
let escapedKey = key.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
let escapedValue: String = value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
return "\(escapedKey)=\(escapedValue)"
}
return parameterArray.joined(separator: "&")
}
}
extension String {
// https://stackoverflow.com/questions/34262863/how-to-calculate-height-of-a-string
func dynamicHeight(font: UIFont, width: CGFloat) -> CGFloat {
let calString = NSString(string: self)
let textSize = calString.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): font]), context: nil)
return textSize.height
}
func getMatches(for pattern: String) -> [String] {
let regex = try! NSRegularExpression(pattern: pattern)
let result = regex.matches(in: self, range: NSMakeRange(0, self.utf16.count))
var matches = [String]()
for res in result {
let r = res.range(at: 1)
let start = self.index(self.startIndex, offsetBy: r.location)
let end = self.index(self.startIndex, offsetBy: r.location + r.length)
matches.append(String(self[start..<end]))
}
return matches
}
func removingRegexMatches(pattern: String, replaceWith: String = "") -> String {
let regex = try! NSRegularExpression(pattern: pattern)
let range = NSMakeRange(0, self.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// https://sarunw.com/posts/how-to-compare-two-app-version-strings-in-swift/
func versionCompare(_ otherVersion: String) -> ComparisonResult {
let versionDelimiter = "."
var versionComponents = self.components(separatedBy: versionDelimiter) // <1>
var otherVersionComponents = otherVersion.components(separatedBy: versionDelimiter)
let zeroDiff = versionComponents.count - otherVersionComponents.count // <2>
if zeroDiff == 0 { // <3>
// Same format, compare normally
return self.compare(otherVersion, options: .numeric)
} else {
let zeros = Array(repeating: "0", count: abs(zeroDiff)) // <4>
if zeroDiff > 0 {
otherVersionComponents.append(contentsOf: zeros) // <5>
} else {
versionComponents.append(contentsOf: zeros)
}
return versionComponents.joined(separator: versionDelimiter)
.compare(otherVersionComponents.joined(separator: versionDelimiter), options: .numeric) // <6>
}
}
// https://stackoverflow.com/questions/37048759/swift-display-html-data-in-a-label-or-textview
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
// slicing Penn Events API image source urls
extension String {
//https://stackoverflow.com/questions/31725424/swift-get-string-between-2-strings-in-a-string
func slice(from: String, to: String) -> String? {
return (range(of: from)?.upperBound).flatMap { substringFrom in
(range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
String(self[substringFrom..<substringTo])
}
}
}
}
// Source: https://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift/33860834
extension String {
static func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map { _ in letters.randomElement()! })
}
}
extension NSMutableAttributedString {
@discardableResult func bold(_ text: String, size: CGFloat) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: size, weight: .bold)]
let boldString = NSMutableAttributedString(string: text, attributes: attrs)
append(boldString)
return self
}
@discardableResult func weighted(_ text: String, weight: UIFont.Weight, size: CGFloat) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: size, weight: weight)]
let boldString = NSMutableAttributedString(string: text, attributes: attrs)
append(boldString)
return self
}
@discardableResult func weightedColored(_ text: String, weight: UIFont.Weight, color: UIColor, size: CGFloat) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: size, weight: weight), NSAttributedString.Key.foregroundColor: color]
let boldString = NSMutableAttributedString(string: text, attributes: attrs)
append(boldString)
return self
}
@discardableResult func colored(_ text: String, color: UIColor) -> NSMutableAttributedString {
let attrs: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: color]
let colorString = NSMutableAttributedString(string: text, attributes: attrs)
append(colorString)
return self
}
@discardableResult func normal(_ text: String) -> NSMutableAttributedString {
let normal = NSAttributedString(string: text)
append(normal)
return self
}
}
// Decodes .json data for SwiftUI Previews
// https://www.hackingwithswift.com/books/ios-swiftui/using-generics-to-load-any-kind-of-codable-data
extension Bundle {
func decode<T: Codable>(_ file: String, dateFormat: String? = nil) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("unable to find data")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle")
}
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = dateFormat
decoder.dateDecodingStrategy = .formatted(formatter)
guard let decoded = try? decoder.decode(T.self, from: data) else {
fatalError("Data does not conform to desired structure")
}
return decoded
}
}
extension URL {
mutating func appendQueryItem(name: String, value: String?) {
guard var urlComponents = URLComponents(string: absoluteString) else { return }
var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
let queryItem = URLQueryItem(name: name, value: value)
queryItems.append(queryItem)
urlComponents.queryItems = queryItems
self = urlComponents.url!
}
public var queryParameters: [String: String] {
guard
let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else { return [:] }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
}
extension JSONDecoder {
convenience init(keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy) {
self.init()
self.keyDecodingStrategy = keyDecodingStrategy
self.dateDecodingStrategy = dateDecodingStrategy
}
}
|
mit
|
c5d902f3f83a8c1a10b6cabed1dc319b
| 34.852239 | 347 | 0.6476 | 4.54169 | false | false | false | false |
emmerge/ObjectiveDDP
|
Example/swiftExample/swiftddp/LoginViewController.swift
|
2
|
3063
|
//
// LoginViewController.swift
// swiftddp
//
// Created by Michael Arthur on 12/08/14.
// Copyright (c) 2014. All rights reserved.
//
import Foundation
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var email: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var connectionStatusLight: UIImageView!
@IBOutlet weak var connectionStatusText: UILabel!
var meteor:MeteorClient!
override func viewWillAppear(animated: Bool) {
let observingOption = NSKeyValueObservingOptions.New
meteor.addObserver(self, forKeyPath:"websocketReady", options: observingOption, context:nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (keyPath == "websocketReady" && meteor.websocketReady) {
connectionStatusText.text = "Connected to Todo Server"
let image:UIImage = UIImage(named: "green_light.png")!
connectionStatusLight.image = image
}
}
@IBAction func didTapLoginButton(sender: AnyObject) {
if (!meteor.websocketReady) {
let notConnectedAlert = UIAlertView(title: "Connection Error", message: "Can't find the Todo server, try again", delegate: nil, cancelButtonTitle: "OK")
notConnectedAlert.show()
return
}
meteor.logonWithEmail(self.email.text, password: self.password.text) {(response, error) -> Void in
if((error) != nil) {
self.handleFailedAuth(error)
return
}
self.handleSuccessfulAuth()
}
}
func handleSuccessfulAuth() {
let listViewController = ListViewController(nibName: "ListViewController", bundle: nil, meteor: self.meteor)
listViewController.userId = self.meteor.userId
self.navigationController?.pushViewController(listViewController, animated: true)
}
func handleFailedAuth(error: NSError) {
UIAlertView(title: "Meteor Todos", message:error.localizedDescription, delegate: nil, cancelButtonTitle: "Try Again").show()
}
@IBAction func didTapSayHiButton(sender: AnyObject) {
self.meteor.callMethodName("sayHelloTo", parameters:[self.email.text!]) {(response, error) -> Void in
if((error) != nil) {
self.handleFailedAuth(error)
return
}
let message = response["result"] as! String
UIAlertView(title: "Meteor Todos", message: message, delegate: nil, cancelButtonTitle:"Great").show()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
|
mit
|
647035528249e553b8346eab7ac3e8f3
| 33.033333 | 164 | 0.634019 | 4.988599 | false | false | false | false |
mlpqaz/V2ex
|
ZZV2ex/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift
|
1
|
6743
|
//
// Request.swift
// AlamofireObjectMapper
//
// Created by Tristan Himmelman on 2015-04-30.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Tristan Himmelman
//
// 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
import Alamofire
import ObjectMapper
extension DataRequest {
enum ErrorCode: Int {
case noData = 1
case dataSerializationFailed = 2
}
internal static func newError(_ code: ErrorCode, failureReason: String) -> NSError {
let errorDomain = "com.alamofireobjectmapper.error"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo)
return returnError
}
public static func ObjectMapperSerializer<T: BaseMappable>(_ keyPath: String?, mapToObject object: T? = nil, context: MapContext? = nil) -> DataResponseSerializer<T> {
return DataResponseSerializer { request, response, data, error in
guard error == nil else {
return .failure(error!)
}
guard let _ = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = newError(.noData, failureReason: failureReason)
return .failure(error)
}
let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonResponseSerializer.serializeResponse(request, response, data, error)
let JSONToMap: Any?
if let keyPath = keyPath , keyPath.isEmpty == false {
JSONToMap = (result.value as AnyObject?)?.value(forKeyPath: keyPath)
} else {
JSONToMap = result.value
}
if let object = object {
_ = Mapper<T>().map(JSONObject: JSONToMap, toObject: object)
return .success(object)
} else if let parsedObject = Mapper<T>(context: context).map(JSONObject: JSONToMap){
return .success(parsedObject)
}
let failureReason = "ObjectMapper failed to serialize response."
let error = newError(.dataSerializationFailed, failureReason: failureReason)
return .failure(error)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter keyPath: The key path where object mapping should be performed
- parameter object: An object to perform the mapping on to
- parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
- returns: The request.
*/
@discardableResult
public func responseObject<T: BaseMappable>(queue: DispatchQueue? = nil, keyPath: String? = nil, mapToObject object: T? = nil, context: MapContext? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self {
return response(queue: queue, responseSerializer: DataRequest.ObjectMapperSerializer(keyPath, mapToObject: object, context: context), completionHandler: completionHandler)
}
public static func ObjectMapperArraySerializer<T: BaseMappable>(_ keyPath: String?, context: MapContext? = nil) -> DataResponseSerializer<[T]> {
return DataResponseSerializer { request, response, data, error in
guard error == nil else {
return .failure(error!)
}
guard let _ = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = newError(.dataSerializationFailed, failureReason: failureReason)
return .failure(error)
}
let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonResponseSerializer.serializeResponse(request, response, data, error)
let JSONToMap: Any?
if let keyPath = keyPath, keyPath.isEmpty == false {
JSONToMap = (result.value as AnyObject?)?.value(forKeyPath: keyPath)
} else {
JSONToMap = result.value
}
if let parsedObject = Mapper<T>(context: context).mapArray(JSONObject: JSONToMap){
return .success(parsedObject)
}
let failureReason = "ObjectMapper failed to serialize response."
let error = newError(.dataSerializationFailed, failureReason: failureReason)
return .failure(error)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter keyPath: The key path where object mapping should be performed
- parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper.
- returns: The request.
*/
@discardableResult
public func responseArray<T: BaseMappable>(queue: DispatchQueue? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self {
return response(queue: queue, responseSerializer: DataRequest.ObjectMapperArraySerializer(keyPath, context: context), completionHandler: completionHandler)
}
}
|
apache-2.0
|
0d8f4f0687b504c7ca2c89cab4a1b445
| 45.503448 | 224 | 0.648079 | 5.377193 | false | false | false | false |
jphacks/TK_08
|
iOS/AirMeet/AirMeet/SABlurImageView/UIImage+BlurEffect.swift
|
1
|
1918
|
//
// UIImage+BlurEffect.swift
// SABlurImageView
//
// Created by 鈴木大貴 on 2015/03/27.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import QuartzCore
import Accelerate
extension UIImage {
class func blurEffect(cgImage: CGImageRef) -> UIImage! {
return UIImage(CGImage: cgImage)
}
func blurEffect(boxSize: Float) -> UIImage! {
return UIImage(CGImage: bluredCGImage(boxSize))
}
func bluredCGImage(boxSize: Float) -> CGImageRef! {
return CGImage!.blurEffect(boxSize)
}
}
extension CGImage {
func blurEffect(boxSize: Float) -> CGImageRef! {
let boxSize = boxSize - (boxSize % 2) + 1
let inProvider = CGImageGetDataProvider(self)
let height = vImagePixelCount(CGImageGetHeight(self))
let width = vImagePixelCount(CGImageGetWidth(self))
let rowBytes = CGImageGetBytesPerRow(self)
let inBitmapData = CGDataProviderCopyData(inProvider)
let inData = UnsafeMutablePointer<Void>(CFDataGetBytePtr(inBitmapData))
var inBuffer = vImage_Buffer(data: inData, height: height, width: width, rowBytes: rowBytes)
let outData = malloc(CGImageGetBytesPerRow(self) * CGImageGetHeight(self))
var outBuffer = vImage_Buffer(data: outData, height: height, width: width, rowBytes: rowBytes)
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend))
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGBitmapContextCreate(outBuffer.data, Int(outBuffer.width), Int(outBuffer.height), 8, outBuffer.rowBytes, colorSpace, CGImageGetBitmapInfo(self).rawValue)
let imageRef = CGBitmapContextCreateImage(context)
free(outData)
return imageRef
}
}
|
mit
|
5fe617679a9b6bd7c6db91d10696a3e4
| 33.545455 | 176 | 0.67 | 4.52381 | false | false | false | false |
embryoconcepts/TIY-Assignments
|
34 -- Contacts/Contacts/Contacts/ContactListViewController.swift
|
1
|
4501
|
//
// ContactListViewController.swift
// Contacts
//
// Created by Jennifer Hamilton on 11/20/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import RealmSwift
protocol AddContactDelegate
{
func contactWasAdded(newContact: Contact)
}
class ContactListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AddContactDelegate
{
@IBOutlet weak var tableSortSegmentedController: UISegmentedControl!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addFriendButton: UIBarButtonItem!
// use 'try!' in case the Realm object fails
let realm = try! Realm()
var allContacts: Results<Contact>!
var currentCreateAction: UIAlertAction!
override func viewDidLoad()
{
super.viewDidLoad()
allContacts = realm.objects(Contact).sorted("name")
// self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(true)
tableView.reloadData()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - UITableView
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return allContacts.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "Contacts:"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath)
let aContact = allContacts[indexPath.row]
cell.textLabel?.text = aContact.name
cell.detailTextLabel?.text = "\(aContact.phoneNumber)"
return cell
}
// Override to support conditional editing of the table view.
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
// Delete the row from the data source
let aContact = allContacts[indexPath.row]
try! self.realm.write( { () -> Void in
self.realm.delete(aContact)
} )
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
@IBAction func changeSortCriteria(sender: UISegmentedControl)
{
if sender.selectedSegmentIndex == 0
{
allContacts = allContacts.sorted("firstName")
}
else
{
allContacts = allContacts.sorted("lastName")
}
tableView.reloadData()
}
// MARK: - Navigation
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let contactDetailVC = storyboard?.instantiateViewControllerWithIdentifier("ContactDetailViewController") as! ContactDetailViewController
contactDetailVC.contact = allContacts[indexPath.row]
navigationController?.pushViewController(contactDetailVC, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "AddContactModalSegue"
{
let destVC = segue.destinationViewController as! UINavigationController
// modalVC is the first view controller after the navigation controller
let modalVC = destVC.viewControllers[0] as! AddContactViewController
modalVC.delegate = self
}
}
// MARK: - Add Contact Delegate
func contactWasAdded(newContact: Contact)
{
// add new contact to Realm database, persist the data
try! self.realm.write( { () -> Void in
self.realm.add(newContact)
self.tableView.reloadData()
} )
}
@IBAction func clearAllButton(sender: AnyObject)
{
// self.contacts
self.realm.deleteAll()
}
}
|
cc0-1.0
|
f1bbf8f40241ad3725b987dd2cdfc52c
| 29.821918 | 146 | 0.659111 | 5.428227 | false | false | false | false |
bvankuik/sevendayrogue
|
sevendayrogue/LineReader.swift
|
1
|
1797
|
//
// LineReader.swift
// sevendayrogue
//
// Created by Bart van Kuik on 02/09/2017.
// Copyright © 2017 DutchVirtual. All rights reserved.
//
import Foundation
class LineReader {
let path: String
fileprivate let file: UnsafeMutablePointer<FILE>!
init?(path: String) {
self.path = path
file = fopen(path, "r")
guard file != nil else { return nil }
}
var nextLine: String? {
var line:UnsafeMutablePointer<CChar>? = nil
var linecap:Int = 0
defer { free(line) }
return getline(&line, &linecap, file) > 0 ? String(cString: line!) : nil
}
deinit {
fclose(file)
}
}
extension LineReader: Sequence {
func makeIterator() -> AnyIterator<String> {
return AnyIterator<String> {
return self.nextLine
}
}
}
func readFile(filename: String) -> [String] {
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return []
}
let path = dir.appendingPathComponent(filename)
guard let reader = LineReader(path: path.absoluteString) else {
return []
}
var lines: [String] = []
for line in reader {
print(">" + line.trimmingCharacters(in: .whitespacesAndNewlines))
lines.append(line)
}
return lines
}
func readFileFromBundle(forResource resource: String, ofType type: String) -> [String] {
guard let path = Bundle.main.path(forResource: resource, ofType: type, inDirectory: nil, forLocalization: nil) else {
fatalError("Resource not found")
}
guard let reader = LineReader(path: path) else {
return []
}
var lines: [String] = []
for line in reader {
lines.append(line)
}
return lines
}
|
mit
|
59418de107aeb187a477450946cca071
| 20.902439 | 121 | 0.610802 | 4.045045 | false | false | false | false |
CPRTeam/CCIP-iOS
|
Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift
|
3
|
2303
|
// CryptoSwift
//
// Copyright (C) 2014-2018 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
final class StreamEncryptor: Cryptor, Updatable {
private let blockSize: Int
private var worker: CipherModeWorker
private let padding: Padding
private var lastBlockRemainder = 0
init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
self.blockSize = blockSize
self.padding = padding
self.worker = worker
}
// MARK: Updatable
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> {
var accumulated = Array(bytes)
if isLast {
// CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't.
accumulated = self.padding.add(to: accumulated, blockSize: self.blockSize - self.lastBlockRemainder)
}
var encrypted = Array<UInt8>(reserveCapacity: bytes.count)
for chunk in accumulated.batched(by: self.blockSize) {
encrypted += self.worker.encrypt(block: chunk)
}
// omit unecessary calculation if not needed
if self.padding != .noPadding {
self.lastBlockRemainder = encrypted.count.quotientAndRemainder(dividingBy: self.blockSize).remainder
}
if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true {
encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice))
}
return encrypted
}
func seek(to: Int) throws {
fatalError("Not supported")
}
}
|
gpl-3.0
|
52ec8625e594d8101695872d95b3236a
| 39.385965 | 217 | 0.732841 | 4.46124 | false | false | false | false |
sjtu-meow/iOS
|
Meow/ChatManager.swift
|
1
|
5974
|
//
// ChatManager.swift
// Meow
//
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import Foundation
import ChatKit
import RxSwift
class ChatManager {
open class func didFinishLaunching() {
// 如果APP是在国外使用,开启北美节点
// 必须在 APPID 初始化之前调用,否则走的是中国节点。
// [AVOSCloud setServiceRegion:AVServiceRegionUS];
// 启用未读消息
AVIMClient.setUserOptions([AVIMUserOptionUseUnread:true])
AVIMClient.setTimeoutIntervalInSeconds(20)
//添加输入框底部插件,如需更换图标标题,可子类化,然后调用 `+registerSubclass`
LCCKInputViewPluginTakePhoto.registerSubclass()
LCCKInputViewPluginPickImage.registerSubclass()
LCCKInputViewPluginLocation.registerSubclass()
LCChatKit.sharedInstance().fetchProfilesBlock = {
userIds, completionHandler in
if (userIds!.count == 0) {
let error = NSError()
completionHandler?(nil, error)
} else {
Observable.from(userIds!).concatMap({ userId in
return MeowAPIProvider.shared.request(.herProfile(id: Int(userId)!))
})
.mapTo(type: Profile.self)
.map({ profile in
return ChatKitUser.from(profile: profile as! Profile)
})
.reduce([ChatKitUser]()) {(users, user)in
var mutableUsers = users!
mutableUsers.append(user)
return mutableUsers
}
.subscribeOn(CurrentThreadScheduler.instance)
.subscribe(onNext: {
users in
completionHandler?(users, nil)
}, onError: {
e in
completionHandler?(nil, e)
})
}
}
LCChatKit.sharedInstance().didSelectConversationsListCellBlock = {
(indexPath, conversation, controller) in
let vc = LCCKConversationViewController(conversationId: conversation!.conversationId)!
controller?.navigationController?.pushViewController(vc, animated: true)
}
LCChatKit.sharedInstance().openProfileBlock = {
userId, user, parentController in
guard let userId = userId, let currentUser = UserManager.shared.currentUser else { return }
if currentUser.userId == Int(userId)! {
let vc = R.storyboard.selfPage.meViewController()!
parentController?.navigationController?.pushViewController(vc, animated: true)
} else {
let vc = R.storyboard.main.userProfileViewController()!
vc.configure(userId: Int(userId)!)
parentController?.navigationController?.pushViewController(vc, animated: true)
}
}
}
open class func didRegisterForRemoteNotificationsWithDeviceToken(deviceToken: Data) {
AVOSCloud.handleRemoteNotifications(withDeviceToken: deviceToken)
}
open class func willLogoutSuccess() {
AVOSCloudIM.handleRemoteNotifications(withDeviceToken: Data())
LCChatKit.sharedInstance().removeAllCachedProfiles()
LCChatKit.sharedInstance().close(callback: { succeeded, error in
// do nothing
})
}
open class func didLoginSuccess(withClientId clientId: String) {
//success:(LCCKVoidBlock)success
//failed:(LCCKErrorBlock)failed {
// [[self sharedInstance] exampleInit];
LCChatKit.sharedInstance().open(withClientId: clientId) {
succeeded, error in
if(succeeded) {
logger.log("ChatKit login successfully")
} else {
logger.log(error!.localizedDescription)
}
}
}
open class func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
if (application.applicationState == UIApplicationState.active) {
// 应用在前台时收到推送,只能来自于普通的推送,而非离线消息推送
} else {
/*!
* 当使用 https://github.com/leancloud/leanchat-cloudcode 云代码更改推送内容的时候
{
aps = {
alert = "lcckkit : sdfsdf";
badge = 4;
sound = default;
};
convid = 55bae86300b0efdcbe3e742e;
}
*/
LCChatKit.sharedInstance().didReceiveRemoteNotification(userInfo)
}
}
open class func applicationWillResignActive(application:UIApplication) {
LCChatKit.sharedInstance().syncBadge()
}
open class func applicationWillTerminate(application: UIApplication) {
LCChatKit.sharedInstance().syncBadge()
}
/**
* 打开单聊页面
*/
open class func openConversationViewController(withPeerId peerId: String,
from navigationController:UINavigationController) {
guard let currentUser = UserManager.shared.currentUser else { return }
guard currentUser.userId != Int(peerId) else { return }
let vc = LCCKConversationViewController(peerId: peerId)!
vc.hidesBottomBarWhenPushed = true
navigationController.pushViewController(vc, animated: true)
}
open class func openConversationViewController(
conversaionId: String,
fromNavigationController navigationController:
UINavigationController) {
let vc = LCCKConversationViewController(conversationId: conversaionId)!
vc.isEnableAutoJoin = true
vc.hidesBottomBarWhenPushed = true
navigationController.pushViewController(vc, animated: true)
}
}
|
apache-2.0
|
98be8940c31b45460c4ea3bbcfafac21
| 34.07362 | 124 | 0.602939 | 5.197273 | false | false | false | false |
marioestrada/tipper
|
Tipper/Tipper/ViewController.swift
|
1
|
1345
|
//
// ViewController.swift
// Tipper
//
// Created by Mario Estrada on 10/4/15.
// Copyright © 2015 Mario Estrada. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var fieldBill: UITextField!
@IBOutlet weak var labelTip: UILabel!
@IBOutlet weak var labelTotal: UILabel!
@IBOutlet weak var segmentPercentage: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
labelTip.text = "$0.00"
labelTotal.text = "$0.00"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onDataChange(sender: AnyObject) {
let percentages = [0.15,0.2,0.25]
let tipPercentage = percentages[segmentPercentage.selectedSegmentIndex]
let billValue = fieldBill.text
let billAmount = Double(billValue!)
let tip = billAmount! * tipPercentage
let total = tip + billAmount!
labelTip.text = String(format: "$%.2f", tip)
labelTotal.text = String(format: "$%.2f", total)
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
}
|
mit
|
a84acee773d2750051ba9451d401c0ce
| 26.428571 | 80 | 0.637649 | 4.421053 | false | false | false | false |
Multinerd-Swift/PermissionsKit
|
PermissionsKit/Core/PermissionsKitAlert.swift
|
1
|
437
|
public struct PermissionsKitAlert {
var title: String!
var message: String!
var allowButtonTitle: String!
var denyButtonTitle: String!
public init(title: String = "", message: String = "", allowButtonTitle: String = "", denyButtonTitle: String = "") {
self.title = title
self.message = message
self.allowButtonTitle = allowButtonTitle
self.denyButtonTitle = denyButtonTitle
}
}
|
mit
|
61c1aafe4ae951f34c813d1ca8c1918d
| 28.133333 | 120 | 0.661327 | 4.910112 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro
|
Pods/Former/Former/RowFormers/CheckRowFormer.swift
|
2
|
2145
|
//
// CheckRowFormer.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/26/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public protocol CheckFormableRow: FormableRow {
func formTitleLabel() -> UILabel?
}
open class CheckRowFormer<T: UITableViewCell>
: BaseRowFormer<T>, Formable where T: CheckFormableRow {
// MARK: Public
open var checked = false
open var customCheckView: UIView?
open var titleDisabledColor: UIColor? = .lightGray
public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) {
super.init(instantiateType: instantiateType, cellSetup: cellSetup)
}
@discardableResult
public final func onCheckChanged(_ handler: @escaping ((Bool) -> Void)) -> Self {
onCheckChanged = handler
return self
}
open override func update() {
super.update()
if let customCheckView = customCheckView {
cell.accessoryView = customCheckView
customCheckView.isHidden = checked ? false : true
} else {
cell.accessoryType = checked ? .checkmark : .none
}
let titleLabel = cell.formTitleLabel()
if enabled {
_ = titleColor.map { titleLabel?.textColor = $0 }
titleColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .black }
titleLabel?.textColor = titleDisabledColor
}
}
open override func cellSelected(indexPath: IndexPath) {
former?.deselect(animated: true)
if enabled {
checked = !checked
onCheckChanged?(checked)
if let customCheckView = customCheckView {
cell.accessoryView = customCheckView
customCheckView.isHidden = checked ? false : true
} else {
cell.accessoryType = checked ? .checkmark : .none
}
}
}
// MARK: Private
private final var titleColor: UIColor?
private final var onCheckChanged: ((Bool) -> Void)?
}
|
mit
|
bc979516257e24fd86401ae51b709fb8
| 28.777778 | 109 | 0.60028 | 4.872727 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Components/Announcements/AnnouncementDisplayAction.swift
|
1
|
1245
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
/// A action that needs to be taken to display an announcement to the user
public enum AnnouncementDisplayAction: Equatable {
/// Show an announcement
case show(AnnouncementCardViewModel)
/// Agnostically hide whatever announcement that is currently displayed
case hide
/// No announcement
case none
public static func == (lhs: AnnouncementDisplayAction, rhs: AnnouncementDisplayAction) -> Bool {
switch (lhs, rhs) {
case (.show(let first), .show(let second)):
return first == second
case (.hide, .hide), (.none, .none):
return true
default:
return false
}
}
public var isHide: Bool {
if case .hide = self {
return true
}
return false
}
}
// MARK: - CustomDebugStringConvertible
extension AnnouncementDisplayAction: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .show:
return "shows card announcement"
case .hide:
return "hides announcement"
case .none:
return "doesn't show announcement"
}
}
}
|
lgpl-3.0
|
541eed99249be3935c3c97ffda2e0e0d
| 25.468085 | 100 | 0.613344 | 5.056911 | false | false | false | false |
modum-io/ios_client
|
PharmaSupplyChain/CompanyDefaults.swift
|
1
|
3007
|
//
// CompanyDefaults.swift
// PharmaSupplyChain
//
// Created by Yury Belevskiy on 03.03.17.
// Copyright © 2017 Modum. All rights reserved.
//
import ObjectMapper
import CoreData
class CompanyDefaults : Mappable, CoreDataObject {
// MARK: Properties
var defaultTemperatureCategoryIndex: Int?
var defaultMeasurementInterval: Int?
var companyTemperatureCategories: [CompanyTemperatureCategory] = []
// MARK: Mappable
public required init?(map: Map) {}
public func mapping(map: Map) {
defaultTemperatureCategoryIndex <- map["defaultTemperatureCategoryIndex"]
defaultMeasurementInterval <- map["defaultMeasurementInterval"]
companyTemperatureCategories <- map["temperatureCategories"]
}
// MARK: CoreDataObject
public required init?(WithCoreDataObject object: CDCompanyDefaults) {
defaultMeasurementInterval = object.defaultMeasurementInterval
if let companyTemperatureCategories = Array(object.tempCategories) as? [CDTempCategory] {
self.companyTemperatureCategories = companyTemperatureCategories.flatMap{ CompanyTemperatureCategory(WithCoreDataObject: $0) }
}
defaultTemperatureCategoryIndex = companyTemperatureCategories.index(where: {
tempCategory in
if let minTemp = tempCategory.tempLow, let maxTemp = tempCategory.tempHigh {
return object.defaultTempCategory.minTemp == minTemp && object.defaultTempCategory.maxTemp == maxTemp
} else {
return false
}
})
}
public func toCoreDataObject(object: CDCompanyDefaults) {
if let defaultMeasurementInterval = defaultMeasurementInterval, let defaultTemperatureCategoryIndex = defaultTemperatureCategoryIndex {
object.defaultMeasurementInterval = defaultMeasurementInterval
if let context = object.managedObjectContext {
object.tempCategories = NSSet()
for tempCategory in companyTemperatureCategories {
let cdTempCategory = NSEntityDescription.insertNewObject(forEntityName: "CDTempCategory", into: context) as! CDTempCategory
tempCategory.toCoreDataObject(object: cdTempCategory)
object.addToTempCategories(cdTempCategory)
}
if defaultTemperatureCategoryIndex >= 0 && defaultTemperatureCategoryIndex < companyTemperatureCategories.count && !companyTemperatureCategories.isEmpty {
let tempCategory = companyTemperatureCategories[defaultTemperatureCategoryIndex]
let cdTempCategory = NSEntityDescription.insertNewObject(forEntityName: "CDTempCategory", into: context) as! CDTempCategory
tempCategory.toCoreDataObject(object: cdTempCategory)
object.defaultTempCategory = cdTempCategory
}
}
}
}
}
|
apache-2.0
|
705e8b967874c2629193b2a010e5e598
| 42.565217 | 170 | 0.67831 | 5.515596 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/ViewRelated/Jetpack/Jetpack Scan/JetpackScanCoordinator.swift
|
1
|
13689
|
import Foundation
protocol JetpackScanView {
func render()
func showLoading()
func showNoConnectionError()
func showGenericError()
func showScanStartError()
func showMultisiteNotSupportedError()
func toggleHistoryButton(_ isEnabled: Bool)
func presentAlert(_ alert: UIAlertController)
func presentNotice(with title: String, message: String?)
func showIgnoreThreatSuccess(for threat: JetpackScanThreat)
func showIgnoreThreatError(for threat: JetpackScanThreat)
func showJetpackSettings(with siteID: Int)
}
class JetpackScanCoordinator {
private let service: JetpackScanService
private let view: JetpackScanView
private(set) var scan: JetpackScan? {
didSet {
configureSections()
scanDidChange(from: oldValue, to: scan)
}
}
var hasValidCredentials: Bool {
return scan?.hasValidCredentials ?? false
}
let blog: Blog
/// Returns the threats if we're in the idle state
var threats: [JetpackScanThreat]? {
let returnThreats: [JetpackScanThreat]?
if scan?.state == .fixingThreats {
returnThreats = scan?.threatFixStatus?.compactMap { $0.threat } ?? nil
} else {
returnThreats = scan?.state == .idle ? scan?.threats : nil
}
// Sort the threats by date then by threat ID
return returnThreats?.sorted(by: {
if $0.firstDetected != $1.firstDetected {
return $0.firstDetected > $1.firstDetected
}
return $0.id > $1.id
})
}
var sections: [JetpackThreatSection]?
private var actionButtonState: ErrorButtonAction?
init(blog: Blog,
view: JetpackScanView,
service: JetpackScanService? = nil,
context: NSManagedObjectContext = ContextManager.sharedInstance().mainContext) {
self.service = service ?? JetpackScanService(managedObjectContext: context)
self.blog = blog
self.view = view
}
public func viewDidLoad() {
view.showLoading()
refreshData()
}
public func refreshData() {
service.getScanWithFixableThreatsStatus(for: blog) { [weak self] scanObj in
self?.refreshDidSucceed(with: scanObj)
} failure: { [weak self] error in
DDLogError("Error fetching scan object: \(String(describing: error?.localizedDescription))")
self?.refreshDidFail(with: error)
}
}
public func viewWillDisappear() {
stopPolling()
}
public func startScan() {
// Optimistically trigger the scanning state
scan?.state = .scanning
// Refresh the view's scan state
view.render()
// Since we've locally entered the scanning state, start polling
// but don't trigger a refresh immediately after calling because the
// server doesn't update its state immediately after starting a scan
startPolling(triggerImmediately: false)
service.startScan(for: blog) { [weak self] (success) in
if success == false {
DDLogError("Error starting scan: Scan response returned false")
WPAnalytics.track(.jetpackScanError, properties: ["action": "scan",
"cause": "scan response returned false"])
self?.stopPolling()
self?.view.showScanStartError()
}
} failure: { [weak self] (error) in
DDLogError("Error starting scan: \(String(describing: error?.localizedDescription))")
WPAnalytics.track(.jetpackScanError, properties: ["action": "scan",
"cause": error?.localizedDescription ?? "remote"])
self?.refreshDidFail(with: error)
}
}
// MARK: - Public Actions
public func presentFixAllAlert() {
let threatCount = scan?.fixableThreats?.count ?? 0
let title: String
let message: String
if threatCount == 1 {
title = Strings.fixAllSingleAlertTitle
message = Strings.fixAllSingleAlertMessage
} else {
title = String(format: Strings.fixAllAlertTitleFormat, threatCount)
message = Strings.fixAllAlertTitleMessage
}
let controller = UIAlertController(title: title, message: message, preferredStyle: .alert)
controller.addAction(UIAlertAction(title: Strings.fixAllAlertCancelButtonTitle, style: .cancel, handler: nil))
controller.addAction(UIAlertAction(title: Strings.fixAllAlertConfirmButtonTitle, style: .default, handler: { [weak self] _ in
WPAnalytics.track(.jetpackScanAllthreatsFixTapped, properties: ["threats_fixed": threatCount])
self?.fixAllThreats()
}))
view.presentAlert(controller)
}
private func fixThreats(threats: [JetpackScanThreat]) {
// If there are no fixable threats just reload the state since it may be out of date
guard threats.count > 0 else {
refreshData()
return
}
// Optimistically trigger the fixing state
// and map all the fixable threats to in progress threats
scan?.state = .fixingThreats
scan?.threatFixStatus = threats.compactMap {
var threatCopy = $0
threatCopy.status = .fixing
return JetpackThreatFixStatus(with: threatCopy)
}
// Refresh the view to show the new scan state
view.render()
startPolling(triggerImmediately: false)
service.fixThreats(threats, blog: blog) { [weak self] (response) in
if response.success == false {
DDLogError("Error starting scan: Scan response returned false")
self?.stopPolling()
self?.view.showScanStartError()
} else {
self?.refreshData()
}
} failure: { [weak self] (error) in
DDLogError("Error fixing threats: \(String(describing: error.localizedDescription))")
self?.refreshDidFail(with: error)
}
}
public func fixAllThreats() {
let fixableThreats = threats?.filter { $0.fixable != nil } ?? []
fixThreats(threats: fixableThreats)
}
public func fixThreat(threat: JetpackScanThreat) {
fixThreats(threats: [threat])
}
public func ignoreThreat(threat: JetpackScanThreat) {
service.ignoreThreat(threat, blog: blog, success: { [weak self] in
self?.view.showIgnoreThreatSuccess(for: threat)
}, failure: { [weak self] error in
DDLogError("Error ignoring threat: \(error.localizedDescription)")
WPAnalytics.track(.jetpackScanError, properties: ["action": "ignore",
"cause": error.localizedDescription])
self?.view.showIgnoreThreatError(for: threat)
})
}
public func openSupport() {
let supportVC = SupportTableViewController()
supportVC.showFromTabBar()
}
public func openJetpackSettings() {
guard let siteID = blog.dotComID as? Int else {
view.presentNotice(with: Strings.jetpackSettingsNotice.title, message: nil)
return
}
view.showJetpackSettings(with: siteID)
}
public func noResultsButtonPressed() {
guard let action = actionButtonState else {
return
}
switch action {
case .contactSupport:
openSupport()
case .tryAgain:
refreshData()
}
}
private func configureSections() {
guard let threats = self.threats, let siteRef = JetpackSiteRef(blog: self.blog) else {
sections = nil
return
}
guard scan?.state == .fixingThreats else {
sections = JetpackScanThreatSectionGrouping(threats: threats, siteRef: siteRef).sections
return
}
sections = [JetpackThreatSection(title: nil, date: Date(), threats: threats)]
}
// MARK: - Private: Network Handlers
private func refreshDidSucceed(with scanObj: JetpackScan) {
scan = scanObj
switch (scanObj.state, scanObj.reason) {
case (.unavailable, JetpackScan.Reason.multiSiteNotSupported):
view.showMultisiteNotSupportedError()
default:
view.render()
}
view.toggleHistoryButton(scan?.isEnabled ?? false)
togglePolling()
}
private func refreshDidFail(with error: Error? = nil) {
let appDelegate = WordPressAppDelegate.shared
guard
let connectionAvailable = appDelegate?.connectionAvailable, connectionAvailable == true
else {
view.showNoConnectionError()
actionButtonState = .tryAgain
return
}
view.showGenericError()
actionButtonState = .contactSupport
}
private func scanDidChange(from: JetpackScan?, to: JetpackScan?) {
let fromState = from?.state ?? .unknown
let toState = to?.state ?? .unknown
// Trigger scan finished alert
guard fromState == .scanning, toState == .idle else {
return
}
let threatCount = threats?.count ?? 0
let message: String
switch threatCount {
case 0:
message = Strings.scanNotice.message
case 1:
message = Strings.scanNotice.messageSingleThreatFound
default:
message = String(format: Strings.scanNotice.messageThreatsFound, threatCount)
}
view.presentNotice(with: Strings.scanNotice.title, message: message)
}
// MARK: - Private: Refresh Timer
private var refreshTimer: Timer?
/// Starts or stops the refresh timer based on the status of the scan
private func togglePolling() {
switch scan?.state {
case .provisioning, .scanning, .fixingThreats:
startPolling()
default:
stopPolling()
}
}
private func stopPolling() {
refreshTimer?.invalidate()
refreshTimer = nil
}
private func startPolling(triggerImmediately: Bool = true) {
guard refreshTimer == nil else {
return
}
refreshTimer = Timer.scheduledTimer(withTimeInterval: Constants.refreshTimerInterval, repeats: true, block: { [weak self] (_) in
self?.refreshData()
})
// Immediately trigger the refresh if needed
guard triggerImmediately else {
return
}
refreshData()
}
private struct Constants {
static let refreshTimerInterval: TimeInterval = 5
}
private struct Strings {
struct scanNotice {
static let title = NSLocalizedString("Scan Finished", comment: "Title for a notice informing the user their scan has completed")
static let message = NSLocalizedString("No threats found", comment: "Message for a notice informing the user their scan completed and no threats were found")
static let messageThreatsFound = NSLocalizedString("%d potential threats found", comment: "Message for a notice informing the user their scan completed and %d threats were found")
static let messageSingleThreatFound = NSLocalizedString("1 potential threat found", comment: "Message for a notice informing the user their scan completed and 1 threat was found")
}
struct jetpackSettingsNotice {
static let title = NSLocalizedString("Unable to visit Jetpack settings for site", comment: "Message displayed when visiting the Jetpack settings page fails.")
}
static let fixAllAlertTitleFormat = NSLocalizedString("Please confirm you want to fix all %1$d active threats", comment: "Confirmation title presented before fixing all the threats, displays the number of threats to be fixed")
static let fixAllSingleAlertTitle = NSLocalizedString("Please confirm you want to fix this threat", comment: "Confirmation title presented before fixing a single threat")
static let fixAllAlertTitleMessage = NSLocalizedString("Jetpack will be fixing all the detected active threats.", comment: "Confirmation message presented before fixing all the threats, displays the number of threats to be fixed")
static let fixAllSingleAlertMessage = NSLocalizedString("Jetpack will be fixing the detected active threat.", comment: "Confirmation message presented before fixing a single threat")
static let fixAllAlertCancelButtonTitle = NSLocalizedString("Cancel", comment: "Button title, cancel fixing all threats")
static let fixAllAlertConfirmButtonTitle = NSLocalizedString("Fix all threats", comment: "Button title, confirm fixing all threats")
}
private enum ErrorButtonAction {
case contactSupport
case tryAgain
}
}
extension JetpackScan {
var hasValidCredentials: Bool {
return credentials?.first?.stillValid ?? false
}
var hasFixableThreats: Bool {
let count = fixableThreats?.count ?? 0
return count > 0
}
var fixableThreats: [JetpackScanThreat]? {
return threats?.filter { $0.fixable != nil }
}
}
extension JetpackScan {
struct Reason {
static let multiSiteNotSupported = "multisite_not_supported"
}
}
/// Represents a sorted section of threats
struct JetpackThreatSection {
let title: String?
let date: Date
let threats: [JetpackScanThreat]
}
|
gpl-2.0
|
edcbbc38a37188ea56151aaea278d4ff
| 32.883663 | 238 | 0.629922 | 4.899427 | false | false | false | false |
gerryisaac/iPhone-CTA-Bus-Tracker-App
|
Bus Tracker/Views/PatternCell.swift
|
1
|
8384
|
//
// PatternCell.swift
// Bus Tracker
//
// Created by Gerard Isaac on 10/29/14.
// Copyright (c) 2014 Gerard Isaac. All rights reserved.
//
import UIKit
class PatternCell: UITableViewCell {
//Pattern Values
var cellBgImageViewColor:UIImageView = UIImageView()
var cellBgImageViewBW:UIImageView = UIImageView()
var cellstopType:NSString = NSString()
var cellstopID:NSString = NSString()
var cellstopName:NSString = NSString()
var cellLat:NSString = NSString()
var cellLong:NSString = NSString()
var cellSequence:NSString = NSString()
var cellDistance:NSString = NSString()
//Pattern Labels
var cellstopTypeLabel:UILabel = UILabel()
var cellstopIDLabel:UILabel = UILabel()
var cellstopNameLabel:UILabel = UILabel()
var clatValueLabel:UILabel = UILabel()
var clongValueLabel:UILabel = UILabel()
var cellseqLabel:UILabel = UILabel()
var celldistLabel:UILabel = UILabel()
var cellLatLabel:UILabel = UILabel()
var cellLongLabel:UILabel = UILabel()
var iconBusStop:UIImageView = UIImageView()
var iconWaypoint:UIImageView = UIImageView()
var iconOnline:UIImageView = UIImageView()
var iconOffline:UIImageView = UIImageView()
var routeNumberLabel:UILabel = UILabel()
var routeNameLabel:UILabel = UILabel()
var timeButton: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var newsButton: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
//println("Cell Loaded")
//Create Cell Background
self.backgroundColor = UIColor.clearColor()
let cellBgImage = UIImage(named:"patternsCellBgLarge.png")!
cellBgImageViewColor = UIImageView(frame: CGRectMake(0, 0, 320, 200))
cellBgImageViewColor.image = cellBgImage
cellBgImageViewColor.hidden = true
//cellBgImageView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
self.addSubview(cellBgImageViewColor)
let cellBgImageBW = UIImage(named:"patternsCellBgLargeBW.png")!
cellBgImageViewBW = UIImageView(frame: CGRectMake(0, 0, 320, 200))
cellBgImageViewBW.image = cellBgImageBW
cellBgImageViewBW.hidden = true
self.addSubview(cellBgImageViewBW)
cellstopTypeLabel.frame = CGRectMake(3, 3, 157, 20)
cellstopTypeLabel.font = UIFont(name:"HelveticaNeue-CondensedBold", size:14.0)
cellstopTypeLabel.textColor = UIColor.whiteColor()
cellstopTypeLabel.textAlignment = NSTextAlignment.Center
cellstopTypeLabel.text = cellstopType.uppercaseString
self.addSubview(cellstopTypeLabel)
cellstopIDLabel.frame = CGRectMake(160, 3, 157, 20)
cellstopIDLabel.font = UIFont(name:"HelveticaNeue-CondensedBold", size:14.0)
cellstopIDLabel.textColor = UIColor.whiteColor()
cellstopIDLabel.textAlignment = NSTextAlignment.Center
cellstopIDLabel.text = cellstopID
self.addSubview(cellstopIDLabel)
cellstopNameLabel.frame = CGRectMake(6, 23, 314, 67)
cellstopNameLabel.font = UIFont(name:"Gotham-Medium", size:25.0)
cellstopNameLabel.textColor = UIColor.whiteColor()
cellstopNameLabel.textAlignment = NSTextAlignment.Left
cellstopNameLabel.numberOfLines = 0
cellstopNameLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
cellstopNameLabel.text = cellstopName
self.addSubview(cellstopNameLabel)
cellLatLabel.frame = CGRectMake(103, 96, 142, 20)
cellLatLabel.font = UIFont(name:"Gotham-Medium", size:14.0)
cellLatLabel.textColor = uicolorFromHex(0x828282)
cellLatLabel.textAlignment = NSTextAlignment.Left
cellLatLabel.text = cellLat
self.addSubview(cellLatLabel)
cellLongLabel.frame = CGRectMake(103, 119, 142, 20)
cellLongLabel.font = UIFont(name:"Gotham-Medium", size:14.0)
cellLongLabel.textColor = uicolorFromHex(0x828282)
cellLongLabel.textAlignment = NSTextAlignment.Left
cellLongLabel.text = cellLong
self.addSubview(cellLongLabel)
cellseqLabel.frame = CGRectMake(121, 148, 54, 15)
cellseqLabel.font = UIFont(name:"Gotham-Bold", size:12.0)
cellseqLabel.textColor = uicolorFromHex(0x828282)
cellseqLabel.textAlignment = NSTextAlignment.Left
cellseqLabel.text = cellSequence
self.addSubview(cellseqLabel)
celldistLabel.frame = CGRectMake(121, 176, 54, 15)
celldistLabel.font = UIFont(name:"Gotham-Bold", size:12.0)
celldistLabel.textColor = uicolorFromHex(0x828282)
celldistLabel.textAlignment = NSTextAlignment.Left
celldistLabel.text = cellDistance
self.addSubview(celldistLabel)
//Bus Stop Icon
let busStopImage = UIImage(named:"patternCell-IconStop.png")!
iconBusStop = UIImageView(frame: CGRectMake(3, 142, 55, 55))
iconBusStop.image = busStopImage
iconBusStop.hidden = true
self.addSubview(iconBusStop)
//Waypoint Icon
let waypointImage = UIImage(named:"patternCell-IconWayPoint.png")!
iconWaypoint = UIImageView(frame: CGRectMake(3, 142, 55, 55))
iconWaypoint.image = waypointImage
iconWaypoint.hidden = true
self.addSubview(iconWaypoint)
//Online and Offline Icons
let onlineImage = UIImage(named:"patternCell-footerOnline.png")!
let offlineImage = UIImage(named:"patternCell-footerOffline.png")!
iconOnline = UIImageView(frame: CGRectMake(248, 96, 69, 20))
iconOnline.image = onlineImage
iconOnline.hidden = false
self.addSubview(iconOnline)
iconOffline = UIImageView(frame: CGRectMake(248, 119, 69, 20))
iconOffline.image = offlineImage
iconOffline.hidden = false
self.addSubview(iconOffline)
//Create Buttons
let timeButtonNormal = UIImage(named:"patternBtn-TimeNormal.png")!
let timeButtonActive = UIImage(named:"patternBtn-TimeOver.png")!
let timeButtonDisabled = UIImage(named:"patternBtn-TimeDisabled.png")!
let newsButtonNormal = UIImage(named:"patternBtn-NewsNormal.png")!
let newsButtonActive = UIImage(named:"patternBtn-NewsOver.png")!
let newsButtonDisabled = UIImage(named:"patternBtn-NewsDisabled.png")!
timeButton.frame = CGRectMake(176, 142, 69, 55)
timeButton.setImage(timeButtonNormal, forState: UIControlState.Normal)
timeButton.setImage(timeButtonActive, forState: UIControlState.Highlighted)
timeButton.setImage(timeButtonDisabled, forState: UIControlState.Disabled)
//timeButton.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(timeButton)
newsButton.frame = CGRectMake(248, 142, 69, 55)
newsButton.setImage(newsButtonNormal, forState: UIControlState.Normal)
newsButton.setImage(newsButtonActive, forState: UIControlState.Highlighted)
newsButton.setImage(newsButtonDisabled, forState: UIControlState.Disabled)
//newsButton.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(newsButton)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
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
}
//Hex Color Values Function
func uicolorFromHex(rgbValue:UInt32)->UIColor{
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:1.0)
}
}
|
mit
|
6eb8ef00f878618ae5d501a146930c41
| 40.300493 | 104 | 0.679509 | 4.549105 | false | false | false | false |
GEOSwift/GEOSwift
|
Sources/GEOSwift/Codable/Feature+Codable.swift
|
2
|
1700
|
extension Feature.FeatureId: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let string = try? container.decode(String.self) {
self = .string(string)
} else if let number = try? container.decode(Double.self) {
self = .number(number)
} else {
throw GEOSwiftError.invalidFeatureId
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case let .string(string):
try container.encode(string)
case let .number(number):
try container.encode(number)
}
}
}
extension Feature: Codable {
enum CodingKeys: CodingKey {
case type
case geometry
case properties
case id
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try container.geoJSONType(forKey: .type, expectedType: .feature)
try self.init(
geometry: container.decode(Geometry?.self, forKey: .geometry),
properties: container.decode([String: JSON]?.self, forKey: .properties),
id: container.decodeIfPresent(FeatureId.self, forKey: .id))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(GeoJSONType.feature, forKey: .type)
try container.encode(geometry, forKey: .geometry)
try container.encode(properties, forKey: .properties)
try container.encodeIfPresent(id, forKey: .id)
}
}
|
mit
|
05e2fa40dbc7a7a7da289136b6327724
| 34.416667 | 84 | 0.631176 | 4.58221 | false | false | false | false |
apple/swift
|
test/Generics/interdependent_protocol_conformance_example_5.swift
|
6
|
3224
|
// RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -disable-requirement-machine-reuse 2>&1 | %FileCheck %s
// CHECK-LABEL: .NonEmptyProtocol@
// CHECK-NEXT: Requirement signature: <Self where Self : Collection, Self.[NonEmptyProtocol]C : Collection, Self.[Sequence]Element == Self.[NonEmptyProtocol]C.[Sequence]Element, Self.[Collection]Index == Self.[NonEmptyProtocol]C.[Collection]Index>
public protocol NonEmptyProtocol: Collection
where Element == C.Element,
Index == C.Index {
associatedtype C: Collection
}
// CHECK-LABEL: .MultiPoint@
// CHECK-NEXT: Requirement signature: <Self where Self.[MultiPoint]C : CoordinateSystem, Self.[MultiPoint]P == Self.[MultiPoint]C.[CoordinateSystem]P, Self.[MultiPoint]X : NonEmptyProtocol, Self.[MultiPoint]C.[CoordinateSystem]P == Self.[MultiPoint]X.[Sequence]Element, Self.[MultiPoint]X.[NonEmptyProtocol]C : NonEmptyProtocol>
public protocol MultiPoint {
associatedtype C: CoordinateSystem
associatedtype P: Point where Self.P == Self.C.P
// expected-warning@-1 {{redundant conformance constraint 'Self.P' : 'Point'}}
associatedtype X: NonEmptyProtocol
where X.C: NonEmptyProtocol,
X.Element == Self.P
}
// CHECK-LABEL: .CoordinateSystem@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[CoordinateSystem]B.[BoundingBox]C, Self.[CoordinateSystem]B : BoundingBox, Self.[CoordinateSystem]L : Line, Self.[CoordinateSystem]P : Point, Self.[CoordinateSystem]S : Size, Self.[CoordinateSystem]B.[BoundingBox]C == Self.[CoordinateSystem]L.[MultiPoint]C, Self.[CoordinateSystem]L.[MultiPoint]C == Self.[CoordinateSystem]S.[Size]C>
public protocol CoordinateSystem {
associatedtype P: Point where Self.P.C == Self
associatedtype S: Size where Self.S.C == Self
associatedtype L: Line where Self.L.C == Self
associatedtype B: BoundingBox where Self.B.C == Self
}
// CHECK-LABEL: .Line@
// CHECK-NEXT: Requirement signature: <Self where Self : MultiPoint, Self.[MultiPoint]C == Self.[MultiPoint]P.[Point]C>
public protocol Line: MultiPoint {}
// CHECK-LABEL: .Size@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[Size]C.[CoordinateSystem]S, Self.[Size]C : CoordinateSystem>
public protocol Size {
associatedtype C: CoordinateSystem where Self.C.S == Self
}
// CHECK-LABEL: .BoundingBox@
// CHECK-NEXT: Requirement signature: <Self where Self.[BoundingBox]C : CoordinateSystem>
public protocol BoundingBox {
associatedtype C: CoordinateSystem
typealias P = Self.C.P
typealias S = Self.C.S
}
// CHECK-LABEL: .Point@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[Point]C.[CoordinateSystem]P, Self.[Point]C : CoordinateSystem>
public protocol Point {
associatedtype C: CoordinateSystem where Self.C.P == Self
}
func sameType<T>(_: T, _: T) {}
func conformsToPoint<T : Point>(_: T.Type) {}
func testMultiPoint<T : MultiPoint>(_: T) {
sameType(T.C.P.self, T.X.Element.self)
conformsToPoint(T.P.self)
}
func testCoordinateSystem<T : CoordinateSystem>(_: T) {
sameType(T.P.C.self, T.self)
}
|
apache-2.0
|
cc26206a656f8f661b999ce43755f84a
| 41.421053 | 397 | 0.734801 | 3.655329 | false | false | false | false |
wess/reddift
|
reddiftSample/ProfileViewController.swift
|
1
|
1432
|
//
// ProfileViewController.swift
// reddift
//
// Created by sonson on 2015/04/15.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class ProfileViewController: UITableViewController {
var session:Session?
@IBOutlet var cell1:UITableViewCell?
@IBOutlet var cell2:UITableViewCell?
@IBOutlet var cell3:UITableViewCell?
@IBOutlet var cell4:UITableViewCell?
@IBOutlet var cell5:UITableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
session?.getProfile({ (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
if let profile = result.value as? Account {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.cell1?.detailTextLabel?.text = profile.name
self.cell2?.detailTextLabel?.text = profile.id
self.cell3?.detailTextLabel?.text = NSDate(timeIntervalSince1970: Double(profile.created)).description
self.cell4?.detailTextLabel?.text = profile.commentKarma.description
self.cell5?.detailTextLabel?.text = profile.linkKarma.description
})
}
}
})
}
}
|
mit
|
43f220230f37f8e99e629bdabaeee1e3
| 33.047619 | 126 | 0.597203 | 4.931034 | false | false | false | false |
SagarSDagdu/SDDownloadManager
|
SDDownloadManager/ViewController.swift
|
1
|
4359
|
//
// ViewController.swift
// SDDownloadManager
//
// Created by Sagar Dagdu on 8/5/17.
// Copyright © 2017 Sagar Dagdu. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class ViewController: UIViewController {
//MARK:- Properties
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var finalUrlLabel: UILabel!
private let downloadManager = SDDownloadManager.shared
let directoryName : String = "TestDirectory"
let fiveMBUrl = "https://sample-videos.com/video123/mp4/480/big_buck_bunny_480p_5mb.mp4"
let tenMBUrl = "https://sample-videos.com/video123/mp4/480/big_buck_bunny_480p_10mb.mp4"
//MARK:- Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
self.foregrounDownloadDemo()
self.backgroundDownloadDemo()
}
private func setupUI() {
self.progressView.setProgress(0, animated: false)
self.progressLabel.text = "0.0 %"
self.finalUrlLabel.text = ""
}
private func foregrounDownloadDemo() {
let request = URLRequest(url: URL(string: self.fiveMBUrl)!)
let downloadKey = self.downloadManager.downloadFile(withRequest: request,
inDirectory: directoryName,
onProgress: { [weak self] (progress) in
let percentage = String(format: "%.1f %", (progress * 100))
self?.progressView.setProgress(Float(progress), animated: true)
self?.progressLabel.text = "\(percentage) %"
}) { [weak self] (error, url) in
if let error = error {
print("Error is \(error as NSError)")
} else {
if let url = url {
print("Downloaded file's url is \(url.path)")
self?.finalUrlLabel.text = url.path
}
}
}
print("The key is \(downloadKey!)")
}
private func backgroundDownloadDemo() {
let request = URLRequest(url: URL(string: self.tenMBUrl)!)
self.downloadManager.showLocalNotificationOnBackgroundDownloadDone = true
self.downloadManager.localNotificationText = "All background downloads complete"
let downloadKey = self.downloadManager.downloadFile(withRequest: request, inDirectory: directoryName, withName: directoryName, shouldDownloadInBackground: true, onProgress: { (progress) in
let percentage = String(format: "%.1f %", (progress * 100))
debugPrint("Background progress : \(percentage)")
}) { [weak self] (error, url) in
if let error = error {
print("Error is \(error as NSError)")
} else {
if let url = url {
print("Downloaded file's url is \(url.path)")
self?.finalUrlLabel.text = url.path
}
}
}
print("The key is \(downloadKey!)")
}
}
|
mit
|
b7dbd17cd922cc769ce40ac96f77046c
| 40.903846 | 196 | 0.599358 | 4.858417 | false | false | false | false |
JavierAmorDeLaCruz/Poketris
|
Practica2_2/BlockView.swift
|
1
|
2739
|
//
// BlockView.swift
// Practica2_2
//
// Created by Javier Amor De La Cruz on 9/10/16.
// Copyright © 2016 Javier Amor De La Cruz. All rights reserved.
//
import UIKit
protocol BlockViewDataSource: class {
/// Preguntar al Data Source cual es el ancho de la ficha
func BlockWidth(for blockView: BlockView) -> Int
/// Preguntar al Data Source cual es el alto de la ficha
func BlockHeight(for blockView: BlockView) -> Int
/// Preguntar al Data Source que imagen hay que poner en primer plano en una posicion de la ficha.
func backgroundImageName(for blockView: BlockView, atRow row: Int, atColumn column: Int) -> UIImage?
func foregroundImageName(for blockView: BlockView, atRow row: Int, atColumn column: Int) -> UIImage?
}
class BlockView: UIView {
weak var dataSource: BlockViewDataSource!
var boxSize: CGFloat!
override func draw(_ rect: CGRect) {
updateBoxSize()
drawBlock()
}
// Pinta el bloque siguiente
private func drawBlock() {
let width = dataSource.BlockWidth(for: self)
let heigth = dataSource.BlockHeight(for: self)
for r in 0..<heigth {
for c in 0..<width {
drawBox(row: r, column:c)
}
}
}
// Dibuja un cuadrado en la pos. indicada
private func drawBox(row: Int, column: Int){
if let bgImg = dataSource.backgroundImageName(for: self, atRow: row, atColumn: column),
let fgImg = dataSource.foregroundImageName(for: self, atRow: row, atColumn: column) {
let x = box2Point(column)
let y = box2Point(row)
let width = box2Point(1)
let height = box2Point(1)
let rect = CGRect(x: x, y: y, width: width, height: height)
bgImg.draw(in: rect)
fgImg.draw(in: rect)
}
}
// Calcula el tamaño actual de la box ????
private func updateBoxSize() {
// Tamaño del tablero
let rows = dataSource.BlockHeight(for: self)
let columns = dataSource.BlockWidth(for: self)
// Tamaño en puntos de la zona de la zona de la View donde voy a dibujar
let width = bounds.size.width
let height = bounds.size.height
// Tamaño de un cuadrado en puntos
let boxWidth = width / CGFloat(columns)
let boxHeight = height / CGFloat(rows)
boxSize = min(boxWidth, boxHeight)
}
// Transforma una coordenada box a puntos. ???
private func box2Point(_ box: Int) -> CGFloat {
return CGFloat(box) * boxSize
}
}
|
mit
|
838b93c265466a01b161ba46f1bf33ee
| 28.085106 | 104 | 0.587052 | 3.922525 | false | false | false | false |
TouchInstinct/LeadKit
|
TIFoundationUtils/CodableKeyValueStorage/Sources/CodableKeyValueStorage+BackingStore.swift
|
1
|
2432
|
//
// Copyright (c) 2020 Touch Instinct
//
// 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 TISwiftUtils
public typealias CodableKeyValueBackingStore<S: CodableKeyValueStorage, T: Codable> = BackingStore<S, T>
public extension BackingStore where Store: CodableKeyValueStorage, StoreContent: Codable {
init<Value: Codable>(key: StorageKey<Value>,
codableKeyValueStorage: Store,
decoder: CodableKeyValueDecoder = JSONKeyValueDecoder(),
encoder: CodableKeyValueEncoder = JSONKeyValueEncoder())
where StoreContent == Value? {
self.init(store: codableKeyValueStorage,
getClosure: { try? $0.codableObject(forKey: key, decoder: decoder) },
setClosure: { try? $0.setOrRemove(codableObject: $1, forKey: key, encoder: encoder) })
}
init(wrappedValue: StoreContent,
key: StorageKey<StoreContent>,
codableKeyValueStorage: Store,
decoder: CodableKeyValueDecoder = JSONKeyValueDecoder(),
encoder: CodableKeyValueEncoder = JSONKeyValueEncoder()) {
self.init(store: codableKeyValueStorage,
getClosure: { $0.codableObject(forKey: key, defaultValue: wrappedValue, decoder: decoder) },
setClosure: { try? $0.setOrRemove(codableObject: $1, forKey: key, encoder: encoder) })
}
}
|
apache-2.0
|
fe2f93f60e65e694b3bfd0742aad2911
| 48.632653 | 110 | 0.70148 | 4.659004 | false | false | false | false |
kickstarter/ios-oss
|
Kickstarter-iOS/Features/Comments/Views/CommentTableViewFooterView.swift
|
1
|
3606
|
import Library
import Prelude
import UIKit
protocol CommentTableViewFooterViewDelegate: AnyObject {
func commentTableViewFooterViewDidTapRetry(_ view: CommentTableViewFooterView)
}
final class CommentTableViewFooterView: UIView {
// MARK: - Properties
private let viewModel = CommentTableViewFooterViewModel()
private lazy var activityIndicatorView: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
return indicator
}()
weak var delegate: CommentTableViewFooterViewDelegate?
private lazy var retryButton = { UIButton(type: .custom) }()
private lazy var rootStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.bindViewModel()
self.configureViews()
self.retryButton.addTarget(self, action: #selector(self.retryButtonTapped), for: .touchUpInside)
self.activityIndicatorView.startAnimating()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Actions
@objc func retryButtonTapped() {
self.delegate?.commentTableViewFooterViewDidTapRetry(self)
}
// MARK: - Configuration
func configureWith(value: CommentTableViewFooterViewState) {
self.viewModel.inputs.configure(with: value)
}
private func configureViews() {
_ = self
|> \.backgroundColor .~ .ksr_white
_ = (self.rootStackView, self)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToMarginsInParent()
_ = ([self.activityIndicatorView, self.retryButton], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
}
// MARK: - View model
override func bindViewModel() {
super.bindViewModel()
self.activityIndicatorView.rac.hidden = self.viewModel.outputs.activityIndicatorHidden
self.retryButton.rac.hidden = self.viewModel.outputs.retryButtonHidden
self.rootStackView.rac.hidden = self.viewModel.outputs.rootStackViewHidden
self.viewModel.outputs.bottomInsetHeight
.observeForUI()
.observeValues { [weak self] height in
guard let self = self else { return }
_ = self.rootStackView
|> \.layoutMargins .~ .init(
top: Styles.grid(2),
left: Styles.grid(3),
bottom: Styles.grid(height),
right: Styles.grid(3)
)
}
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self.rootStackView
|> rootStackViewStyle
_ = self.retryButton
|> retryButtonStyle
}
}
// MARK: - Styles
private let retryButtonStyle: ButtonStyle = { button in
button
|> UIButton.lens.title(for: .normal) %~ { _ in
Strings.Couldnt_load_more_comments_Tap_to_retry()
}
|> UIButton.lens.titleLabel.lineBreakMode .~ .byWordWrapping
|> UIButton.lens.titleLabel.font .~ UIFont.ksr_subhead()
|> UIButton.lens.image(for: .normal) .~ Library.image(named: "circle-back")?
.withRenderingMode(.alwaysTemplate)
|> UIButton.lens.titleColor(for: .normal) .~ UIColor.ksr_celebrate_700
|> UIButton.lens.tintColor .~ UIColor.ksr_celebrate_700
|> UIButton.lens.titleEdgeInsets .~ UIEdgeInsets(left: Styles.grid(1))
|> UIButton.lens.contentVerticalAlignment .~ .top
|> UIButton.lens.contentHorizontalAlignment .~ .left
}
private let rootStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.isLayoutMarginsRelativeArrangement .~ true
}
|
apache-2.0
|
39b5e9a6b98e1809639252269cfb8894
| 27.393701 | 100 | 0.696062 | 4.658915 | false | false | false | false |
movier/learn-ios
|
learn-ios/core-montion/CoreMotionViewController.swift
|
1
|
4378
|
//
// CoreMotionViewController.swift
// learn-ios
//
// Created by Oliver on 16/1/4.
// Copyright © 2016年 movier. All rights reserved.
//
import UIKit
import CoreMotion
//
// http://nshipster.com/cmdevicemotion/
//
class CoreMotionViewController: UIViewController {
@IBOutlet weak var value: UILabel!
@IBOutlet weak var image: UIImageView!
let manager = CMMotionManager()
// get magnitude of vector via Pythagorean theorem
func magnitudeFromAttitude(attitude: CMAttitude) -> Double {
return sqrt(pow(attitude.roll, 2) + pow(attitude.yaw, 2) + pow(attitude.pitch, 2))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print("Hello")
guard manager.deviceMotionAvailable else {
fatalError("CMMotionManager not available.")
}
// initial configuration
// var initialAttitude = manager.deviceMotion.attitude
}
override func viewDidAppear(animated: Bool) {
print("view will appear")
// trigger values - a gap so there isn't a flicker zone
let beginRoll = 1.5
var beginCapture = false
let queue = NSOperationQueue.mainQueue()
manager.deviceMotionUpdateInterval = 0.1
manager.startDeviceMotionUpdatesToQueue(queue) {
(data: CMDeviceMotion?, error: NSError?) in
// let rotation = atan2(data!.gravity.x, data!.gravity.y) - M_PI
// self.image.transform = CGAffineTransformMakeRotation(CGFloat(rotation))
// (data: CMDeviceMotion?, error: NSError?) in
// translate the attitude
// data!.attitude.multiplyByInverseOfAttitude(initialAttitude)
// // calculate magnitude of the change from our initial attitude
// let magnitude = self.magnitudeFromAttitude(data!.attitude) ?? 0
//
// print("Magnitude:\(magnitude)")
//
// // show the prompt
// if !showingPrompt && magnitude > showPromptTrigger {
// showingPrompt = true
// self.image.image = UIImage(named: "photo1.png")
// }
//
// // hide the prompt
// if showingPrompt && magnitude < showAnswerTrigger {
// showingPrompt = false
// self.image.image = UIImage(named: "IMG_5356.JPG")
// }
// print("Pitch:\(data!.attitude.pitch)")
// print("Roll:\(data!.attitude.roll)")
// print("Yaw:\(data!.attitude.yaw)")
if data!.attitude.roll >= beginRoll {
beginCapture = true
}
if beginCapture && data!.attitude.roll >= 2.5 {
// self.image.image = UIImage(named: "photo1.png")
// print("Set image")
// beginCapture = false
print("klklkl")
self.performSegueWithIdentifier("redirectToAA", sender: self)
self.manager.stopDeviceMotionUpdates()
}
}
}
@IBAction func redirect(sender: UIButton) {
performSegueWithIdentifier("redirectToHelper", sender: self)
// self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func unwindToVC(segue: UIStoryboardSegue) {
}
// 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.
}
}
|
mit
|
e8930d12ceaee4ec0c80d29406aaef0f
| 32.396947 | 106 | 0.533943 | 5.394575 | false | false | false | false |
donald-pinckney/Ideal-Gas-Simulator
|
Thermo/GameViewController.swift
|
1
|
4434
|
//
// GameViewController.swift
// Thermo
//
// Created by Donald Pinckney on 2/12/15.
// Copyright (c) 2015 donald. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController, SCNSceneRendererDelegate {
@IBOutlet weak var sceneView: SCNView!
@IBOutlet weak var labelN: UILabel!
@IBOutlet weak var labelD: UILabel!
@IBOutlet weak var totalKELabel: UILabel!
@IBOutlet weak var graphView: DPMovingAverageGraphView! {
didSet {
graphView.dataSource = container
graphView.minX = 0
graphView.maxX = 13 / 3.68182944105251
graphView.minY = 0
graphView.maxY = 1
graphView.numberOfHistogramBars = 30
// graphView.displayGridlines = true
// graphView.displayAxes = true
// graphView.dashGridlines = true
graphView.displayAsBoxedPlot = true
}
}
var container: RectangularContainer! {
didSet {
graphView.dataSource = container
}
}
var containerNode: RectangularContainerNode!
var lastTime: NSTimeInterval = 0
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = SCNScene()
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 2)
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
// retrieve the SCNView
let scnView = self.sceneView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = false
// show statistics such as fps and timing information
scnView.showsStatistics = false
// configure the view
scnView.backgroundColor = UIColor.blackColor()
container = RectangularContainer(numDims: 3, squareDimen: 1)
containerNode = RectangularContainerNode(r: container)
scene.rootNode.addChildNode(containerNode)
scnView.delegate = self
scnView.playing = true
let pan = UIPanGestureRecognizer(target: self, action: "pan:")
scnView.addGestureRecognizer(pan)
}
func renderer(aRenderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) {
// per-frame code here
let dt = time - lastTime
if dt < 0.1 {
container.update(dt)
}
// Do stuff with output calculations
let totalKE = container.totalKE
dispatch_async(dispatch_get_main_queue()) {
self.totalKELabel.text = "∑ KE = \(totalKE)"
self.graphView.setNeedsDisplay()
}
lastTime = time
}
func pan(pan: UIPanGestureRecognizer) {
container?.node?.eulerAngles.y += 0.005 * Float(pan.translationInView(view).x)
pan.setTranslation(CGPoint.zeroPoint, inView: view)
}
@IBAction func sliderNChanged(sender: UISlider) {
var N = Int(round(sender.value))
labelN.text = "N = \(N)"
container.N = N
}
@IBAction func sliderDChanged(sender: UISlider) {
var D = Int(round(sender.value))
labelD.text = "D = \(D)"
let N = container.N
containerNode.removeFromParentNode()
container = RectangularContainer(numDims: D, squareDimen: 1)
container.N = N
containerNode = RectangularContainerNode(r: container)
sceneView.scene?.rootNode.addChildNode(containerNode)
}
}
|
mit
|
de9c80a2fbf72d54cb7a93a460b8cd64
| 29.777778 | 86 | 0.600632 | 4.946429 | false | false | false | false |
crazypoo/PTools
|
Pods/KakaJSON/Sources/KakaJSON/Metadata/Property.swift
|
1
|
1096
|
//
// Property.swift
// KakaJSON
//
// Created by MJ Lee on 2019/7/30.
// Copyright © 2019 MJ Lee. All rights reserved.
//
/// Info for stored property(存储属性的相关信息)
public class Property: CustomStringConvertible {
public let name: String
public let type: Any.Type
public private(set) lazy var dataType: Any.Type = type~!
public let isVar: Bool
public let offset: Int
public let ownerType: Any.Type
init(name: String, type: Any.Type,
isVar: Bool, offset: Int,
ownerType: Any.Type) {
self.name = name
self.type = type
self.isVar = isVar
self.offset = offset
self.ownerType = ownerType
}
func set(_ value: Any, for model: UnsafeMutableRawPointer) {
(model + offset).kj_set(value, type)
}
func get(from model: UnsafeMutableRawPointer) -> Any {
return (model + offset).kj_get(type)
}
public var description: String {
return "\(name) { type = \(type), isVar = \(isVar), offset = \(offset), ownerType = \(ownerType) }"
}
}
|
mit
|
bb97cd67eaa354d14caa8976905f4ec3
| 26.615385 | 107 | 0.604457 | 3.765734 | false | false | false | false |
payjp/payjp-ios
|
Sources/Extensions/UIView+PAYJP.swift
|
1
|
1770
|
//
// UIView+PAYJP.swift
// PAYJP
//
// Created by Li-Hsuan Chen on 2019/08/09.
// Copyright © 2019 PAY, Inc. All rights reserved.
//
import UIKit
extension UIView {
struct RectCorner: OptionSet {
let rawValue: UInt
static var minXMinYCorner = RectCorner(rawValue: 1 << 0)
static var maxXMinYCorner = RectCorner(rawValue: 1 << 1)
static var minXMaxYCorner = RectCorner(rawValue: 1 << 2)
static var maxXMaxYCorner = RectCorner(rawValue: 1 << 3)
static var allCorners: RectCorner = [.minXMinYCorner,
.maxXMinYCorner,
.minXMaxYCorner,
.maxXMaxYCorner]
}
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
func roundingCorners(corners: RectCorner, radius: CGFloat) {
if #available(iOS 11.0, *) {
let corners = CACornerMask(rawValue: corners.rawValue)
layer.cornerRadius = radius
layer.maskedCorners = corners
} else {
let corners = UIRectCorner(rawValue: corners.rawValue)
let path = UIBezierPath(roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
}
|
mit
|
8294035ef0a412c184545685660979cd
| 33.686275 | 87 | 0.552855 | 5.409786 | false | false | false | false |
DanielAsher/SwiftParse
|
SwiftParse/Playgrounds/Parsing.playground/Pages/Misc.xcplaygroundpage/Contents.swift
|
1
|
2290
|
//: [Previous](@previous)
import Cocoa
import SwiftParse
let chars = ("\u{38}")
let a = Character(UnicodeScalar(379))
SwiftxTrace = true
prefix operator £ {}
public prefix func £ (literal: String) -> 𝐏<String, String>.𝒇 {
return %literal |> P.token
}
public struct P {
static let whitespace = %" " | %"\t" | %"\n"
static let spaces = ignore(whitespace*)
//: Our `token` defines whitespace handling.
static func token(parser: 𝐏<String, String>.𝒇 ) -> 𝐏<String, String>.𝒇 {
return parser ++ spaces
}
static let separator = (%";" | %",") |> P.token
static let lower = %("a"..."z")
static let upper = %("A"..."Z")
static let digit = %("0"..."9")
// simpleId cannot start with a digit.
static let simpleId = (lower | upper | %"_") & (lower | upper | digit | %"_")*^
static let number = %"." & digit+^ | (digit+^ & (%"." & digit*^)|?)
static let decimal = (%"-")|? & number
static let quotedChar = %"\\\"" | not("\"")
static let quotedId = %"\"" & quotedChar+^ & %"\""
static let ID = (simpleId | decimal | quotedId) |> P.token
static let id_equality = ID *> £"=" ++ ID
// |> map { Attribute(name: $0, value: $1) }
static let attr_list = id_equality+
}
let r1 = parse(P.ID, input: "\"í\"\t")
r1.0!.characters.count
//
//let url:NSURL = NSURL(string:"www.google.com")!
//let request:NSURLRequest = NSURLRequest(URL:url)
//let queue:NSOperationQueue = NSOperationQueue()
//
//func asynchronousWork(completion: (getResult: () throws -> NSDictionary) -> Void) -> Void {
// NSURLConnection.sendAsynchronousRequest(request, queue: queue) {
// (response, data, error) -> Void in
// guard let data = data else { return }
// do {
// let result = try NSJSONSerialization.JSONObjectWithData(data, options: [])
// as! NSDictionary
// completion(getResult: {return result})
// } catch let error {
// completion(getResult: {throw error})
// }
// }
//}
//
//// Call-site
//asynchronousWork { getResult in
// do {
// let result = try getResult()
// } catch let error {
// print(error)
// }
//}
//: [Next](@next)
|
mit
|
75691833d06e7ac6e29d118141781590
| 27.708861 | 93 | 0.553351 | 3.571654 | false | false | false | false |
mcgraw/dojo-homekit
|
dojo-homekit/XMCBaseViewController.swift
|
1
|
4395
|
//
// XMCBaseViewController.swift
// dojo-homekit
//
// Created by David McGraw on 2/11/15.
// Copyright (c) 2015 David McGraw. All rights reserved.
//
import UIKit
import HomeKit
class XMCBaseViewController: UITableViewController, HMHomeManagerDelegate {
let homeManager = HMHomeManager()
var activeHome: HMHome?
var activeRoom: HMRoom?
var lastSelectedIndexRow = 0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
homeManager.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
func updateControllerWithHome(home: HMHome) {
if let room = home.rooms.first as HMRoom? {
activeRoom = room
title = room.name + " Devices"
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showServicesSegue" {
let vc = segue.destinationViewController as! XMCAccessoryViewController
if let accessories = activeRoom?.accessories {
vc.accessory = accessories[lastSelectedIndexRow] as HMAccessory?
}
}
}
// MARK: - Table Delegate
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let accessories = activeRoom?.accessories {
return accessories.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("deviceId") as UITableViewCell?
let accessory = activeRoom!.accessories[indexPath.row] as HMAccessory
cell?.textLabel?.text = accessory.name
// ignore the information service
cell?.detailTextLabel?.text = "\(accessory.services.count - 1) service(s)"
return (cell != nil) ? cell! : UITableViewCell()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
lastSelectedIndexRow = indexPath.row
}
// MARK: - Home Delegate
// Homes are not loaded right away. Monitor the delegate so we catch the loaded signal.
func homeManager(manager: HMHomeManager, didAddHome home: HMHome) {
}
func homeManager(manager: HMHomeManager, didRemoveHome home: HMHome) {
}
func homeManagerDidUpdateHomes(manager: HMHomeManager) {
if let home = homeManager.primaryHome {
activeHome = home
updateControllerWithHome(home)
} else {
initialHomeSetup()
}
tableView.reloadData()
}
func homeManagerDidUpdatePrimaryHome(manager: HMHomeManager) {
}
// MARK: - Setup
// Create our primary home if it doens't exist yet
private func initialHomeSetup() {
homeManager.addHomeWithName("Porter Ave", completionHandler: { (home, error) in
if error != nil {
print("Something went wrong when attempting to create our home. \(error?.localizedDescription)")
} else {
if let discoveredHome = home {
// Add a new room to our home
discoveredHome.addRoomWithName("Office", completionHandler: { (room, error) in
if error != nil {
print("Something went wrong when attempting to create our room. \(error?.localizedDescription)")
} else {
self.updateControllerWithHome(discoveredHome)
}
})
// Assign this home as our primary home
self.homeManager.updatePrimaryHome(discoveredHome, completionHandler: { (error) in
if error != nil {
print("Something went wrong when attempting to make this home our primary home. \(error?.localizedDescription)")
}
})
} else {
print("Something went wrong when attempting to create our home")
}
}
})
}
}
|
mit
|
7702022b36dea945f1e8b033c673dbcb
| 33.335938 | 140 | 0.587941 | 5.507519 | false | false | false | false |
hightower/UIAlertController-Show
|
UIAlertController+Show/UIAlertController+Show.swift
|
1
|
1319
|
//
// UIAlertController+Show.swift
// UIAlertController+Show
//
// Created by Erik Ackermann on 1/20/16.
//
//
import Foundation
import UIKit
import ObjectiveC
private var alertWindowAssociationKey: UInt8 = 0
extension UIAlertController {
var alertWindow: UIWindow? {
get {
return objc_getAssociatedObject(self, &alertWindowAssociationKey) as? UIWindow
}
set(newValue) {
objc_setAssociatedObject(self, &alertWindowAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
@objc public func show() {
show(true)
}
@objc public func show(_ animated: Bool) {
show(animated, completion: nil)
}
@objc public func show(_ animated: Bool, completion: (() -> Void)? = nil) {
self.alertWindow = UIWindow(frame: UIScreen.main.bounds)
self.alertWindow?.rootViewController = UIViewController()
self.alertWindow?.windowLevel = UIWindowLevelAlert + 1
self.alertWindow?.makeKeyAndVisible()
self.alertWindow?.rootViewController?.present(self, animated: animated, completion: completion)
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.alertWindow?.isHidden = true
self.alertWindow = nil
}
}
|
mit
|
7b417c4f435f36e784ab6b902cecbd5d
| 26.479167 | 116 | 0.665656 | 4.727599 | false | false | false | false |
BennyHarv3/habitica-ios
|
HabitRPG/Views/PaddedView.swift
|
2
|
1130
|
//
// PaddedView.swift
// Habitica
//
// Created by Phillip Thelen on 27/02/2017.
// Copyright © 2017 Phillip Thelen. All rights reserved.
//
import UIKit
class PaddedView: UIView {
var horizontalPadding: CGFloat = 8.0
var verticalPadding: CGFloat = 4.0
var containedView: UIView? {
willSet(newView) {
if let containedView = containedView {
containedView.removeFromSuperview()
}
if let newView = newView {
self.addSubview(newView)
}
}
}
override func layoutSubviews() {
if let containedView = containedView {
containedView.frame = CGRect(x: horizontalPadding, y: verticalPadding, width: self.frame.size.width-self.horizontalPadding*2, height: self.frame.size.height-self.verticalPadding*2)
}
}
override var intrinsicContentSize: CGSize {
if let containedSize = containedView?.intrinsicContentSize {
return CGSize(width: containedSize.width+horizontalPadding*2, height: containedSize.height+verticalPadding*2)
}
return CGSize()
}
}
|
gpl-3.0
|
43c6fde9fa98d746dce84c1e64f01bbd
| 27.948718 | 188 | 0.641275 | 4.57085 | false | false | false | false |
pluralsight/PSOperations
|
PSOperations/OperationQueue.swift
|
1
|
5066
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains an NSOperationQueue subclass.
*/
import Foundation
public typealias PSOperationQueueDelegate = OperationQueueDelegate
/**
The delegate of an `OperationQueue` can respond to `Operation` lifecycle
events by implementing these methods.
In general, implementing `OperationQueueDelegate` is not necessary; you would
want to use an `OperationObserver` instead. However, there are a couple of
situations where using `OperationQueueDelegate` can lead to simpler code.
For example, `GroupOperation` is the delegate of its own internal
`OperationQueue` and uses it to manage dependencies.
*/
@objc public protocol OperationQueueDelegate: NSObjectProtocol {
@objc optional func operationQueue(_ operationQueue: OperationQueue, willAddOperation operation: Foundation.Operation)
@objc optional func operationQueue(_ operationQueue: OperationQueue, operationDidFinish operation: Foundation.Operation, withErrors errors: [Error])
}
public typealias PSOperationQueue = OperationQueue
/**
`OperationQueue` is an `NSOperationQueue` subclass that implements a large
number of "extra features" related to the `Operation` class:
- Notifying a delegate of all operation completion
- Extracting generated dependencies from operation conditions
- Setting up dependencies to enforce mutual exclusivity
*/
open class OperationQueue: Foundation.OperationQueue {
open weak var delegate: OperationQueueDelegate?
override open func addOperation(_ operation: Foundation.Operation) {
if let op = operation as? Operation {
// Set up a `BlockObserver` to invoke the `OperationQueueDelegate` method.
let delegate = BlockObserver(
startHandler: nil,
produceHandler: { [weak self] in
self?.addOperation($1)
},
finishHandler: { [weak self] finishedOperation, errors in
if let q = self {
q.delegate?.operationQueue?(q, operationDidFinish: finishedOperation, withErrors: errors)
}
}
)
op.addObserver(delegate)
// Extract any dependencies needed by this operation.
let dependencies = op.conditions.compactMap {
$0.dependencyForOperation(op)
}
for dependency in dependencies {
op.addDependency(dependency)
self.addOperation(dependency)
}
/*
With condition dependencies added, we can now see if this needs
dependencies to enforce mutual exclusivity.
*/
let concurrencyCategories: [String] = op.conditions.compactMap { condition in
guard type(of: condition).isMutuallyExclusive else { return nil }
return "\(type(of: condition))"
}
if !concurrencyCategories.isEmpty {
// Set up the mutual exclusivity dependencies.
let exclusivityController = ExclusivityController.sharedExclusivityController
exclusivityController.addOperation(op, categories: concurrencyCategories)
op.addObserver(BlockObserver(finishHandler: { operation, _ in
exclusivityController.removeOperation(operation, categories: concurrencyCategories)
}))
}
} else {
/*
For regular `NSOperation`s, we'll manually call out to the queue's
delegate we don't want to just capture "operation" because that
would lead to the operation strongly referencing itself and that's
the pure definition of a memory leak.
*/
operation.addCompletionBlock { [weak self, weak operation] in
guard let queue = self, let operation = operation else { return }
queue.delegate?.operationQueue?(queue, operationDidFinish: operation, withErrors: [])
}
}
delegate?.operationQueue?(self, willAddOperation: operation)
super.addOperation(operation)
/*
Indicate to the operation that we've finished our extra work on it
and it's now it a state where it can proceed with evaluating conditions,
if appropriate.
*/
if let op = operation as? Operation {
op.didEnqueue()
}
}
override open func addOperations(_ ops: [Foundation.Operation], waitUntilFinished wait: Bool) {
/*
The base implementation of this method does not call `addOperation()`,
so we'll call it ourselves.
*/
for operation in ops {
addOperation(operation)
}
if wait {
for operation in ops {
operation.waitUntilFinished()
}
}
}
}
|
apache-2.0
|
428777869b7612b8e5c0986ab06679b3
| 38.5625 | 152 | 0.633491 | 5.767654 | false | false | false | false |
UnsignedInt8/LightSwordX
|
LightSwordX/Socks5/Socks5Helper.swift
|
2
|
2376
|
//
// Socks5Helper.swift
// LightSwordX
//
// Created by Neko on 12/17/15.
// Copyright © 2015 Neko. All rights reserved.
//
import Foundation
import SINQ
class Socks5Helper {
static func refineDestination(rawData: [UInt8]) -> (cmd: REQUEST_CMD, addr: String, port: Int, headerSize: Int)? {
if rawData.count < 4 {
return nil
}
if let cmd = REQUEST_CMD(rawValue: rawData[1]) {
let atyp = rawData[3]
var addr = ""
var dnLength: UInt8 = 0
switch (atyp) {
case ATYP.DN.rawValue:
dnLength = rawData[4]
let data = sinq(rawData).skip(5).take(Int(dnLength)).toArray()
addr = NSString(bytes: data, length: data.count, encoding: NSUTF8StringEncoding) as! String
break
case ATYP.IPV4.rawValue:
dnLength = 4
addr = sinq(rawData).skip(4).take(4).aggregate("", combine: { (c: String, n: UInt8) in c.characters.count > 1 ? c + String(format: ".%d", n) : String(format: "%d.%d", c, n)})
break
case ATYP.IPV6.rawValue:
dnLength = 16
let bytes = sinq(rawData).skip(4).take(16).toArray()
addr = bytes.reduce("", combine: { (s: String, n: UInt8) -> String in
let length = s.length
let lastSemicolon = s.lastIndexOf(":")
if length == 4 {
return "\(s):\(String(format: "%02x", n))"
}
return length - lastSemicolon == 5 ? "\(s):\(String(format: "%02x", n))" : "\(s)\(String(format: "%02x", n))"
})
break
default:
return nil
}
let headerSize = Int(4 + (atyp == ATYP.DN.rawValue ? 1 : 0) + dnLength + 2)
if rawData.count < headerSize {
return nil
}
let littleEndian = [rawData[headerSize - 2], rawData[headerSize - 1]]
let port = UnsafePointer<UInt16>(littleEndian).memory.bigEndian
return ( cmd, addr, Int(port), headerSize )
}
return nil
}
}
|
gpl-2.0
|
cfe40fd6a9fb3a69b803dd638b543dc9
| 34.462687 | 190 | 0.462316 | 4.326047 | false | false | false | false |
noraesae/kawa
|
kawa/StatusBar.swift
|
1
|
612
|
import AppKit
import Cocoa
class StatusBar {
static let shared: StatusBar = StatusBar()
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
init() {
let button = item.button!
let buttonImage = NSImage(named: "StatusItemIcon")
buttonImage?.isTemplate = true
button.target = self
button.action = #selector(StatusBar.action(_:))
button.image = buttonImage
button.appearsDisabled = false;
button.toolTip = "Click to open preferences"
}
@objc func action(_ sender: NSButton) {
MainWindowController.shared.showAndActivate(sender)
}
}
|
mit
|
58de8daf0013f9d185fe5eed1d904ab6
| 23.48 | 83 | 0.714052 | 4.434783 | false | false | false | false |
jwfriese/Fleet
|
FleetTests/CoreExtensions/Controls/UIControlEventEqualityMatcher.swift
|
1
|
4087
|
import UIKit
import Nimble
func equal(_ expectedValue: UIControl.Event?) -> Predicate<UIControl.Event> {
return Predicate { actualExpression in
guard let expectedValue = expectedValue else {
return PredicateResult(
status: .doesNotMatch,
message: .expectedTo("(use beNil() to match nils)")
)
}
let errorMessage: ExpectationMessage =
.expectedActualValueTo("equal <\(stringify(expectedValue))>")
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .doesNotMatch,
message: errorMessage.appendedBeNilHint()
)
}
let matches = actualValue.rawValue == expectedValue.rawValue
if !matches {
return PredicateResult(
status: .doesNotMatch,
message: .expectedCustomValueTo("equal \(stringify(expectedValue))", actual: "<\(stringify(actualValue))>")
)
}
return PredicateResult(status: .matches, message: errorMessage)
}.requireNonNil
}
func equal(_ expectedValue: [UIControl.Event]?) -> Predicate<[UIControl.Event]> {
return Predicate { actualExpression in
guard let expectedValue = expectedValue else {
return PredicateResult(
status: .doesNotMatch,
message: .expectedTo("(use beNil() to match nils)")
)
}
let errorMessage: ExpectationMessage =
.expectedActualValueTo("equal <\(allToString(controlEvents: expectedValue))>")
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .doesNotMatch,
message: errorMessage.appendedBeNilHint()
)
}
let matches = actualValue.elementsEqual(expectedValue)
if !matches {
return PredicateResult(
status: .doesNotMatch,
message: .expectedCustomValueTo("equal \(stringify(expectedValue))", actual: "<\(allToString(controlEvents: actualValue))>")
)
}
return PredicateResult(status: .matches, message: errorMessage)
}
}
extension UIControl.Event {
func toString() -> String {
switch self {
case UIControl.Event.touchDown:
return "touchDown"
case UIControl.Event.touchDownRepeat:
return "touchDownRepeat"
case UIControl.Event.touchDragInside:
return "touchDragInside"
case UIControl.Event.touchDragOutside:
return "touchDragOutside"
case UIControl.Event.touchDragEnter:
return "touchDragEnter"
case UIControl.Event.touchDragExit:
return "touchDragExit"
case UIControl.Event.touchUpInside:
return "touchUpInside"
case UIControl.Event.touchUpOutside:
return "touchUpOutside"
case UIControl.Event.touchCancel:
return "touchCancel"
case UIControl.Event.valueChanged:
return "valueChanged"
case UIControl.Event.editingDidBegin:
return "editingDidBegin"
case UIControl.Event.editingChanged:
return "editingChanged"
case UIControl.Event.editingDidEnd:
return "editingDidEnd"
case UIControl.Event.editingDidEndOnExit:
return "editingDidEndOnExit"
case UIControl.Event.allTouchEvents:
return "allTouchEvents"
case UIControl.Event.allEditingEvents:
return "allEditingEvents"
default:
return "<unrecognized>"
}
}
}
fileprivate func allToString(controlEvents: [UIControl.Event]) -> String {
var string = "["
for event in controlEvents {
string += "\(event.toString()), "
}
if !controlEvents.isEmpty {
string.remove(at: string.index(before: string.endIndex))
string.remove(at: string.index(before: string.endIndex))
}
string += "]"
return string
}
|
apache-2.0
|
f055f83cad1cfdb88fe77f19e07fcf35
| 33.635593 | 140 | 0.610472 | 5.838571 | false | false | false | false |
mownier/photostream
|
Photostream/UI/User Profile/UserProfileViewController.swift
|
1
|
2357
|
//
// UserProfileViewController.swift
// Photostream
//
// Created by Mounir Ybanez on 10/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
class UserProfileViewController: UIViewController {
var userProfileView: UserProfileView!
var presenter: UserProfileModuleInterface!
override func loadView() {
let frame = CGRect(origin: .zero, size: UIScreen.main.bounds.size)
userProfileView = UserProfileView()
userProfileView.frame = frame
userProfileView.delegate = self
view = userProfileView
}
override func viewDidLoad() {
super.viewDidLoad()
userProfileView.actionLoadingView.startAnimating()
presenter.fetchUserProfile()
}
func startLoadingView() {
userProfileView.actionLoadingView.startAnimating()
}
func stopLoadingView() {
userProfileView.actionLoadingView.stopAnimating()
}
}
extension UserProfileViewController: UserProfileScene {
var controller: UIViewController? {
return self
}
func didFetchUserProfile(with data: UserProfileData) {
update(with: data)
}
func didFollow(with data: UserProfileData) {
update(with: data)
}
func didUnfollow(with data: UserProfileData) {
update(with: data)
}
func didFetchUserProfile(with error: String?) {
stopLoadingView()
}
func didFollow(with error: String) {
stopLoadingView()
}
func didUnfollow(with error: String) {
stopLoadingView()
}
private func update(with data: UserProfileData) {
let item = data as? UserProfileViewItem
userProfileView.configure(wiht: item)
stopLoadingView()
}
}
extension UserProfileViewController: UserProfileViewDelegate {
func willEdit(view: UserProfileView) {
presenter.presentProfileEdit()
}
func willFollow(view: UserProfileView) {
startLoadingView()
presenter.follow()
}
func willUnfollow(view: UserProfileView) {
startLoadingView()
presenter.unfollow()
}
func willShowFollowers() {
presenter.presentFollowers()
}
func willShowFollowing() {
presenter.presentFollowing()
}
}
|
mit
|
0dc89d1ef473f7f5e1dc5cf728ae0197
| 22.326733 | 74 | 0.637946 | 5.178022 | false | false | false | false |
safaride/XKTabbedSplitViewController
|
XKTabbedSplitViewController/Tabs/FatherTableViewController.swift
|
1
|
1002
|
//
// FatherTableViewController.swift
// XKTabbedSplitViewController
//
// Created by DengYikai on 3/28/16.
// Copyright © 2016 Safaride. All rights reserved.
//
import UIKit
class FatherTableViewController: UITableViewController {
override func viewDidLoad() {
let red: CGFloat = CGFloat(Double(arc4random_uniform(255)) / 255.0)
let green: CGFloat = CGFloat(Double(arc4random_uniform(255)) / 255.0)
let blue: CGFloat = CGFloat(Double(arc4random_uniform(255)) / 255.0)
self.view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
self.tableView.scrollEnabled = false
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
}
|
gpl-2.0
|
ce7b2bd8b169a0bc05ef48b5fee656fc
| 28.441176 | 96 | 0.66034 | 4.409692 | false | false | false | false |
EstebanVallejo/sdk-ios
|
MercadoPagoSDK/MercadoPagoSDK/InstallmentsViewController.swift
|
2
|
2969
|
//
// InstallmentsViewController.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 9/1/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import Foundation
import UIKit
public class InstallmentsViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
var publicKey : String?
@IBOutlet weak private var tableView : UITableView!
var loadingView : UILoadingView!
var payerCosts : [PayerCost]!
var amount : Double = 0
var callback : ((payerCost: PayerCost?) -> Void)?
var bundle : NSBundle? = MercadoPago.getBundle()
init(payerCosts: [PayerCost]?, amount: Double, callback: (payerCost: PayerCost?) -> Void) {
super.init(nibName: "InstallmentsViewController", bundle: bundle)
self.payerCosts = payerCosts
self.amount = amount
self.callback = callback
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public init() {
super.init(nibName: "InstallmentsViewController", bundle: self.bundle)
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override public func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override public func viewDidLoad() {
super.viewDidLoad()
self.title = "Cuotas".localized
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
var installmentNib = UINib(nibName: "InstallmentTableViewCell", bundle: self.bundle)
self.tableView.registerNib(installmentNib, forCellReuseIdentifier: "installmentCell")
self.tableView.estimatedRowHeight = 44.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return payerCosts == nil ? 0 : payerCosts.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var pccell : InstallmentTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("installmentCell") as! InstallmentTableViewCell
let payerCost : PayerCost = self.payerCosts![indexPath.row]
pccell.fillWithPayerCost(payerCost, amount: amount)
return pccell
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
callback!(payerCost: self.payerCosts![indexPath.row])
}
}
|
mit
|
2882786b804b660e3029805e8420b26b
| 33.929412 | 144 | 0.684299 | 5.082192 | false | false | false | false |
s9998373/PHP-SRePS
|
PHP-SRePS/PHP-SRePS/SalesEntry.swift
|
1
|
1428
|
//
// SalesEntry.swift
// PHP-SRePS
//
// Created by School on 24/08/2016.
// Copyright © 2016 swindp2. All rights reserved.
//
import UIKit
import RealmSwift
class SalesEntry: Object {
dynamic var product:Product? = nil
private dynamic var _quantity:Int = 0
var quantity: Int? {
get {
return _quantity
}
set {
_quantity = newValue!
calculateTotalCost()
}
}
dynamic var totalCost:String? = nil
/// Creates a sales entry from a product and quantity.
///
/// - parameter product: The product.
/// - parameter quanity: The quantity of the product.
///
/// - returns: The SalesEntry for the product and quantity.
convenience init(product: Product, quanity: Int){
self.init();
self.product = product;
_quantity = quanity;
calculateTotalCost()
}
/// Calculates the total value of the SalesEntry.
func calculateTotalCost(){
let total = self.product!.price.decimalNumberByMultiplyingBy(NSDecimalNumber.init(long: _quantity))
totalCost = total.stringValue
}
/// Translates the total cost to an NSDecimalNumber.
///
/// - returns: An NSDecimalNumber representation of the total cost.
func decimalCost() -> NSDecimalNumber{
let cost = NSDecimalNumber.init(string: totalCost)
return cost
}
}
|
mit
|
c88a0ff5f1fe76fe7b4ca21ad1fe8440
| 25.425926 | 107 | 0.613174 | 4.445483 | false | false | false | false |
kickstarter/ios-ksapi
|
KsApi/models/lenses/FriendStatsEnvelopeLenses.swift
|
1
|
671
|
import Prelude
extension FriendStatsEnvelope {
public enum lens {
public static let stats = Lens<FriendStatsEnvelope, FriendStatsEnvelope.Stats>(
view: { $0.stats },
set: { stats, _ in FriendStatsEnvelope(stats: stats) }
)
}
}
extension Lens where Whole == FriendStatsEnvelope, Part == FriendStatsEnvelope.Stats {
public var friendProjectsCount: Lens<FriendStatsEnvelope, Int> {
return FriendStatsEnvelope.lens.stats..FriendStatsEnvelope.Stats.lens.friendProjectsCount
}
public var remoteFriendsCount: Lens<FriendStatsEnvelope, Int> {
return FriendStatsEnvelope.lens.stats..FriendStatsEnvelope.Stats.lens.remoteFriendsCount
}
}
|
apache-2.0
|
b1b27901e4a806acee416f4be8999d5e
| 32.55 | 93 | 0.758569 | 4.473333 | false | false | false | false |
sharath-cliqz/browser-ios
|
Push/PushRegistration.swift
|
2
|
4880
|
/* 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 FxA
import Shared
import SwiftyJSON
public class PushRegistration: NSObject, NSCoding {
let uaid: String
let secret: String
// We don't need to have more than one subscription until WebPush is exposed to content Javascript
// however, if/when we do, it'll make migrating easier if we have been serializing it like this all along.
fileprivate var subscriptions: [String: PushSubscription]
var defaultSubscription: PushSubscription {
return subscriptions[defaultSubscriptionID]!
}
public init(uaid: String, secret: String, subscriptions: [String: PushSubscription] = [:]) {
self.uaid = uaid
self.secret = secret
self.subscriptions = subscriptions
}
public convenience init(uaid: String, secret: String, subscription: PushSubscription) {
self.init(uaid: uaid, secret: secret, subscriptions: [defaultSubscriptionID: subscription])
}
@objc public convenience required init?(coder aDecoder: NSCoder) {
guard let uaid = aDecoder.decodeObject(forKey: "uaid") as? String,
let secret = aDecoder.decodeObject(forKey: "secret") as? String,
let subscriptions = aDecoder.decodeObject(forKey: "subscriptions") as? [String: PushSubscription] else {
fatalError("Cannot decode registration")
}
self.init(uaid: uaid, secret: secret, subscriptions: subscriptions)
}
@objc public func encode(with aCoder: NSCoder) {
aCoder.encode(uaid, forKey: "uaid")
aCoder.encode(secret, forKey: "secret")
aCoder.encode(subscriptions, forKey: "subscriptions")
}
public static func from(json: JSON) -> PushRegistration? {
guard let endpointString = json["endpoint"].stringValue(),
let endpoint = URL(string: endpointString),
let secret = json["secret"].stringValue(),
let uaid = json["uaid"].stringValue(),
let channelID = json["channelID"].stringValue() else {
return nil
}
guard let defaultSubscription = try? PushSubscription(channelID: channelID, endpoint: endpoint) else {
return nil
}
return PushRegistration(uaid: uaid, secret: secret, subscriptions: [defaultSubscriptionID: defaultSubscription])
}
}
fileprivate let defaultSubscriptionID = "defaultSubscription"
/// Small NSCodable class for persisting a channel subscription.
/// We use NSCoder because we expect it to be stored in the profile.
public class PushSubscription: NSObject, NSCoding {
let channelID: String
let endpoint: URL
let p256dhPublicKey: String
let p256dhPrivateKey: String
let authKey: String
init(channelID: String, endpoint: URL, p256dhPrivateKey: String, p256dhPublicKey: String, authKey: String) {
self.channelID = channelID
self.endpoint = endpoint
self.p256dhPrivateKey = p256dhPrivateKey
self.p256dhPublicKey = p256dhPublicKey
self.authKey = authKey
}
convenience init(channelID: String, endpoint: URL, keys: PushKeys) {
self.init(channelID: channelID,
endpoint: endpoint,
p256dhPrivateKey: keys.p256dhPrivateKey,
p256dhPublicKey: keys.p256dhPublicKey,
authKey: keys.auth)
}
convenience init(channelID: String, endpoint: URL) throws {
let keys = try PushCrypto.sharedInstance.generateKeys()
self.init(channelID: channelID, endpoint: endpoint, keys: keys)
}
@objc public convenience required init?(coder aDecoder: NSCoder) {
guard let channelID = aDecoder.decodeObject(forKey: "channelID") as? String,
let urlString = aDecoder.decodeObject(forKey: "endpoint") as? String,
let endpoint = URL(string: urlString),
let p256dhPrivateKey = aDecoder.decodeObject(forKey: "p256dhPrivateKey") as? String,
let p256dhPublicKey = aDecoder.decodeObject(forKey: "p256dhPublicKey") as? String,
let authKey = aDecoder.decodeObject(forKey: "authKey") as? String else {
return nil
}
self.init(channelID: channelID,
endpoint: endpoint,
p256dhPrivateKey: p256dhPrivateKey,
p256dhPublicKey: p256dhPublicKey,
authKey: authKey)
}
@objc public func encode(with aCoder: NSCoder) {
aCoder.encode(channelID, forKey: "channelID")
aCoder.encode(endpoint.absoluteString, forKey: "endpoint")
aCoder.encode(p256dhPrivateKey, forKey: "p256dhPrivateKey")
aCoder.encode(p256dhPublicKey, forKey: "p256dhPublicKey")
aCoder.encode(authKey, forKey: "authKey")
}
}
|
mpl-2.0
|
fcfb4f941b61847b6baea4134a99c4af
| 40.355932 | 120 | 0.676844 | 4.518519 | false | false | false | false |
zixun/CocoaChinaPlus
|
Code/CocoaChinaPlus/Application/Business/Util/Helper/HTMLModel/Parser/CCHTMLParser+HomePage.swift
|
1
|
3329
|
//
// CCHTMLParser+HomePage.swift
// CocoaChinaPlus
//
// Created by user on 15/10/30.
// Copyright © 2015年 zixun. All rights reserved.
//
import Foundation
import Ji
import Kingfisher
extension CCHTMLParser {
func parseHome(_ result: @escaping (_ model:CCPHomeModel) ->Void) {
let baseURL:String = "http://www.cocoachina.com"
_ = CCRequest(.get, baseURL).responseJi { [weak self] (ji, error) -> Void in
//TODO: ERROR处理
if let sself = self {
var options = sself.parseOptions(ji!)
let first = CCPOptionModel(href: "", title: "最新")
options.insert(first, at: options.startIndex)
//banner轮播信息
let banners = sself.parseBanner(ji!)
//最新文章
let page = sself.parseNewest(ji!)
let model = CCPHomeModel(options: options, banners: banners, page: page)
result(model)
}
}
}
fileprivate func parseNewest(_ ji: Ji) -> [CCArticleModel] {
var models = [CCArticleModel]()
guard let nodes = ji.xPath("//div[@class='forum-c']/ul/li/a") else {
return models
}
for node in nodes {
let href = node["href"]!
var inner = node.xPath("p[@class='img']/img").first!
let imageURL = inner["src"]!
inner = node.xPath("div/h4").first!
let title = inner.content!
inner = node.xPath("div/span").first!
let postTime = inner.content!
let model = CCArticleModel()
model.linkURL = href
model.title = title
model.postTime = postTime
model.imageURL = imageURL
models.append(model)
}
return models
}
fileprivate func parseBanner(_ ji:Ji) -> [CCArticleModel] {
guard let nodes = ji.xPath("//ul[@class='role-main']/li/a") else {
return [CCArticleModel]()
}
var banners = [CCArticleModel]()
for node in nodes {
let linkURL = node["href"]!
let imageURL = node.firstChildWithName("img")!["src"]!
let title = node.firstChildWithName("img")!["title"]!
let model = CCArticleModel()
model.linkURL = linkURL
model.title = title
model.imageURL = imageURL
banners.append(model)
}
return banners
}
fileprivate func parseOptions(_ ji:Ji) ->[CCPOptionModel] {
guard let nodes = ji.xPath("//div[@class='m-board']/div/h3/a") else {
return [CCPOptionModel]()
}
var options = [CCPOptionModel]()
for node:JiNode in nodes {
let model = CCPOptionModel(href:node["href"]! , title: node.content!)
if model.title.lowercased().contains("android") == false {
//因为app store 审核不能有android的任何信息
options.append(model)
}
}
return options
}
}
|
mit
|
5e6ffa852dc92b3ed0c177feadc534fa
| 29.073394 | 88 | 0.494204 | 4.643059 | false | false | false | false |
Holmusk/HMRequestFramework-iOS
|
HMRequestFrameworkTests/database/CoreDataFRCTest.swift
|
1
|
17325
|
//
// CoreDataFRCTest.swift
// HMRequestFrameworkTests
//
// Created by Hai Pham on 8/23/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import CoreData
import RxSwift
import RxTest
import XCTest
import SwiftFP
import SwiftUtilities
@testable import HMRequestFramework
public final class CoreDataFRCTest: CoreDataRootTest {
var iterationCount: Int!
deinit {
print("Deinit \(self)")
}
override public func setUp() {
super.setUp()
iterationCount = 5
dummyCount = 1000
dbWait = 0.1
}
public func test_sectionWithObjectLimit_shouldWork() {
/// Setup
let sectionCount = 1000
let times = 1
for _ in 0..<times {
/// Setup
let sections = (0..<sectionCount).map({_ -> HMCDSection<Void> in
let objectCount = Int.random(100, 1000)
let objects = (0..<objectCount).map({_ in ()})
return HMCDSection<Void>(indexTitle: "",
name: "",
numberOfObjects: objectCount,
objects: objects)
})
let limit = Int.random(100, 1000)
/// When
let slicedSections = HMCDSections.sectionsWithLimit(sections, limit)
/// Then
XCTAssertEqual(slicedSections.flatMap({$0.objects}).count, limit)
}
/// Then
}
public func test_streamDBInsertsWithProcessor_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Any.self)
let frcObserver = scheduler.createObserver(Any.self)
let expect = expectation(description: "Should have completed")
let frcExpect = expectation(description: "Should have completed")
let processor = self.dbProcessor!
let iterationCount = self.iterationCount!
let dummyCount = self.dummyCount!
var allDummies: [Dummy1] = []
var callCount = 0
var willLoadCount = 0
var didLoadCount = 0
var willChangeCount = 0
var didChangeCount = 0
var insertCount = 0
let terminateSbj = PublishSubject<Void>()
/// When
processor
.streamDBEvents(Dummy1.self, .background)
.doOnNext({_ in callCount += 1})
.map({try $0.getOrThrow()})
.doOnNext({
switch $0 {
case .didLoad: didLoadCount += 1
case .willLoad: willLoadCount += 1
case .didChange: didChangeCount += 1
case .willChange: willChangeCount += 1
case .insert: insertCount += 1
default: break
}
})
.doOnNext(self.validateDidLoad)
.doOnNext(self.validateInsert)
.cast(to: Any.self)
.takeUntil(terminateSbj)
.doOnDispose(frcExpect.fulfill)
.subscribe(frcObserver)
.disposed(by: disposeBag)
insertNewObjects({allDummies.append(contentsOf: $0)})
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
background(.background, closure: {
while didChangeCount < iterationCount {}
terminateSbj.onNext(())
})
waitForExpectations(timeout: timeout, handler: nil)
/// Then
XCTAssertTrue(callCount >= iterationCount)
// Initialize event adds 1 to the count.
XCTAssertEqual(didLoadCount, iterationCount + 1)
XCTAssertEqual(willLoadCount, iterationCount + 1)
XCTAssertEqual(didChangeCount, iterationCount)
XCTAssertEqual(willChangeCount, iterationCount)
XCTAssertEqual(insertCount, iterationCount * dummyCount)
XCTAssertEqual(callCount, 0
+ didLoadCount
+ willLoadCount
+ didChangeCount
+ willChangeCount
+ insertCount
)
}
// For this test, we are introducing section events as well, so we need
// to take care when comparing event counts.
public func test_streamDBUpdateAndDeleteEvents_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Any.self)
let expect = expectation(description: "Should have completed")
let frcExpect = expectation(description: "Should have completed")
let frcRequest = dummy1FetchRequest()
.cloneBuilder()
.with(frcSectionName: "id")
.build()
let iterationCount = self.iterationCount!
let dummyCount = self.dummyCount!
var originalObjects: [Dummy1] = []
// The willLoad and didLoad counts will be higher than update count
// because they apply to inserts and deletes as well.
var callCount = 0
var willLoadCount = 0
var didLoadCount = 0
var willChangeCount = 0
var didChangeCount = 0
var insertCount = 0
var insertSectionCount = 0
var updateCount = 0
var updateSectionCount = 0
var deleteCount = 0
var deleteSectionCount = 0
let terminateSbj = PublishSubject<Void>()
/// When
manager.rx.startDBStream(frcRequest, Dummy1.self, .background)
.doOnNext({_ in callCount += 1})
.doOnNext({
switch $0 {
case .willLoad: willLoadCount += 1
case .didLoad: didLoadCount += 1
case .willChange: willChangeCount += 1
case .didChange: didChangeCount += 1
case .insert: insertCount += 1
case .insertSection: insertSectionCount += 1
case .update: updateCount += 1
case .updateSection: updateSectionCount += 1
case .delete: deleteCount += 1
case .deleteSection: deleteSectionCount += 1
default: break
}
})
.doOnNext({self.validateDidLoad($0)})
.doOnNext({self.validateInsert($0)})
.doOnNext(self.validateInsertSection)
.doOnNext(self.validateUpdate)
.doOnNext(self.validateUpdateSection)
.doOnNext({self.validateDelete($0)})
.doOnNext(self.validateDeleteSection)
.cast(to: Any.self)
.takeUntil(terminateSbj)
.doOnDispose(frcExpect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
self.upsertAndDelete({originalObjects.append(contentsOf: $0)},
{_ in}, {})
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
background(.background, closure: {
while didChangeCount < iterationCount + 2 {}
terminateSbj.onNext(())
})
waitForExpectations(timeout: timeout, handler: nil)
/// Then
XCTAssertTrue(callCount > iterationCount)
// Initialize event adds 1 to the count, and so did delete event. That's
// why we add 2 to the iterationCount.
XCTAssertEqual(willChangeCount, iterationCount + 2)
XCTAssertEqual(didChangeCount, iterationCount + 2)
XCTAssertEqual(willLoadCount, iterationCount + 3)
XCTAssertEqual(didLoadCount, iterationCount + 3)
XCTAssertEqual(insertCount, dummyCount)
XCTAssertEqual(insertSectionCount, dummyCount)
XCTAssertEqual(updateCount, iterationCount * dummyCount)
XCTAssertEqual(updateSectionCount, 0)
XCTAssertEqual(deleteCount, dummyCount)
XCTAssertEqual(deleteSectionCount, dummyCount)
XCTAssertEqual(callCount, 0
+ willLoadCount
+ didLoadCount
+ willChangeCount
+ didChangeCount
+ insertCount
+ insertSectionCount
+ updateCount
+ updateSectionCount
+ deleteCount
+ deleteSectionCount
)
}
public func test_streamDBEventsWithPagination_shouldWork(_ mode: HMCDPaginationMode) {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let streamObserver = scheduler.createObserver([Dummy1].self)
let expect = expectation(description: "Should have completed")
let disposeBag = self.disposeBag!
let dummyCount = self.dummyCount!
let fetchLimit: UInt = 50
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let dbProcessor = self.dbProcessor!
let qos: DispatchQoS.QoSClass = .background
let fetchOffset: UInt = 0
let pageLoadTimes = dummyCount / Int(fetchLimit)
dbProcessor.saveToMemory(Try.success(pureObjects), qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, pureObjects.count)
XCTAssertTrue(pureObjects.all(nextElements.contains))
// Here comes the actual streams.
let sortedPureObjects = pureObjects.sorted(by: {$0.id! < $1.id!})
let pageSubject = BehaviorSubject<HMCursorDirection>(value: .remain)
var callCount = 0
let original = HMCDPagination.builder()
.with(fetchLimit: fetchLimit)
.with(fetchOffset: fetchOffset)
.with(paginationMode: mode)
.build()
let terminateSbj = PublishSubject<Void>()
/// When
dbProcessor
.streamPaginatedDBEvents(Dummy1.self, pageSubject, original, qos, {
Observable.just($0.cloneBuilder()
.add(ascendingSortWithKey: "id")
.build())
})
// There is only one initialize event, because we are not
// changing/updating anything in the DB. This event contains
// only the original, unchanged objects.
.flatMap(HMCDEvents.didLoadSections)
.filter({!$0.isEmpty})
.map({$0.flatMap({$0.objects})})
.ifEmpty(default: [Dummy1]())
.doOnNext({_ in callCount += 1})
.doOnNext({XCTAssertTrue($0.count > 0)})
.takeUntil(terminateSbj)
.subscribe(streamObserver)
.disposed(by: disposeBag)
var currentPages: [UInt] = []
for _ in (0...pageLoadTimes) {
let direction = HMCursorDirection.randomValue()!
let oldPage = currentPages.last
let currentPage = UInt(dbProcessor.currentPage(Int(oldPage ?? 1), direction))
if currentPage != oldPage {
currentPages.append(currentPage)
}
pageSubject.onNext(direction)
// We need to block for some time because the stream uses flatMapLatest.
// Everytime we push an event with the subject, the old streams are
// killed and thus we don't see any result. It's important to have
// some delay between consecutive triggers for DB events to appear.
waitOnMainThread(1)
}
pageSubject.onCompleted()
/// Then
let nextStreamElements = streamObserver.nextElements()
XCTAssertTrue(nextStreamElements.count > 0)
// Call count may be different from pageLoadTimes because repeat events
// are discarded until changed.
XCTAssertTrue(callCount > 0)
for (currentPage, objs) in zip(currentPages, nextStreamElements) {
let count = UInt(objs.count)
let start: Int
let end: Int
switch mode {
case .fixedPageCount:
start = Int(fetchOffset + (currentPage - 1) * fetchLimit)
end = start + Int(fetchLimit)
XCTAssertEqual(count, fetchLimit)
case .variablePageCount:
start = 0
end = Int(fetchLimit * currentPage)
print(currentPage)
XCTAssertEqual(count, fetchLimit * currentPage)
}
let slice = sortedPureObjects[start..<end].map({$0})
XCTAssertEqual(objs, slice)
}
}
public func test_streamDBEventsWithFixedPageCount_shouldWork() {
test_streamDBEventsWithPagination_shouldWork(.fixedPageCount)
}
public func test_streamDBEventsWithVariablePageCount_shouldWork() {
test_streamDBEventsWithPagination_shouldWork(.variablePageCount)
}
}
public extension CoreDataFRCTest {
func validateDidLoad(_ event: HMCDEvent<Dummy1>) {}
func validateInsert(_ event: HMCDEvent<Dummy1>) {
if case .insert(let change) = event {
XCTAssertNil(change.oldIndex)
XCTAssertNotNil(change.newIndex)
}
}
func validateInsertSection(_ event: HMCDEvent<Dummy1>) {
if case .insertSection(let change) = event {
let sectionInfo = change.section
XCTAssertEqual(sectionInfo.numberOfObjects, 1)
XCTAssertTrue(sectionInfo.objects.count > 0)
}
}
func validateUpdate(_ event: HMCDEvent<Dummy1>) {
if case .update(let change) = event {
XCTAssertNotNil(change.oldIndex)
XCTAssertNotNil(change.newIndex)
}
}
func validateUpdateSection(_ event: HMCDEvent<Dummy1>) {}
func validateDelete(_ event: HMCDEvent<Dummy1>,
_ asserts: ((Dummy1) -> Bool)...) {
if case .delete(let change) = event {
XCTAssertNotNil(change.oldIndex)
XCTAssertNil(change.newIndex)
XCTAssertTrue(asserts.map({$0(change.object)}).all({$0}))
}
}
func validateDeleteSection(_ event: HMCDEvent<Dummy1>) {
if case .deleteSection(let change) = event {
let sectionInfo = change.section
XCTAssertEqual(sectionInfo.numberOfObjects, 0)
XCTAssertEqual(sectionInfo.objects.count, 0)
}
}
}
public extension CoreDataFRCTest {
func insertNewObjects(_ onSave: @escaping ([Dummy1]) -> Void) -> Observable<Any> {
let manager = self.manager!
let iterationCount = self.iterationCount!
let dummyCount = self.dummyCount!
return Observable
.range(start: 0, count: iterationCount)
.flatMap({(_) -> Observable<Void> in
let context = manager.disposableObjectContext()
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
return Observable
.concat(
manager.rx.savePureObjects(context, pureObjects),
manager.rx.persistLocally()
)
.reduce((), accumulator: {(_, _) in ()})
.doOnNext({onSave(pureObjects)})
.subscribeOnConcurrent(qos: .background)
})
.reduce((), accumulator: {(_, _) in ()})
.subscribeOnConcurrent(qos: .background)
.cast(to: Any.self)
}
func upsertAndDelete(_ onInsert: @escaping ([Dummy1]) -> Void,
_ onUpsert: @escaping ([Dummy1]) -> Void,
_ onDelete: @escaping () -> Void) -> Observable<Any> {
let manager = self.manager!
let context = manager.disposableObjectContext()
let deleteContext = manager.disposableObjectContext()
let iterationCount = self.iterationCount!
let dummyCount = self.dummyCount!
let original = (0..<dummyCount).map({_ in Dummy1()})
let entity = try! Dummy1.CDClass.entityName()
return manager.rx.savePureObjects(context, original)
.flatMap({manager.rx.persistLocally()})
.doOnNext({onInsert(original)})
.flatMap({_ in Observable.range(start: 0, count: iterationCount)
.flatMap({(_) -> Observable<Void> in
let context = manager.disposableObjectContext()
let upsertCtx = manager.disposableObjectContext()
let replace = (0..<dummyCount).map({(i) -> Dummy1 in
let previous = original[i]
return Dummy1.builder().with(id: previous.id).build()
})
return Observable
.concat(
manager.rx.construct(context, replace)
.flatMap({manager.rx.upsert(upsertCtx, entity, $0)})
.map(toVoid),
manager.rx.persistLocally()
)
.reduce((), accumulator: {(_, _) in ()})
.doOnNext({onUpsert(replace)})
.subscribeOnConcurrent(qos: .background)
})
.reduce((), accumulator: {(_, _) in ()})
})
.flatMap({manager.rx.deleteIdentifiables(deleteContext, entity, original)})
.flatMap({manager.rx.persistLocally()})
.subscribeOnConcurrent(qos: .background)
.doOnNext(onDelete)
.cast(to: Any.self)
}
}
public extension CoreDataFRCTest {
public func test_fetchWithLimit_shouldNotReturnMoreThanLimit(_ limit: Int) {
print("Testing fetch limit with \(limit) count")
/// Setup
let observer = scheduler.createObserver(Try<Void>.self)
let streamObserver = scheduler.createObserver([Dummy1].self)
let expect = expectation(description: "Should have completed")
let disposeBag = self.disposeBag!
let dbWait = self.dbWait!
let dbProcessor = self.dbProcessor!
let dummyCount = 10
let qos: DispatchQoS.QoSClass = .background
/// When
dbProcessor
.streamDBEvents(Dummy1.self, qos, {
Observable.just($0.cloneBuilder().with(fetchLimit: limit).build())
})
// Skip the initialize (both willLoad and didLoad) events, since
// they will just return an empty Array anyway.
.flatMap(HMCDEvents.didLoadSections)
.filter({!$0.isEmpty})
.map({$0.flatMap({$0.objects})})
.skip(1)
.subscribe(streamObserver)
.disposed(by: disposeBag)
Observable.range(start: 0, count: dummyCount)
.map({_ in Dummy1()})
.map(Try.success)
.map({$0.map({[$0]})})
.concatMap({
dbProcessor.saveToMemory($0, qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
.subscribeOnConcurrent(qos: qos)
.delay(dbWait, scheduler: ConcurrentDispatchQueueScheduler(qos: qos))
})
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = streamObserver.nextElements()
XCTAssertTrue(nextElements.count > 0)
XCTAssertTrue(nextElements.all({$0.count <= limit}))
}
public func test_fetchWithLimit_shouldNotReturnMoreThanLimit() {
for i in 1..<10 {
setUp()
test_fetchWithLimit_shouldNotReturnMoreThanLimit(i)
tearDown()
}
}
}
|
apache-2.0
|
f2e8d67e9ad90206540ad13a353342a7
| 31.022181 | 88 | 0.652505 | 4.402541 | false | false | false | false |
pabloroca/NewsApp
|
NewsApp/Helpers/PR2Extensions.swift
|
1
|
4171
|
//
// PR2Extensions.swift
// WeatherSwift
//
// Created by Pablo Roca Rozas on 12/3/17.
// Copyright © 2017 PR2Studio. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import AlamofireImage
import RealmSwift
// requires Alamofire / AlamofireImage / PR2Common
extension UIImageView {
func PR2ImageFromNetwork(_ imageURL: String, indicatorStyle: UIActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let indicator = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle)
indicator.center = self.center;// it will display in center of image view
self.addSubview(indicator)
indicator.startAnimating()
Alamofire.request(imageURL, method: .get)
.responseImage { response in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
indicator.stopAnimating()
indicator.isHidden = true
indicator.removeFromSuperview()
if let image = response.result.value {
// let image = UIImage(data: response.data!, scale: UIScreen.mainScreen().scale)!
self.image = image
}
}
}
}
extension Realm {
public func safeWrite(_ block: (() throws -> Void)) throws {
if isInWriteTransaction {
try block()
} else {
try write(block)
}
}
}
extension String {
public func PR2DateFormatterFromWeb() -> Date {
return DateFormatter.PR2DateFormatterFromWeb.date(from: self)!
}
public func PR2DateFormatterFromAPI() -> Date {
return DateFormatter.PR2DateFormatterFromAPI.date(from: self)!
}
public func PR2DateFormatterUTCiso8601() -> Date {
return DateFormatter.PR2DateFormatterUTCiso8601.date(from: self)!
}
}
extension NSDate {
// Date format for API
public func PR2DateFormatterFromAPI() -> String {
return DateFormatter.PR2DateFormatterFromAPI.string(from: self as Date)
}
// Date format for Logs
public func PR2DateFormatterForLog() -> String {
return DateFormatter.PR2DateFormatterForLog.string(from: self as Date)
}
// Date in UTC
public func PR2DateFormatterUTC() -> String {
return DateFormatter.PR2DateFormatterUTC.string(from: self as Date)
}
// Date in UTCiso8601
public func PR2DateFormatterUTCiso8601() -> String {
return DateFormatter.PR2DateFormatterUTCiso8601.string(from: self as Date)
}
// Date in HHMMh
public func PR2DateFormatterHHMM() -> String {
return DateFormatter.PR2DateFormatterHHMM.string(from: self as Date)
}
}
extension DateFormatter {
public static let PR2DateFormatterFromWeb: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
return formatter
}()
public static let PR2DateFormatterFromAPI: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
public static let PR2DateFormatterForLog: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
public static let PR2DateFormatterUTC: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
// from http://stackoverflow.com/questions/28016578/swift-how-to-create-a-date-time-stamp-and-format-as-iso-8601-rfc-3339-utc-tim
public static let PR2DateFormatterUTCiso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
return formatter
}()
public static let PR2DateFormatterHHMM: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter
}()
}
|
mit
|
520b8dfeb6b4c5b8ba6d180b9fec954f
| 30.353383 | 133 | 0.6494 | 4.717195 | false | false | false | false |
chourobin/RCRefreshControl
|
Source/RCRefreshControl.swift
|
1
|
7931
|
//
// RCRefreshControl.swift
// RCRefreshControl
//
// Created by Robin Chou on 2/7/15.
// Copyright (c) 2015 Robin Chou. All rights reserved.
//
import UIKit
class RCRefreshControl: UIRefreshControl {
// MARK: - Customization
var lineWidth: CGFloat = 2 {
didSet {
progressLayer?.lineWidth = lineWidth
}
}
var radius: CGFloat = 10 {
didSet {
updatePath()
}
}
// MARK: - Private variables
private var context = 0
private var progressLayer: CAShapeLayer?
private var strokeColor: UIColor?
private var initialOpacity: CGFloat = 0.2
private var isAnimating: Bool = false
private let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
private let kHideCircleAnimationKey = "rcrefreshcontrol.hidecircle"
private let kFadeOutAnimationKey = "rcrefreshcontrol.fadeout"
private let kRotationAnimationKey = "rcrefreshcontrol.rotation"
private let kRingStrokeAnimationKey = "rcrefreshcontrol.ringstroke"
// MARK: - Internal Methods
override init() {
super.init()
progressLayer = CAShapeLayer()
progressLayer?.strokeColor = UIView(frame: CGRectZero).tintColor.CGColor
progressLayer?.opacity = Float(initialOpacity)
progressLayer?.fillColor = nil
progressLayer?.lineWidth = lineWidth
progressLayer?.rasterizationScale = 2 * UIScreen.mainScreen().scale
progressLayer?.shouldRasterize = true
layer.addSublayer(progressLayer!)
tintColor = UIColor.clearColor()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resetAnimations", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}
override func endRefreshing() {
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.duration = 0.3
opacityAnimation.fromValue = 1
opacityAnimation.toValue = 0
let shrinkAnimation = CABasicAnimation(keyPath: "transform.scale")
shrinkAnimation.duration = 0.3
shrinkAnimation.toValue = 0.4
let group = CAAnimationGroup()
group.animations = [opacityAnimation, shrinkAnimation]
group.duration = 0.3
progressLayer?.addAnimation(group, forKey: kFadeOutAnimationKey)
super.endRefreshing()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
self.progressLayer?.opacity = Float(self.initialOpacity)
self.stopAnimating()
return
})
}
override func tintColorDidChange() {
super.tintColorDidChange()
if tintColor != UIColor.clearColor() {
strokeColor = tintColor
progressLayer?.strokeColor = strokeColor?.CGColor
tintColor = UIColor.clearColor()
}
}
func resetAnimations() {
// If the app goes to the background, returning it to the foreground causes the animation to stop (even though it's not explicitly stopped by our code). Resetting the animation seems to kick it back into gear.
if isAnimating {
stopAnimating()
startAnimating()
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
}
// MARK: Private Methods
private func updatePath() {
let center = CGPointMake(radius, radius + (frame.origin.y < -64 && !isAnimating ? abs(frame.origin.y) - 64 : 0))
let startAngle: CGFloat = CGFloat(0.5 * M_PI)
let endAngle: CGFloat = CGFloat(2.5 * M_PI)
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
progressLayer?.bounds = CGPathGetPathBoundingBox(path.CGPath)
progressLayer?.position = CGPointMake(frame.width / 2, frame.height / 2 + (frame.origin.y < -64 && !isAnimating ? abs(frame.origin.y) - 64 : 0))
progressLayer?.path = path.CGPath
if refreshing {
startAnimating()
}
if !refreshing && !isAnimating {
let threshold: CGFloat = 8
let opacity = frame.origin.y < -64 ? 0.3 + (min(abs(frame.origin.y) - 64, threshold) / threshold) : 0.3
let pullRatio = min(abs(frame.origin.y), 64) / 64
progressLayer?.strokeStart = 0
progressLayer?.strokeEnd = pullRatio
progressLayer?.opacity = Float(opacity)
}
}
private func startAnimating() {
if isAnimating {
return
}
isAnimating = true
progressLayer?.opacity = 1
progressLayer?.strokeStart = 0
progressLayer?.strokeEnd = 1
let hideCircle = CABasicAnimation(keyPath: "strokeStart")
hideCircle.duration = 0.8
hideCircle.fromValue = 0
hideCircle.toValue = 1
hideCircle.fillMode = kCAFillModeForwards
hideCircle.removedOnCompletion = false
hideCircle.timingFunction = timingFunction
progressLayer?.addAnimation(hideCircle, forKey: kHideCircleAnimationKey)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.8 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.duration = 4
rotationAnimation.fromValue = 0
rotationAnimation.toValue = 2 * M_PI
rotationAnimation.repeatCount = Float.infinity
self.progressLayer?.addAnimation(rotationAnimation, forKey: self.kRotationAnimationKey)
let headAnimation = CABasicAnimation(keyPath: "strokeStart")
headAnimation.duration = 1
headAnimation.fromValue = 0
headAnimation.toValue = 0.25
headAnimation.timingFunction = self.timingFunction
let tailAnimation = CABasicAnimation(keyPath: "strokeEnd")
tailAnimation.duration = 1
tailAnimation.fromValue = 0
tailAnimation.toValue = 1
tailAnimation.timingFunction = self.timingFunction
let endHeadAnimation = CABasicAnimation(keyPath: "strokeStart")
endHeadAnimation.beginTime = 1
endHeadAnimation.duration = 0.5
endHeadAnimation.fromValue = 0.25
endHeadAnimation.toValue = 1
endHeadAnimation.timingFunction = self.timingFunction
let endTailAnimation = CABasicAnimation(keyPath: "strokeEnd")
endTailAnimation.beginTime = 1
endTailAnimation.duration = 0.5
endTailAnimation.fromValue = 1
endTailAnimation.toValue = 1
endTailAnimation.timingFunction = self.timingFunction
let group = CAAnimationGroup()
group.animations = [headAnimation, tailAnimation, endHeadAnimation, endTailAnimation]
group.duration = 1.5
group.repeatCount = Float.infinity
self.progressLayer?.addAnimation(group, forKey: self.kRingStrokeAnimationKey)
}
}
private func stopAnimating() {
progressLayer?.removeAnimationForKey(kHideCircleAnimationKey)
progressLayer?.removeAnimationForKey(kFadeOutAnimationKey)
progressLayer?.removeAnimationForKey(kRotationAnimationKey)
progressLayer?.removeAnimationForKey(kRingStrokeAnimationKey)
isAnimating = false
}
}
|
mit
|
c7327e9dc2666b48490b5a838e4e6ed3
| 37.5 | 217 | 0.638129 | 5.421053 | false | false | false | false |
nixzhu/MonkeyKing
|
Sources/MonkeyKing/MonkeyKing+QQUniversalLink.swift
|
1
|
888
|
import Foundation
extension MonkeyKing {
static var qqAppSignTxid: String? {
get {
return UserDefaults.standard.string(forKey: _txidKey)
}
set {
if newValue == nil {
UserDefaults.standard.removeObject(forKey: _txidKey)
} else {
UserDefaults.standard.set(newValue, forKey: _txidKey)
}
}
}
static var qqAppSignToken: String? {
get {
return UserDefaults.standard.string(forKey: _tokenKey)
}
set {
if newValue == nil {
UserDefaults.standard.removeObject(forKey: _tokenKey)
} else {
UserDefaults.standard.set(newValue, forKey: _tokenKey)
}
}
}
}
private let _txidKey = "_MonkeyKingQQAppSignTxid"
private let _tokenKey = "_MonkeyKingQQAppSignToken"
|
mit
|
302741484a483832b15660f3f775c19e
| 25.117647 | 70 | 0.552928 | 4.44 | false | false | false | false |
gradyzhuo/GZHTTPConnection
|
GZHTTPConnectionDemo/GZHTTPConnectionDemo/AppDelegate.swift
|
1
|
6166
|
//
// AppDelegate.swift
// GZHTTPConnectionDemo
//
// Created by Grady Zhuo on 2/19/15.
// Copyright (c) 2015 Grady Zhuo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.offsky.GZHTTPConnectionDemo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("GZHTTPConnectionDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("GZHTTPConnectionDemo.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
mit
|
ebc42cc3af1b76887af2656cacf78490
| 54.54955 | 290 | 0.717483 | 5.741155 | false | false | false | false |
zitao0322/ShopCar
|
Shoping_Car/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift
|
19
|
4003
|
//
// RxTableViewDataSourceProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
let tableViewDataSourceNotSet = TableViewDataSourceNotSet()
class TableViewDataSourceNotSet
: NSObject
, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
rxAbstractMethodWithMessage(dataSourceNotSet)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
rxAbstractMethodWithMessage(dataSourceNotSet)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
rxAbstractMethodWithMessage(dataSourceNotSet)
}
}
/**
For more information take a look at `DelegateProxyType`.
*/
public class RxTableViewDataSourceProxy
: DelegateProxy
, UITableViewDataSource
, DelegateProxyType {
/**
Typed parent object.
*/
public weak private(set) var tableView: UITableView?
private weak var _requiredMethodsDataSource: UITableViewDataSource? = tableViewDataSourceNotSet
/**
Initializes `RxTableViewDataSourceProxy`
- parameter parentObject: Parent object for delegate proxy.
*/
public required init(parentObject: AnyObject) {
self.tableView = (parentObject as! UITableView)
super.init(parentObject: parentObject)
}
// MARK: delegate
/**
Required delegate method implementation.
*/
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSectionsInTableView?(tableView) ?? 1
}
/**
Required delegate method implementation.
*/
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, numberOfRowsInSection: section)
}
/**
Required delegate method implementation.
*/
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, cellForRowAtIndexPath: indexPath)
}
// MARK: proxy
/**
For more information take a look at `DelegateProxyType`.
*/
public override class func createProxyForObject(object: AnyObject) -> AnyObject {
let tableView = (object as! UITableView)
return castOrFatalError(tableView.rx_createDataSourceProxy())
}
/**
For more information take a look at `DelegateProxyType`.
*/
public override class func delegateAssociatedObjectTag() -> UnsafePointer<Void> {
return _pointer(&dataSourceAssociatedTag)
}
/**
For more information take a look at `DelegateProxyType`.
*/
public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let tableView: UITableView = castOrFatalError(object)
tableView.dataSource = castOptionalOrFatalError(delegate)
}
/**
For more information take a look at `DelegateProxyType`.
*/
public class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let tableView: UITableView = castOrFatalError(object)
return tableView.dataSource
}
/**
For more information take a look at `DelegateProxyType`.
*/
public override func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) {
let requiredMethodsDataSource: UITableViewDataSource? = castOptionalOrFatalError(forwardToDelegate)
_requiredMethodsDataSource = requiredMethodsDataSource ?? tableViewDataSourceNotSet
super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate)
}
}
#endif
|
mit
|
e718dc5f593c87ffeb0dcba8293759e8
| 30.511811 | 127 | 0.716392 | 5.902655 | false | false | false | false |
mathewa6/7Segment
|
7Segment/7Segment.playground/Contents.swift
|
1
|
4317
|
import UIKit
/// UIView subclass to draw one segment in a 7Segment display.
class Segment: UIView {
enum Orientation {
case horizontal
case vertical
case null
}
/// The dominant color of each segment. Defaults to red.
var fillColor: UIColor = UIColor.red {
didSet {
setNeedsDisplay()
}
}
/// The outline color of each segment. Defaults to white.
var strokeColor: UIColor = UIColor.white {
didSet {
setNeedsDisplay()
}
}
/// How 'thick' the segment is. This is always the smaller value between length and breadth.
private var breadth: CGFloat = 5.0
/// Length of the segment. It is always the longer value between length and breadth.
private var length: CGFloat = 25.0
/// The side of triangle at each corner that is cutoff to give the 'tip' of the segment. Otherwise it is 1/15th of the length.
private var cutoff: CGFloat { return length/10 }
/// The width used to stroke the outline of each segment. It is always breadth/10.
private var strokeWidth: CGFloat { return breadth/10 }
/// Indicates whether the segment is "upright": vertical or "sideways": horizontal. This is ONLY to indicate which dimension is longer to help draw the segment.
private var orientation: Orientation
override init(frame: CGRect) {
let h = frame.size.height
let w = frame.size.width
orientation = w > h ? .horizontal : .vertical
switch orientation {
case .horizontal:
length = w
breadth = h
case .vertical:
length = h
breadth = w
default:
length = w
breadth = h
}
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
orientation = .null
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
let h = self.frame.size.height
let w = self.frame.size.width
orientation = w > h ? .horizontal : .vertical
switch orientation {
case .horizontal:
length = w
breadth = h
case .vertical:
length = h
breadth = w
default:
length = w
breadth = h
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()
// Set up the stroke/fill color and stroke width.
context?.setStrokeColor(strokeColor.cgColor)
context?.setLineWidth(strokeWidth)
context?.setFillColor(fillColor.cgColor)
// Create an offset to account for the stroke thickness and prevent drawing outside the rect.
let offset = strokeWidth/2
switch orientation {
case .horizontal:
context?.move(to: CGPoint(x: cutoff, y: offset))
context?.addLine(to: CGPoint(x: length - cutoff, y: offset))
context?.addLine(to: CGPoint(x: length - offset, y: breadth/2))
context?.addLine(to: CGPoint(x: length - cutoff, y: breadth - offset))
context?.addLine(to: CGPoint(x: cutoff, y: breadth - offset))
context?.addLine(to: CGPoint(x: offset, y: breadth/2))
case .vertical:
context?.move(to: CGPoint(x: offset, y: cutoff))
context?.addLine(to: CGPoint(x: offset, y: length - cutoff))
context?.addLine(to: CGPoint(x: breadth/2, y: length - offset))
context?.addLine(to: CGPoint(x: breadth - offset, y: length - cutoff))
context?.addLine(to: CGPoint(x: breadth - offset, y: cutoff))
context?.addLine(to: CGPoint(x: breadth/2, y: offset))
default:
break
}
context?.closePath()
context?.drawPath(using: .fillStroke)
}
override var description: String {
return "\(orientation) > (\(breadth), \(length))"
}
}
let seg = Segment(frame: CGRect.init(x: 0, y: 0, width: 30, height: 150))
let hseg = Segment(frame: CGRect.init(x: 0, y: 0, width: 150, height: 30))
|
mit
|
0be837718cc40575fa2c83b9100b2d97
| 31.458647 | 164 | 0.574705 | 4.534664 | false | false | false | false |
batuhankok/swift-tap-me
|
TapMe/Extensions.swift
|
1
|
2432
|
//
// Extensions.swift
// Hürriyet Gündem
//
// Created by Batuhan Kök on 8.06.2017.
// Copyright © 2017 Batuhan Kök. All rights reserved.
//
import Foundation
import UIKit
extension CAGradientLayer {
convenience init(frame: CGRect, colors: [UIColor]) {
self.init()
self.frame = frame
self.colors = []
for color in colors {
self.colors?.append(color.cgColor)
}
startPoint = CGPoint(x: 0, y: 0)
endPoint = CGPoint(x: 0, y: 1)
}
func creatGradientImage() -> UIImage? {
var image: UIImage? = nil
UIGraphicsBeginImageContext(bounds.size)
if let context = UIGraphicsGetCurrentContext() {
render(in: context)
image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return image
}
}
extension UINavigationBar {
func setGradientBackground(colors: [UIColor]) {
var updatedFrame = bounds
updatedFrame.size.height += 20
let gradientLayer = CAGradientLayer(frame: updatedFrame, colors: colors)
setBackgroundImage(gradientLayer.creatGradientImage(), for: UIBarMetrics.default)
}
}
extension UIColor {
convenience init(hex: Int) {
let components = (
R: CGFloat((hex >> 16) & 0xff) / 255,
G: CGFloat((hex >> 08) & 0xff) / 255,
B: CGFloat((hex >> 00) & 0xff) / 255
)
self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
}
}
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
extension NSObject {
var className: String {
return String(describing: type(of: self))
}
class var className: String {
return String(describing: self)
}
}
|
gpl-3.0
|
ec1157f032ac1f6bdad1d1d9e908dd14
| 25.096774 | 133 | 0.599506 | 4.685328 | false | false | false | false |
ztyjr888/WeChat
|
WeChat/Main/Register/WeChatRegisterViewController.swift
|
1
|
13706
|
//
// WeChatRegisterViewController.swift
// WeChat
//
// Created by Smile on 16/3/25.
// Copyright © 2016年 [email protected]. All rights reserved.
//
import UIKit
//注册页面
class WeChatRegisterViewController: UIViewController,WeChatCustomNavigationHeaderDelegate,
UITableViewDelegate,UITableViewDataSource{
var navigation:WeChatCustomNavigationHeaderView!
var navigationHeight:CGFloat = 44
let fontName:String = "AlNile"
let topPadding:CGFloat = 20
let tableHeaderHeight:CGFloat = 80
let bottomHeight:CGFloat = 40
var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
initFrame()
}
func initFrame(){
initNavigationBar()
initTableView()
addBottom()
}
//MARKS: 自己定义导航条
func initNavigationBar(){
//获取状态栏
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
self.navigationHeight += statusBarFrame.height
self.navigation = WeChatCustomNavigationHeaderView(frame: CGRectMake(0, 0,UIScreen.mainScreen().bounds.width, navigationHeight), backImage: nil, backTitle: "取消", centerLabel: "", rightButtonText: "", rightButtonImage: nil, backgroundColor: UIColor.whiteColor(), leftLabelColor: UIColor(red: 46/255, green: 139/255, blue: 87/255, alpha: 1), rightLabelColor: nil)
self.view.addSubview(self.navigation)
self.view.bringSubviewToFront(self.navigation)
self.navigation.delegate = self
}
func initTableView(){
self.tableView = UITableView()
self.tableView.frame = CGRectMake(0, self.navigationHeight, self.view.frame.width, self.view.frame.height - self.navigationHeight - self.bottomHeight)
self.tableView.separatorStyle = .None
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(tableView)
initTableHeaderView()
}
//MARKS: 初始化tableHeader
func initTableHeaderView(){
//画底部线条
//let shape = WeChatDrawView().drawLineAtLast(0,height: headerView.frame.height)
//shape.lineWidth = 0.2
//headerView.layer.addSublayer(shape)
let topView = UIView()
topView.frame = CGRectMake(0, 0, tableView.frame.size.width, tableHeaderHeight)
topView.backgroundColor = UIColor.whiteColor()
let label = createLabel(
CGRectMake(0, topPadding, self.view.frame.width, 30),
string: "请输入你的手机号码",
color: UIColor.blackColor(),
font: UIFont(name: self.fontName, size: 25)!)
label.textAlignment = .Center
topView.addSubview(label)
self.tableView.tableHeaderView = topView
}
//MARKS: 添加底部协议
func addBottom(){
let bottomView = UIView()
bottomView.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height - self.bottomHeight, UIScreen.mainScreen().bounds.width, self.bottomHeight)
let font = UIFont(name: self.fontName,size: 10)
let label1 = createLabel(CGRectMake(0, 10, bottomView.frame.width, 10), string: "轻触上面的“注册”按钮,即表示你同意\n", color: UIColor.darkGrayColor(), font: font!)
label1.textAlignment = .Center
let label2 = createLabel(CGRectMake(0, label1.frame.origin.y + label1.frame.height + 2, bottomView.frame.width, label1.frame.height), string: "《WeChat软件许可及服务协议》", color: UIColor(red: 0/255,green:191/255,blue:255/255,alpha:1), font: font!)
label2.textAlignment = .Center
bottomView.addSubview(label1)
bottomView.addSubview(label2)
self.view.addSubview(bottomView)
}
func createLabel(frame:CGRect,string:String,color:UIColor,font:UIFont) -> UILabel{
let label = UILabel(frame: frame)
label.font = font
label.textColor = color
label.numberOfLines = 1
label.text = string
return label
}
func createTextField(frame:CGRect,placeholder:String) -> UITextField{
let textField = UITextField(frame: frame)
textField.frame = frame
textField.placeholder = placeholder
textField.font = UIFont(name: "宋体", size: 16)
textField.contentMode = .Center
textField.borderStyle = .None
textField.tintColor = WeChatColor().curColor//设置光标颜色
textField.keyboardType = .PhonePad
return textField
}
//MARKS: 返回每组行数
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
//MARKS: 返回分组数
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 2 {
return lastCellHeight
}
return cellHeight
}
let cellLeftPadding:CGFloat = 15
let cellComponentHeight:CGFloat = 25
var labelLeftWidth:CGFloat = 0
let addLabelWidth:CGFloat = 10
let addLabelHeight:CGFloat = 20
let cellTextFieldLeftPadding:CGFloat = 7
let cellButtonTopPadding:CGFloat = 20
let cellButtonHeight:CGFloat = 40
let cellHeight:CGFloat = 40
let lastCellHeight:CGFloat = 60
let cellWidth:CGFloat = UIScreen.mainScreen().bounds.width
var phoneTextField:UITextField?
var registerBtn:UIButton?
var numberTextField:UITextField?
var loadingView:WeChatNormalLoadingView?
var loadingViewWidth:CGFloat = 120
var loadingViewHeight:CGFloat = 120
//MARKS: 返回每行的单元格
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell\(indexPath.section)\(indexPath.row)")
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell\(indexPath.section)\(indexPath.row)")
}
for view in cell!.subviews {
view.removeFromSuperview()
}
labelLeftWidth = (cellWidth - cellLeftPadding) / 4
let toppadding:CGFloat = (cellHeight - cellComponentHeight) / 2
if indexPath.row == 0 {//国家/地区
let areaLabel = createLabel(
CGRectMake(cellLeftPadding, toppadding, labelLeftWidth, cellComponentHeight),
string: "国家/地区",
color: UIColor.blackColor(),
font: UIFont(name: self.fontName, size: 15)!)
let countryLabel = createLabel(
CGRectMake(cellLeftPadding + labelLeftWidth + cellTextFieldLeftPadding, toppadding, cellWidth - cellLeftPadding - labelLeftWidth, cellComponentHeight),
string: "中国",
color: UIColor.blackColor(),
font: UIFont(name: self.fontName, size: 15)!)
cell?.addSubview(areaLabel)
cell?.addSubview(countryLabel)
cell?.accessoryType = .DisclosureIndicator//显示右箭头
} else if indexPath.row == 1 { //电话号码
let addLabel = createLabel(
CGRectMake(cellLeftPadding, (cell!.frame.height - addLabelHeight ) / 2, addLabelWidth, addLabelHeight),
string: "+",
color: UIColor.blackColor(),
font: UIFont(name: self.fontName, size: 25)!)
cell?.addSubview(addLabel)
let numberBeginX:CGFloat = addLabelWidth + cellLeftPadding
self.numberTextField = createTextField(CGRectMake(numberBeginX, toppadding, labelLeftWidth - addLabelWidth, cellComponentHeight), placeholder: "")
numberTextField!.text = "86"
//numberTextField?.font = UIFont(name: self.fontName, size: 22)
cell?.addSubview(numberTextField!)
let phoneWidth:CGFloat = cell!.frame.width - cellLeftPadding - labelLeftWidth
let phoneBeginX:CGFloat = cellLeftPadding + labelLeftWidth + cellTextFieldLeftPadding
self.phoneTextField = createTextField(CGRectMake(phoneBeginX, toppadding, phoneWidth, cellComponentHeight), placeholder: "请输入手机号码")
//phoneTextField?.font = UIFont(name: self.fontName, size: 22)
//注册change事件通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "phoneTextChange", name: UITextFieldTextDidChangeNotification, object: phoneTextField)
cell?.addSubview(self.phoneTextField!)
let lineShape = WeChatDrawView().drawLine(beginPointX: cellLeftPadding + labelLeftWidth, beginPointY: 0, endPointX: cellLeftPadding + labelLeftWidth, endPointY:cellHeight,color:UIColor.darkGrayColor())
lineShape.lineWidth = 0.1
cell?.layer.addSublayer(lineShape)
} else if indexPath.row == 2 { //注册按钮
self.registerBtn = UIButton(type: .Custom)
registerBtn!.frame = CGRectMake(cellLeftPadding, cellButtonTopPadding, cellWidth - cellLeftPadding * 2, cellButtonHeight)
registerBtn!.setTitle("注册", forState: UIControlState.Normal)
registerBtn!.backgroundColor = UIColor(red: 46/255, green: 139/255, blue: 87/255, alpha: 1)
registerBtn!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
registerBtn!.enabled = false
registerBtn!.layer.cornerRadius = 3
registerBtn!.layer.masksToBounds = true
cell?.addSubview(registerBtn!)
registerBtn!.addTarget(self, action: "registerBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
}
//添加底部线条
if indexPath.row == 0 || indexPath.row == 1 {
let shape = WeChatDrawView().drawLineAtLast(cellLeftPadding,height: cellHeight)
shape.lineWidth = 0.1
cell?.layer.addSublayer(shape)
}
cell?.selectionStyle = .None
// cell?.layer.borderWidth = 1
return cell!
}
//MARKS: 创建加载View
func createLoadingView(){
if loadingView == nil {
let beginY:CGFloat = (self.view.frame.height - navigationHeight) / 2 - self.loadingViewHeight / 2
let beginX:CGFloat = self.view.frame.width / 2 - self.loadingViewWidth / 2
loadingView = WeChatNormalLoadingView(frame: CGRectMake(beginX, beginY, loadingViewWidth, loadingViewHeight), labelText: "请稍候...")
}
self.view.addSubview(loadingView!)
}
//MARKS: 注册按钮点击事件
func registerBtnClick(){
self.createLoadingView()
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "validateNumber", userInfo: nil, repeats: false)
}
func validateNumber(){
self.loadingView?.removeFromSuperview()
if self.phoneTextField?.text?.characters.count != 11 {
createErrorAlert()
}else{
createCorrectAlert()
}
}
func createErrorAlert(){
let alertController = UIAlertController(title: "手机号码错误", message: "你输入的是一个无效的手机号码", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default,handler: nil)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func createCorrectAlert(){
let alertController = UIAlertController(title: "确认手机号码", message: "我们将发送验证码短信到这个号码:\n" + self.phoneTextField!.text!, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
let okAction = UIAlertAction(title: "好", style: UIAlertActionStyle.Default) { (UIAlertAction) in
self.createLoadingView()
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "openSendMsgViewController", userInfo: nil, repeats: false)
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func openSendMsgViewController(){
self.loadingView?.removeFromSuperview()
}
//MARKS: 手机号码textField改变事件
func phoneTextChange(){
if !self.phoneTextField!.text!.isEmpty {
self.registerBtn?.enabled = true
} else {
self.registerBtn?.enabled = false
}
if self.phoneTextField!.text?.characters.count > 11 {
var text = NSString(string: self.phoneTextField!.text!)
let range = NSRange(location: 0,length: 11)
text = text.substringWithRange(range)
self.phoneTextField!.text = text as String
}
}
//MARKS: 取消事件
func leftBarClick() {
self.numberTextField?.resignFirstResponder()
self.phoneTextField?.resignFirstResponder()
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
apache-2.0
|
c0d886b644485e4e5dfa48b42cc30506
| 39.978395 | 369 | 0.642464 | 4.870506 | false | false | false | false |
hacktoolkit/hacktoolkit-ios_lib
|
Hacktoolkit/utils/HTKUtils.swift
|
1
|
1099
|
//
// HTKUtils.swift
//
// Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai)
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import Foundation
class HTKUtils {
class func setDefaults(key: String, withValue value: AnyObject?) {
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(value, forKey: key)
defaults.synchronize()
}
class func getDefaults(key: String) -> AnyObject? {
var defaults = NSUserDefaults.standardUserDefaults()
var value: AnyObject? = defaults.objectForKey(key)
return value
}
class func getStringFromInfoBundleForKey(key: String) -> String {
var value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String
return value ?? ""
}
class func formatCurrency(amount: Double) -> String {
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
var formattedAmount = numberFormatter.stringFromNumber(amount)!
return formattedAmount
}
}
|
mit
|
96b2feadcb613e6566f13ac47a99a24e
| 29.527778 | 84 | 0.689718 | 4.862832 | false | false | false | false |
gribozavr/swift
|
test/SILGen/ivar_destroyer.swift
|
1
|
3237
|
// RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s
// Only derived classes with non-trivial ivars need an ivar destroyer.
struct TrivialStruct {}
class RootClassWithoutProperties {}
class RootClassWithTrivialProperties {
var x: Int = 0
var y: TrivialStruct = TrivialStruct()
}
class Canary {}
class RootClassWithNonTrivialProperties {
var x: Canary = Canary()
}
class DerivedClassWithTrivialProperties : RootClassWithoutProperties {
var z: Int = 12
}
class DerivedClassWithNonTrivialProperties : RootClassWithoutProperties {
var z: Canary = Canary()
}
// CHECK-LABEL: sil hidden [ossa] @$s14ivar_destroyer36DerivedClassWithNonTrivialPropertiesCfE
// CHECK: bb0(%0 : @guaranteed $DerivedClassWithNonTrivialProperties):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: [[Z_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: [[Z_ADDR_DEINIT_ACCESS:%.*]] = begin_access [deinit] [static] [[Z_ADDR]]
// CHECK-NEXT: destroy_addr [[Z_ADDR_DEINIT_ACCESS]]
// CHECK-NEXT: end_access [[Z_ADDR_DEINIT_ACCESS]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil_vtable RootClassWithoutProperties {
// CHECK-NEXT: #RootClassWithoutProperties.init!allocator.1
// CHECK-NEXT: #RootClassWithoutProperties.deinit!deallocator
// CHECK-NEXT: }
// CHECK-LABEL: sil_vtable RootClassWithTrivialProperties {
// CHECK-NEXT: #RootClassWithTrivialProperties.x!getter.1
// CHECK-NEXT: #RootClassWithTrivialProperties.x!setter.1
// CHECK-NEXT: #RootClassWithTrivialProperties.x!modify.1
// CHECK-NEXT: #RootClassWithTrivialProperties.y!getter.1
// CHECK-NEXT: #RootClassWithTrivialProperties.y!setter.1
// CHECK-NEXT: #RootClassWithTrivialProperties.y!modify.1
// CHECK-NEXT: #RootClassWithTrivialProperties.init!allocator.1
// CHECK-NEXT: #RootClassWithTrivialProperties.deinit!deallocator
// CHECK-NEXT: }
// CHECK-LABEL: sil_vtable RootClassWithNonTrivialProperties {
// CHECK-NEXT: #RootClassWithNonTrivialProperties.x!getter.1
// CHECK-NEXT: #RootClassWithNonTrivialProperties.x!setter.1
// CHECK-NEXT: #RootClassWithNonTrivialProperties.x!modify.1
// CHECK-NEXT: #RootClassWithNonTrivialProperties.init!allocator.1
// CHECK-NEXT: #RootClassWithNonTrivialProperties.deinit!deallocator
// CHECK-NEXT: }
// CHECK-LABEL: sil_vtable DerivedClassWithTrivialProperties {
// CHECK-NEXT: #RootClassWithoutProperties.init!allocator.1
// CHECK-NEXT: #DerivedClassWithTrivialProperties.z!getter.1
// CHECK-NEXT: #DerivedClassWithTrivialProperties.z!setter.1
// CHECK-NEXT: #DerivedClassWithTrivialProperties.z!modify.1
// CHECK-NEXT: #DerivedClassWithTrivialProperties.deinit!deallocator
// CHECK-NEXT: }
// CHECK-LABEL: sil_vtable DerivedClassWithNonTrivialProperties {
// CHECK-NEXT: #RootClassWithoutProperties.init!allocator.1
// CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!getter.1
// CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!setter.1
// CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!modify.1
// CHECK-NEXT: #DerivedClassWithNonTrivialProperties.deinit!deallocator
// CHECK-NEXT: #DerivedClassWithNonTrivialProperties!ivardestroyer.1
// CHECK-NEXT: }
|
apache-2.0
|
f5e6994f7b23d5217500a299205f6ea4
| 41.038961 | 94 | 0.754402 | 4.171392 | false | false | false | false |
Khmelevsky/QuickForms
|
Sources/Validators/Required.swift
|
1
|
868
|
//
// Required.swift
// QuickForms
//
// Created by Alexander Khmelevsky on 20.12.16.
// Copyright © 2016 Alexander Khmelevsky. All rights reserved.
//
import Foundation
extension Validators {
public static func Required<T:Equatable>(message:String = "Field is required") -> Validator<T> {
return RequiredValidator<T>(message:message)
}
}
class RequiredValidator<T:Equatable>: Validator<T> {
private var message:String!
public init(message:String) {
self.message = message
}
override open func validate(value: T?) -> [Swift.Error] {
var valid = true
if value == nil {
valid = false
} else if let str = value as? String, str.count == 0 {
valid = false
}
return valid ? [] : [Form.makeError(message: message)]
}
}
|
mit
|
437693e95b076739f6ec38b374f27611
| 21.230769 | 100 | 0.591696 | 4.148325 | false | false | false | false |
aloe-kawase/aloeutils
|
Pod/Classes/animation/AloeEaseBezier.swift
|
1
|
747
|
//
// AloeEaseBezier.swift
// Pods
//
// Created by kawase yu on 2016/06/11.
//
//
import UIKit
public class AloeEaseBezier: NSObject {
private let p1:CGPoint
private let p2:CGPoint
public init(p1:CGPoint, p2:CGPoint){
self.p1 = p1
self.p2 = p2
super.init()
}
public func calc(t:CGFloat)->CGFloat{
return AloeEaseBezier.calc(Double(t), p1: p1, p2: p2)
}
public class func calc(t:Double, p1:CGPoint, p2:CGPoint)->CGFloat{
let q1 = (t*t*t*3) + (t * t * -6) + (t*3)
let q2 = (t * t * t * -3) + (t*t*3)
let q3 = t*t*t;
let qy = q1*Double(p1.y) + q2*Double(p2.y) + q3
return CGFloat(qy)
}
}
|
mit
|
0435be4863cb80e9a758d91629618096
| 19.189189 | 70 | 0.511379 | 2.829545 | false | false | false | false |
bluwave/TwitterClient
|
TwitterClient/apiClient/TwitterAPIClient.swift
|
1
|
1093
|
//
// TwitterAPIClient.swift
// TwitterClient
//
// Created by Garrett Richards on 9/12/14.
// Copyright (c) 2014 bluewaves. All rights reserved.
//
import UIKit
import Accounts
import Social
class TwitterAPIClient: NSObject {
var account:ACAccount?
var username:String? {
get{
return account?.username
}
}
init(_ account:ACAccount?)
{
if let a = account
{
self.account = a
}
}
class func fetchTwitterAccounts(handler:([AnyObject]?, NSError!)->Void)
{
var availableUserAccounts:[AnyObject]?
let account = ACAccountStore()
let accountType = account.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
account.requestAccessToAccountsWithType(accountType, options: nil) {
accessGranted, error in
if(accessGranted)
{
availableUserAccounts = account.accountsWithAccountType(accountType)
}
handler(availableUserAccounts, error)
}
}
}
|
mit
|
4b886056a0531b3e235e906f11d1052c
| 21.770833 | 102 | 0.608417 | 4.901345 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/Model/Activity.swift
|
1
|
3756
|
//
// Activity.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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
@objc
open class Activity: NSObject, Identifiable {
open let identifier: String
open let type: ActivityType
open let count: Int
open let itemsCount: Int
open let createdAt: Date
open let lastUpdatedAt: Date
open let owners: Array<User>?
open let creation: Creation?
open let gallery: Gallery?
open let user: User?
open let relatedCreations: Array<Creation>?
open let relatedComments: Array<Comment>?
open let ownersRelationships: Array<Relationship>?
open let creationRelationship: Relationship?
open let galleryRelationship: Relationship?
open let userRelationship: Relationship?
open let relatedCreationsRelationships: Array<Relationship>?
open let relatedCommentsRelationships: Array<Relationship>?
init(mapper: ActivityMapper, dataMapper: DataIncludeMapper? = nil, metadata: Metadata? = nil) {
identifier = mapper.identifier!
type = mapper.parseType()
count = mapper.count!
itemsCount = mapper.itemsCount!
createdAt = mapper.createdAt! as Date
lastUpdatedAt = mapper.lastUpdatedAt! as Date
ownersRelationships = mapper.ownersRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) })
creationRelationship = MappingUtils.relationshipFromMapper(mapper.creationRelationship)
galleryRelationship = MappingUtils.relationshipFromMapper(mapper.galleryRelationship)
userRelationship = MappingUtils.relationshipFromMapper(mapper.userRelationship)
relatedCreationsRelationships = mapper.relatedCreationsRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) })
relatedCommentsRelationships = mapper.relatedCommentsRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) })
owners = ownersRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: User.self) })
creation = MappingUtils.objectFromMapper(dataMapper, relationship: creationRelationship, type: Creation.self)
user = MappingUtils.objectFromMapper(dataMapper, relationship: userRelationship, type: User.self)
gallery = MappingUtils.objectFromMapper(dataMapper, relationship: galleryRelationship, type: Gallery.self)
relatedCreations = relatedCreationsRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: Creation.self) })
relatedComments = relatedCommentsRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: Comment.self) })
}
}
|
mit
|
a1fafba46731b6e983313c1243e3cd7b
| 47.153846 | 151 | 0.753195 | 4.877922 | false | false | false | false |
jpedrosa/sua_sdl
|
Sources/SuaSDL/span.swift
|
1
|
7713
|
import _Sua
public enum VerticalAlign {
case Top
case Center
case Bottom
}
public enum TextAlign {
case Left
case Center
case Right
}
public class Span: Element {
public var type = SType.Span
public var children = [Element]()
public var maxWidth = -1
public var maxHeight = -1
public var width = -1
public var height = -1
public var borderTop = false
public var borderRight = false
public var borderBottom = false
public var borderLeft = false
public var borderType = BorderType.LightCurved
public var expandWidth = false
public var expandHeight = false
public var expandParentWidth = false
public var expandParentHeight = false
public var backgroundStrings = [" "]
public var borderBackgroundColor: Color?
public var borderColor: Color?
public var _borderStyle: Int32 = 0
public var align = TextAlign.Left
public var verticalAlign = VerticalAlign.Top
public var lastx = 0
public var lasty = 0
public var lastSize = TellSize.EMPTY
public var eventStore: EventStore?
public init() { }
public func add(args: Any...) {
addArgs(args)
}
public func div(fn: (inout Div) throws -> Void) throws {
var d = Div()
try fn(&d)
children.append(d)
}
public func addArgs(args: [Any]) {
for v in args {
if v is String {
let vs = (v as! String)
do {
for (s, hc) in try Hexastyle.parseText(vs) {
let t = Text()
if let ahc = hc {
t.updateFromHexastyle(ahc)
}
t._text = s
children.append(t)
}
} catch {
let t = Text()
t._text = vs
children.append(t)
}
} else if v is Text {
children.append(v as! Text)
} else if v is Span {
children.append(v as! Span)
} else if v is Div {
children.append(v as! Div)
}
}
}
public func tellSize() -> TellSize {
var t = TellSize()
t.element = self
t.children = []
for e in children {
let s = e.tellSize()
t.children!.append(s)
t.childrenWidth += s.width
if s.height > t.childrenHeight {
t.childrenHeight = s.height
}
if s.expandWidth {
t.childWidthExpander += 1
if s.expandMaxWidth < 0 {
t.childExpandMaxWidth = -1
} else if t.childExpandMaxWidth >= 0 {
t.childExpandMaxWidth += s.expandMaxWidth
}
}
if s.expandHeight {
t.childWidthExpander = 1
if s.expandMaxHeight < 0 {
t.childExpandMaxHeight = -1
} else if t.childExpandMaxHeight >= 0 &&
s.expandMaxHeight > t.childExpandMaxHeight {
t.childExpandMaxHeight = s.expandMaxHeight
}
}
if s.expandParentWidth {
t.expandParentWidth = true
}
if s.expandParentHeight {
t.expandParentHeight = true
}
}
t.width = width
if t.childrenWidth > t.width {
t.width = t.childrenWidth
}
t.height = height
if t.childrenHeight > t.height {
t.height = t.childrenHeight
}
if t.width > 0 {
if borderRight {
t.borderRight = 1
t.width += 1
}
if borderLeft {
t.borderLeft = 1
t.width += 1
}
}
if maxWidth >= 0 && t.width > maxWidth {
t.width = maxWidth
}
if t.height > 0 {
if borderTop {
t.borderTop = 1
t.height += 1
}
if borderBottom {
t.borderBottom = 1
t.height += 1
}
}
if maxHeight >= 0 && t.height > maxHeight {
t.height = maxHeight
}
t.expandWidth = expandWidth
t.expandHeight = expandHeight
if t.expandParentWidth {
t.expandParentWidth = true
t.expandWidth = true
} else if expandParentWidth {
t.expandParentWidth = true
}
if t.expandParentHeight {
t.expandParentHeight = true
t.expandHeight = true
} else if expandParentHeight {
t.expandParentHeight = true
}
if t.expandWidth {
t.expandMaxWidth = maxWidth
}
if t.expandHeight {
t.expandMaxHeight = maxHeight
}
return t
}
public func draw(x: Int, y: Int, size: TellSize) {
lastx = x
lasty = y
lastSize = size
var w = size.contentWidth
let contentHeight = size.contentHeight
if w <= 0 || contentHeight <= 0 {
return
}
var ap = S.textGrid.withStyle(_borderStyle) { () -> Point in
return S.textGrid.withColor(borderColor,
backgroundColor: borderBackgroundColor) { () -> Point in
return self.drawBorder(x, y: y, size: size)
}
}
var availableWidth = w - size.childrenWidth
drawBackground(ap.x, y: ap.y, width: w, height: contentHeight,
strings: backgroundStrings)
///////////////////////////// start /////////////////////////////////////
// This code served as a template for Div's height expanding.
var childrenList = size.children!
var widthExpander = size.childWidthExpander
if widthExpander > 0 {
var changedChildren = childrenList
let len = changedChildren.count
var expanders = [Bool](count: len, repeatedValue: false)
for i in 0..<len {
if childrenList[i].expandWidth {
expanders[i] = true
}
}
while availableWidth > 0 && widthExpander > 0 {
var widthShare = availableWidth
if widthExpander > 1 {
widthShare = availableWidth / widthExpander
if widthShare == 0 {
widthShare = 1
}
}
for i in 0..<len {
let c = changedChildren[i]
if expanders[i] {
if c.expandMaxWidth == -1 {
changedChildren[i].width += widthShare
availableWidth -= widthShare
} else if widthShare <= c.expandMaxWidth {
changedChildren[i].width += widthShare
changedChildren[i].expandMaxWidth -= widthShare
availableWidth -= widthShare
} else if c.expandMaxWidth == 0 {
widthExpander -= 1
expanders[i] = false
}
if availableWidth == 0 {
break
}
}
}
}
childrenList = changedChildren
///////////////////////////// end /////////////////////////////////////
}
if align != .Left && size.expandWidth && availableWidth > 0 {
ap.x += commonAlign(align, availableWidth: availableWidth)
}
for s in childrenList {
var candidateSize = s
if s.width > w {
candidateSize.width = w
}
if verticalAlign != .Top && s.height < contentHeight {
let yo = verticalAlign == .Center ? (contentHeight - s.height) / 2 :
contentHeight - s.height
s.element!.draw(ap.x, y: ap.y + yo, size: candidateSize)
} else {
if s.height > contentHeight {
candidateSize.height = contentHeight
}
s.element!.draw(ap.x, y: ap.y, size: candidateSize)
}
w -= s.width
if w <= 0 {
break
}
ap.x += s.width
}
}
public func pointToList(x: Int, y: Int, inout list: [Element]) -> Bool {
if matchPoint(x, y: y) {
list.append(self)
for c in children {
if c.type == .Text {
if c.matchPoint(x, y: y) {
list.append(c)
}
} else if c.type == .Div {
if (c as! Div).pointToList(x, y: y, list: &list) {
break
}
} else if c.type == .Span {
if (c as! Span).pointToList(x, y: y, list: &list) {
break
}
}
}
return true
}
return false
}
}
|
apache-2.0
|
a6b4ba3209e1d11a191714e4be93347c
| 25.234694 | 77 | 0.547776 | 4.025574 | false | false | false | false |
google/JacquardSDKiOS
|
JacquardSDK/Classes/Internal/TagAPIDetails/DFUCommands.swift
|
1
|
6584
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Checks the status of the image if already present any(partial/full) for the specified component.
struct DFUStatusCommand: CommandRequest {
/// Vendor ID of the component for which DFU has to be performed.
let vendorID: UInt32
/// Product ID of the component for which DFU has to be performed.
let productID: UInt32
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dfu
request.opcode = .dfuStatus
let dfuStatusRequest = Google_Jacquard_Protocol_DFUStatusRequest(
vendorID: vendorID,
productID: productID
)
request.Google_Jacquard_Protocol_DFUStatusRequest_dfuStatus = dfuStatusRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Google_Jacquard_Protocol_DFUStatusResponse, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
guard outerProto.hasGoogle_Jacquard_Protocol_DFUStatusResponse_dfuStatus else {
return .failure(JacquardCommandError.malformedResponse)
}
return .success((outerProto.Google_Jacquard_Protocol_DFUStatusResponse_dfuStatus))
}
}
/// Prepares for uploading the image for the specified component.
struct DFUPrepareCommand: CommandRequest {
/// Vendor ID of the component for which DFU has to be performed.
let vendorID: UInt32
/// Product ID of the component for which DFU has to be performed.
let productID: UInt32
/// ID of the component for which DFU has to be performed.
let componentID: UInt32
/// CRC for the image to be used for the DFU.
let finalCrc: UInt32
/// Final size of the image to be used for the DFU.
let finalSize: UInt32
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dfu
request.opcode = .dfuPrepare
let dfuPrepareRequest = Google_Jacquard_Protocol_DFUPrepareRequest(
vendorID: vendorID,
productID: productID,
componentID: componentID,
finalCrc: finalCrc,
finalSize: finalSize
)
request.Google_Jacquard_Protocol_DFUPrepareRequest_dfuPrepare = dfuPrepareRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard outerProto is Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
return .success(())
}
}
/// Writes the data chunk from the image being uploaded.
struct DFUWriteCommand: CommandRequest {
/// Image data chunk to be transferred over the BLE.
let data: Data
/// Offset at which the data chunk has to be written.
let offset: UInt32
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dfu
request.opcode = .dfuWrite
let dfuWriteRequest = Google_Jacquard_Protocol_DFUWriteRequest(
data: data,
offset: offset
)
request.Google_Jacquard_Protocol_DFUWriteRequest_dfuWrite = dfuWriteRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Google_Jacquard_Protocol_DFUWriteResponse, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
guard outerProto.hasGoogle_Jacquard_Protocol_DFUWriteResponse_dfuWrite else {
return .failure(JacquardCommandError.malformedResponse)
}
return .success((outerProto.Google_Jacquard_Protocol_DFUWriteResponse_dfuWrite))
}
}
/// Executes the uploaded image for the specified component.
struct DFUExecuteCommand: CommandRequest {
/// Vendor ID of the component for which DFU has to be performed.
let vendorID: UInt32
/// Product ID of the component for which DFU has to be performed.
let productID: UInt32
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dfu
request.opcode = .dfuExecute
var dfuExecuteRequest = Google_Jacquard_Protocol_DFUExecuteRequest(
vendorID: vendorID,
productID: productID
)
dfuExecuteRequest.updateSched = Google_Jacquard_Protocol_UpdateSchedule.updateNow
request.Google_Jacquard_Protocol_DFUExecuteRequest_dfuExecute = dfuExecuteRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard outerProto is Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
return .success(())
}
}
extension Google_Jacquard_Protocol_DFUStatusRequest {
init(vendorID: UInt32, productID: UInt32) {
self.vendorID = vendorID
self.productID = productID
}
}
extension Google_Jacquard_Protocol_DFUPrepareRequest {
init(
vendorID: UInt32,
productID: UInt32,
componentID: UInt32,
finalCrc: UInt32,
finalSize: UInt32
) {
self.vendorID = vendorID
self.productID = productID
self.component = componentID
self.finalCrc = finalCrc
self.finalSize = finalSize
}
}
extension Google_Jacquard_Protocol_DFUWriteRequest {
init(data: Data, offset: UInt32) {
self.data = data
self.offset = offset
}
}
extension Google_Jacquard_Protocol_DFUExecuteRequest {
init(vendorID: UInt32, productID: UInt32) {
self.vendorID = vendorID
self.productID = productID
}
}
|
apache-2.0
|
7d0693278772ae62fa96a11082c00e8c
| 31.756219 | 104 | 0.734204 | 4.280884 | false | false | false | false |
usbong/Usbong-iOS
|
Usbong/AppDelegate.swift
|
2
|
4851
|
//
// AppDelegate.swift
// Usbong
//
// Created by Chris Amanse on 11/26/15.
// Copyright © 2015 Usbong Social Systems, Inc. All rights reserved.
//
import UIKit
import UsbongKit
struct SampleTree {
static let fileName = "Usbong iOS"
static let ext = "utree"
}
struct UsbongNotification {
static let CopiedTreeInApp = "ph.usbong.Usbong.CopiedTreeInApp"
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let launchedKey = "launched-\(UIApplication.appVersion)"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
print("App Version: \(UIApplication.appVersion)")
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
// Navigation bar appearance
let navBarAppearance = UINavigationBar.appearance()
navBarAppearance.barTintColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1)
navBarAppearance.translucent = false
navBarAppearance.tintColor = UIColor.whiteColor()
navBarAppearance.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
guard let fileNameExtension = url.pathExtension else { return false }
guard let fileName = url.URLByDeletingPathExtension?.lastPathComponent else { return false }
switch fileNameExtension {
case "utree":
// Copy .utree files to Documents/
print("Opening file: \(url)")
let fileManager = NSFileManager.defaultManager()
let rootURL = UsbongFileManager.defaultManager().rootURL
// If filename exists, add suffix with the appropriate count
var suffixNumber = 0
var newURL = rootURL
repeat {
let suffix = suffixNumber == 0 ? "" : "-\(suffixNumber)"
newURL = rootURL.URLByAppendingPathComponent("\(fileName)\(suffix)").URLByAppendingPathExtension(fileNameExtension)
suffixNumber += 1
} while fileManager.fileExistsAtPath(newURL.path!)
print("Copying file to: \(newURL.path!)")
do {
try fileManager.moveItemAtURL(url, toURL: newURL)
NSNotificationCenter.defaultCenter().postNotificationName(UsbongNotification.CopiedTreeInApp, object: nil)
print("Successfully copied file!")
return true
} catch {
print("Failed to copy file")
return false
}
default:
return false
}
}
}
extension UIApplication {
static var appVersion: String {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as? String ?? "0.0"
}
}
|
apache-2.0
|
da50f20b4ee2eba218a8ff449819f04a
| 41.920354 | 285 | 0.670309 | 5.705882 | false | false | false | false |
tgsala/HackingWithSwift
|
project05/project05/MasterViewController.swift
|
1
|
4930
|
//
// MasterViewController.swift
// project05
//
// Created by g5 on 3/4/16.
// Copyright © 2016 tgsala. All rights reserved.
//
import UIKit
import GameplayKit
class MasterViewController: UITableViewController {
var objects = [String]()
var allWords = [String]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add,
target: self, action: "promptForAnswer")
if let startWordsPath = NSBundle.mainBundle().pathForResource("start", ofType: "txt") {
if let startWords = try? String(contentsOfFile: startWordsPath, usedEncoding: nil) {
allWords = startWords.componentsSeparatedByString("\n")
} else {
loadDefaultWords()
}
} else {
loadDefaultWords()
}
startGame()
}
func loadDefaultWords() {
allWords = ["abjectly", "beguiles", "contains", "dynamism", "eleventh", "frighten", "goutiest"]
}
func startGame() {
allWords = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(allWords) as! [String]
title = allWords[0]
objects.removeAll(keepCapacity: true)
tableView.reloadData()
}
func promptForAnswer() {
let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .Alert)
ac.addTextFieldWithConfigurationHandler(nil)
let submitAction = UIAlertAction(title: "Submit", style: .Default) { [unowned self, ac] (action: UIAlertAction!) in
let answer = ac.textFields![0]
self.submitAnswer(answer.text!)
}
ac.addAction(submitAction)
presentViewController(ac, animated: true, completion: nil)
}
func submitAnswer(answer: String) {
let lowerAnswer = answer.lowercaseString
if lowerAnswer.characters.count >= 3 {
if wordIsPossible(lowerAnswer) {
if wordIsOriginal(lowerAnswer) {
if wordIsReal(lowerAnswer) {
objects.insert(answer, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
return
} else {
showErrorMessage("You can't just make them up, you know!", title: "Word not recognised")
}
} else {
showErrorMessage("Be more original!", title: "Word used already")
}
} else {
showErrorMessage("You can't spell that word from '\(title!.lowercaseString)'!",
title: "Word not possible")
}
} else {
showErrorMessage("Words must have 3 characters or more!", title: "Word too short")
}
}
func showErrorMessage(message: String, title: String) {
let ac = UIAlertController(title: title, message: message, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
func wordIsPossible(word: String) -> Bool {
var tempWord = title!.lowercaseString
for letter in word.characters {
if let pos = tempWord.rangeOfString(String(letter)) {
tempWord.removeAtIndex(pos.startIndex)
} else {
return false
}
}
return true
}
func wordIsOriginal(word: String) -> Bool {
return !objects.contains(word) && word != title!
}
func wordIsReal(word: String) -> Bool {
let checker = UITextChecker()
let range = NSMakeRange(0, word.characters.count)
let misspelledRange = checker.rangeOfMisspelledWordInString(
word, range: range, startingAt: 0, wrap: false, language: "en")
return misspelledRange.location == NSNotFound
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row]
cell.textLabel!.text = object
return cell
}
}
|
unlicense
|
c6462f364b7e99951e2a3431a719cf8f
| 33.957447 | 123 | 0.591601 | 5.177521 | false | false | false | false |
Jogga/ios-programmatic-layout-examples
|
ios-programmatic-layout-examples/JunctionViewController.swift
|
1
|
6642
|
//
// JunctionViewController.swift
// ios-programmatic-layout-examples
//
// Created by Joachim Fröstl on 16.08.16.
// Copyright © 2016 Joachim Fröstl. All rights reserved.
//
import UIKit
class JunctionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Examples"
// Setup Buttons
let constraintButton = UIButton(type: .System)
constraintButton.setTitle("NSLayoutConstraint", forState: .Normal)
constraintButton.addTarget(self, action: #selector(JunctionViewController.constraintButtonClicked), forControlEvents: .TouchUpInside)
let anchorButton = UIButton(type: .System)
anchorButton.setTitle("NSLayoutAnchor", forState: .Normal)
anchorButton.addTarget(self, action: #selector(JunctionViewController.anchorButtonClicked), forControlEvents: .TouchUpInside)
let frameButton = UIButton(type: .System)
frameButton.setTitle("Frame Based Layout", forState: .Normal)
frameButton.addTarget(self, action: #selector(JunctionViewController.frameButtonClicked), forControlEvents: .TouchUpInside)
let stackButton = UIButton(type: .System)
stackButton.setTitle("UIStackView", forState: .Normal)
stackButton.addTarget(self, action: #selector(JunctionViewController.stackButtonClicked), forControlEvents: .TouchUpInside)
let visualFormatButton = UIButton(type: .System)
visualFormatButton.setTitle("Visual Format Language", forState: .Normal)
visualFormatButton.addTarget(self, action: #selector(JunctionViewController.visualFormatLanguageButton), forControlEvents: .TouchUpInside)
// Setup and add StackView
let navStack = UIStackView()
navStack.translatesAutoresizingMaskIntoConstraints = false
navStack.alignment = .Center
navStack.axis = .Vertical
navStack.distribution = .EqualSpacing
navStack.spacing = 8
navStack.addArrangedSubview(constraintButton)
navStack.addArrangedSubview(anchorButton)
navStack.addArrangedSubview(frameButton)
navStack.addArrangedSubview(stackButton)
navStack.addArrangedSubview(visualFormatButton)
// Setup ScrollView
let examplesScrollView = UIScrollView()
examplesScrollView.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 16, right: 0)
examplesScrollView.translatesAutoresizingMaskIntoConstraints = false
examplesScrollView.addSubview(navStack)
// Add Views
view.addSubview(examplesScrollView)
view.backgroundColor = UIColor.whiteColor()
// Setup and Activate Constraints
let exampleScrollViewLeadingConstraint = NSLayoutConstraint(
item: examplesScrollView,
attribute: .LeadingMargin,
relatedBy: .Equal,
toItem: view,
attribute: .Leading,
multiplier: 1.0,
constant: 0)
let exampleScrollViewTrailingConstraint = NSLayoutConstraint(
item: examplesScrollView,
attribute: .TrailingMargin,
relatedBy: .Equal,
toItem: view,
attribute: .Trailing,
multiplier: 1.0,
constant: 0)
let exampleScrollViewTopConstraint = NSLayoutConstraint(
item: examplesScrollView,
attribute: .Top,
relatedBy: .Equal,
toItem: view,
attribute: .Top,
multiplier: 1.0,
constant: 0)
let exampleScrollViewBottomConstraint = NSLayoutConstraint(
item: examplesScrollView,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1.0,
constant: 0)
let navStackLeadingConstraint = NSLayoutConstraint(
item: navStack,
attribute: .Leading,
relatedBy: .Equal,
toItem: examplesScrollView,
attribute: .Leading,
multiplier: 1.0,
constant: 0)
let navStackTrailingConstraint = NSLayoutConstraint(
item: navStack,
attribute: .Trailing,
relatedBy: .Equal,
toItem: examplesScrollView,
attribute: .Trailing,
multiplier: 1.0,
constant: 0)
let navStackTopConstraint = NSLayoutConstraint(
item: navStack,
attribute: .Top,
relatedBy: .Equal,
toItem: examplesScrollView,
attribute: .Top,
multiplier: 1.0,
constant: 0)
let navStackBottomConstraint = NSLayoutConstraint(
item: navStack,
attribute: .Bottom,
relatedBy: .Equal,
toItem: examplesScrollView,
attribute: .Bottom,
multiplier: 1.0,
constant: 0)
let navStackWidthConstraint = NSLayoutConstraint(
item: navStack,
attribute: .Width,
relatedBy: .Equal,
toItem: examplesScrollView,
attribute: .Width,
multiplier: 1.0,
constant: 0)
NSLayoutConstraint.activateConstraints([
exampleScrollViewLeadingConstraint,
exampleScrollViewTrailingConstraint,
exampleScrollViewTopConstraint,
exampleScrollViewBottomConstraint,
navStackLeadingConstraint,
navStackTrailingConstraint,
navStackTopConstraint,
navStackBottomConstraint,
navStackWidthConstraint ])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func constraintButtonClicked(sender: UIButton!) {
print("constraint")
}
func anchorButtonClicked(sender: UIButton!) {
print("anchor")
}
func frameButtonClicked(sender: UIButton!) {
let frameVC = FrameBasedLayoutViewController()
navigationController?.pushViewController(frameVC, animated: true)
}
func stackButtonClicked(sender: UIButton!) {
let stackVC = StackViewLayoutViewController()
navigationController?.pushViewController(stackVC, animated: true)
}
func visualFormatLanguageButton(sender: UIButton!) {
print("format")
}
}
|
mit
|
d9aa002514b886a4da7f70c2e9637014
| 34.502674 | 146 | 0.619973 | 5.664676 | false | false | false | false |
KoCMoHaBTa/MHAppKit
|
MHAppKit/ViewControllers/StaticTableViewController.swift
|
1
|
4950
|
//
// StaticTableViewController.swift
// MHAppKit
//
// Created by Milen Halachev on 2/12/15.
// Copyright (c) 2015 Milen Halachev. All rights reserved.
//
#if canImport(UIKit) && !os(watchOS)
import UIKit
open class StaticTableViewController: UITableViewController, UINavigationControllerPreferencesProvider {
open var prefersStatusBarHiddenValue: Bool?
open override func viewDidLoad() {
super.viewDidLoad()
}
#if !os(tvOS)
open override var prefersStatusBarHidden : Bool {
return self.prefersStatusBarHiddenValue ?? super.prefersStatusBarHidden
}
#endif
//MARK: - UINavigationControllerPreferencesProvider
@IBInspectable open var providesNavigationControllerPreferencesIB: Bool = false
@IBInspectable open var prefersNavigationBarHiddenIB: Bool = false
open func providesNavigationControllerPreferences() -> Bool {
return self.providesNavigationControllerPreferencesIB
}
open func prefersNavigationBarHidden() -> Bool {
return self.prefersNavigationBarHiddenIB
}
//MARK: - Accessory Action
@IBAction open func accessoryViewTouchAction(_ sender: Any?, event: UIEvent) {
if let indexPath = self.tableView.indexPaths(for: event).first {
self.tableView(self.tableView, accessoryButtonTappedForRowWith: indexPath)
}
}
//MARK: Scrolling
private var animationCompletionBlock: (() -> ())?
open func scrollToRowAtIndexPath(_ indexPath: IndexPath, atScrollPosition scrollPosition: UITableView.ScrollPosition, animationCompletionBlock: (() -> ())?) {
let rect = tableView.rectForRow(at: indexPath)
if (rect.origin.y != self.tableView.contentOffset.y + self.tableView.contentInset.top) {
// scrollToRowAtIndexPath will animate and callback scrollViewDidEndScrollingAnimation
self.animationCompletionBlock = animationCompletionBlock
self.tableView.scrollToRow(at: indexPath, at: scrollPosition, animated: true)
} else {
// scrollToRowAtIndexPath will have no effect
animationCompletionBlock?()
}
}
//MARK: - UIScrollViewDelegate
open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.animationCompletionBlock?()
self.animationCompletionBlock = nil
}
//MARK: - UIRefreshControl
@available(tvOS, unavailable)
open func beginRefresh() {
self.refreshControl?.beginRefreshing()
}
@available(tvOS, unavailable)
open func endRefresh() {
self.refreshControl?.endRefreshing()
}
@available(tvOS, unavailable)
open func showRefreshControl(animated: Bool) {
guard self.refreshControl?.isRefreshing == false else {
return
}
let h = self.refreshControl?.frame.size.height ?? 0
var offset = self.tableView.contentOffset
offset.y = -h - self.view.safeAreaInsets.top
self.tableView.setContentOffset(offset, animated: animated)
}
//programatic refresh - shouldRefresh -> tableView content inset (animated) -> refreshControlAction
@available(tvOS, unavailable)
@IBAction open func performRefresh() {
self.performRefresh(animated: true)
}
@available(tvOS, unavailable)
open func performRefresh(animated: Bool) {
self.showRefreshControl(animated: animated)
self.refreshControl?.sendActions(for: .valueChanged)
}
///Performs a refresh with custom action
@available(tvOS, unavailable)
open func performRefresh(animated: Bool, action: @escaping (_ completion: @escaping () -> Void) -> Void) {
self.showRefreshControl(animated: animated)
self.beginRefresh()
action {
self.endRefresh()
}
}
///Assign this action to the refresh control. If you do so, the `refreshControlActionWithCompletionBlock` method will be called automatically
@available(tvOS, unavailable)
@IBAction open func refreshControlAction(_ sender: Any?) {
self.beginRefresh()
self.refreshControlActionWithCompletionBlock { () -> () in
self.endRefresh()
}
}
///Override this in order to implement the refersh control action
@available(tvOS, unavailable)
open func refreshControlActionWithCompletionBlock(_ completionBlock: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in
completionBlock()
}
}
}
#endif
|
mit
|
b3567fd860d6ed73300925e978e27c2e
| 30.329114 | 162 | 0.637576 | 5.543113 | false | false | false | false |
NelsonLeDuc/proteus
|
test/lexer/utilities.swift
|
1
|
1540
|
//
// utilities.swift
// protc
//
// Created by David Owens II on 10/13/14.
// Copyright (c) 2014 owensd.io. All rights reserved.
//
import Foundation
import XCTest
func pathForFile(name: String, #type: String) -> String
{
let bundle = NSBundle(forClass: lexer_enum_tests.self)
return bundle.pathForResource(name, ofType: type) ?? ""
}
func stringForFile(file: String, #type: String) -> String?
{
let bundle = NSBundle(forClass: lexer_enum_tests.self)
let path = bundle.pathForResource(file, ofType: type)
if let path = path {
return String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}
else {
return nil
}
}
func assertEqual(stringA: String?, stringB: String?)
{
XCTAssertTrue(stringA != nil)
XCTAssertTrue(stringB != nil)
if (stringA == nil || stringB == nil) { return }
let linesA = stringA!.componentsSeparatedByString("\n")
let linesB = stringB!.componentsSeparatedByString("\n")
for idx in 0..<linesA.count {
if idx >= linesB.count { break; }
XCTAssertEqual(linesA[idx], linesB[idx], "\nLeft: \n\(context(linesA, idx))\nRight:\n\(context(linesB, idx))")
}
XCTAssertEqual(linesA.count, linesB.count)
}
private func context(lines: [String], index: Int) -> String
{
var context = ""
if index > 1 { context = "\(index - 1): \(lines[index - 1])\n" }
context += "\(index): \(lines[index])\n"
if index < lines.count - 1 { context += "\(index + 1): \(lines[index + 1])\n" }
return context
}
|
mit
|
c55c65ec5b3fe91278bade74744b0beb
| 26.517857 | 118 | 0.637662 | 3.484163 | false | true | false | false |
RockyAo/Dictionary
|
Dictionary/Classes/Home/ViewModel/HomeViewModel.swift
|
1
|
2166
|
//
// HomeViewModel.swift
// Dictionary
//
// Created by Rocky on 2017/5/23.
// Copyright © 2017年 Rocky. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Action
import RxDataSources
typealias WordSection = AnimatableSectionModel<String,WordModel>
struct HomeViewModel {
let coordinator : SceneCoordinatorType!
let service : HomeServices!
let disposeBag = DisposeBag()
/// input:
let searchText:Variable<String> = Variable("")
let wordViewHidden:Variable<Bool> = Variable(false)
///output
var translateData:Driver<WordModel>
var sectionItems:Observable<[WordSection]>{
return service.allHistory()
.observeOn(scheduler: .Main)
.map({ (dataArray) in
return [WordSection(model: "历史查询", items: dataArray)]
})
}
let deleteAction:Action<Void,Void>
let playAudioAction:Action<String,Void>
let collectAction:Action<WordModel,WordModel>
init(coordinator:SceneCoordinatorType,service:HomeServices) {
self.coordinator = coordinator
self.service = service
translateData = searchText.asDriver()
.skip(1)
.throttle(1)
.filter({ (data) -> Bool in
return data.characters.count > 1
})
.flatMap{
return service.requestData(string: $0).asDriver(onErrorJustReturn: WordModel())
}
.flatMap{
return service.storageNewWord(item: $0).asDriver(onErrorJustReturn: WordModel())
}
playAudioAction = Action{ input in
return service.playAudio(urlString: input)
}
deleteAction = Action{_ in
return service.databaseService.deleteAll()
}
collectAction = Action{ input in
return service.update(item: input)
}
}
}
|
agpl-3.0
|
c0b1cbd32eff4f219f91b70a61c1c8e5
| 21.447917 | 96 | 0.546172 | 5.256098 | false | false | false | false |
xwu/swift
|
test/IDE/complete_stmt_controlling_expr.swift
|
1
|
18296
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t
struct FooStruct {
var instanceVar : Int
init(_: Int = 0) { }
func boolGen() -> Bool { return false }
func intGen() -> Int { return 1 }
}
func testGuard1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
guard #^COND_GUARD_1?check=COND-WITH-RELATION^#
}
func testIf1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if #^COND_IF_1?check=COND-WITH-RELATION^#
}
func testIf2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if #^COND_IF_2?check=COND-WITH-RELATION^# {
}
}
func testIf2b(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true, #^COND_IF_2B?check=COND-WITH-RELATION^# {
}
}
func testIf3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if var z = #^COND_IF_3?check=COND_COMMON^# {
}
}
func testIf4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if var z = #^COND_IF_4?check=COND_COMMON^# {
}
}
func testIfElseIf1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if #^COND_IF_ELSE_IF_1?check=COND-WITH-RELATION^#
}
func testIfElseIf2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if #^COND_IF_ELSE_IF_2?check=COND-WITH-RELATION^# {
}
}
func testIfElseIf3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if true {
} else if #^COND_IF_ELSE_IF_3?check=COND-WITH-RELATION^#
}
func testIfElseIf4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if true {
} else if #^COND_IF_ELSE_IF_4?check=COND-WITH-RELATION^# {
}
}
func testIfElseIf5(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if var z = #^COND_IF_ELSE_IF_5?check=COND_COMMON^#
}
func testIfElseIf6(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if let z = #^COND_IF_ELSE_IF_6?check=COND_COMMON^# {
}
}
func testWhile1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while #^COND_WHILE_1?check=COND-WITH-RELATION^#
}
func testWhile2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while #^COND_WHILE_2?check=COND-WITH-RELATION^# {
}
}
func testWhile2b(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while true, #^COND_WHILE_2B?check=COND-WITH-RELATION^# {
}
}
func testWhile3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while var z = #^COND_WHILE_3?check=COND_COMMON^#
}
func testWhile4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while let z = #^COND_WHILE_4?check=COND_COMMON^#
}
func testRepeatWhile1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
repeat {
} while #^COND_DO_WHILE_1?check=COND-WITH-RELATION^#
}
func testRepeatWhile2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
repeat {
} while localFooObject.#^COND_DO_WHILE_2?check=COND-WITH-RELATION1^#
}
func testForeachPattern1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for #^FOREACH_PATTERN_1^#
// FOREACH_PATTERN_1: Begin completions, 4 items
// FOREACH_PATTERN_1-DAG: Keyword[try]/None: try; name=try
// FOREACH_PATTERN_1-DAG: Keyword/None: await; name=await
// FOREACH_PATTERN_1-DAG: Keyword[var]/None: var; name=var
// FOREACH_PATTERN_1-DAG: Keyword[case]/None: case; name=case
// FOREACH_PATTERN_1: End completions
}
func testForeachPattern2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for try #^FOREACH_PATTERN_2^#
// FOREACH_PATTERN_2: Begin completions, 3 items
// FOREACH_PATTERN_2-DAG: Keyword/None: await; name=await
// FOREACH_PATTERN_2-DAG: Keyword[var]/None: var; name=var
// FOREACH_PATTERN_2-DAG: Keyword[case]/None: case; name=case
// FOREACH_PATTERN_2: End completions
}
func testForeachPattern3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for try await #^FOREACH_PATTERN_3^#
// FOREACH_PATTERN_3: Begin completions, 2 items
// FOREACH_PATTERN_3-DAG: Keyword[var]/None: var; name=var
// FOREACH_PATTERN_3-DAG: Keyword[case]/None: case; name=case
// FOREACH_PATTERN_3: End completions
}
func testForeachPattern4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var #^FOREACH_PATTERN_4?check=COND_NONE^#
}
func testCStyleForCond1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_1?check=COND_COMMON^#
}
func testCStyleForCond2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_2?check=COND_COMMON^#;
}
func testCStyleForCond3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_3?check=COND_COMMON^# ;
}
func testCStyleForCondI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; #^C_STYLE_FOR_COND_I_1?check=COND_COMMON^#
}
func testCStyleForCondI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; #^C_STYLE_FOR_COND_I_2?check=COND_COMMON^#
}
func testCStyleForCondIE1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0, e = 10; true; #^C_STYLE_FOR_COND_I_E_1?check=COND_COMMON^#
}
func testCStyleForIncr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; ; #^C_STYLE_FOR_INCR_1?check=COND_COMMON^#
}
func testCStyleForIncr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; ; #^C_STYLE_FOR_INCR_2?check=COND_COMMON^# {
}
}
func testCStyleForIncrI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; true; #^C_STYLE_FOR_INCR_I_1?check=COND_COMMON^#
}
func testCStyleForIncrI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; i != 10; #^C_STYLE_FOR_INCR_I_2?check=COND_COMMON^#
}
func testCStyleForIncrI3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; unknown_var != 10; #^C_STYLE_FOR_INCR_I_3?check=COND_COMMON^#
}
func testCStyleForIncrI4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; unknown_var != 10; #^C_STYLE_FOR_INCR_I_4?check=COND_COMMON^#
}
func testCStyleForIncrIE1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0, e = 10; true; #^C_STYLE_FOR_INCR_I_E_1?check=COND_COMMON^#
}
func testCStyleForBodyI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0 {
#^C_STYLE_FOR_BODY_I_1?check=COND_COMMON;check=WITH_I_ERROR_LOCAL^#
}
}
func testCStyleForBodyI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; {
#^C_STYLE_FOR_BODY_I_2?check=COND_COMMON;check=WITH_I_ERROR_LOCAL^#
}
}
func testCStyleForBodyI3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; {
#^C_STYLE_FOR_BODY_I_3?check=COND_COMMON;check=WITH_I_ERROR_LOCAL^#
}
}
func testCStyleForBodyI4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; ; {
#^C_STYLE_FOR_BODY_I_4?check=COND_COMMON;check=WITH_I_ERROR_LOCAL^#
}
}
func testCStyleForBodyI5(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; unknown_var != 10; {
#^C_STYLE_FOR_BODY_I_5?check=COND_COMMON;check=WITH_I_ERROR_LOCAL^#
}
}
func testCStyleForBodyI6(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; ; unknown_var++ {
#^C_STYLE_FOR_BODY_I_6?check=COND_COMMON;check=WITH_I_ERROR_LOCAL^#
}
}
func testForEachExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for i in #^FOR_EACH_EXPR_1?check=COND_COMMON^#
}
func testForEachExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for i in #^FOR_EACH_EXPR_2?check=COND_COMMON^# {
}
}
func testSwitchExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch #^SWITCH_EXPR_1?check=COND_COMMON^#
}
func testSwitchExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch #^SWITCH_EXPR_2?check=COND_COMMON^# {
}
}
func testSwitchCaseWhereExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_1?check=COND_COMMON^#
}
}
func testSwitchCaseWhereExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_2?check=COND_COMMON^#:
}
}
func testSwitchCaseWhereExpr3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_3?check=COND_COMMON^# :
}
}
func testSwitchCaseWhereExprI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (var i, 0) where #^SWITCH_CASE_WHERE_EXPR_I_1?check=COND_COMMON;check=WITH_I_INT_LOCAL^#
}
}
func testSwitchCaseWhereExprI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, var i) where #^SWITCH_CASE_WHERE_EXPR_I_2?check=COND_COMMON;check=WITH_I_INT_LOCAL^#
}
}
func testSwitchCaseWhereExprIJ1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (var i, var j) where #^SWITCH_CASE_WHERE_EXPR_I_J_1?check=COND_COMMON;check=WITH_I_INT_LOCAL;check=WITH_J_INT^#
}
}
// COND_NONE-NOT: Begin completions
// COND_NONE-NOT: End completions
// COND_COMMON: Begin completions
// COND_COMMON-DAG: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}}
// COND_COMMON-DAG: Literal[Boolean]/None: false[#Bool#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: localInt[#Int#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: localFooObject[#FooStruct#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COND_COMMON: End completions
// COND-WITH-RELATION: Begin completions
// COND-WITH-RELATION-DAG: Literal[Boolean]/None/TypeRelation[Identical]: true[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Literal[Boolean]/None/TypeRelation[Identical]: false[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: localInt[#Int#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: localFooObject[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testIf2({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testWhile3({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testIfElseIf5({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testCStyleForIncrIE1({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION1: Begin completions
// COND-WITH-RELATION1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// COND-WITH-RELATION1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: boolGen()[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION1-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#]{{; name=.+$}}
// COND-WITH-RELATION1: End completions
// WITH_I_INT_LOCAL: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// WITH_I_ERROR_LOCAL: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}}
// WITH_J_INT: Decl[LocalVar]/Local: j[#Int#]{{; name=.+$}}
enum A { case aaa }
enum B { case bbb }
// UNRESOLVED_B-NOT: aaa
// UNRESOLVED_B: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: bbb[#B#]; name=bbb
// UNRESOLVED_B-NOT: aaa
struct AA {
func takeEnum(_: A) {}
}
struct BB {
func takeEnum(_: B) {}
}
func testUnresolvedIF1(x: BB) {
if x.takeEnum(.#^UNRESOLVED_IF_1?check=UNRESOLVED_B^#)
}
func testUnresolvedIF2(x: BB) {
if true, x.takeEnum(.#^UNRESOLVED_IF_2?check=UNRESOLVED_B^#)
}
func testUnresolvedIF3(x: BB) {
if true, x.takeEnum(.#^UNRESOLVED_IF_3?check=UNRESOLVED_B^#) {}
}
func testUnresolvedIF4(x: BB) {
if let x.takeEnum(.#^UNRESOLVED_IF_4?check=UNRESOLVED_B^#)
}
func testUnresolvedWhile1(x: BB) {
while x.takeEnum(.#^UNRESOLVED_WHILE_1?check=UNRESOLVED_B^#)
}
func testUnresolvedWhile2(x: BB) {
while true, x.takeEnum(.#^UNRESOLVED_WHILE_2?check=UNRESOLVED_B^#)
}
func testUnresolvedWhile3(x: BB) {
while let x.takeEnum(.#^UNRESOLVED_WHILE_3?check=UNRESOLVED_B^#)
}
func testUnresolvedWhile4(x: BB) {
while true, x.takeEnum(.#^UNRESOLVED_WHILE_4?check=UNRESOLVED_B^#) {}
}
func testUnresolvedGuard1(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_1?check=UNRESOLVED_B^#)
}
func testUnresolvedGuard2(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_2?check=UNRESOLVED_B^#) {}
}
func testUnresolvedGuard3(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_3?check=UNRESOLVED_B^#) else
}
func testUnresolvedGuard4(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_4?check=UNRESOLVED_B^#) else {}
}
func testUnresolvedGuard5(x: BB) {
guard true, x.takeEnum(.#^UNRESOLVED_GUARD_5?check=UNRESOLVED_B^#)
}
func testUnresolvedGuard6(x: BB) {
guard let x.takeEnum(.#^UNRESOLVED_GUARD_6?check=UNRESOLVED_B^#)
}
func testUnresolvedGuard7(x: BB) {
guard let x.takeEnum(.#^UNRESOLVED_GUARD_7?check=UNRESOLVED_B^#) else {}
}
func testIfLetBinding1(x: FooStruct?) {
if let y = x, y.#^IF_LET_BIND_1?check=FOOSTRUCT_DOT_BOOL^# {}
}
func testIfLetBinding2(x: FooStruct?) {
if let y = x, y.#^IF_LET_BIND_2?check=FOOSTRUCT_DOT_BOOL^#
}
func testIfLetBinding3(x: FooStruct?) {
if let y = x, let z = y.#^IF_LET_BIND_3?check=FOOSTRUCT_DOT^# {}
}
func testIfLetBinding3(x: FooStruct?) {
if let y = x, let z = y#^IF_LET_BIND_4?check=FOOSTRUCT_NODOT^# {}
}
func testGuardLetBinding1(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_1?check=FOOSTRUCT_DOT_BOOL^# else {}
}
func testGuardLetBinding2(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_2?check=FOOSTRUCT_DOT_BOOL^#
}
func testGuardLetBinding3(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_3?check=FOOSTRUCT_DOT_BOOL^# else
}
func testGuardLetBinding4(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_4?check=FOOSTRUCT_DOT_BOOL^# {}
}
func testGuardLetBinding5(x: FooStruct?) {
guard let y = x, let z = y.#^GUARD_LET_BIND_5?check=FOOSTRUCT_DOT^# else {}
}
func testGuardLetBinding5(x: FooStruct?) {
guard let y = x, z = y#^GUARD_LET_BIND_6?check=FOOSTRUCT_NODOT^# else {}
}
func testGuardLetBinding7(x: FooStruct?) {
guard let boundVal = x, let other = #^GUARD_LET_BIND_7?check=FOOSTRUCT_LOCALVAL^# else {}
}
func testGuardLetBinding8(_ x: FooStruct?) {
guard let boundVal = x, let other = testGuardLetBinding8(#^GUARD_LET_BIND_8?check=FOOSTRUCT_LOCALVAL^#) else {}
}
func testGuardCase(x:FooStruct?) {
guard case .#^GUARD_CASE_PATTERN_1?check=OPTIONAL_FOOSTRUCT^# = x {}
}
func testGuardCase(x:FooStruct?) {
guard case .#^GUARD_CASE_PATTERN_2?check=OPTIONAL_FOOSTRUCT^#some() = x {}
}
// FOOSTRUCT_DOT: Begin completions
// FOOSTRUCT_DOT-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#];
// FOOSTRUCT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: boolGen()[#Bool#];
// FOOSTRUCT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#];
// FOOSTRUCT_DOT: End completions
// FOOSTRUCT_DOT_BOOL: Begin completions
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#];
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: boolGen()[#Bool#];
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#];
// FOOSTRUCT_DOT_BOOL: End completions
// FOOSTRUCT_NODOT: Begin completions
// FOOSTRUCT_NODOT-DAG: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#];
// FOOSTRUCT_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .boolGen()[#Bool#];
// FOOSTRUCT_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .intGen()[#Int#];
// FOOSTRUCT_NODOT: End completions
// FOOSTRUCT_LOCALVAL: Begin completions
// FOOSTRUCT_LOCALVAL-DAG: Decl[LocalVar]/Local{{(/TypeRelation\[Convertible\])?}}: boundVal[#FooStruct#];
// FOOSTRUCT_LOCALVAL: End completions
// OPTIONAL_FOOSTRUCT: Begin completions, 2 items
// OPTIONAL_FOOSTRUCT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: none[#Optional<FooStruct>#]; name=none
// OPTIONAL_FOOSTRUCT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: some({#FooStruct#})[#Optional<FooStruct>#]; name=some()
// OPTIONAL_FOOSTRUCT: End completions
|
apache-2.0
|
61c0de9812e0d9e62f8fc69fff0ba4f4
| 32.326047 | 150 | 0.694523 | 3.379387 | false | true | false | false |
Finb/V2ex-Swift
|
Controller/LeftViewController.swift
|
1
|
8062
|
//
// LeftViewController.swift
// V2ex-Swift
//
// Created by huangfeng on 1/14/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
import FXBlurView
class LeftViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var backgroundImageView: UIImageView = {
let backgroundImageView = UIImageView()
backgroundImageView.contentMode = .scaleToFill
return backgroundImageView
}()
var frostedView: FXBlurView = {
let frostedView = FXBlurView()
frostedView.isDynamic = false
frostedView.tintColor = UIColor.black
return frostedView;
}()
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView();
tableView.backgroundColor = UIColor.clear
tableView.estimatedRowHeight=100;
tableView.separatorStyle = .none
regClass(tableView, cell: LeftUserHeadCell.self)
regClass(tableView, cell: LeftNodeTableViewCell.self)
regClass(tableView, cell: LeftNotifictionCell.self)
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
override var preferredStatusBarStyle: UIStatusBarStyle{
get {
if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault {
if #available(iOS 13.0, *) {
return .darkContent
} else {
return .default
}
}
else{
return .lightContent
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor;
self.backgroundImageView.frame = self.view.frame
view.addSubview(self.backgroundImageView)
self.frostedView.underlyingView = self.backgroundImageView
self.frostedView.frame = self.view.frame
self.view.addSubview(self.frostedView)
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints{ (make) -> Void in
make.top.right.bottom.left.equalTo(self.view);
}
if V2User.sharedInstance.isLogin {
self.getUserInfo(V2User.sharedInstance.username!)
}
self.themeChangedHandler = {[weak self] (style) -> Void in
if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault {
self?.backgroundImageView.image = UIImage(named: "32.jpg")
}
else{
self?.backgroundImageView.image = UIImage(named: "12.jpg")
}
self?.frostedView.updateAsynchronously(true, completion: nil)
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return [1,3,2][section]
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath.section == 1 && indexPath.row == 2){
return 55 + 10
}
return [180, 55+SEPARATOR_HEIGHT, 55+SEPARATOR_HEIGHT][indexPath.section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = getCell(tableView, cell: LeftUserHeadCell.self, indexPath: indexPath);
return cell ;
}
else {
return UITableViewCell()
}
}
else if (indexPath.section == 1) {
if indexPath.row == 1 {
let cell = getCell(tableView, cell: LeftNotifictionCell.self, indexPath: indexPath)
cell.nodeImageView.image = UIImage.imageUsedTemplateMode("ic_notifications_none")
return cell
}
else {
let cell = getCell(tableView, cell: LeftNodeTableViewCell.self, indexPath: indexPath)
cell.nodeNameLabel.text = [NSLocalizedString("me"),"",NSLocalizedString("favorites")][indexPath.row]
let names = ["ic_face","","ic_turned_in_not"]
cell.nodeImageView.image = UIImage.imageUsedTemplateMode(names[indexPath.row])
return cell
}
}
else {
let cell = getCell(tableView, cell: LeftNodeTableViewCell.self, indexPath: indexPath)
cell.nodeNameLabel.text = [NSLocalizedString("nodes"),NSLocalizedString("more")][indexPath.row]
let names = ["ic_navigation","ic_settings_input_svideo"]
cell.nodeImageView.image = UIImage.imageUsedTemplateMode(names[indexPath.row])
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
if indexPath.row == 0 {
if !V2User.sharedInstance.isLogin {
let loginViewController = LoginViewController()
V2Client.sharedInstance.centerViewController!.navigationController?.present(loginViewController, animated: true, completion: nil);
}else{
let memberViewController = MyCenterViewController()
memberViewController.username = V2User.sharedInstance.username
V2Client.sharedInstance.centerNavigation?.pushViewController(memberViewController, animated: true)
V2Client.sharedInstance.drawerController?.closeDrawer(animated: true, completion: nil)
}
}
}
else if indexPath.section == 1 {
if !V2User.sharedInstance.isLogin {
let loginViewController = LoginViewController()
V2Client.sharedInstance.centerNavigation?.present(loginViewController, animated: true, completion: nil);
return
}
if indexPath.row == 0 {
let memberViewController = MyCenterViewController()
memberViewController.username = V2User.sharedInstance.username
V2Client.sharedInstance.centerNavigation?.pushViewController(memberViewController, animated: true)
}
else if indexPath.row == 1 {
let notificationsViewController = NotificationsViewController()
V2Client.sharedInstance.centerNavigation?.pushViewController(notificationsViewController, animated: true)
}
else if indexPath.row == 2 {
let favoritesViewController = FavoritesViewController()
V2Client.sharedInstance.centerNavigation?.pushViewController(favoritesViewController, animated: true)
}
V2Client.sharedInstance.drawerController?.closeDrawer(animated: true, completion: nil)
}
else if indexPath.section == 2 {
if indexPath.row == 0 {
let nodesViewController = NodesViewController()
V2Client.sharedInstance.centerViewController!.navigationController?.pushViewController(nodesViewController, animated: true)
}
else if indexPath.row == 1 {
let moreViewController = MoreViewController()
V2Client.sharedInstance.centerViewController!.navigationController?.pushViewController(moreViewController, animated: true)
}
V2Client.sharedInstance.drawerController?.closeDrawer(animated: true, completion: nil)
}
}
// MARK: 获取用户信息
func getUserInfo(_ userName:String){
UserModel.getUserInfoByUsername(userName) {(response:V2ValueResponse<UserModel>) -> Void in
if response.success {
// self?.tableView.reloadData()
NSLog("获取用户信息成功")
}
else{
NSLog("获取用户信息失败")
}
}
}
}
|
mit
|
467248c8a9301535bbf6fef32428761e
| 40.973822 | 150 | 0.609954 | 5.366131 | false | false | false | false |
skyylex/HaffmanSwift
|
Haffman.playground/Sources/Haffman.swift
|
1
|
7646
|
//
// HaffmanTree.swift
// HaffmanCoding
//
// Created by Yury Lapitsky on 12/9/15.
// Copyright © 2015 skyylex. All rights reserved.
//
import Foundation
/// Phase 1. Get source string and save it
/// Phase 2. Parse source string into characters
/// Phase 3. Calculate quantity of the each symbols in the text
/// Phase 4. Build HaffmanTree
/// Phase 5. Create encoding map
/// Phase 6. Encode text using created tree
public class HaffmanTreeBuilder {
public typealias DistributionMap = [Int : [Character]]
public typealias ReverseDistributionMap = [Character : Int]
public let text: String
public init(text: String) {
self.text = text
}
public func generateDistribution() -> DistributionMap {
let distributionMap = self.text.characters.reduce(ReverseDistributionMap()) { current, next -> ReverseDistributionMap in
var distributionTable = current
if let existingQuantity = distributionTable[next] {
distributionTable[next] = existingQuantity + 1
} else {
distributionTable[next] = 1
}
return distributionTable
}
let invertedDistributionMap = distributionMap.reduce(DistributionMap()) { currentMap, nextTuple -> DistributionMap in
let symbol = nextTuple.0
let quantity = nextTuple.1
var updatedMap = currentMap
if let existingSymbols = updatedMap[quantity] as Array<Character>? {
updatedMap[quantity] = existingSymbols + [symbol]
} else {
updatedMap[quantity] = [symbol]
}
return updatedMap
}
return invertedDistributionMap
}
public func buildTree() -> HaffmanTree? {
let sortedDistribution = generateDistribution().sort { $0.0 < $1.0 }
let collectedTrees = sortedDistribution.reduce([HaffmanTree]()) { collectedTrees, nextTuple -> [HaffmanTree] in
let quantity = nextTuple.0
let symbols = nextTuple.1
let trees = symbols.map { symbol -> HaffmanTree in
let node = Node(value: String(symbol), quantity: quantity)
return HaffmanTree(root: node)
}
return collectedTrees + trees
}
let sortedTrees = collectedTrees.sort { first, second -> Bool in first.root.quantity < second.root.quantity }
let finalTrees = simplify(sortedTrees)
precondition(finalTrees.count == 1)
let finalTree = finalTrees.first
digitize(finalTree?.root)
return finalTree
}
private func digitize(node: Node?) {
if let aliveNode = node {
aliveNode.leftChild?.digit = 0
aliveNode.rightChild?.digit = 1
digitize(aliveNode.leftChild)
digitize(aliveNode.rightChild)
}
}
private func simplify(trees: [HaffmanTree]) -> [HaffmanTree] {
/// print(trees.map { $0.root.symbol } )
if trees.count == 1 {
return trees
} else {
let first = trees[0], second = trees[1]
let combinedTree = first.join(second)
let partedTrees = (trees.count > 2) ? Array(trees[2...(trees.count - 1)]) : [HaffmanTree]()
let beforeInsertingTreesAmount = partedTrees.count
var insertPosition = 0
for nextTree in partedTrees {
if (combinedTree.root.quantity < nextTree.root.quantity) {
break
} else {
insertPosition += 1
}
}
var updatedTreeGroup = partedTrees
updatedTreeGroup.insert(combinedTree, atIndex: insertPosition)
let afterInsertingTreesAmount = updatedTreeGroup.count
/// If there are no changes combined tree should be placed as the last
let finalTreeGroup = (afterInsertingTreesAmount == beforeInsertingTreesAmount) ? updatedTreeGroup + [combinedTree] : updatedTreeGroup
return simplify(finalTreeGroup)
}
}
}
public class Node {
/// Values for building tree
public let quantity: Int
/// Values for the decoding/encoding
public let symbol: String
public var digit: Int?
public var leftChild: Node?
public var rightChild: Node?
public var isLeaf: Bool {
return self.rightChild == nil && self.leftChild == nil
}
public init(value: String, quantity: Int) {
self.quantity = quantity
self.symbol = value
}
func join(anotherNode: Node) -> Node {
let parentNodeValue = self.symbol + anotherNode.symbol
let parentNodeQuantity = self.quantity + anotherNode.quantity
let parentNode = Node(value: parentNodeValue, quantity: parentNodeQuantity)
parentNode.leftChild = (self.quantity <= anotherNode.quantity) ? self : anotherNode
parentNode.rightChild = (self.quantity > anotherNode.quantity) ? self : anotherNode
return parentNode
}
}
public class HaffmanTree {
public let root: Node
public func description() -> String {
return root.symbol
}
public func validate() -> Bool {
var validationResult = true
let decodingMap = generateDecodingMap()
for key1 in decodingMap.keys {
for key2 in decodingMap.keys {
if key1 == key2 {
continue
} else if key1.hasPrefix(key2) == true {
print(key1 + " contains " + key2)
validationResult = false
}
}
}
return validationResult
}
public init(root: Node) {
self.root = root
}
public func join(node: Node) -> HaffmanTree {
let rootNode = self.root.join(node)
return HaffmanTree(root: rootNode)
}
func join(anotherTree: HaffmanTree) -> HaffmanTree {
let rootNode = self.root.join(anotherTree.root)
return HaffmanTree(root: rootNode)
}
public func generateDecodingMap() -> [String: Character] {
return generateEncodingMap().reduce([String: Character]()) { current, next -> [String: Character] in
let symbol = next.0
let string = next.1
return current.join([string : symbol])
}
}
public func generateEncodingMap() -> [Character: String] {
return generateEncodingMap(self.root, digitString: "")
}
private func generateEncodingMap(node: Node?, digitString: String) -> [Character : String] {
let encodingMap = [Character:String]()
if let aliveNode = node {
var updatedDigitString = digitString
if let symbol = aliveNode.symbol.characters.first, digit = aliveNode.digit {
updatedDigitString += String(digit)
if aliveNode.isLeaf {
return [symbol : updatedDigitString]
}
}
let leftPartResults = generateEncodingMap(aliveNode.leftChild, digitString:updatedDigitString)
let rightPartResults = generateEncodingMap(aliveNode.rightChild, digitString:updatedDigitString)
let result = encodingMap.join(leftPartResults).join(rightPartResults)
return result
}
return encodingMap
}
}
|
mit
|
ff5a7dbb3b827d98de5ffc57cf3a0db8
| 32.977778 | 145 | 0.584173 | 4.808176 | false | false | false | false |
RenanGreca/Advent-of-Code
|
AdventOfCode.playground/Pages/DayFour.xcplaygroundpage/Sources/MD5.swift
|
1
|
7260
|
//
// MD5.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 06/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
extension NSData {
public func md5() -> NSData? {
return MD5(self).calculate()
}
public func toHexString() -> String {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
var s:String = "";
for byte in bytesArray {
s = s + String(format:"%02x", byte)
}
return s
}
}
extension String {
public func md5() -> String? {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.md5()?.toHexString()
}
}
extension NSMutableData {
/** Convenient way to append bytes */
internal func appendBytes(arrayOfBytes: [UInt8]) {
self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
struct NSDataSequence: SequenceType {
let chunkSize: Int
let data: NSData
func generate() -> AnyGenerator<NSData> {
var offset:Int = 0
return anyGenerator {
let result = self.data.subdataWithRange(NSRange(location: offset, length: min(self.chunkSize, self.data.length - offset)))
offset += result.length
return result.length > 0 ? result : nil
}
}
}
func rotateLeft(v:UInt32, n:UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
public class MD5 {
var size:Int = 16 // 128 / 8
let message: NSData
init (_ message: NSData) {
self.message = message
}
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
private func prepare(len:Int) -> NSMutableData {
let tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.length
var counter = 0
while msgLength % len != (len - 8) {
counter++
msgLength++
}
let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
tmpMessage.appendBytes(bufZeros, length: counter)
bufZeros.destroy()
bufZeros.dealloc(1)
return tmpMessage
}
private func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
let totalBytes = length ?? sizeof(T)
let valuePointer = UnsafeMutablePointer<T>.alloc(1)
valuePointer.memory = value
let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
for j in 0..<min(sizeof(T),totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
}
valuePointer.destroy()
valuePointer.dealloc(1)
return bytes
}
public func calculate() -> NSData {
let tmpMessage = prepare(64)
// hash values
var hh = h
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = (message.length * 8)
let lengthBytes = arrayOfBytes(lengthInBits, length: 64 / 8)
tmpMessage.appendBytes(Array(lengthBytes.reverse())); //FIXME: Array?
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in NSDataSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M = [UInt32](count: 16, repeatedValue: 0)
let range = NSRange(location:0, length: M.count * sizeof(UInt32))
chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
// Initialize hash value for this chunk:
var A:UInt32 = hh[0]
var B:UInt32 = hh[1]
var C:UInt32 = hh[2]
var D:UInt32 = hh[3]
var dTemp:UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
let buf: NSMutableData = NSMutableData();
hh.forEach({ (item) -> () in
var i:UInt32 = item.littleEndian
buf.appendBytes(&i, length: sizeofValue(i))
})
return buf.copy() as! NSData
}
}
|
mit
|
654b9b0218a982250ecd3c02d48c0418
| 32.583333 | 134 | 0.509926 | 3.699133 | false | false | false | false |
inacioferrarini/OMDBSpy
|
OMDBSpy/AppDelegate.swift
|
1
|
4001
|
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var appContext: AppContext?
// MARK: - App LifeCycle
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.updateStatusBarColor(UIColor(red: 0.247, green: 0.317, blue: 0.709, alpha: 0.50))
if let window = self.window {
let rootNavigationController = window.rootViewController as! UINavigationController
var firstViewController = rootNavigationController.topViewController as! AppContextAwareProtocol
let logger = Logger()
let stack = CoreDataStack(modelFileName: "OMDBSpy", databaseFileName: "OMDBSpy", logger: logger)
let router = NavigationRouter(schema: "OMDBSpy", logger: logger)
let syncRulesStack = CoreDataStack(modelFileName: "DataSyncRules", databaseFileName: "DataSyncRules", logger: logger)
let syncRules = DataSyncRules(coreDataStack: syncRulesStack)
self.appContext = AppContext(navigationController: rootNavigationController,
coreDataStack: stack,
syncRules: syncRules,
router: router,
logger: logger)
firstViewController.appContext = self.appContext
router.registerRoutes(self.createNavigationRoutes())
self.addSyncRules(syncRules)
}
return true
}
func applicationWillTerminate(application: UIApplication) {
if let appContext = self.appContext {
appContext.coreDataStack.saveContext()
}
}
// MARK: - Deep Linking Navigation
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if let appContext = self.appContext {
return appContext.router.dispatch(url)
}
return true
}
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
if let url = userActivity.webpageURL,
let appContext = self.appContext {
return appContext.router.dispatch(url)
}
return true
}
// MARK: - UI Theme
func updateStatusBarColor(color: UIColor) {
guard let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
return
}
statusBar.backgroundColor = color
}
// MARK: - AppContext Setup
func createNavigationRoutes() -> [RoutingElement] {
var routes = [RoutingElement]()
routes.append(RoutingElement(pattern: "/", handler: { (params: [NSObject : AnyObject]) -> Bool in
return true
}))
routes.append(RoutingElement(pattern: "/movie/:imdbID", handler: { (params: [NSObject : AnyObject]) -> Bool in
guard let imdbID = params["imdbID"] as? String else { return false }
if let appContext = self.appContext {
let context = appContext.coreDataStack.managedObjectContext
let viewController = ViewControllerManager().movieDetailViewController(appContext)
if let movie = OmdbMovie.fetchOmdbMovieByImdbID(imdbID, inManagedObjectContext: context) {
viewController.movie = movie
}
appContext.navigationController.presentViewController(viewController, animated: true, completion: nil)
}
return true
}))
return routes
}
func addSyncRules(syncRules: DataSyncRules) {
}
}
|
mit
|
2e83e8b3e17e373e893c86808186242c
| 34.40708 | 153 | 0.612597 | 5.740316 | false | false | false | false |
li1024316925/Swift-TimeMovie
|
Swift-TimeMovie/Swift-TimeMovie/NewsCell.swift
|
1
|
2239
|
//
// NewsCell.swift
// SwiftTimeMovie
//
// Created by DahaiZhang on 16/10/25.
// Copyright © 2016年 LLQ. All rights reserved.
//
import UIKit
class NewsCell: UITableViewCell {
//cell1
@IBOutlet weak var imageCell1: UIImageView!
@IBOutlet weak var titleCell1: UILabel!
@IBOutlet weak var title2Cell1: UILabel!
@IBOutlet weak var timeCell1: UILabel!
@IBOutlet weak var commentCell1: UILabel!
//cell2
@IBOutlet weak var titleCell2: UILabel!
@IBOutlet weak var timeCell2: UILabel!
@IBOutlet weak var commentCell2: UILabel!
@IBOutlet weak var image1Cell2: UIImageView!
@IBOutlet weak var image2Cell2: UIImageView!
@IBOutlet weak var image3Cell2: UIImageView!
//赋值时调用
var model:NewsModel?{
didSet{
if model?.type == 1 {
//cell2
titleCell2.text = model?.title
let dic1 = model?.images?[0] as? [String:Any]
let dic2 = model?.images?[1] as? [String:Any]
let dic3 = model?.images?[2] as? [String:Any]
image1Cell2.sd_setImage(with: URL(string: (dic1?["url1"] as? String)!))
image2Cell2.sd_setImage(with: URL(string: (dic2?["url1"] as? String)!))
image3Cell2.sd_setImage(with: URL(string: (dic3?["url1"] as? String)!))
timeCell2.text = "4小时前评论"
commentCell2.text = "\((model?.commentCount)!)条评论"
}else{
//cell1
timeCell1.text = "4小时前评论"
titleCell1.text = model?.title
title2Cell1.text = model?.title2
imageCell1.sd_setImage(with: URL(string: (model?.image)!))
commentCell1.text = "\((model?.commentCount)!)条评论"
}
}
}
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
}
}
|
apache-2.0
|
0842f076c847c3f218a287308a415ab5
| 29.901408 | 87 | 0.552871 | 4.195029 | false | false | false | false |
spire-inc/Bond
|
Sources/UIKit/UITableView.swift
|
6
|
6261
|
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import ReactiveKit
public extension UITableView {
public var bnd_delegate: ProtocolProxy {
return protocolProxy(for: UITableViewDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
public var bnd_dataSource: ProtocolProxy {
return protocolProxy(for: UITableViewDataSource.self, setter: NSSelectorFromString("setDataSource:"))
}
}
public protocol TableViewBond {
associatedtype DataSource: DataSourceProtocol
var animated: Bool { get }
func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: DataSource) -> UITableViewCell
func titleForHeader(in section: Int, dataSource: DataSource) -> String?
func titleForFooter(in section: Int, dataSource: DataSource) -> String?
}
extension TableViewBond {
public var animated: Bool {
return true
}
public func titleForHeader(in section: Int, dataSource: DataSource) -> String? {
return nil
}
public func titleForFooter(in section: Int, dataSource: DataSource) -> String? {
return nil
}
}
private struct SimpleTableViewBond<DataSource: DataSourceProtocol>: TableViewBond {
let animated: Bool
let createCell: (DataSource, IndexPath, UITableView) -> UITableViewCell
func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: DataSource) -> UITableViewCell {
return createCell(dataSource, indexPath, tableView)
}
}
public extension SignalProtocol where Element: DataSourceEventProtocol, Error == NoError {
public typealias DataSource = Element.DataSource
@discardableResult
public func bind(to tableView: UITableView, animated: Bool = true, createCell: @escaping (DataSource, IndexPath, UITableView) -> UITableViewCell) -> Disposable {
return bind(to: tableView, using: SimpleTableViewBond<DataSource>(animated: animated, createCell: createCell))
}
@discardableResult
public func bind<B: TableViewBond>(to tableView: UITableView, using bond: B) -> Disposable where B.DataSource == DataSource {
let dataSource = Property<DataSource?>(nil)
tableView.bnd_dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:cellForRowAt:)),
map: { (dataSource: DataSource?, tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell in
return bond.cellForRow(at: indexPath as IndexPath, tableView: tableView, dataSource: dataSource!)
})
tableView.bnd_dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:titleForHeaderInSection:)),
map: { (dataSource: DataSource?, tableView: UITableView, index: Int) -> NSString? in
return bond.titleForHeader(in: index, dataSource: dataSource!) as NSString?
})
tableView.bnd_dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:titleForFooterInSection:)),
map: { (dataSource: DataSource?, tableView: UITableView, index: Int) -> NSString? in
return bond.titleForFooter(in: index, dataSource: dataSource!) as NSString?
})
tableView.bnd_dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:numberOfRowsInSection:)),
map: { (dataSource: DataSource?, _: UITableView, section: Int) -> Int in
dataSource?.numberOfItems(inSection: section) ?? 0
})
tableView.bnd_dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.numberOfSections(in:)),
map: { (dataSource: DataSource?, _: UITableView) -> Int in dataSource?.numberOfSections ?? 0 }
)
let serialDisposable = SerialDisposable(otherDisposable: nil)
serialDisposable.otherDisposable = observeIn(ImmediateOnMainExecutionContext).observeNext { [weak tableView] event in
guard let tableView = tableView else {
serialDisposable.dispose()
return
}
dataSource.value = event.dataSource
guard bond.animated else {
tableView.reloadData()
return
}
switch event.kind {
case .reload:
tableView.reloadData()
case .insertItems(let indexPaths):
tableView.insertRows(at: indexPaths, with: .automatic)
case .deleteItems(let indexPaths):
tableView.deleteRows(at: indexPaths, with: .automatic)
case .reloadItems(let indexPaths):
tableView.reloadRows(at: indexPaths, with: .automatic)
case .moveItem(let indexPath, let newIndexPath):
tableView.moveRow(at: indexPath, to: newIndexPath)
case .insertSections(let indexSet):
tableView.insertSections(indexSet, with: .automatic)
case .deleteSections(let indexSet):
tableView.deleteSections(indexSet, with: .automatic)
case .reloadSections(let indexSet):
tableView.reloadSections(indexSet, with: .automatic)
case .moveSection(let index, let newIndex):
tableView.moveSection(index, toSection: newIndex)
case .beginUpdates:
tableView.beginUpdates()
case .endUpdates:
tableView.endUpdates()
}
}
return serialDisposable
}
}
|
mit
|
6e3f2d56ca0d178d3eab3bd0dc56afa3
| 36.716867 | 163 | 0.720332 | 4.883775 | false | false | false | false |
Zyj163/YJPageViewController
|
YJPagerViewController/YJPageViewController/YJCacheManager.swift
|
1
|
2358
|
//
// YJCacheManager.swift
// YJPagerViewController
//
// Created by ddn on 16/8/24.
// Copyright © 2016年 张永俊. All rights reserved.
//
import Foundation
enum YJCachePolicy {
case none
case lowMemory
case balanced
case high
var limitCount: Int {
switch self {
case .none:
return 0
case .lowMemory:
return 1
case .balanced:
return 3
case .high:
return 5
}
}
}
class YJCacheManager: NSObject {
var cachePolicy: YJCachePolicy = YJCachePolicy.balanced {
didSet {
memCache.countLimit = self.cachePolicy.limitCount
}
}
var memoryWarningCount = 0
fileprivate lazy var memCache : NSCache<NSNumber, AnyObject> = { [weak self] in
let memCache = NSCache<NSNumber, AnyObject>()
memCache.countLimit = self!.cachePolicy.limitCount
return memCache
}()
subscript(idx: Int) -> AnyObject? {
get {
return memCache.object(forKey: NSNumber(value: idx))
}
set {
if let newValue = newValue {
memCache.setObject(newValue, forKey: NSNumber(value: idx))
}
}
}
func didReceiveMemoryWarning() {
memoryWarningCount += 1
cachePolicy = YJCachePolicy.lowMemory
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(growCachePolicyAfterMemoryWarning), object: nil)
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(growCachePolicyToHigh), object: nil)
clear()
//如果收到内存警告次数小于 3,一段时间后切换到模式 Balanced
if memoryWarningCount < 3 {
perform(#selector(growCachePolicyAfterMemoryWarning), with: nil, afterDelay: 3.0, inModes: [RunLoopMode.commonModes])
}
}
func growCachePolicyAfterMemoryWarning() {
cachePolicy = YJCachePolicy.balanced
perform(#selector(growCachePolicyToHigh), with: nil, afterDelay: 2.0, inModes: [RunLoopMode.commonModes])
}
func growCachePolicyToHigh() {
cachePolicy = YJCachePolicy.high
}
func clear() {
memCache.removeAllObjects()
}
}
|
gpl-3.0
|
d3b5dd5010990e0c714087a2b473347a
| 22.742268 | 133 | 0.597916 | 4.807933 | false | false | false | false |
wasm3/wasm3
|
platforms/ios/wasm3/ViewController.swift
|
1
|
837
|
//
// ViewController.swift
// wasm3
//
// Created by Volodymyr Shymanskyy on 1/10/20.
// Copyright © 2020 wasm3. All rights reserved.
//
import UIKit
var gLog: UITextView!
class ViewController: UIViewController {
// MARK: Properties
@IBOutlet var log: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
gLog = log
redirect_output({
if let ptr = $0 {
let data = Data(bytes: ptr, count: Int($1))
if let str = String(data: data, encoding: String.Encoding.utf8) {
DispatchQueue.main.async {
gLog.text += str
}
}
}
})
run_app()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
f76acd06d6788c608d99d4f90a48610c
| 19.390244 | 81 | 0.528708 | 4.354167 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS
|
NoticiasLeganes/News/News.swift
|
1
|
2074
|
//
// Entry.swift
// NoticiasLeganes
//
// Created by Alvaro Blazquez Montero on 15/5/17.
// Copyright © 2017 Alvaro Blazquez Montero. All rights reserved.
//
import UIKit
public struct News : CustomStringConvertible{
var title : String
var link : URL?
var date : Date?
var imageUrl : URL?
var desc : String?
var origen : String?
var defaultImage : UIImage?
init(title : String, link : URL?, date : Date?, imageUrl : URL?, description : String?, origen : String?, defaultImage : UIImage?) {
self.title = title
self.link = link
self.date = date
self.imageUrl = imageUrl
self.desc = description
self.origen = origen
self.defaultImage = defaultImage
}
init(title : String, link : String?, date : Date?, imageUrl : String?, description : String?, origen : String?, defaultImage : UIImage?) {
var linkUrl : URL?
var imageUrlAux : URL?
if let _link = link {
linkUrl = URL(string: _link)
}
if let _imageUrl = imageUrl {
imageUrlAux = URL(string: _imageUrl)
}
self.init(title: title, link: linkUrl, date: date, imageUrl: imageUrlAux, description: description, origen: origen, defaultImage: defaultImage)
}
public var description: String {
var description = "Title: \(self.title)\n"
description = description + "Description: \(self.desc ?? "")\n"
description = description + "Link: \(self.link?.absoluteString ?? "")\n"
description = description + "Image: \(self.imageUrl?.absoluteString ?? "")\n"
description = description + "Date: \(self.date ?? Date())\n"
description = description + "Origen: \(self.origen ?? "")\n"
description = description + "DefaultImage: \(self.defaultImage?.accessibilityIdentifier ?? "")\n"
return description
}
}
|
mit
|
9bfcc9b3960236efa41674170ef06a2c
| 32.983607 | 151 | 0.56054 | 4.526201 | false | false | false | false |
exyte/Macaw
|
MacawTests/MacawTests.swift
|
1
|
4088
|
import XCTest
#if os(OSX)
@testable import MacawOSX
#elseif os(iOS)
@testable import Macaw
#endif
class MacawTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSVGTriangle() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("triangle", referenceObject: createTriangleReferenceObject()))
}
func testSVGLine() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("line", referenceObject: createLineReferenceObject()))
}
func testSVGRect() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("rect", referenceObject: createRectReferenceObject()))
}
func testSVGRoundRect() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("roundRect", referenceObject: createRoundRectReferenceObject()))
}
func testSVGPolygon() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("polygon", referenceObject: createPolygonReferenceObject()))
}
func testSVGPolyline() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("polyline", referenceObject: createPolylineReferenceObject()))
}
func testSVGCircle() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("circle", referenceObject: createCircleReferenceObject()))
}
func testSVGEllipse() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("ellipse", referenceObject: createEllipseReferenceObject()))
}
func testSVGGroup() {
XCTAssertTrue(TestUtils.compareWithReferenceObject("group", referenceObject: createGroupReferenceObject()))
}
func createTriangleReferenceObject() -> Group {
let path = MoveTo(x: 150, y: 0).lineTo(x: 75, y: 200).lineTo(x: 225, y: 200).close().build()
return Group(contents: [Shape(form: path, stroke: Stroke(fill: Color.black, width: 2, cap: .round, join: .round))])
}
func createLineReferenceObject() -> Group {
let line = Line(x1: 0, y1: 0, x2: 200, y2: 200)
return Group(contents: [Shape(form: line, stroke: Stroke(fill: Color.red, width: 2, cap: .round, join: .round))])
}
func createRectReferenceObject() -> Group {
let rect = Rect(x: 50, w: 150, h: 150)
return Group(contents: [Shape(form: rect)])
}
func createRoundRectReferenceObject() -> Group {
let roundRect = RoundRect(rect: Rect(w: 150, h: 150), rx: 20, ry: 20)
return Group(contents: [Shape(form: roundRect)])
}
func createPolygonReferenceObject() -> Group {
let polygon = Polygon(points: [200, 10, 250, 190, 160, 210])
return Group(contents: [Shape(form: polygon)])
}
func createPolylineReferenceObject() -> Group {
let polyline = Polyline(points: [0, 40, 40, 40, 40, 80, 80, 80, 80, 120, 120, 120, 120, 160])
return Group(contents: [Shape(form: polyline,
fill: Color.white,
stroke: Stroke(fill: Color.red, width: 4, cap: .round, join: .round))])
}
func createCircleReferenceObject() -> Group {
let circle = Circle(cx: 50, cy: 50, r: 40)
return Group(contents: [Shape(form: circle,
fill: Color.red,
stroke: Stroke(fill: Color.black, width: 3, cap: .round, join: .round))])
}
func createEllipseReferenceObject() -> Group {
let ellipse = Ellipse(cx: 200, cy: 80, rx: 100, ry: 50)
return Group(contents: [Shape(form: ellipse,
fill: Color.yellow,
stroke: Stroke(fill: Color.purple, width: 2, cap: .round, join: .round))])
}
func createGroupReferenceObject() -> Group {
let pathShape = Shape(form: MoveTo(x: 150, y: 0).lineTo(x: 75, y: 200).lineTo(x: 225, y: 200).close().build(),
stroke: Stroke(fill: Color.black, width: 2, cap: .round, join: .round))
let lineShape = Shape(form: Line(x1: 0, y1: 0, x2: 200, y2: 200),
stroke: Stroke(fill: Color.white, width: 2, cap: .round, join: .round))
return Group(contents: [Group(contents: [pathShape, lineShape])])
}
}
|
mit
|
88ce8d38c487657d75e542d8362e7d06
| 34.547826 | 117 | 0.685176 | 3.533276 | false | true | false | false |
jhwayne/Minimo
|
SwifferApp/SwifferApp/TimelineTableViewController.swift
|
1
|
9198
|
//
// TimelineTableViewController.swift
// SwifferApp
//
// Created by Training on 29/06/14.
// Copyright (c) 2014 Training. All rights reserved.
//
import UIKit
class TimelineTableViewController: UITableViewController {
func UIColorFromRGB(colorCode: String, alpha: Float = 1.0) -> UIColor {
var scanner = NSScanner(string:colorCode)
var color:UInt32 = 0;
scanner.scanHexInt(&color)
let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)
return UIColor(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
var timelineData:NSMutableArray! = NSMutableArray()
override init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func loadData(){
timelineData.removeAllObjects()
var query = PFQuery(className:"Posts")
query.whereKey("DisplayToday", equalTo:"Yes")
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject!, error: NSError!) -> Void in
if (error != nil || object == nil) {
println("The getFirstObject request failed.")
}
else {
// The find succeeded.
let ID = object["PostID"] as Int
var findTimelineData:PFQuery = PFQuery(className: "Sweets")
findTimelineData.whereKey("PostID", equalTo:ID)
findTimelineData.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]!, error:NSError!)->Void in
if error == nil{
for object in objects{
let sweet:PFObject = object as PFObject
self.timelineData.addObject(sweet)
}
let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects
self.timelineData = NSMutableArray(array: array)
self.tableView.reloadData()
}
}
}
}
}
override func viewDidAppear(animated: Bool) {
self.loadData()
if PFUser.currentUser() == nil{
var loginAlert:UIAlertController = UIAlertController(title: "Sign Up / Login", message: "Please sign up or login", preferredStyle: UIAlertControllerStyle.Alert)
loginAlert.addTextFieldWithConfigurationHandler({
textfield in
textfield.placeholder = "Your username"
})
loginAlert.addTextFieldWithConfigurationHandler({
textfield in
textfield.placeholder = "Your password"
textfield.secureTextEntry = true
})
loginAlert.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.Default, handler: {
alertAction in
let textFields:NSArray = loginAlert.textFields! as NSArray
let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField
let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField
PFUser.logInWithUsernameInBackground(usernameTextfield.text, password: passwordTextfield.text){
(user:PFUser!, error:NSError!)->Void in
if user != nil{
println("Login successfull")
}else{
println("Login failed")
}
}
}))
loginAlert.addAction(UIAlertAction(title: "Sign Up", style: UIAlertActionStyle.Default, handler: {
alertAction in
let textFields:NSArray = loginAlert.textFields! as NSArray
let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField
let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField
var sweeter:PFUser = PFUser()
sweeter.username = usernameTextfield.text
sweeter.password = passwordTextfield.text
sweeter.signUpInBackgroundWithBlock{
(success:Bool!, error:NSError!)->Void in
if error == nil{
println("Sign Up successfull")
}else{
let errorString = error.localizedDescription
println(errorString)
}
}
}))
self.presentViewController(loginAlert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return timelineData.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:SweetTableViewCell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as SweetTableViewCell
let sweet:PFObject = self.timelineData.objectAtIndex(indexPath.row) as PFObject
cell.sweetTextView.alpha = 0
cell.timestampLabel.alpha = 0
cell.usernameLabel.alpha = 0
cell.sweetTextView.text = sweet.objectForKey("content") as String
var dataFormatter:NSDateFormatter = NSDateFormatter()
dataFormatter.dateFormat = "MM/dd/yyyy hh:mm a"
cell.timestampLabel.text = dataFormatter.stringFromDate(sweet.createdAt)
var findSweeter:PFQuery = PFUser.query()
findSweeter.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]!, error:NSError!)->Void in
if error == nil{
let user:PFUser = (objects as NSArray).lastObject as PFUser
cell.usernameLabel.text = user.username
UIView.animateWithDuration(0.5, animations: {
cell.sweetTextView.alpha = 1
cell.timestampLabel.alpha = 1
cell.usernameLabel.alpha = 1
})
}
}
// if indexPath.row % 2 == 0 {
//
// cell.backgroundColor = UIColor.orangeColor()
//
// }
// else{
//
// cell.backgroundColor = UIColor.yellowColor()
//
// }
return cell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{cell.contentView.backgroundColor=UIColor.clearColor()
var whiteRoundedCornerView:UIView!
whiteRoundedCornerView=UIView(frame: CGRectMake(5,10,self.view.bounds.width-10,120))
whiteRoundedCornerView.backgroundColor=UIColor(red: 174/255.0, green: 174/255.0, blue: 174/255.0, alpha: 1.0)
whiteRoundedCornerView.layer.masksToBounds=false
whiteRoundedCornerView.layer.shadowOpacity = 1.55;
whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(1, 0);
whiteRoundedCornerView.layer.shadowColor=UIColor(red: 53/255.0, green: 143/255.0, blue: 185/255.0, alpha: 1.0).CGColor
whiteRoundedCornerView.layer.cornerRadius=3.0
whiteRoundedCornerView.layer.shadowOffset=CGSizeMake(-1, -1)
whiteRoundedCornerView.layer.shadowOpacity=0.5
cell.contentView.addSubview(whiteRoundedCornerView)
cell.contentView.sendSubviewToBack(whiteRoundedCornerView)
}
}
|
mit
|
d3cfeec6c1912a083efc28abc82d8c08
| 35.212598 | 172 | 0.567297 | 5.705955 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.