repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
quangpc/HQPagerViewController | HQPagerViewController/HQPagerViewController/Controllers/SampleViewController.swift | 1 | 2007 | //
// SampleViewController.swift
// HQPagerViewController
//
// Created by quangpc on 11/11/16.
// Copyright © 2016 quangpc. All rights reserved.
//
import UIKit
let titles = ["Trending", "Search", "Recents", "Me"]
let colors = [UIColor.hexColor(hex: "82b840"), UIColor.hexColor(hex: "26abfc"), UIColor.hexColor(hex: "ff9c29"), UIColor.hexColor(hex: "f59c94")]
let normalIcons = [UIImage(named: "icon-trend"), UIImage(named: "icon-react"), UIImage(named: "icon-favorite"), UIImage(named: "icon-me")]
let highlightedIcons = [UIImage(named: "icon-trend-selected"), UIImage(named: "icon-react-selected"), UIImage(named: "icon-favorite-selected"), UIImage(named: "icon-me-selected")]
class SampleViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
var index: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
titleLabel.text = "ViewController #\(index)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension SampleViewController: HQPagerViewControllerDataSource {
func menuViewItemOf(inPager pagerViewController: HQPagerViewController) -> HQPagerMenuViewItemProvider {
let item = HQPagerMenuViewItemProvider(title: titles[index], normalImage: normalIcons[index], selectedImage: highlightedIcons[index], selectedBackgroundColor: colors[index])
return item
}
}
| mit | 48645ad89c5fccce21918d7f939ae5e1 | 35.472727 | 181 | 0.702393 | 4.313978 | false | false | false | false |
delannoyk/SoundcloudSDK | sources/SoundcloudSDK/request/Request.swift | 1 | 5825 | //
// Request.swift
// SoundcloudSDK
//
// Created by Kevin DELANNOY on 15/03/15.
// Copyright (c) 2015 Kevin Delannoy. All rights reserved.
//
import Foundation
class JSONObject {
let value: Any?
var index: Int = 0
init(_ value: Any?) {
self.value = value
}
subscript(index: Int) -> JSONObject {
return (value as? [Any]).map { JSONObject($0[index]) } ?? JSONObject(nil)
}
subscript(key: String) -> JSONObject {
return (value as? NSDictionary).map { JSONObject($0.object(forKey: key)) } ?? JSONObject(nil)
}
func map<U>(transform: (JSONObject) -> U) -> [U]? {
if let value = value as? [Any] {
return value.map({ transform(JSONObject($0)) })
}
return nil
}
func flatMap<U>(transform: (JSONObject) -> U?) -> [U]? {
if let value = value as? [Any] {
return value.compactMap { transform(JSONObject($0)) }
}
return nil
}
}
extension JSONObject {
var anyValue: Any? {
return value
}
var intValue: Int? {
return (value as? Int)
}
var uint64Value: UInt64? {
return (value as? UInt64)
}
var doubleValue: Double? {
return (value as? Double)
}
var boolValue: Bool? {
return (value as? Bool)
}
var stringValue: String? {
return (value as? String)
}
var urlValue: URL? {
return (value as? String).map { URL(string: $0)?.appendingQueryString("client_id=\(SoundcloudClient.clientIdentifier!)") } ?? nil
}
func dateValue(format: String) -> Date? {
let date: Date?? = stringValue.map {
return DateFormatter.dateFormatter(with: format).date(from: $0)
}
return date ?? nil
}
}
extension DateFormatter {
private static var dateFormatters = [String: DateFormatter]()
fileprivate static func dateFormatter(with format: String) -> DateFormatter {
if let dateFormatter = dateFormatters[format] {
return dateFormatter
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatters[format] = dateFormatter
return dateFormatter
}
}
public enum Result<T, E> {
case success(T)
case failure(E)
public var isSuccessful: Bool {
switch self {
case .success(_):
return true
default:
return false
}
}
public var result: T? {
switch self {
case .success(let result):
return result
default:
return nil
}
}
public var error: E? {
switch self {
case .failure(let error):
return error
default:
return nil
}
}
public func recover(_ transform: (E) -> T) -> T {
switch self {
case .success(let result):
return result
case .failure(let error):
return transform(error)
}
}
}
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
func urlRequest(url: URL, parameters: HTTPParametersConvertible? = nil, headers: [String: String]? = nil) -> URLRequest {
let URLRequestInfo: (url: URL, HTTPBody: Data?) = {
if let parameters = parameters {
if self == .get {
return (url: url.appendingQueryString(parameters.queryStringValue), HTTPBody: nil)
}
return (url: url, HTTPBody: parameters.formDataValue)
}
return (url: url, HTTPBody: nil)
}()
var request = URLRequest(url: URLRequestInfo.url)
request.httpBody = URLRequestInfo.HTTPBody
request.httpMethod = rawValue
headers?.forEach { key, value in
request.addValue(value, forHTTPHeaderField: key)
}
return request
}
}
protocol HTTPParametersConvertible {
var queryStringValue: String { get }
var formDataValue: Data { get }
}
protocol RequestError {
init(networkError: Error)
init(jsonError: Error)
init?(httpURLResponse: HTTPURLResponse)
}
public protocol CancelableOperation {
func cancel()
}
struct Request<T, E: RequestError>: CancelableOperation {
private let dataTask: URLSessionDataTask
init(url: URL, method: HTTPMethod, parameters: HTTPParametersConvertible?, headers: [String: String]? = nil, parse: @escaping (JSONObject) -> Result<T, E>, completion: @escaping (Result<T, E>) -> Void) {
let URLRequest = method.urlRequest(url: url, parameters: parameters, headers: headers)
dataTask = URLSession.shared.dataTask(with: URLRequest) { data, response, error in
if let response = response as? HTTPURLResponse, let error = E(httpURLResponse: response) {
DispatchQueue.main.async {
completion(.failure(error))
}
} else {
if let data = data {
var result: Result<T, E>
do {
let JSON = try JSONObject(JSONSerialization.jsonObject(with: data, options: []))
result = parse(JSON)
} catch let error {
result = .failure(E(jsonError: error))
}
DispatchQueue.main.async {
completion(result)
}
} else if let error = error {
DispatchQueue.main.async {
completion(.failure(E(networkError: error)))
}
}
}
}
}
func start() {
dataTask.resume()
}
func cancel() {
dataTask.cancel()
}
}
| mit | 108b65b0e3c46f002a3a66bda11ad50d | 25.843318 | 207 | 0.552446 | 4.572214 | false | false | false | false |
nathanlentz/rivals | Rivals/Rivals/FirebaseService.swift | 1 | 4188 | //
// FirebaseService.swift
// Rivals
//
// Created by Nate Lentz on 4/16/17.
// Copyright © 2017 ntnl.design. All rights reserved.
//
// This service should be used to pull all Firebase usage out of the view controllers
//
import Foundation
import Firebase
var ref = FIRDatabase.database().reference()
func createUserInDatabase(uid: String, userInfo: [String : Any]) {
ref.child("profiles").child(uid).setValue(userInfo)
}
/**
Follows the user that belongs to some uid
*/
func followUser(userToFollowUid: String) -> Bool {
return false
}
/**
Unfollows the user that belongs to some uid
*/
func unfollowUser(userToUnfollowUid: String) -> Bool {
return false
}
/**
Return an array of all users within the Firebase Database
*/
func getAllUsers() -> Array<User> {
var users = [User]()
ref.child("profiles").observe(.childAdded, with: { (snapshot) in
if let dict = snapshot.value as? [String: AnyObject] {
let user = User()
user.name = dict["name"] as? String
user.email = dict["email"] as? String
user.wins = dict["wins"] as? Int
user.losses = dict["losses"] as? Int
user.uid = dict["uid"] as? String
users.append(user)
}
}) { (error) in
print(error.localizedDescription)
}
return users
}
/**
Return an array of all rivalries
*/
func getAllRivalries() -> Array<Rivalry> {
let rivalries = [Rivalry]()
// TODO: Implement all the things
return rivalries
}
/**
Attepts to POST a new rivalry to firebase
*/
func createNewRivlary(creatorId: String, gameName: String, players: [String], creationDate: String) -> Bool {
var success = true
let key = ref.child("rivalries").childByAutoId().key
// TODO: Add init for historical data
let rivalryInfo: [String : Any] = ["rivalry_key": key, "creator_id": creatorId, "game_name": gameName, "players": players, "in_progress": true, "creation_date": creationDate, "games_played": 0]
ref.updateChildValues(["profiles/\(creatorId)/rivalries_in_progress/\(key)": rivalryInfo, "rivalries/\(key)": rivalryInfo], withCompletionBlock: { (error) in
print(error)
success = false
})
return success
}
/**
Attepts to GET all rivalries from firebase given a uid
*/
func getRivalry(userId: String) -> Array<Rivalry> {
let rivalries = [Rivalry]()
// TODO: getAllRivalries()
// Filter all rivalries by those who have creator id of passed in id
return rivalries
}
/**
Attepts to GET all in progress rivalries from firebase given a uid
*/
func getInProgressRivalries(userId: String) -> Array<Rivalry> {
var rivalries = [Rivalry]()
let uid = FIRAuth.auth()?.currentUser?.uid
ref.child("rivalries").observe(.childAdded, with: { (snapshot) in
if let dict = snapshot.value as? [String : Any] {
if dict["creator_id"] as? String == uid {
let rivalry = Rivalry()
rivalry.title = dict["game_name"] as? String
rivalry.rivalryKey = dict["rivalry_key"] as? String
rivalry.players = dict["players"] as? [String]
rivalry.inProgress = dict["in_progress"] as? Bool
rivalry.dateCreated = dict["creation_date"] as? String
rivalry.gamesPlayed = dict["games_played"] as? Int
rivalries.append(rivalry)
}
}
})
// TODO: getAllRivalries()
// Filter all rivalries that are "In Progress" by a user
return rivalries
}
func completeRivalry(rivalryId: String) {
ref.child("rivalries").child(rivalryId).child("in_progress").setValue(false)
}
/**
Attepts to GET all finished rivalries from firebase given a uid
*/
func getFinishedRivalries(userId: String) -> Array<Rivalry> {
let rivalries = [Rivalry]()
// TODO: getAllRivalries()
// Filter all rivalries that are "finished" by a user
return rivalries
}
/**
Update an existing rivalry
*/
func updateRivalry(rivalryId: String, rivalryStatus: Bool, winnerIds: [String]) {
}
| apache-2.0 | 1ee387ee0c0f22ad00636a54e2a93ee4 | 23.343023 | 197 | 0.624313 | 4.025962 | false | false | false | false |
1985apps/PineKit | Pod/Classes/PineFluidGridLayout.swift | 2 | 2035 | //
// PineFluidLayout.swift
// Pods
//
// Created by Prakash Raman on 05/04/16.
//
//
import UIKit
open class PineFluidGridLayout: UIView {
open var items : [UIView] = []
open var containers : [UIView] = []
open var maxColumns: Int = 3
open var rows : Int = 0
public init(views: [UIView], maxColumns: Int = 3){
super.init(frame: CGRect.zero)
self.maxColumns = maxColumns
self.items = views
setup()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(){
if items.count == 0 {
return
}
self.rows = Int(ceil((CGFloat(items.count) / CGFloat(maxColumns))))
for item in items {
let box = UIView()
self.containers.append(box)
self.addSubview(box)
box.addSubview(item)
}
}
open override func layoutSubviews() {
super.layoutSubviews()
positionBoxes()
}
// THIS METHOD ONLY FIXES THE FRAMES OF THE BOXES
func positionBoxes(){
let boxWidth = self.frame.width / CGFloat(items.count > maxColumns ? maxColumns : items.count)
let boxHeight = self.frame.height / CGFloat(rows)
var x = CGFloat(0.0);
var y = CGFloat(0.0);
var index = 0
for itemIndex in 0...containers.count - 1 {
let box = containers[itemIndex]
let item = items[itemIndex]
let frame = CGRect(x: x, y: boxHeight * y, width: boxWidth, height: boxHeight)
box.frame = frame
x += boxWidth
if (index >= maxColumns - 1) {
index = 0
x = 0
y += 1
} else {
index += 1
}
item.snp_makeConstraints({ (make) in
make.center.equalTo(box)
})
}
}
}
| mit | e9ecd09451d0db7dd685b1a0b3503177 | 23.817073 | 102 | 0.499754 | 4.311441 | false | false | false | false |
resmio/TastyTomato | TastyTomato/Code/Types/CustomViews/ZoomView/ZoomToPointScrollView.swift | 1 | 3008 | //
// ZoomToPointScrollView.swift
// TastyTomato
//
// Created by Jan Nash on 6/30/17.
// Copyright © 2017 resmio. All rights reserved.
//
import UIKit
// MARK: // Internal
// MARK: Interface
extension ZoomToPointScrollView {
func zoom(to zoomPoint: CGPoint, with scale: CGFloat, animated: Bool = true) {
self._zoom(to: zoomPoint, with: scale, animated: animated)
}
}
// MARK: Class Declaration
class ZoomToPointScrollView: UIScrollView {
// MARK: ContentOffset Override
// !!!: This is an intentional noop, since when the contentSize is smaller
// than the bounds of the scrollView,self.zoom(to rect: CGRect, animated: Bool)
// calls this method with the contentOffset doubled. Why? I don't know. Nooping
// the method does actually work around that problem, still, it makes the method
// unusable, that's why it's marked as unavailabe here.
@available(*, unavailable)
override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
super.setContentOffset(CGPoint(x: contentOffset.x / 2, y: contentOffset.y / 2), animated: animated)
}
}
// MARK: // Private
// MARK: ZoomToPoint implementation
private extension ZoomToPointScrollView {
func _zoom(to zoomPoint: CGPoint, with scale: CGFloat, animated: Bool) {
let clampedScale: CGFloat = min(self.maximumZoomScale, max(self.minimumZoomScale, scale))
let normalizationFactor: CGFloat = (1 / self.zoomScale)
let contentOffset: CGPoint = self.contentOffset
let normalizedZoomPoint: CGPoint = CGPoint(
x: (zoomPoint.x + contentOffset.x) * normalizationFactor,
y: (zoomPoint.y + contentOffset.y) * normalizationFactor
)
let bounds: CGRect = self.bounds
let zoomRectSize: CGSize = CGSize(
width: bounds.width / scale,
height: bounds.height / scale
)
let zoomRectOrigin: CGPoint = CGPoint(
x: normalizedZoomPoint.x - (zoomRectSize.width / 2),
y: normalizedZoomPoint.y - (zoomRectSize.height / 2)
)
let zoomRect: CGRect = CGRect(
origin: zoomRectOrigin,
size: zoomRectSize
)
guard animated else {
self.zoom(to: zoomRect, animated: false)
return
}
UIView.animate(
withDuration: 0.3,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0.6,
options: [.allowUserInteraction],
animations: {
self.zoom(to: zoomRect, animated: false)
},
completion: { _ in
guard let delegate: UIScrollViewDelegate = self.delegate else { return }
guard let viewForZooming: UIView = delegate.viewForZooming?(in: self) else { return }
delegate.scrollViewDidEndZooming?(self, with: viewForZooming, atScale: clampedScale)
}
)
}
}
| mit | 6c0278fa3947253237086fd19c4e0c69 | 33.965116 | 107 | 0.621217 | 4.691108 | false | false | false | false |
SafeCar/iOS | Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/MadokaTextField.swift | 2 | 6460 | //
// MadokaTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 05/02/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
/**
A MadokaTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the edges of the control.
*/
@IBDesignable public class MadokaTextField: TextFieldEffects {
/**
The color of the placeholder text.
This property applies a color to the complete placeholder string. The default value for this property is a black color.
*/
@IBInspectable dynamic public var placeholderColor: UIColor = .blackColor() {
didSet {
updatePlaceholder()
}
}
/**
The color of the border.
This property applies a color to the lower edge of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic public var borderColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The scale of the placeholder font.
This property determines the size of the placeholder label relative to the font size of the text field.
*/
@IBInspectable dynamic public var placeholderFontScale: CGFloat = 0.65 {
didSet {
updatePlaceholder()
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: CGFloat = 1
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
private let borderLayer = CAShapeLayer()
private var backgroundLayerColor: UIColor?
// MARK: - TextFieldsEffects
override public func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
}
override public func animateViewsForTextEntry() {
borderLayer.strokeEnd = 1
UIView.animateWithDuration(0.3, animations: {
let translate = CGAffineTransformMakeTranslation(-self.placeholderInsets.x, self.placeholderLabel.bounds.height + (self.placeholderInsets.y * 2))
let scale = CGAffineTransformMakeScale(0.9, 0.9)
self.placeholderLabel.transform = CGAffineTransformConcat(translate, scale)
}) { _ in
self.animationCompletionHandler?(type: .TextEntry)
}
}
override public func animateViewsForTextDisplay() {
if text!.isEmpty {
borderLayer.strokeEnd = percentageForBottomBorder()
UIView.animateWithDuration(0.3, animations: {
self.placeholderLabel.transform = CGAffineTransformIdentity
}) { _ in
self.animationCompletionHandler?(type: .TextDisplay)
}
}
}
// MARK: - Private
private func updateBorder() {
let rect = rectForBorder(bounds)
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.height - borderThickness))
path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.height - borderThickness))
path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.origin.y + borderThickness))
path.addLineToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.origin.y + borderThickness))
path.closePath()
borderLayer.path = path.CGPath
borderLayer.lineCap = kCALineCapSquare
borderLayer.lineWidth = borderThickness
borderLayer.fillColor = nil
borderLayer.strokeColor = borderColor?.CGColor
borderLayer.strokeEnd = percentageForBottomBorder()
}
private func percentageForBottomBorder() -> CGFloat {
let borderRect = rectForBorder(bounds)
let sumOfSides = (borderRect.width * 2) + (borderRect.height * 2)
return (borderRect.width * 100 / sumOfSides) / 100
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder() || text!.isNotEmpty {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale)
return smallerFont
}
private func rectForBorder(bounds: CGRect) -> CGRect {
let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newRect
}
private func layoutPlaceholderInTextRect() {
placeholderLabel.transform = CGAffineTransformIdentity
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch textAlignment {
case .Center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .Right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: textRect.height - placeholderLabel.bounds.height - placeholderInsets.y,
width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height)
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
}
| mit | e5b852bfa65bf48b630efa70a7bbd2a5 | 33.913514 | 173 | 0.640656 | 5.378018 | false | false | false | false |
Sephiroth87/C-swifty4 | C64/Utils/CircularBuffer.swift | 1 | 1219 | //
// CircularBuffer.swift
// C64
//
// Created by Fabio Ritrovato on 30/11/2015.
// Copyright © 2015 orange in a day. All rights reserved.
//
import Foundation
public final class CircularBuffer<T: CustomStringConvertible> {
fileprivate var buffer: Array<T?>
fileprivate var index = 0
public init(capacity: Int) {
self.buffer = Array<T?>(repeating: nil, count: capacity)
}
public func add(_ item: T) {
index = (index + 1) % buffer.count
buffer[index] = item
}
}
extension CircularBuffer: Sequence {
public func makeIterator() -> AnyIterator<T> {
var index = self.index
return AnyIterator {
if index - 1 == self.index {
return nil
} else {
let value = self.buffer[index]
index -= 1
if index == -1 {
index = self.buffer.count - 1
}
return value
}
}
}
}
extension CircularBuffer: CustomStringConvertible {
public var description: String {
get {
return self.reduce("") { $0 + $1.description + "\n" }
}
}
}
| mit | 4022ce276971de8f23996412eab88f2d | 21.145455 | 65 | 0.519704 | 4.35 | false | false | false | false |
wangjianquan/wjq-weibo | weibo_wjq/Tool/Transition/WjPresentationCoutro.swift | 1 | 1351 | //
// WjPresentationCoutro.swift
// weibo_wjq
//
// Created by landixing on 2017/5/25.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
class WjPresentationCoutro: UIPresentationController {
var presentedFrame:CGRect = CGRect.zero
override func containerViewWillLayoutSubviews() {
// containerView 容器视图,所有modal的视图都被添加到它上
// presentedView () 拿到弹出视图
presentedView?.frame = presentedFrame
//初始化蒙版
setupMaskView()
}
}
extension WjPresentationCoutro {
fileprivate func setupMaskView() {
// 1.创建蒙版
let maskView = UIView(frame: containerView!.bounds)
// 2.设置蒙版的颜色
maskView.backgroundColor = UIColor(white: 0.7, alpha: 0.2)
// 3.监听蒙版的点击
let tapGes = UITapGestureRecognizer(target: self, action: #selector(WjPresentationCoutro.maskViewClick))
maskView.addGestureRecognizer(tapGes)
// 4.将蒙版添加到容器视图中
containerView?.insertSubview(maskView, belowSubview: presentedView!)
}
@objc fileprivate func maskViewClick() {
//点击蒙版弹出视图消失
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | a56a92f4e270684b9a35812913f2837e | 24.333333 | 112 | 0.646382 | 4.421818 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples | GooglePlaces-Swift/GooglePlacesSwiftDemos/Swift/Samples/Autocomplete/AutocompleteWithTextFieldController.swift | 1 | 5831 | // Copyright 2020 Google LLC. 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 GooglePlaces
import UIKit
/// Demo showing how to manually present a UITableViewController and supply it with autocomplete
/// text from an arbitrary source, in this case a UITextField. Please refer to:
/// https://developers.google.com/places/ios-sdk/autocomplete
class AutocompleteWithTextFieldController: AutocompleteBaseViewController {
private let padding: CGFloat = 20
private let topPadding: CGFloat = 8
private lazy var searchField: UITextField = {
let searchField = UITextField(frame: .zero)
searchField.translatesAutoresizingMaskIntoConstraints = false
searchField.borderStyle = .none
if #available(iOS 13.0, *) {
searchField.textColor = .label
searchField.backgroundColor = .systemBackground
} else {
searchField.backgroundColor = .white
}
searchField.placeholder = NSLocalizedString(
"Demo.Content.Autocomplete.EnterTextPrompt",
comment: "Prompt to enter text for autocomplete demo")
searchField.autocorrectionType = .no
searchField.keyboardType = .default
searchField.returnKeyType = .done
searchField.clearButtonMode = .whileEditing
searchField.contentVerticalAlignment = .center
searchField.addTarget(self, action: #selector(textFieldChanged), for: .editingChanged)
return searchField
}()
private lazy var resultsController: UITableViewController = {
return UITableViewController(style: .plain)
}()
private lazy var tableDataSource: GMSAutocompleteTableDataSource = {
let tableDataSource = GMSAutocompleteTableDataSource()
tableDataSource.tableCellBackgroundColor = .white
tableDataSource.delegate = self
if let config = autocompleteConfiguration {
tableDataSource.autocompleteFilter = config.autocompleteFilter
tableDataSource.placeFields = config.placeFields
}
return tableDataSource
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
searchField.delegate = self
view.addSubview(searchField)
NSLayoutConstraint.activate([
searchField.topAnchor.constraint(
equalTo: self.topLayoutGuide.bottomAnchor, constant: topPadding),
searchField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding),
searchField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding),
])
tableDataSource.delegate = self
resultsController.tableView.delegate = tableDataSource
resultsController.tableView.dataSource = tableDataSource
// Add the results controller
guard let resultView = resultsController.view else { return }
resultView.translatesAutoresizingMaskIntoConstraints = false
resultView.alpha = 0
view.addSubview(resultView)
NSLayoutConstraint.activate([
resultView.topAnchor.constraint(equalTo: searchField.bottomAnchor, constant: 0),
resultView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
resultView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
resultView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
@objc func textFieldChanged(sender: UIControl) {
guard let textField = sender as? UITextField else { return }
tableDataSource.sourceTextHasChanged(textField.text)
}
func dismissResultView() {
resultsController.willMove(toParent: nil)
UIView.animate(
withDuration: 0.5,
animations: {
self.resultsController.view.alpha = 0
}
) { (_) in
self.resultsController.view.removeFromSuperview()
self.resultsController.removeFromParent()
}
}
}
extension AutocompleteWithTextFieldController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
addChild(resultsController)
resultsController.tableView.reloadData()
UIView.animate(
withDuration: 0.5,
animations: {
self.resultsController.view.alpha = 1
}
) { (_) in
self.resultsController.didMove(toParent: self)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
dismissResultView()
textField.resignFirstResponder()
textField.text = ""
tableDataSource.clearResults()
return false
}
}
extension AutocompleteWithTextFieldController: GMSAutocompleteTableDataSourceDelegate {
func tableDataSource(
_ tableDataSource: GMSAutocompleteTableDataSource, didAutocompleteWith place: GMSPlace
) {
dismissResultView()
searchField.resignFirstResponder()
searchField.isHidden = true
autocompleteDidSelectPlace(place)
}
func tableDataSource(
_ tableDataSource: GMSAutocompleteTableDataSource, didFailAutocompleteWithError error: Error
) {
dismissResultView()
searchField.resignFirstResponder()
searchField.isHidden = true
autocompleteDidFail(error)
}
func didRequestAutocompletePredictions(for tableDataSource: GMSAutocompleteTableDataSource) {
resultsController.tableView.reloadData()
}
func didUpdateAutocompletePredictions(for tableDataSource: GMSAutocompleteTableDataSource) {
resultsController.tableView.reloadData()
}
}
| apache-2.0 | e73ee0d658c48ab6d928feb47d716d4b | 34.339394 | 96 | 0.749957 | 5.344638 | false | false | false | false |
spf2/FirebaseAdapter | FirebaseAdapterTests/Fakebase.swift | 1 | 3809 | //
// Fakebase.swift
// FirebaseAdapter
//
// Created by Steve Farrell on 8/31/15.
// Copyright (c) 2015 Movem3nt, Inc. All rights reserved.
//
import FirebaseAdapter
import Firebase
func paths(paths: (Int, Int)...) -> [NSIndexPath] {
return paths.map { NSIndexPath(forRow: $0.1, inSection: $0.0) }
}
class TestItem : BaseItem {
static let a = TestItem(key: "a")
static let b = TestItem(key: "b")
static let c = TestItem(key: "c")
static let d = TestItem(key: "d")
var bool: Bool?
var int: Int?
var float: Float?
var string: String?
override var dict: [String: AnyObject] {
var d = super.dict
d["bool"] = bool ?? NSNull()
d["int"] = int ?? NSNull()
d["float"] = float ?? NSNull()
d["string"] = string ?? NSNull()
return d
}
override func update(dict: [String: AnyObject]?) {
super.update(dict)
bool = dict?["bool"] as? Bool
int = dict?["int"] as? Int
float = dict?["float"] as? Float
string = dict?["string"] as? String
}
}
class TestDelegate : StreamBaseDelegate {
var willChangeCount = 0
var didChangeCount = 0
var itemAdded = [NSIndexPath]()
var itemDeleted = [NSIndexPath]()
var itemChanged = [NSIndexPath]()
func streamWillChange() {
willChangeCount++
itemAdded = []
itemDeleted = []
itemChanged = []
}
func streamDidChange() {
didChangeCount++
}
func streamItemsAdded(paths: [NSIndexPath]) {
itemAdded.appendContentsOf(paths)
}
func streamItemsDeleted(paths: [NSIndexPath]) {
itemDeleted.appendContentsOf(paths)
}
func streamItemsChanged(paths: [NSIndexPath]) {
itemChanged.appendContentsOf(paths)
}
func streamDidFinishInitialLoad(error: NSError?) {
}
}
class FakeFQuery : FQuery {
let fakebase: Fakebase
init(fakebase: Fakebase) {
self.fakebase = fakebase
}
override func observeEventType(eventType: FEventType, withBlock block: ((FDataSnapshot!) -> Void)!) -> UInt {
fakebase.handlers[eventType] = block
return UInt(fakebase.handlers.count)
}
}
class FakeSnapshot : FDataSnapshot {
let k: String
let v: [String: AnyObject]
override var key: String {
return k
}
override var value: AnyObject {
return v
}
init(key: String, value: [String: AnyObject] = [:]) {
self.k = key
self.v = value
}
}
class Fakebase : Firebase {
typealias Handler = ((FDataSnapshot!) -> Void)
var handlers = [FEventType: Handler]()
var fakeKey: String?
override var key: String? {
return fakeKey
}
convenience override init() {
self.init(fakeKey: nil)
}
init(fakeKey: String?) {
super.init()
self.fakeKey = fakeKey
}
override func childByAppendingPath(pathString: String!) -> Firebase! {
assert(pathString.rangeOfString("/") == nil, "Cannot handle paths")
return Fakebase(fakeKey: pathString)
}
override func queryLimitedToLast(limit: UInt) -> FQuery! {
return FakeFQuery(fakebase: self)
}
override func queryOrderedByKey() -> FQuery! {
return FakeFQuery(fakebase: self)
}
override func observeEventType(eventType: FEventType, withBlock block: ((FDataSnapshot!) -> Void)!) -> UInt {
handlers[eventType] = block
return UInt(handlers.count)
}
func add(snap: FDataSnapshot) {
handlers[.ChildAdded]!(snap)
}
func remove(snap: FDataSnapshot) {
handlers[.ChildRemoved]!(snap)
}
func change(snap: FDataSnapshot) {
handlers[.ChildChanged]!(snap)
}
}
| mit | 30eb87a197fee95c5be84e372773209b | 24.059211 | 113 | 0.592281 | 4.08691 | false | false | false | false |
Telll/receiver | TelllClient/Movie.swift | 3 | 1266 | //
// Movie.swift
// TelllClient
//
// Created by Fernando Oliveira on 26/11/15.
// Copyright © 2015 FCO. All rights reserved.
//
import Foundation
import SwiftyJSON
/*
{
"category" : "NYI",
"author" : "NYI",
"player" : {
"_" : "NYI"
},
"id" : "0",
"image": "http://pugim.com.br/pudim.jpg"
"media" : {
"_" : "NYI"
},
"cript" : "NYI",
"title" : "Perl Hackers",
"description" : "Perl developers coding",
"url" : "http:\/\/www.perl.org\/"
},
*/
class Movie {
var json : JSON?
var id : Int?
var category : String?
var author : String?
var title : String?
var description : String?
var url : NSURL
var image : NSURL?
init(origJson : JSON) {
json = origJson
id = origJson["id"].int
category = origJson["category"].string
author = origJson["author"].string
title = origJson["title"].string
description = origJson["description"].string
if let sUrl = origJson["url"].string {
url = NSURL(string: sUrl)!
} else {
url = NSURL()
}
if let sImage = origJson["image"].string {
image = NSURL(string: sImage)
}
}
}
| agpl-3.0 | a64682b411364c6c7ec99ff7e47b2f7e | 19.403226 | 52 | 0.509091 | 3.382353 | false | false | false | false |
Czajnikowski/TrainTrippin | Pods/RxCocoa/RxCocoa/CocoaUnits/Driver/Driver+Subscription.swift | 3 | 6434 | //
// Driver+Subscription.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
private let driverErrorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" +
"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n"
// This would ideally be Driver, but unfortunatelly Driver can't be extended in Swift 3.0
extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy {
/**
Creates new subscription and sends elements to observer.
This method can be only called from `MainThread`.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asSharedSequence().asObservable().subscribe(observer)
}
/**
Creates new subscription and sends elements to observer.
This method can be only called from `MainThread`.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<O: ObserverType>(_ observer: O) -> Disposable where O.E == E? {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asSharedSequence().asObservable().map { $0 as E? }.subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
This method can be only called from `MainThread`.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive(_ variable: Variable<E>) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return drive(onNext: { e in
variable.value = e
})
}
/**
Creates new subscription and sends elements to variable.
This method can be only called from `MainThread`.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive(_ variable: Variable<E?>) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return drive(onNext: { e in
variable.value = e
})
}
/**
Subscribes to observable sequence using custom binder function.
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- returns: Object representing subscription.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<R>(_ transformation: (Observable<E>) -> R) -> R {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return transformation(self.asObservable())
}
/**
Subscribes to observable sequence using custom binder function and final parameter passed to binder function
after `self` is passed.
public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return with(self)(curriedArgument)
}
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- parameter curriedArgument: Final argument passed to `binder` to finish binding process.
- returns: Object representing subscription.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<R1, R2>(_ with: (Observable<E>) -> (R1) -> R2, curriedArgument: R1) -> R2 {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return with(self.asObservable())(curriedArgument)
}
/**
Subscribes an element handler, a completion handler and disposed handler to an observable sequence.
This method can be only called from `MainThread`.
Error callback is not exposed because `Driver` can't error out.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive(onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)
}
/**
Subscribes an element handler to an observable sequence.
This method can be only called from `MainThread`.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
@available(*, deprecated, renamed: "drive(onNext:)")
public func driveNext(_ onNext: @escaping (E) -> Void) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asObservable().subscribe(onNext: onNext)
}
}
| mit | ddac8d0bcc2ed933e13086df46317726 | 43.061644 | 134 | 0.703093 | 4.833208 | false | false | false | false |
Luavis/Async.swift | Classes/AsyncWhilstTaskManager.swift | 1 | 1416 | //
// AsyncWhilstTaskManager.swift
// Async
//
// Created by 강성일 on 3/10/15.
// Copyright (c) 2015 Luavis. All rights reserved.
//
import Foundation
class AsyncWhilstTaskManager<ResultType> : AsyncTaskManager<AsyncCallbackType<ResultType>.WhilstTaskCallback, ResultType> {
// property
var completedCount = 0
var runIndex = 0;
var results:Array<ResultType?> = []
lazy var nextCallback:AsyncCallbackType<ResultType>.SeriesCallback = {
[unowned self] (err: AnyObject?, result: ResultType?) -> Void in
if let err:AnyObject = err? {
if let callback = self.callback? {
callback(error:err, results:nil);
}
}
else {
if let result:ResultType = result? {
self.results.append(result);
}
self.doNext()
}
};
// methods
init(tasks:Array<AsyncCallbackType<ResultType>.WhilstTaskCallback>, callback: AsyncCallbackType<ResultType>.ManagerCallback?) {
super.init()
self.tasks = tasks
self.callback = callback
self.results = Array<ResultType?>(count: self.tasks.count, repeatedValue: nil)
}
override func run() -> Void {
if self.completedCount < tasks.count && !self.isEnd { // validate up
for (index, task:(AsyncCallbackType<ResultType>.WhilstTaskCallback)) in enumerate(self.tasks) {
task(self.createCallback(index))
}
}
}
}
| mit | 80ea77492c3982a90e3f173159352b34 | 22.5 | 129 | 0.643262 | 4.028571 | false | false | false | false |
CNKCQ/oschina | OSCHINA/ViewModels/Home/NewsViewModel.swift | 1 | 1949 | ////
//// Copyright © 2016年 KingCQ. All rights reserved.
//// Created by KingCQ on 16/9/1.
import Moya
import ObjectMapper
import RxSwift
import Alamofire
class NewsViewModel {
lazy var disposeBag = DisposeBag()
var provider: RxMoyaProvider<OSCIOService>
var backgroundScheduler: OperationQueueScheduler!
var pageIndex = 0
// var pageSize = 2
init() {
let operationQueue = OperationQueue()
backgroundScheduler = OperationQueueScheduler(operationQueue: operationQueue)
provider = RxMoyaProvider<OSCIOService>()
}
func banner() -> Observable<BannerRootClass<BannerItem>> {
return request(OSCIOService.newBanner)
}
func newsArr() -> Observable<[NewsObjList]> {
return news().flatMap({ newRoot -> Observable<[NewsObjList]> in
Variable(newRoot.objList!).asObservable()
})
}
func news() -> Observable<NewsRootClass> {
return request(OSCIOService.newsList(para: ["pageIndex": 0]))
}
func request<M: Mappable>(_ token: OSCIOService) -> Observable<M> {
return Observable.create({ observer -> Disposable in
self.provider.request(token) { result in
result.analysis(ifSuccess: { response in
guard let entity = Mapper<M>().map(JSONString: String(
data: response.data,
encoding: String.Encoding.utf8)!) else {
fatalError()
}
observer.on(Event.next(entity))
}, ifFailure: { error in
observer.on(Event.error(error))
})
observer.onCompleted()
}
return Disposables.create()
})
.observeOn(backgroundScheduler)
// .observeOn(MainScheduler.asyncInstance)
}
}
// RxSwif 的使用场景 http://blog.csdn.net/lzyzsd/article/details/50120801
| mit | 7aa309594a4784979359b2288431a092 | 31.266667 | 85 | 0.594525 | 4.768473 | false | false | false | false |
huonw/swift | test/IRGen/objc_ns_enum.swift | 1 | 6486 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
// CHECK: @"$SSo16NSRuncingOptionsVWV" = linkonce_odr hidden constant
// CHECK: @"$SSo16NSRuncingOptionsVMn" = linkonce_odr hidden constant
// CHECK: @"$SSo16NSRuncingOptionsVN" = linkonce_odr hidden global
// CHECK: @"$SSo16NSRuncingOptionsVs9EquatableSCMc" = linkonce_odr hidden constant %swift.protocol_conformance_descriptor { {{.*}}@"$SSo16NSRuncingOptionsVs9EquatableSCWa
// CHECK: @"$SSo28NeverActuallyMentionedByNameVs9EquatableSCWp" = linkonce_odr hidden constant
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} i32 @main
// CHECK: call swiftcc %swift.metadata_response @"$SSo16NSRuncingOptionsVMa"(i64 0)
// CHECK: define hidden swiftcc i16 @"$S12objc_ns_enum09imported_C9_inject_aSo16NSRuncingOptionsVyF"()
// CHECK: ret i16 123
func imported_enum_inject_a() -> NSRuncingOptions {
return .mince
}
// CHECK: define hidden swiftcc i16 @"$S12objc_ns_enum09imported_C9_inject_bSo16NSRuncingOptionsVyF"()
// CHECK: ret i16 4567
func imported_enum_inject_b() -> NSRuncingOptions {
return .quinceSliced
}
// CHECK: define hidden swiftcc i16 @"$S12objc_ns_enum09imported_C9_inject_cSo16NSRuncingOptionsVyF"()
// CHECK: ret i16 5678
func imported_enum_inject_c() -> NSRuncingOptions {
return .quinceJulienned
}
// CHECK: define hidden swiftcc i16 @"$S12objc_ns_enum09imported_C9_inject_dSo16NSRuncingOptionsVyF"()
// CHECK: ret i16 6789
func imported_enum_inject_d() -> NSRuncingOptions {
return .quinceDiced
}
// CHECK: define hidden swiftcc i32 @"$S12objc_ns_enum09imported_C17_inject_radixed_aSo16NSRadixedOptionsVyF"() {{.*}} {
// -- octal 0755
// CHECK: ret i32 493
func imported_enum_inject_radixed_a() -> NSRadixedOptions {
return .octal
}
// CHECK: define hidden swiftcc i32 @"$S12objc_ns_enum09imported_C17_inject_radixed_bSo16NSRadixedOptionsVyF"() {{.*}} {
// -- hex 0xFFFF
// CHECK: ret i32 65535
func imported_enum_inject_radixed_b() -> NSRadixedOptions {
return .hex
}
// CHECK: define hidden swiftcc i32 @"$S12objc_ns_enum09imported_C18_inject_negative_aSo17NSNegativeOptionsVyF"() {{.*}} {
// CHECK: ret i32 -1
func imported_enum_inject_negative_a() -> NSNegativeOptions {
return .foo
}
// CHECK: define hidden swiftcc i32 @"$S12objc_ns_enum09imported_C18_inject_negative_bSo17NSNegativeOptionsVyF"() {{.*}} {
// CHECK: ret i32 -2147483648
func imported_enum_inject_negative_b() -> NSNegativeOptions {
return .bar
}
// CHECK: define hidden swiftcc i32 @"$S12objc_ns_enum09imported_C27_inject_negative_unsigned_aSo25NSNegativeUnsignedOptionsVyF"() {{.*}} {
// CHECK: ret i32 -1
func imported_enum_inject_negative_unsigned_a() -> NSNegativeUnsignedOptions {
return .foo
}
// CHECK: define hidden swiftcc i32 @"$S12objc_ns_enum09imported_C27_inject_negative_unsigned_bSo25NSNegativeUnsignedOptionsVyF"() {{.*}} {
// CHECK: ret i32 -2147483648
func imported_enum_inject_negative_unsigned_b() -> NSNegativeUnsignedOptions {
return .bar
}
func test_enum_without_name_Equatable(_ obj: TestThatEnumType) -> Bool {
return obj.getValue() != .ValueOfThatEnumType
}
func use_metadata<T: Equatable>(_ t:T){}
use_metadata(NSRuncingOptions.mince)
// CHECK-LABEL: define linkonce_odr hidden swiftcc %swift.metadata_response @"$SSo16NSRuncingOptionsVMa"(i64)
// CHECK: call %swift.type* @swift_getForeignTypeMetadata({{.*}} @"$SSo16NSRuncingOptionsVN" {{.*}}) [[NOUNWIND_READNONE:#[0-9]+]]
// CHECK-LABEL: define linkonce_odr hidden i8** @"$SSo16NSRuncingOptionsVs9EquatableSCWa"()
// CHECK: [[NONUNIQUE:%.*]] = call i8** @swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @"$SSo16NSRuncingOptionsVs9EquatableSCWG", %swift.type* null, i8*** null)
// CHECK: [[UNIQUE:%.*]] = call i8** @swift_getForeignWitnessTable(i8** [[NONUNIQUE]], %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32 }>* @"$SSo16NSRuncingOptionsVMn" to %swift.type_descriptor*), %swift.protocol* @"$Ss9EquatableMp")
// CHECK: ret i8** [[UNIQUE]]
@objc enum ExportedToObjC: Int {
case Foo = -1, Bar, Bas
}
// CHECK-LABEL: define hidden swiftcc i64 @"$S12objc_ns_enum0a1_C7_injectAA14ExportedToObjCOyF"()
// CHECK: ret i64 -1
func objc_enum_inject() -> ExportedToObjC {
return .Foo
}
// CHECK-LABEL: define hidden swiftcc i64 @"$S12objc_ns_enum0a1_C7_switchySiAA14ExportedToObjCOF"(i64)
// CHECK: switch i64 %0, label {{%.*}} [
// CHECK: i64 -1, label {{%.*}}
// CHECK: i64 0, label {{%.*}}
// CHECK: i64 1, label {{%.*}}
func objc_enum_switch(_ x: ExportedToObjC) -> Int {
switch x {
case .Foo:
return 0
case .Bar:
return 1
case .Bas:
return 2
}
}
@objc class ObjCEnumMethods : NSObject {
// CHECK: define internal void @"$S12objc_ns_enum15ObjCEnumMethodsC0C2InyyAA010ExportedToD1COFTo"([[OBJC_ENUM_METHODS:.*]]*, i8*, i64)
dynamic func enumIn(_ x: ExportedToObjC) {}
// CHECK: define internal i64 @"$S12objc_ns_enum15ObjCEnumMethodsC0C3OutAA010ExportedToD1COyFTo"([[OBJC_ENUM_METHODS]]*, i8*)
dynamic func enumOut() -> ExportedToObjC { return .Foo }
// CHECK: define internal i64 @"$S12objc_ns_enum15ObjCEnumMethodsC4propAA010ExportedToD1COvgTo"([[OBJC_ENUM_METHODS]]*, i8*)
// CHECK: define internal void @"$S12objc_ns_enum15ObjCEnumMethodsC4propAA010ExportedToD1COvsTo"([[OBJC_ENUM_METHODS]]*, i8*, i64)
dynamic var prop: ExportedToObjC = .Foo
}
// CHECK-LABEL: define hidden swiftcc void @"$S12objc_ns_enum0a1_C13_method_callsyyAA15ObjCEnumMethodsCF"(%T12objc_ns_enum15ObjCEnumMethodsC*)
func objc_enum_method_calls(_ x: ObjCEnumMethods) {
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.enumIn(x.enumOut())
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.enumIn(x.prop)
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.prop = x.enumOut()
}
// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
| apache-2.0 | 03ab420eae91cd84b252589e1205ebf9 | 42.530201 | 251 | 0.705674 | 3.274104 | false | false | false | false |
testpress/ios-app | Testpress iOS AppUITests/Testpress_iOS_AppUITests.swift | 1 | 1945 | //
// Testpress_iOS_AppUITests.swift
// Testpress iOS AppUITests
//
// Created by Karthik on 02/01/19.
// Copyright © 2019 Testpress. All rights reserved.
//
import XCTest
class Testpress_iOS_AppUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
// func testCountryCode() {
//
// let app = XCUIApplication()
// let scrollViewsQuery = app.scrollViews
// scrollViewsQuery.otherElements.buttons["Sign up"].tap()
//
// let textField = scrollViewsQuery.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element(boundBy: 1).children(matching: .other).element(boundBy: 0).children(matching: .textField).element(boundBy: 0)
//
// XCTAssertEqual(textField.value as! String, "91")
//
// textField.tap()
// app/*@START_MENU_TOKEN@*/.pickerWheels["Andorra"]/*[[".pickers.pickerWheels[\"Andorra\"]",".pickerWheels[\"Andorra\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.swipeUp()
//
// let toolbarDoneButtonButton = app.toolbars["Toolbar"].buttons["Toolbar Done Button"]
// toolbarDoneButtonButton.tap()
//
// XCTAssertEqual(textField.value as! String, "226")
// }
}
| mit | 77d8ea4f660ff00455a4246f0a0c05f6 | 39.458333 | 257 | 0.667353 | 4.221739 | false | true | false | false |
53ningen/todo | TODO/UI/Issue/IssueViewController.swift | 1 | 5106 |
import UIKit
final class IssueViewController: BaseViewController {
fileprivate lazy var viewModel: IssueViewModel? = nil
func setViewModel(_ viewModel: IssueViewModel) {
self.viewModel = viewModel
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var editButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.registerNib(MilestoneCellView.self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
bind()
subscribeEvents()
viewModel?.updateIssue()
}
private func bind() {
viewModel?.issue.asObservable().map { _ in () }.subscribe(onNext: tableView.reloadData).addDisposableTo(disposeBag)
}
private func subscribeEvents() {
tableView.rx.itemSelected
.subscribe(onNext: { [weak self] indexPath in
self?.tableView.deselectRow(at: indexPath, animated: true)
switch IssueViewSection(rawValue: indexPath.section) {
case .some(.info):
self?.viewModel?.issue.value?.info.milestone.forEach {
let vc = UIStoryboard.issuesViewController(IssuesQuery.milestoneQuery(milestone: $0))
self?.navigationController?.pushViewController(vc, animated: true)
}
case .some(.labels):
self?.viewModel?.issue.value?.info.labels.safeIndex(indexPath.item).forEach {
let vc = UIStoryboard.issuesViewController(IssuesQuery.labelQuery(label: $0))
self?.navigationController?.pushViewController(vc, animated: true)
}
break
default:
break
}
})
.addDisposableTo(disposeBag)
editButton.rx.tap
.subscribe(onNext: { [weak self] _ in
self?.viewModel?.issue.value.forEach {
let vc = UIStoryboard.editIssueViewController()
vc.setViewModel(EditIssueViewModel(issue: $0))
self?.present(vc, animated: true, completion: nil)
}
})
.addDisposableTo(disposeBag)
}
}
extension IssueViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return IssueViewSection(rawValue: section).map {
switch $0 {
case .info: return viewModel?.issue.value?.info.milestone == nil ? 0 : 1
case .labels: return viewModel?.issue.value?.info.labels.count ?? 0
}
} ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return IssueViewSection(rawValue: (indexPath as NSIndexPath).section).flatMap {
switch $0 {
case .info:
let cell = UIView.getInstance(MilestoneCellView.self)
if let milestone = viewModel?.issue.value?.info.milestone {
cell?.bind(milestone)
}
return cell
case .labels:
let cell = UIView.getInstance(LabelCellView.self)
if let label = viewModel?.issue.value?.info.labels.safeIndex(indexPath.item) {
cell?.bind(label)
}
return cell
}
} ?? UITableViewCell()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
}
extension IssueViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return IssueViewSection(rawValue: section).map {
switch $0 {
case .info: return 210
case .labels: return 56
}
} ?? 0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return IssueViewSection(rawValue: section).flatMap { sec in
switch sec {
case .info:
let cell = UIView.getInstance(IssueInfoCellView.self)
if let issue = self.viewModel?.issue.value {
cell?.bind(issue)
}
return cell
case .labels:
let cell = UIView.getInstance(HeaderCellView.self)
cell?.bind("Labels")
return cell
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return IssueViewSection(rawValue: (indexPath as NSIndexPath).section).map {
switch $0 {
case .info: return 82
case .labels: return 75
}
} ?? 0
}
}
fileprivate enum IssueViewSection: Int {
case info = 0
case labels = 1
}
| mit | 81d5d3e29529f520daec4e15f353ee5c | 33.734694 | 123 | 0.562476 | 5.357817 | false | false | false | false |
MartinOSix/DemoKit | dSwift/SwiftSyntaxDemo/SwiftSyntaxDemo/ViewController_Class.swift | 1 | 1907 | //
// ViewController_Class.swift
// SwiftSyntaxDemo
//
// Created by runo on 16/12/27.
// Copyright © 2016年 com.runo. All rights reserved.
//
import UIKit
/*
使用类的好处
继承获得一个类的属性到其他类
类型转换使用户能够在运行时检查类的类型
初始化器需要处理释放内存资源
引用计数允许类实例有一个以上的参考
类和结构的共同特征
属性被定义为存储值
下标被定义为提供访问值
方法被初始化来改善功能
初始状态是由初始化函数定义
功能被扩大,超出默认值
确认协议功能标准
*/
class Student{
var studentName: String = ""
var mark: Int = 0
//属性观察者
var mark2: Int = 0 {
willSet(newValue) {
print(newValue)
}
didSet {
if mark2 > oldValue {
print("mark2 \(mark2) oldValue \(oldValue)")
}
}
}
//计算属性
var total: Int {
get {
return mark + mark2
}
set {
mark = newValue/2
mark2 = newValue/2
}
}
}
class ViewController_Class: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let stu = Student.init()
stu.mark = 10
stu.mark2 = 30
print(stu.total)
//值类型嵌套引用类型的赋值
var outer = Outer()
var outer2 = outer
outer2.value = 43
outer.value = 43
outer.inner.value = 43
print("outer2.value = \(outer2.value), outer.value = \(outer.value) outer2.inner.value = \(outer2.inner.value) outer.inner.value = \(outer.inner.value)")
}
}
class Innser {
var value = 42
}
struct Outer {
var value = 42
var inner = Innser()
}
| apache-2.0 | 77586c760f5b6e9c22da23d7409c780d | 15.787234 | 161 | 0.524081 | 3.506667 | false | false | false | false |
tardieu/swift | test/PrintAsObjC/classes.swift | 7 | 31956 | // Please keep this file in alphabetical order!
// REQUIRES: objc_interop
// RUN: rm -rf %t
// RUN: mkdir -p %t
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/AppKit.swift
// FIXME: END -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -I %S/Inputs/custom-modules -o %t %s -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library %t/classes.swiftmodule -typecheck -I %S/Inputs/custom-modules -emit-objc-header-path %t/classes.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck %s < %t/classes.h
// RUN: %FileCheck --check-prefix=NEGATIVE %s < %t/classes.h
// RUN: %check-in-clang -I %S/Inputs/custom-modules/ %t/classes.h
// RUN: not %check-in-clang -I %S/Inputs/custom-modules/ -fno-modules -Qunused-arguments %t/classes.h
// RUN: %check-in-clang -I %S/Inputs/custom-modules/ -fno-modules -Qunused-arguments %t/classes.h -include Foundation.h -include CoreFoundation.h -include objc_generics.h -include SingleGenericClass.h
// CHECK-NOT: AppKit;
// CHECK-NOT: Properties;
// CHECK-NOT: Swift;
// CHECK-LABEL: @import Foundation;
// CHECK-NEXT: @import CoreGraphics;
// CHECK-NEXT: @import CoreFoundation;
// CHECK-NEXT: @import objc_generics;
// CHECK-NEXT: @import SingleGenericClass;
// CHECK-NOT: AppKit;
// CHECK-NOT: Swift;
import Foundation
import objc_generics
import AppKit // only used in implementations
import CoreFoundation
import SingleGenericClass
// CHECK-LABEL: @interface A1{{$}}
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class A1 {}
// CHECK-LABEL: @interface B1 : A1
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class B1 : A1 {}
// CHECK-LABEL: @interface BridgedTypes
// CHECK-NEXT: - (NSDictionary * _Nonnull)dictBridge:(NSDictionary * _Nonnull)x SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (NSSet * _Nonnull)setBridge:(NSSet * _Nonnull)x SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class BridgedTypes {
func dictBridge(_ x: Dictionary<NSObject, AnyObject>) -> Dictionary<NSObject, AnyObject> {
return x
}
func setBridge(_ x: Set<NSObject>) -> Set<NSObject> {
return x
}
}
// CHECK: @class CustomName2;
// CHECK-LABEL: SWIFT_CLASS_NAMED("ClassWithCustomName")
// CHECK-NEXT: @interface CustomName{{$}}
// CHECK-NEXT: - (void)forwardCustomName:(CustomName2 * _Nonnull)_;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc(CustomName)
class ClassWithCustomName {
func forwardCustomName(_: ClassWithCustomName2) {}
}
// CHECK-LABEL: SWIFT_CLASS_NAMED("ClassWithCustomName2")
// CHECK-NEXT: @interface CustomName2{{$}}
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc(CustomName2)
class ClassWithCustomName2 {}
// CHECK-LABEL: SWIFT_CLASS_NAMED("ClassWithCustomNameSub")
// CHECK-NEXT: @interface CustomNameSub : CustomName{{$}}
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc(CustomNameSub)
class ClassWithCustomNameSub : ClassWithCustomName {}
// CHECK-LABEL: @interface ClassWithNSObjectProtocol <NSObject>
// CHECK-NEXT: @property (nonatomic, readonly, copy) NSString * _Nonnull description;
// CHECK-NEXT: - (BOOL)conformsToProtocol:(Protocol * _Nonnull)_ SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (BOOL)isKindOfClass:(Class _Nonnull)aClass SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
@objc class ClassWithNSObjectProtocol : NSObjectProtocol {
var description: String { return "me" }
@objc(conformsToProtocol:)
func conforms(to _: Protocol) -> Bool { return false }
@objc(isKindOfClass:)
func isKind(of aClass: AnyClass) -> Bool { return false }
}
// CHECK-LABEL: @interface DiscardableResult : NSObject
// CHECK-NEXT: - (NSInteger)nonDiscardable:(NSInteger)x SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (NSInteger)discardable:(NSInteger)x;
// CHECK-NEXT: - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
class DiscardableResult : NSObject {
func nonDiscardable(_ x: Int) -> Int { return x }
@discardableResult func discardable(_ x: Int) -> Int { return x }
}
// CHECK-LABEL: @interface Initializers
// CHECK-NEXT: - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nonnull instancetype)initWithInt:(NSInteger)_;
// CHECK-NEXT: - (nonnull instancetype)initWithFloat:(float)f;
// CHECK-NEXT: - (nonnull instancetype)initWithString:(NSString * _Nonnull)s boolean:(BOOL)b;
// CHECK-NEXT: - (nullable instancetype)initWithBoolean:(BOOL)b;
// CHECK-NEXT: - (nonnull instancetype)foo_initWithInt:(NSInteger)_ SWIFT_METHOD_FAMILY(init);
// CHECK-NEXT: - (nonnull instancetype)initializeWithX:(NSInteger)_ SWIFT_METHOD_FAMILY(init);
// CHECK-NEXT: - (nonnull instancetype)initForFun OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nonnull instancetype)initWithMoreFun OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nonnull instancetype)initWithEvenMoreFun OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
@objc class Initializers {
init() {}
convenience init(int _: Int) { self.init() }
convenience init(float f: Float) { self.init() }
convenience init(string s: String, boolean b: ObjCBool) { self.init() }
convenience init?(boolean b: ObjCBool) { self.init() }
@objc(foo_initWithInt:) convenience init(foo_int _: Int) { self.init() }
@objc(initializeWithX:) convenience init(X _: Int) { self.init() }
init(forFun: ()) { }
init(moreFun: ()) { }
init(evenMoreFun: ()) { }
}
// CHECK-LABEL: @interface InheritedInitializers
// CHECK-NEXT: - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nonnull instancetype)initWithFloat:(float)f SWIFT_UNAVAILABLE;
// CHECK-NEXT: - (nonnull instancetype)initWithMoreFun SWIFT_UNAVAILABLE;
// CHECK-NEXT: - (nonnull instancetype)initForFun SWIFT_UNAVAILABLE;
// CHECK-NEXT: - (nonnull instancetype)initWithEvenMoreFun SWIFT_UNAVAILABLE;
// CHECK-NEXT: @end
@objc class InheritedInitializers : Initializers {
override init() {
super.init()
}
private convenience init(float f: Float) { self.init() }
private override init(moreFun: ()) { super.init() }
}
// CHECK-LABEL: @interface InheritedInitializersAgain
// CHECK-NEXT: - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nonnull instancetype)initWithEvenMoreFun OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
@objc class InheritedInitializersAgain : InheritedInitializers {
override init() {
super.init()
}
init(evenMoreFun: ()) { super.init() }
}
// NEGATIVE-NOT: NotObjC
class NotObjC {}
// CHECK-LABEL: @interface Methods{{$}}
// CHECK-NEXT: - (void)test;
// CHECK-NEXT: + (void)test2;
// CHECK-NEXT: - (void * _Nonnull)testPrimitives:(BOOL)b i:(NSInteger)i f:(float)f d:(double)d u:(NSUInteger)u SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)testString:(NSString * _Nonnull)s;
// CHECK-NEXT: - (void)testSelector:(SEL _Nonnull)sel boolean:(BOOL)b;
// CHECK-NEXT: - (void)testCSignedTypes:(signed char)a b:(short)b c:(int)c d:(long)d e:(long long)e;
// CHECK-NEXT: - (void)testCUnsignedTypes:(unsigned char)a b:(unsigned short)b c:(unsigned int)c d:(unsigned long)d e:(unsigned long long)e;
// CHECK-NEXT: - (void)testCChars:(char)basic wchar:(wchar_t)wide char16:(char16_t)char16 char32:(char32_t)char32;
// CHECK-NEXT: - (void)testCFloats:(float)a b:(double)b;
// CHECK-NEXT: - (void)testCBool:(bool)a;
// CHECK-NEXT: - (void)testSizedSignedTypes:(int8_t)a b:(int16_t)b c:(int32_t)c d:(int64_t)d;
// CHECK-NEXT: - (void)testSizedUnsignedTypes:(uint8_t)a b:(uint16_t)b c:(uint32_t)c d:(uint64_t)d;
// CHECK-NEXT: - (void)testSizedFloats:(float)a b:(double)b;
// CHECK-NEXT: - (nonnull instancetype)getDynamicSelf SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: + (SWIFT_METATYPE(Methods) _Nonnull)getSelf SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (Methods * _Nullable)maybeGetSelf SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: + (SWIFT_METATYPE(Methods) _Nullable)maybeGetSelf SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (Methods * _Null_unspecified)uncheckedGetSelf SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: + (SWIFT_METATYPE(Methods) _Null_unspecified)uncheckedGetSelf SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: + (SWIFT_METATYPE(CustomName) _Nonnull)getCustomNameType SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)testParens:(NSInteger)a;
// CHECK-NEXT: - (void)testIgnoredParam:(NSInteger)_;
// CHECK-NEXT: - (void)testIgnoredParams:(NSInteger)_ again:(NSInteger)_;
// CHECK-NEXT: - (void)testArrayBridging:(NSArray<Methods *> * _Nonnull)a;
// CHECK-NEXT: - (void)testArrayBridging2:(NSArray * _Nonnull)a;
// CHECK-NEXT: - (void)testArrayBridging3:(NSArray<NSString *> * _Nonnull)a;
// CHECK-NEXT: - (void)testDictionaryBridging:(NSDictionary * _Nonnull)a;
// CHECK-NEXT: - (void)testDictionaryBridging2:(NSDictionary<NSNumber *, Methods *> * _Nonnull)a;
// CHECK-NEXT: - (void)testDictionaryBridging3:(NSDictionary<NSString *, NSString *> * _Nonnull)a;
// CHECK-NEXT: - (void)testSetBridging:(NSSet * _Nonnull)a;
// CHECK-NEXT: - (IBAction)actionMethod:(id _Nonnull)_;
// CHECK-NEXT: - (void)methodWithReservedParameterNames:(id _Nonnull)long_ protected:(id _Nonnull)protected_;
// CHECK-NEXT: - (void)honorRenames:(CustomName * _Nonnull)_;
// CHECK-NEXT: - (Methods * _Nullable __unsafe_unretained)unmanaged:(id _Nonnull __unsafe_unretained)_ SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)initAllTheThings SWIFT_METHOD_FAMILY(none);
// CHECK-NEXT: - (void)initTheOtherThings SWIFT_METHOD_FAMILY(none);
// CHECK-NEXT: - (void)initializeEvenMoreThings;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Methods {
func test() {}
class func test2() {}
func testPrimitives(_ b: Bool, i: Int, f: Float, d: Double, u: UInt)
-> OpaquePointer { return OpaquePointer(bitPattern: -1)! }
func testString(_ s: String) {}
func testSelector(_ sel: Selector, boolean b: ObjCBool) {}
func testCSignedTypes(_ a: CSignedChar, b: CShort, c: CInt, d: CLong, e: CLongLong) {}
func testCUnsignedTypes(_ a: CUnsignedChar, b: CUnsignedShort, c: CUnsignedInt, d: CUnsignedLong, e: CUnsignedLongLong) {}
func testCChars(_ basic: CChar, wchar wide: CWideChar, char16: CChar16, char32: CChar32) {}
func testCFloats(_ a: CFloat, b: CDouble) {}
func testCBool(_ a: CBool) {}
func testSizedSignedTypes(_ a: Int8, b: Int16, c: Int32, d: Int64) {}
func testSizedUnsignedTypes(_ a: UInt8, b: UInt16, c: UInt32, d: UInt64) {}
func testSizedFloats(_ a: Float32, b: Float64) {}
func getDynamicSelf() -> Self { return self }
class func getSelf() -> Methods.Type { return self }
func maybeGetSelf() -> Methods? { return nil }
class func maybeGetSelf() -> Methods.Type? { return self }
func uncheckedGetSelf() -> Methods! { return self }
class func uncheckedGetSelf() -> Methods.Type! { return self }
class func getCustomNameType() -> ClassWithCustomName.Type {
return ClassWithCustomName.self
}
func testParens(_ a: ((Int))) {}
func testIgnoredParam(_: Int) {}
func testIgnoredParams(_: Int, again _: Int) {}
func testArrayBridging(_ a: [Methods]) {}
func testArrayBridging2(_ a: [AnyObject]) {}
func testArrayBridging3(_ a: [String]) {}
func testDictionaryBridging(_ a: [NSObject : AnyObject]) {}
func testDictionaryBridging2(_ a: [NSNumber : Methods]) {}
func testDictionaryBridging3(_ a: [String : String]) {}
func testSetBridging(_ a: Set<NSObject>) {}
@IBAction func actionMethod(_: AnyObject) {}
func methodWithReservedParameterNames(_ long: AnyObject, protected: AnyObject) {}
func honorRenames(_: ClassWithCustomName) {}
func unmanaged(_: Unmanaged<AnyObject>) -> Unmanaged<Methods>? { return nil }
func initAllTheThings() {}
@objc(initTheOtherThings) func setUpOtherThings() {}
func initializeEvenMoreThings() {}
}
typealias AliasForNSRect = NSRect
// CHECK-LABEL: @class NSURL;
// NEGATIVE-NOT: @class CFTree
// CHECK-LABEL: @interface MethodsWithImports
// CHECK-NEXT: - (NSPoint)getOrigin:(NSRect)r SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (CGFloat)getOriginX:(NSRect)r SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (CGFloat)getOriginY:(CGRect)r SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (NSArray * _Nonnull)emptyArray SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (NSArray * _Nullable)maybeArray SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (NSRuncingMode)someEnum SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (Class <NSCoding> _Nullable)protocolClass SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (struct _NSZone * _Nullable)zone SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (CFTypeRef _Nullable)cf:(CFTreeRef _Nonnull)x str:(CFStringRef _Nonnull)str str2:(CFMutableStringRef _Nonnull)str2 obj:(CFAliasForTypeRef _Nonnull)obj SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)appKitInImplementation;
// CHECK-NEXT: - (NSURL * _Nullable)returnsURL SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class MethodsWithImports {
func getOrigin(_ r: NSRect) -> NSPoint { return r.origin }
func getOriginX(_ r: AliasForNSRect) -> CGFloat { return r.origin.x }
func getOriginY(_ r: CGRect) -> CGFloat { return r.origin.y }
func emptyArray() -> NSArray { return NSArray() }
func maybeArray() -> NSArray? { return nil }
func someEnum() -> NSRuncingMode { return .mince }
func protocolClass() -> NSCoding.Type? { return nil }
func zone() -> NSZone? { return nil }
func cf(_ x: CFTree, str: CFString, str2: CFMutableString, obj: CFAliasForType) -> CFTypeRef? { return nil }
func appKitInImplementation() {
let _ : NSResponder?
}
func returnsURL() -> NSURL? { return nil }
}
// CHECK-LABEL: @interface MethodsWithPointers
// CHECK-NEXT: - (id _Nonnull * _Nonnull)test:(NSInteger * _Nonnull)a SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)testNested:(NSInteger * _Nonnull * _Nonnull)a;
// CHECK-NEXT: - (void)testBridging:(NSInteger const * _Nonnull)a b:(NSInteger * _Nonnull)b c:(Methods * _Nonnull * _Nonnull)c;
// CHECK-NEXT: - (void)testBridgingVoid:(void * _Nonnull)a b:(void const * _Nonnull)b;
// CHECK-NEXT: - (void)testBridgingOptionality:(NSInteger const * _Nullable)a b:(NSInteger * _Null_unspecified)b c:(Methods * _Nullable * _Nullable)c;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class MethodsWithPointers {
func test(_ a: UnsafeMutablePointer<Int>) -> UnsafeMutablePointer<AnyObject> {
return UnsafeMutablePointer(bitPattern: -1)!
}
func testNested(_ a: UnsafeMutablePointer<UnsafeMutablePointer<Int>>) {}
func testBridging(_ a: UnsafePointer<Int>, b: UnsafeMutablePointer<Int>, c: AutoreleasingUnsafeMutablePointer<Methods>) {}
func testBridgingVoid(_ a: UnsafeMutableRawPointer, b: UnsafeRawPointer) {}
func testBridgingOptionality(_ a: UnsafePointer<Int>?, b: UnsafeMutablePointer<Int>!, c: AutoreleasingUnsafeMutablePointer<Methods?>?) {}
}
// CHECK-LABEL: @interface MyObject : NSObject
// CHECK-NEXT: init
// CHECK-NEXT: @end
// NEGATIVE-NOT: @interface NSObject
class MyObject : NSObject {}
// CHECK-LABEL: @protocol MyProtocol <NSObject>
// CHECK-NEXT: @end
@objc protocol MyProtocol : NSObjectProtocol {}
// CHECK-LABEL: @protocol MyProtocolMetaOnly;
// CHECK-LABEL: @interface MyProtocolMetaCheck
// CHECK-NEXT: - (void)test:(Class <MyProtocolMetaOnly> _Nullable)x;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class MyProtocolMetaCheck {
func test(_ x: MyProtocolMetaOnly.Type?) {}
}
// CHECK-LABEL: @protocol MyProtocolMetaOnly
// CHECK-NEXT: @end
@objc protocol MyProtocolMetaOnly {}
// CHECK-LABEL: @interface Nested
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Nested {
// CHECK-LABEL: @interface Inner
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Inner {
// CHECK-LABEL: @interface DeeperIn
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class DeeperIn {}
}
// CHECK-LABEL: @interface AnotherInner : A1
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class AnotherInner : A1 {}
// NEGATIVE-NOT: NonObjCInner
class NonObjCInner {}
// NEGATIVE-NOT: ImplicitObjCInner
class ImplicitObjCInner : A1 {}
}
// CHECK-LABEL: @class Inner2;
// CHECK-LABEL: @interface NestedMembers
// CHECK-NEXT: @property (nonatomic, strong) Inner2 * _Nullable ref2;
// CHECK-NEXT: @property (nonatomic, strong) Inner3 * _Nullable ref3;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class NestedMembers {
// NEGATIVE-NOT: @class NestedMembers;
// CHECK-LABEL: @interface Inner2
// CHECK-NEXT: @property (nonatomic, strong) NestedMembers * _Nullable ref;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Inner2 {
var ref: NestedMembers?
}
var ref2: Inner2?
var ref3: Inner3?
// CHECK-LABEL: @interface Inner3
// CHECK-NEXT: @property (nonatomic, strong) NestedMembers * _Nullable ref;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Inner3 {
var ref: NestedMembers?
}
}
// CHECK-LABEL: @interface NestedSuperclass
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class NestedSuperclass {
// CHECK-LABEL: @interface Subclass : NestedSuperclass
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Subclass : NestedSuperclass {}
}
// NEGATIVE-NOT: @interface Private :
private class Private : A1 {}
// CHECK-LABEL: @interface PrivateMembers
// CHECK-NEXT: @end
@objc class PrivateMembers {
private var i = 0
private func foo() {}
private init() {}
@objc private func bar() {}
}
public class NonObjCClass { }
// CHECK-LABEL: @interface Properties
// CHECK-NEXT: @property (nonatomic) NSInteger i;
// CHECK-NEXT: @property (nonatomic, readonly, strong) Properties * _Nonnull mySelf;
// CHECK-NEXT: @property (nonatomic, readonly) double pi;
// CHECK-NEXT: @property (nonatomic) NSInteger computed;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, strong) Properties * _Nonnull shared;)
// CHECK-NEXT: + (Properties * _Nonnull)shared SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: + (void)setShared:(Properties * _Nonnull)newValue;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly, strong) Properties * _Nonnull sharedRO;)
// CHECK-NEXT: + (Properties * _Nonnull)sharedRO SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: @property (nonatomic, weak) Properties * _Nullable weakOther;
// CHECK-NEXT: @property (nonatomic, assign) Properties * _Nonnull unownedOther;
// CHECK-NEXT: @property (nonatomic, unsafe_unretained) Properties * _Nonnull unmanagedOther;
// CHECK-NEXT: @property (nonatomic, unsafe_unretained) Properties * _Nullable unmanagedByDecl;
// CHECK-NEXT: @property (nonatomic, weak) id <MyProtocol> _Nullable weakProto;
// CHECK-NEXT: @property (nonatomic) CFTypeRef _Nullable weakCF;
// CHECK-NEXT: @property (nonatomic) CFStringRef _Nullable weakCFString;
// CHECK-NEXT: @property (nonatomic) CFTypeRef _Nullable strongCF;
// CHECK-NEXT: @property (nonatomic) CFTypeRef _Nullable strongCFAlias;
// CHECK-NEXT: @property (nonatomic) CFAliasForTypeRef _Nullable anyCF;
// CHECK-NEXT: @property (nonatomic) CFAliasForTypeRef _Nullable anyCF2;
// CHECK-NEXT: @property (nonatomic, weak) IBOutlet id _Null_unspecified outlet;
// CHECK-NEXT: @property (nonatomic, strong) IBOutlet Properties * _Null_unspecified typedOutlet;
// CHECK-NEXT: @property (nonatomic, copy) NSString * _Nonnull string;
// CHECK-NEXT: @property (nonatomic, copy) NSArray * _Nonnull array;
// CHECK-NEXT: @property (nonatomic, copy) NSArray<NSArray<NSNumber *> *> * _Nonnull arrayOfArrays;
// CHECK-NEXT: @property (nonatomic, copy) NSArray<BOOL (^)(id _Nonnull, NSInteger)> * _Nonnull arrayOfBlocks;
// CHECK-NEXT: @property (nonatomic, copy) NSArray<NSArray<void (^)(void)> *> * _Nonnull arrayOfArrayOfBlocks;
// CHECK-NEXT: @property (nonatomic, copy) NSDictionary<NSString *, NSString *> * _Nonnull dictionary;
// CHECK-NEXT: @property (nonatomic, copy) NSDictionary<NSString *, NSNumber *> * _Nonnull dictStringInt;
// CHECK-NEXT: @property (nonatomic, copy) NSSet<NSString *> * _Nonnull stringSet;
// CHECK-NEXT: @property (nonatomic, copy) NSSet<NSNumber *> * _Nonnull intSet;
// CHECK-NEXT: @property (nonatomic, copy) NSArray<NSNumber *> * _Nonnull cgFloatArray;
// CHECK-NEXT: @property (nonatomic, copy) NSArray<NSValue *> * _Nonnull rangeArray;
// CHECK-NEXT: @property (nonatomic, copy) IBOutletCollection(Properties) NSArray<Properties *> * _Null_unspecified outletCollection;
// CHECK-NEXT: @property (nonatomic, copy) IBOutletCollection(CustomName) NSArray<CustomName *> * _Nullable outletCollectionOptional;
// CHECK-NEXT: @property (nonatomic, copy) IBOutletCollection(id) NSArray * _Nullable outletCollectionAnyObject;
// CHECK-NEXT: @property (nonatomic, copy) IBOutletCollection(id) NSArray<id <NSObject>> * _Nullable outletCollectionProto;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly) NSInteger staticInt;)
// CHECK-NEXT: + (NSInteger)staticInt SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, copy) NSString * _Nonnull staticString;)
// CHECK-NEXT: + (NSString * _Nonnull)staticString SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: + (void)setStaticString:(NSString * _Nonnull)value;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly) double staticDouble;)
// CHECK-NEXT: + (double)staticDouble SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly, copy) NSDictionary<NSString *, NSString *> * _Nonnull staticDictionary;)
// CHECK-NEXT: + (NSDictionary<NSString *, NSString *> * _Nonnull)staticDictionary SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: @property (nonatomic, strong) Properties * _Nullable wobble;
// CHECK-NEXT: @property (nonatomic, getter=isEnabled, setter=setIsEnabled:) BOOL enabled;
// CHECK-NEXT: @property (nonatomic) BOOL isAnimated;
// CHECK-NEXT: @property (nonatomic, getter=register, setter=setRegister:) BOOL register_;
// CHECK-NEXT: @property (nonatomic, readonly, strong, getter=this) Properties * _Nonnull this_;
// CHECK-NEXT: @property (nonatomic, readonly) NSInteger privateSetter;
// CHECK-NEXT: @property (nonatomic, readonly, getter=customGetterNameForPrivateSetter) BOOL privateSetterCustomNames;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly) NSInteger privateSetter;)
// CHECK-NEXT: + (NSInteger)privateSetter SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly, getter=customGetterNameForPrivateSetter) BOOL privateSetterCustomNames;)
// CHECK-NEXT: + (BOOL)customGetterNameForPrivateSetter SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly) NSInteger sharedConstant;)
// CHECK-NEXT: + (NSInteger)sharedConstant SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: @property (nonatomic) NSInteger initContext;
// CHECK-NEXT: - (NSInteger)initContext SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: @property (nonatomic, readonly) NSInteger initContextRO;
// CHECK-NEXT: - (NSInteger)initContextRO SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: @property (nonatomic, getter=initGetter) BOOL getterIsInit;
// CHECK-NEXT: - (BOOL)initGetter SWIFT_METHOD_FAMILY(none) SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: @property (nonatomic, setter=initSetter:) BOOL setterIsInit;
// CHECK-NEXT: - (void)initSetter:(BOOL)newValue SWIFT_METHOD_FAMILY(none);
// CHECK-NEXT: @property (nonatomic, copy) NSURL * _Nullable customValueTypeProp;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Properties {
var i: Int = 1
var mySelf: Properties {
return self
}
let pi = 3.14
var computed: Int {
get {
return 42
}
set {
// Ignore it.
}
}
class var shared: Properties {
get { return Properties() }
set { }
}
class var sharedRO: Properties {
get { return Properties() }
}
weak var weakOther: Properties?
unowned var unownedOther: Properties = .shared
unowned(unsafe) var unmanagedOther: Properties = .shared
var unmanagedByDecl: Unmanaged<Properties>?
weak var weakProto: MyProtocol?
weak var weakCF: CFTypeRef?
weak var weakCFString: CFString?
typealias CFTypeRefAlias = CFTypeRef
var strongCF: CFTypeRef?
var strongCFAlias: CFTypeRefAlias?
var anyCF: CFAliasForType?
var anyCF2: CFAliasForType?
@IBOutlet weak var outlet: AnyObject!
@IBOutlet var typedOutlet: Properties!
var string = "abc"
var array: Array<AnyObject> = []
var arrayOfArrays: Array<Array<Int>> = []
var arrayOfBlocks: Array<@convention(block) (AnyObject, Int) -> Bool> = []
var arrayOfArrayOfBlocks: Array<Array<@convention(block) () -> Void>> = []
var dictionary: Dictionary<String, String> = [:]
var dictStringInt: Dictionary<String, Int> = [:]
var stringSet: Set<String> = []
var intSet: Set<Int> = []
var cgFloatArray: Array<CGFloat> = []
var rangeArray: Array<NSRange> = []
@IBOutlet var outletCollection: [Properties]!
@IBOutlet var outletCollectionOptional: [ClassWithCustomName]? = []
@IBOutlet var outletCollectionAnyObject: [AnyObject]?
@IBOutlet var outletCollectionProto: [NSObjectProtocol]?
static let staticInt = 2
static var staticString = "Hello"
static var staticDouble: Double {
return 2.0
}
static var staticDictionary: [String: String] { return [:] }
@objc(wobble) var wibble: Properties?
var enabled: Bool {
@objc(isEnabled) get { return true }
@objc(setIsEnabled:) set { }
}
var isAnimated: Bool = true
var register: Bool = false
var this: Properties { return self }
private(set) var privateSetter = 2
private(set) var privateSetterCustomNames: Bool {
@objc(customGetterNameForPrivateSetter) get { return true }
@objc(customSetterNameForPrivateSetter:) set {}
}
static private(set) var privateSetter = 2
class private(set) var privateSetterCustomNames: Bool {
@objc(customGetterNameForPrivateSetter) get { return true }
@objc(customSetterNameForPrivateSetter:) set {}
}
static let sharedConstant = 2
var initContext = 4
var initContextRO: Int { return 4 }
var getterIsInit: Bool {
@objc(initGetter) get { return true }
set {}
}
var setterIsInit: Bool {
get { return true }
@objc(initSetter:) set {}
}
var customValueTypeProp: URL?
}
// CHECK-LABEL: @interface PropertiesOverridden
// CHECK-NEXT: @property (nonatomic, copy) NSArray<Bee *> * _Nonnull bees;
// CHECK-NEXT: - (null_unspecified instancetype)init
// CHECK-NEXT: - (null_unspecified instancetype)initWithCoder:(NSCoder * _Null_unspecified)aDecoder OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
@objc class PropertiesOverridden : Hive {
override var bees : [Bee] {
get {
return super.bees
}
set {
// Ignore it.
}
}
}
// CHECK-LABEL: @interface ReversedOrder2{{$}}
// CHECK-NEXT: init
// CHECK-NEXT: @end
// CHECK: SWIFT_CLASS("_TtC7classes14ReversedOrder1")
// CHECK-NEXT: @interface ReversedOrder1 : ReversedOrder2
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class ReversedOrder1 : ReversedOrder2 {}
@objc class ReversedOrder2 {}
// CHECK-LABEL: @interface Subscripts1
// CHECK-NEXT: - (Subscripts1 * _Nonnull)objectAtIndexedSubscript:(NSInteger)i SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (Subscripts1 * _Nonnull)objectForKeyedSubscript:(Subscripts1 * _Nonnull)o SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Subscripts1 {
subscript (i: Int) -> Subscripts1 {
return self
}
subscript (o: Subscripts1) -> Subscripts1 {
return self
}
}
// CHECK-LABEL: @interface Subscripts2
// CHECK-NEXT: - (Subscripts2 * _Nonnull)objectAtIndexedSubscript:(int16_t)i SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)setObject:(Subscripts2 * _Nonnull)newValue atIndexedSubscript:(int16_t)i;
// CHECK-NEXT: - (NSObject * _Nonnull)objectForKeyedSubscript:(NSObject * _Nonnull)o SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)setObject:(NSObject * _Nonnull)newValue forKeyedSubscript:(NSObject * _Nonnull)o;
// CHECK-NEXT: @property (nonatomic, copy) NSArray<NSString *> * _Nonnull cardPaths;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Subscripts2 {
subscript (i: Int16) -> Subscripts2 {
get {
return self
}
set {
// Ignore it.
}
}
subscript (o: NSObject) -> NSObject {
get {
return o
}
set {
// Ignore it.
}
}
// <rdar://problem/17165953> Swift: lazy property reflects back into Objective-C with two properties, one for underlying storage
lazy var cardPaths : [String] = []
}
// CHECK-LABEL: @interface Subscripts3
// CHECK-NEXT: - (Subscripts3 * _Nonnull)objectAtIndexedSubscript:(unsigned long)_ SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: init
// CHECK-NEXT: @end
@objc class Subscripts3 {
subscript (_: CUnsignedLong) -> Subscripts3 {
return self
}
subscript (multi: Int, multi2: Int) -> () {
return ()
}
}
// CHECK-LABEL: @interface Throwing1
// CHECK-NEXT: - (BOOL)method1AndReturnError:(NSError * _Nullable * _Nullable)error;
// CHECK-NEXT: - (Throwing1 * _Nullable)method2AndReturnError:(NSError * _Nullable * _Nullable)error SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (NSArray<NSString *> * _Nullable)method3:(NSInteger)x error:(NSError * _Nullable * _Nullable)error SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (nullable instancetype)method4AndReturnError:(NSError * _Nullable * _Nullable)error SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (nullable instancetype)initAndReturnError:(NSError * _Nullable * _Nullable)error OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nullable instancetype)initWithString:(NSString * _Nonnull)string error:(NSError * _Nullable * _Nullable)error OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nullable instancetype)initAndReturnError:(NSError * _Nullable * _Nullable)error fn:(SWIFT_NOESCAPE NSInteger (^ _Nonnull)(NSInteger))fn OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
@objc class Throwing1 {
func method1() throws { }
func method2() throws -> Throwing1 { return self }
func method3(_ x: Int) throws -> [String] { return [] }
func method4() throws -> Self { return self }
init() throws { }
init(string: String) throws { }
init(fn: (Int) -> Int) throws { }
}
@objc class Spoon: Fungible {}
// CHECK-LABEL: @interface UsesImportedGenerics
@objc class UsesImportedGenerics {
// CHECK: - (GenericClass<id> * _Nonnull)takeAndReturnGenericClass:(GenericClass<NSString *> * _Nullable)x SWIFT_WARN_UNUSED_RESULT;
@objc func takeAndReturnGenericClass(_ x: GenericClass<NSString>?) -> GenericClass<AnyObject> { fatalError("") }
// CHECK: - (FungibleContainer<id <Fungible>> * _Null_unspecified)takeAndReturnFungibleContainer:(FungibleContainer<Spoon *> * _Nonnull)x SWIFT_WARN_UNUSED_RESULT;
@objc func takeAndReturnFungibleContainer(_ x: FungibleContainer<Spoon>) -> FungibleContainer<Fungible>! { fatalError("") }
typealias Dipper = Spoon
// CHECK: - (FungibleContainer<FungibleObject> * _Nonnull)fungibleContainerWithAliases:(FungibleContainer<Spoon *> * _Nullable)x SWIFT_WARN_UNUSED_RESULT;
@objc func fungibleContainerWithAliases(_ x: FungibleContainer<Dipper>?) -> FungibleContainer<FungibleObject> { fatalError("") }
// CHECK: - (void)referenceSingleGenericClass:(SingleImportedObjCGeneric<id> * _Nullable)_;
func referenceSingleGenericClass(_: SingleImportedObjCGeneric<AnyObject>?) {}
}
// CHECK: @end
| apache-2.0 | 1868bddf498f99f21c5067561535707b | 42.067385 | 287 | 0.717768 | 3.767952 | false | true | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/SwiftTask/SwiftTask/_Atomic.swift | 3 | 1948 | //
// _Atomic.swift
// SwiftTask
//
// Created by Yasuhiro Inami on 2015/05/18.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import Darwin
internal final class _Atomic<T>
{
private var _spinlock = OS_SPINLOCK_INIT
private var _rawValue: T
internal init(_ rawValue: T)
{
self._rawValue = rawValue
}
internal func withRawValue<U>(@noescape f: T -> U) -> U
{
self._lock()
defer { self._unlock() }
return f(self._rawValue)
}
internal func update(@noescape f: T -> T) -> T
{
return self.updateIf { f($0) }!
}
internal func updateIf(@noescape f: T -> T?) -> T?
{
return self.modify { value in f(value).map { ($0, value) } }
}
internal func modify<U>(@noescape f: T -> (T, U)?) -> U?
{
self._lock()
defer { self._unlock() }
let oldValue = self._rawValue
if let (newValue, retValue) = f(oldValue) {
self._rawValue = newValue
return retValue
}
else {
return nil
}
}
private func _lock()
{
withUnsafeMutablePointer(&self._spinlock, OSSpinLockLock)
}
private func _unlock()
{
withUnsafeMutablePointer(&self._spinlock, OSSpinLockUnlock)
}
}
extension _Atomic: RawRepresentable
{
internal convenience init(rawValue: T)
{
self.init(rawValue)
}
internal var rawValue: T
{
get {
self._lock()
defer { self._unlock() }
return self._rawValue
}
set(newValue) {
self._lock()
defer { self._unlock() }
self._rawValue = newValue
}
}
}
extension _Atomic: CustomStringConvertible
{
internal var description: String
{
return String(self.rawValue)
}
} | apache-2.0 | 26d2ce2846c60eb185d6171a0816ac73 | 19.28125 | 68 | 0.514388 | 4.30531 | false | false | false | false |
sora0077/KeyboardBoundsKit | KeyboardBoundsKit/src/KeyboardBoundsView.swift | 1 | 7684 | //
// KeyboardBoundsView.swift
// KeyboardBoundsKit
//
// Created by 林達也 on 2015/09/24.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import UIKit
/// KeyboardBoundsView
@IBDesignable
public final class KeyboardBoundsView: UIView {
/// if keyboard did appear then `true`
public fileprivate(set) var keyboardAppearing: Bool = false
fileprivate var heightConstraint: NSLayoutConstraint?
fileprivate var keyboardView: UIView? {
willSet {
keyboardView?.removeObserver(self, forKeyPath: "center")
newValue?.addObserver(self, forKeyPath: "center", options: .new, context: nil)
}
}
fileprivate var changeFrameAnimation: Bool = false
/**
intrinsicContentSize
- returns: `superview?.bounds.size`
*/
public override var intrinsicContentSize: CGSize {
return superview?.bounds.size ?? super.intrinsicContentSize
}
/**
didMoveToSuperview
*/
public override func didMoveToSuperview() {
if let newSuperview = superview {
let constraint = NSLayoutConstraint(
item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: newSuperview,
attribute: .bottom,
multiplier: 1,
constant: 0
)
heightConstraint = constraint
NSLayoutConstraint.activate([constraint])
startObserving()
backgroundColor = UIColor.clear
} else {
keyboardView?.removeObserver(self, forKeyPath: "center")
if let constraint = heightConstraint {
NSLayoutConstraint.deactivate([constraint])
}
stopObserving()
heightConstraint = nil
}
}
/**
observeValueForKeyPath:ofObject:change:context
- parameter keyPath: `center`
- parameter object: object
- parameter change: change
- parameter context: context
*/
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard changeFrameAnimation else { return }
guard let keyboardView = keyboardView else { return }
guard let height = superview?.bounds.height else { return }
let dockDistance = UIScreen.main.bounds.height - keyboardView.frame.origin.y - keyboardView.frame.height
heightConstraint?.constant = dockDistance > 0 ? 0 : keyboardView.frame.origin.y - height
superview?.layoutIfNeeded()
}
/**
drawRect
- parameter rect: rect
*/
public override func draw(_ rect: CGRect) {
#if TARGET_INTERFACE_BUILDER
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(),
UIColor(red:0.941, green:0.941, blue:0.941, alpha: 1).CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), rect)
let className = "Keyboard Bounds View"
let attr = [
NSForegroundColorAttributeName : UIColor(red:0.796, green:0.796, blue:0.796, alpha: 1),
NSFontAttributeName : UIFont(name: "Helvetica-Bold", size: 28)!
]
let size = className.boundingRectWithSize(rect.size, options: [], attributes: attr, context: nil)
className.drawAtPoint(CGPointMake(rect.width/2 - size.width/2, rect.height/2 - size.height/2), withAttributes: attr)
if rect.height > 78.0 {
let subTitle:NSString = "Prototype Content"
let subAttr = [
NSForegroundColorAttributeName : UIColor(red:0.796, green:0.796, blue:0.796, alpha: 1),
NSFontAttributeName : UIFont(name: "Helvetica-Bold", size: 17)!
]
let subTitleSize = subTitle.boundingRectWithSize(rect.size, options: [], attributes: subAttr, context: nil)
subTitle.drawAtPoint(CGPointMake(rect.width/2 - subTitleSize.width/2, rect.height/2 - subTitleSize.height/2 + 30), withAttributes: subAttr)
}
#else
super.draw(rect)
#endif
}
}
private extension KeyboardBoundsView {
func startObserving() {
let notifications = [
(NSNotification.Name.UIKeyboardDidHide, #selector(self.keyboardDidHideNotification(_:))),
(NSNotification.Name.UIKeyboardDidShow, #selector(self.keyboardDidShowNotification(_:))),
(NSNotification.Name.UIKeyboardWillChangeFrame, #selector(self.keyboardWillChangeFrameNotification(_:))),
]
notifications.forEach { name, sel in
NotificationCenter.default.addObserver(self, selector: sel, name: name, object: nil)
}
}
func stopObserving() {
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - Notification
private extension KeyboardBoundsView {
@objc
func keyboardDidHideNotification(_ notification: Notification) {
keyboardAppearing = false
}
@objc
func keyboardDidShowNotification(_ notification: Notification) {
keyboardAppearing = true
func getKeyboardView() -> UIView? {
func getUIInputSetHostView(_ view: UIView) -> UIView? {
if let clazz = NSClassFromString("UIInputSetHostView") {
if view.isMember(of: clazz) {
return view
}
}
for subview in view.subviews {
if let subview = getUIInputSetHostView(subview) {
return subview
}
}
return nil
}
for window in UIApplication.shared.windows {
if let clazz = NSClassFromString("UITextEffectsWindow") {
if window.isKind(of: clazz) {
return getUIInputSetHostView(window)
}
}
}
return nil
}
keyboardView = getKeyboardView()
}
@objc
func keyboardWillChangeFrameNotification(_ notification: Notification) {
guard let userInfo = notification.userInfo else { return }
guard
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Float,
let _beginFrame = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue,
let beginFrame = Optional(_beginFrame.cgRectValue),
let _endFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
let endFrame = Optional(_endFrame.cgRectValue)
else {
return
}
let height = superview!.bounds.height
if endFrame.size == CGSize.zero {
heightConstraint?.constant = beginFrame.origin.y - height
} else {
heightConstraint?.constant = endFrame.origin.y - height
}
changeFrameAnimation = true
UIView.animate(
withDuration: TimeInterval(duration),
delay: 0.0,
options: UIViewAnimationOptions(rawValue: UInt(curve) << 16),
animations: {
self.superview?.layoutIfNeeded()
},
completion: { finished in
self.changeFrameAnimation = false
}
)
}
}
| mit | ef7af7c0f850c5dc3e5570414f0b5272 | 33.572072 | 158 | 0.581368 | 5.60219 | false | false | false | false |
tjw/swift | test/IRGen/big_types_corner_cases.swift | 1 | 11252 |
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// REQUIRES: optimized_stdlib
public struct BigStruct {
var i0 : Int32 = 0
var i1 : Int32 = 1
var i2 : Int32 = 2
var i3 : Int32 = 3
var i4 : Int32 = 4
var i5 : Int32 = 5
var i6 : Int32 = 6
var i7 : Int32 = 7
var i8 : Int32 = 8
}
func takeClosure(execute block: () -> Void) {
}
class OptionalInoutFuncType {
private var lp : BigStruct?
private var _handler : ((BigStruct?, Error?) -> ())?
func execute(_ error: Error?) {
var p : BigStruct?
var handler: ((BigStruct?, Error?) -> ())?
takeClosure {
p = self.lp
handler = self._handler
self._handler = nil
}
handler?(p, error)
}
}
// CHECK-LABEL: define{{( protected)?}} i32 @main(i32, i8**)
// CHECK: call void @llvm.lifetime.start
// CHECK: call void @llvm.memcpy
// CHECK: call void @llvm.lifetime.end
// CHECK: ret i32 0
let bigStructGlobalArray : [BigStruct] = [
BigStruct()
]
// CHECK-LABEL: define{{( protected)?}} internal swiftcc void @"$S22big_types_corner_cases21OptionalInoutFuncTypeC7executeyys5Error_pSgFyyXEfU_"(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_Sg* nocapture dereferenceable({{.*}})
// CHECK: call void @"$S22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOe
// CHECK: call void @"$S22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOy
// CHECK: ret void
public func f1_returns_BigType(_ x: BigStruct) -> BigStruct {
return x
}
public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct {
return f1_returns_BigType
}
public func f3_uses_f2() {
let x = BigStruct()
let useOfF2 = f2_returns_f1()
let _ = useOfF2(x)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S22big_types_corner_cases10f3_uses_f2yyF"()
// CHECK: call swiftcc void @"$S22big_types_corner_cases9BigStructVACycfC"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret
// CHECK: call swiftcc { i8*, %swift.refcounted* } @"$S22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"()
// CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK: ret void
public func f4_tuple_use_of_f2() {
let x = BigStruct()
let tupleWithFunc = (f2_returns_f1(), x)
let useOfF2 = tupleWithFunc.0
let _ = useOfF2(x)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S22big_types_corner_cases18f4_tuple_use_of_f2yyF"()
// CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @"$S22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"()
// CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0
// CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)*
// CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}})
// CHECK: ret void
public class BigClass {
public init() {
}
public var optVar: ((BigStruct)-> Void)? = nil
func useBigStruct(bigStruct: BigStruct) {
optVar!(bigStruct)
}
}
// CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @"$S22big_types_corner_cases8BigClassC03useE6Struct0aH0yAA0eH0V_tF"(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself)
// CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)*
// CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself
// CHECK: ret void
public struct MyStruct {
public let a: Int
public let b: String?
}
typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void
func takesUploader(_ u: UploadFunction) { }
class Foo {
func blam() {
takesUploader(self.myMethod) // crash compiling this
}
func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { }
}
// CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @"$S22big_types_corner_cases3FooC8myMethodyyyAA8MyStructV_SitXEFTc"(%T22big_types_corner_cases3FooC*)
// CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC*
// CHECK: getelementptr inbounds void (i8*, %swift.opaque*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.opaque*, %T22big_types_corner_cases3FooC*)**
// CHECK: call noalias %swift.refcounted* @swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata*
// CHECK: ret { i8*, %swift.refcounted* }
public enum LargeEnum {
public enum InnerEnum {
case simple(Int64)
case hard(Int64, String?, Int64)
}
case Empty1
case Empty2
case Full(InnerEnum)
}
public func enumCallee(_ x: LargeEnum) {
switch x {
case .Full(let inner): print(inner)
case .Empty1: break
case .Empty2: break
}
}
// CHECK-LABEL-64: define{{( protected)?}} swiftcc void @"$S22big_types_corner_cases10enumCalleeyAA9LargeEnumOF"(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable({{.*}})) #0 {
// CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O
// CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO
// CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64
// CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64
// CHECK-64: $Ss5print_9separator10terminatoryypd_S2StF
// CHECK-64: ret void
// CHECK-LABEL: define{{( protected)?}} internal swiftcc void @"$S22big_types_corner_cases8SuperSubC1fyyFAA9BigStructVycfU_"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret, %T22big_types_corner_cases8SuperSubC*)
// CHECK-64: [[ALLOC1:%.*]] = alloca %T22big_types_corner_cases9BigStructV
// CHECK-64: [[ALLOC2:%.*]] = alloca %T22big_types_corner_cases9BigStructV
// CHECK-64: [[ALLOC3:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK-64: call swiftcc void @"$S22big_types_corner_cases9SuperBaseC4boomAA9BigStructVyF"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret [[ALLOC1]], %T22big_types_corner_cases9SuperBaseC* swiftself {{.*}})
// CHECK: ret void
class SuperBase {
func boom() -> BigStruct {
return BigStruct()
}
}
class SuperSub : SuperBase {
override func boom() -> BigStruct {
return BigStruct()
}
func f() {
let _ = {
nil ?? super.boom()
}
}
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S22big_types_corner_cases10MUseStructV16superclassMirrorAA03BigF0VSgvg"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret, %T22big_types_corner_cases10MUseStructV* noalias nocapture swiftself dereferenceable({{.*}}))
// CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK: [[LOAD:%.*]] = load %swift.refcounted*, %swift.refcounted** %.callInternalLet.data
// CHECK: call swiftcc void %7(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.refcounted* swiftself [[LOAD]])
// CHECK: ret void
public struct MUseStruct {
var x = BigStruct()
public var superclassMirror: BigStruct? {
return callInternalLet()
}
internal let callInternalLet: () -> BigStruct?
}
// CHECK-LABEL-64: define{{( protected)?}} swiftcc void @"$S22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, %Ts9SubstringV }>* noalias nocapture sret) #0 {
// CHECK-LABEL-32: define{{( protected)?}} swiftcc void @"$S22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, [4 x i8], %Ts9SubstringV }>* noalias nocapture sret) #0 {
// CHECK: alloca %Ts9SubstringV
// CHECK: alloca %Ts9SubstringV
// CHECK: ret void
public func stringAndSubstring() -> (String, Substring) {
let s = "Hello, World"
let a = Substring(s).dropFirst()
return (s, a)
}
func bigStructGet() -> BigStruct {
return BigStruct()
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S22big_types_corner_cases11testGetFuncyyF"()
// CHECK: ret void
public func testGetFunc() {
let testGetPtr: @convention(thin) () -> BigStruct = bigStructGet
}
// CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @"$S22big_types_corner_cases7TestBigC4testyyF"(%T22big_types_corner_cases7TestBigC* swiftself)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$SSayy22big_types_corner_cases9BigStructVcSgGMa"
// CHECK: [[CALL1:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[CALL2:%.*]] = call i8** @"$SSayy22big_types_corner_cases9BigStructVcSgGSayxGs10CollectionsWl
// CHECK: call swiftcc void @"$Ss10CollectionPsE5index5where5IndexQzSgSb7ElementQzKXE_tKF"(%TSq.{{.*}}* noalias nocapture sret {{.*}}, i8* bitcast (i1 (%T22big_types_corner_cases9BigStructVytIegnr_Sg*, %swift.refcounted*, %swift.error**)* @"$S22big_types_corner_cases9BigStructVIegy_SgSbs5Error_pIggdzo_ACytIegnr_SgSbsAE_pIegndzo_TRTA" to i8*), %swift.opaque* {{.*}}, %swift.type* [[CALL1]], i8** [[CALL2]], %swift.opaque* noalias nocapture swiftself
// CHECK: ret void
// CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @"$S22big_types_corner_cases7TestBigC5test2yyF"(%T22big_types_corner_cases7TestBigC* swiftself)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$SSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGMa"
// CHECK: [[CALL1:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[CALL2:%.*]] = call i8** @"$SSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGSayxGs10CollectionsWl"
// CHECK: call swiftcc void @"$Ss10CollectionPss16IndexingIteratorVyxG0C0RtzrlE04makeC0AEyF"(%Ts16IndexingIteratorV* noalias nocapture sret {{.*}}, %swift.type* [[CALL1]], i8** [[CALL2]], %swift.opaque* noalias nocapture swiftself {{.*}})
// CHECK: ret void
class TestBig {
typealias Handler = (BigStruct) -> Void
func test() {
let arr = [Handler?]()
let d = arr.index(where: { _ in true })
}
func test2() {
let arr: [(ID: String, handler: Handler?)] = []
for (_, handler) in arr {
takeClosure {
handler?(BigStruct())
}
}
}
}
struct BigStructWithFunc {
var incSize : BigStruct
var foo: ((BigStruct) -> Void)?
}
// CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @"$S22big_types_corner_cases20UseBigStructWithFuncC5crashyyF"(%T22big_types_corner_cases20UseBigStructWithFuncC* swiftself)
// CHECK: call swiftcc void @"$S22big_types_corner_cases20UseBigStructWithFuncC10callMethod
// CHECK: ret void
class UseBigStructWithFunc {
var optBigStructWithFunc: BigStructWithFunc?
func crash() {
guard let bigStr = optBigStructWithFunc else { return }
callMethod(ptr: bigStr.foo)
}
private func callMethod(ptr: ((BigStruct) -> Void)?) -> () {
}
}
| apache-2.0 | bee32b133a9ecff27f6116cc64066008 | 42.953125 | 450 | 0.702986 | 3.368862 | false | false | false | false |
hsoi/RxSwift | RxCocoa/iOS/Proxies/RxActionSheetDelegateProxy.swift | 2 | 914 | //
// RxActionSheetDelegateProxy.swift
// RxCocoa
//
// Created by Carlos García on 8/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
@available(*, deprecated=2.0.0, message="This class is deprecated by Apple. Removing official support.")
class RxActionSheetDelegateProxy : DelegateProxy
, UIActionSheetDelegate
, DelegateProxyType {
class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let actionSheet: UIActionSheet = castOrFatalError(object)
return actionSheet.delegate
}
class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let actionSheet: UIActionSheet = castOrFatalError(object)
actionSheet.delegate = castOptionalOrFatalError(delegate)
}
}
#endif
| mit | e887a285bfeb11cce03dafb092473742 | 27.5 | 104 | 0.675439 | 4.956522 | false | false | false | false |
maoyi16/Eight-Ball-Game | Eight Ball Pool Game/MenuScene.swift | 1 | 2050 | //
// MenuScene.swift
// Eight Ball Pool Game
//
// Created by 毛易 on 2/12/17.
// Copyright © 2017 Yi Mao. All rights reserved.
//
import SpriteKit
import GameplayKit
class MenuScene: SKScene {
var pvpLabel: SKLabelNode!
var pveLabel: SKLabelNode!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// super.touchesBegan(touches, with: event)
if let location = touches.first?.location(in: self) {
let touchedNode = atPoint(location)
if touchedNode.name == "PVP" || touchedNode.name == "PVE" || touchedNode.name == "EVE" {
// MARK: Go to PoolScene
// Load 'PoolScene.sks' as a GKScene. This provides gameplay related content
// including entities and graphs.
if let scene = GKScene(fileNamed: "PoolScene") {
// Get the SKScene from the loaded GKScene
if let sceneNode = scene.rootNode as! PoolScene? {
sceneNode.mode = touchedNode.name == "PVP" ? .PVP : touchedNode.name == "PVE" ? .PVE : .EVE
// Set the scale mode to scale to fit the window
sceneNode.scaleMode = .aspectFill
// Present the scene
if let view = self.view {
let transition = SKTransition.reveal(with: .down, duration: 1.0)
view.presentScene(sceneNode, transition: transition)
// view.ignoresSiblingOrder = true
view.showsFPS = false
view.showsPhysics = false
view.showsNodeCount = false
}
}
}
}
}
}
override func didMove(to view: SKView) {
pveLabel = childNode(withName: "PVP") as! SKLabelNode!
}
}
| mit | d2ee5a9c1bc0acef0bd46ce457aa550c | 36.181818 | 115 | 0.494866 | 5.036946 | false | false | false | false |
YPaul/YXToolFile | YXToolFile/toolFile/YXSearchBar.swift | 1 | 1753 | //
// YXSearchBar.swift
// XY微博
//
// Created by paul-y on 16/1/6.
// Copyright © 2016年 YX. All rights reserved.
//--创建一个搜索框API--
//MARK:
//MARK:--使用指导--
/*
let searchItem = YXSearchBar()// 创建
searchItem.placeholder = "大家都在搜:"//设置placeholder,如果有的话
searchItem.leftImage = UIImage(named: "searchbar_second_textfield_search_icon")//设置搜索框左边的图片,如果有的话
//调用方法,传入合适的参数,返回合适的搜索框
self.navigationItem.titleView = searchItem.searchBarWith(width: (UIScreen.mainScreen().bounds.size.width - 20), height: 32, bgImageNormal: "search_navigationbar_textfield_background", bgImageHighlighted: nil)
*/
//MARK:
import Foundation
import UIKit
class YXSearchBar: UITextField {
var leftImage : UIImage?
override init(frame: CGRect) {
super.init(frame: frame)
self.leftViewMode = .Always
self.font = UIFont.systemFontOfSize(15)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func searchBarWith(width awidth:CGFloat,height:CGFloat?,bgImageNormal:String?,bgImageHighlighted:String?)->UITextField{
let bgImageNor = UIImage(named: bgImageNormal!)
// let bgImageHigh = UIImage(named: bgImageHighlighted!)
self.background = bgImageNor
self.width = awidth
self.height = height!
if leftImage !== nil {
let imageview = UIImageView(image: leftImage)
imageview.width = height!
imageview.height = height!
imageview.x = 10
imageview.contentMode = .Center
self.leftView = imageview
}
return self
}
} | apache-2.0 | 333fcc3731dd4bcf19a187b3d0b26183 | 27.403509 | 208 | 0.666873 | 3.917676 | false | false | false | false |
pfvernon2/swiftlets | iOSX/iOS/UIViewController+Utilities.swift | 1 | 2241 | //
// File.swift
// swiftlets
//
// Created by Frank Vernon on 5/20/16.
// Copyright © 2016 Frank Vernon. All rights reserved.
//
import UIKit
public extension UIViewController {
class func topViewControllerForRoot(_ rootViewController:UIViewController?) -> UIViewController? {
guard let rootViewController = rootViewController else {
return nil
}
guard let presented = rootViewController.presentedViewController else {
return rootViewController
}
switch presented {
case is UINavigationController:
let navigationController:UINavigationController = presented as! UINavigationController
return UIViewController.topViewControllerForRoot(navigationController.viewControllers.last)
case is UITabBarController:
let tabBarController:UITabBarController = presented as! UITabBarController
return UIViewController.topViewControllerForRoot(tabBarController.selectedViewController)
default:
return UIViewController.topViewControllerForRoot(presented)
}
}
func move(to screen: UIScreen, retry: Int = 2, completion: @escaping (UIWindow?) -> Swift.Void) {
guard let windowScene = UIApplication.shared.sceneForScreen(screen) else {
if retry > 0 {
DispatchQueue.main.asyncAfter(secondsFromNow: 1.0) {
self.move(to :screen, retry: retry - 1, completion: completion)
}
} else {
completion(nil)
}
return
}
let displayWindow = { () -> UIWindow in
let window = UIWindow(frame: screen.bounds)
window.rootViewController = self
window.windowScene = windowScene
window.isHidden = false
window.makeKeyAndVisible()
return window
}()
completion(displayWindow)
}
class func loadVC(vcName: String, fromStoryboard sbName: String) -> UIViewController {
let storyboard = UIStoryboard(name: sbName, bundle: nil)
return storyboard.instantiateViewController(identifier: vcName)
}
}
| apache-2.0 | 6ac06d4e3e20463f7bb7ca21571eaf8d | 34.555556 | 103 | 0.629464 | 5.879265 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/ServerlessApplicationRepository/ServerlessApplicationRepository_Shapes.swift | 1 | 44881 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension ServerlessApplicationRepository {
// MARK: Enums
public enum Capability: String, CustomStringConvertible, Codable {
case capabilityAutoExpand = "CAPABILITY_AUTO_EXPAND"
case capabilityIam = "CAPABILITY_IAM"
case capabilityNamedIam = "CAPABILITY_NAMED_IAM"
case capabilityResourcePolicy = "CAPABILITY_RESOURCE_POLICY"
public var description: String { return self.rawValue }
}
public enum Status: String, CustomStringConvertible, Codable {
case active = "ACTIVE"
case expired = "EXPIRED"
case preparing = "PREPARING"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct ApplicationDependencySummary: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the nested application.
public let applicationId: String
/// The semantic version of the nested application.
public let semanticVersion: String
public init(applicationId: String, semanticVersion: String) {
self.applicationId = applicationId
self.semanticVersion = semanticVersion
}
private enum CodingKeys: String, CodingKey {
case applicationId
case semanticVersion
}
}
public struct ApplicationPolicyStatement: AWSEncodableShape & AWSDecodableShape {
/// For the list of actions supported for this operation, see Application
/// Permissions.
public let actions: [String]
/// An array of PrinciplalOrgIDs, which corresponds to AWS IAM aws:PrincipalOrgID global condition key.
public let principalOrgIDs: [String]?
/// An array of AWS account IDs, or * to make the application public.
public let principals: [String]
/// A unique ID for the statement.
public let statementId: String?
public init(actions: [String], principalOrgIDs: [String]? = nil, principals: [String], statementId: String? = nil) {
self.actions = actions
self.principalOrgIDs = principalOrgIDs
self.principals = principals
self.statementId = statementId
}
private enum CodingKeys: String, CodingKey {
case actions
case principalOrgIDs
case principals
case statementId
}
}
public struct ApplicationSummary: AWSDecodableShape {
/// The application Amazon Resource Name (ARN).
public let applicationId: String
/// The name of the author publishing the app.Minimum length=1. Maximum length=127.Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
public let author: String
/// The date and time this resource was created.
public let creationTime: String?
/// The description of the application.Minimum length=1. Maximum length=256
public let description: String
/// A URL with more information about the application, for example the location of your GitHub repository for the application.
public let homePageUrl: String?
/// Labels to improve discovery of apps in search results.Minimum length=1. Maximum length=127. Maximum number of labels: 10Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
public let labels: [String]?
/// The name of the application.Minimum length=1. Maximum length=140Pattern: "[a-zA-Z0-9\\-]+";
public let name: String
/// A valid identifier from https://spdx.org/licenses/.
public let spdxLicenseId: String?
public init(applicationId: String, author: String, creationTime: String? = nil, description: String, homePageUrl: String? = nil, labels: [String]? = nil, name: String, spdxLicenseId: String? = nil) {
self.applicationId = applicationId
self.author = author
self.creationTime = creationTime
self.description = description
self.homePageUrl = homePageUrl
self.labels = labels
self.name = name
self.spdxLicenseId = spdxLicenseId
}
private enum CodingKeys: String, CodingKey {
case applicationId
case author
case creationTime
case description
case homePageUrl
case labels
case name
case spdxLicenseId
}
}
public struct CreateApplicationRequest: AWSEncodableShape {
public let author: String
public let description: String
public let homePageUrl: String?
public let labels: [String]?
public let licenseBody: String?
public let licenseUrl: String?
public let name: String
public let readmeBody: String?
public let readmeUrl: String?
public let semanticVersion: String?
public let sourceCodeArchiveUrl: String?
public let sourceCodeUrl: String?
public let spdxLicenseId: String?
public let templateBody: String?
public let templateUrl: String?
public init(author: String, description: String, homePageUrl: String? = nil, labels: [String]? = nil, licenseBody: String? = nil, licenseUrl: String? = nil, name: String, readmeBody: String? = nil, readmeUrl: String? = nil, semanticVersion: String? = nil, sourceCodeArchiveUrl: String? = nil, sourceCodeUrl: String? = nil, spdxLicenseId: String? = nil, templateBody: String? = nil, templateUrl: String? = nil) {
self.author = author
self.description = description
self.homePageUrl = homePageUrl
self.labels = labels
self.licenseBody = licenseBody
self.licenseUrl = licenseUrl
self.name = name
self.readmeBody = readmeBody
self.readmeUrl = readmeUrl
self.semanticVersion = semanticVersion
self.sourceCodeArchiveUrl = sourceCodeArchiveUrl
self.sourceCodeUrl = sourceCodeUrl
self.spdxLicenseId = spdxLicenseId
self.templateBody = templateBody
self.templateUrl = templateUrl
}
private enum CodingKeys: String, CodingKey {
case author
case description
case homePageUrl
case labels
case licenseBody
case licenseUrl
case name
case readmeBody
case readmeUrl
case semanticVersion
case sourceCodeArchiveUrl
case sourceCodeUrl
case spdxLicenseId
case templateBody
case templateUrl
}
}
public struct CreateApplicationResponse: AWSDecodableShape {
public let applicationId: String?
public let author: String?
public let creationTime: String?
public let description: String?
public let homePageUrl: String?
public let isVerifiedAuthor: Bool?
public let labels: [String]?
public let licenseUrl: String?
public let name: String?
public let readmeUrl: String?
public let spdxLicenseId: String?
public let verifiedAuthorUrl: String?
public let version: Version?
public init(applicationId: String? = nil, author: String? = nil, creationTime: String? = nil, description: String? = nil, homePageUrl: String? = nil, isVerifiedAuthor: Bool? = nil, labels: [String]? = nil, licenseUrl: String? = nil, name: String? = nil, readmeUrl: String? = nil, spdxLicenseId: String? = nil, verifiedAuthorUrl: String? = nil, version: Version? = nil) {
self.applicationId = applicationId
self.author = author
self.creationTime = creationTime
self.description = description
self.homePageUrl = homePageUrl
self.isVerifiedAuthor = isVerifiedAuthor
self.labels = labels
self.licenseUrl = licenseUrl
self.name = name
self.readmeUrl = readmeUrl
self.spdxLicenseId = spdxLicenseId
self.verifiedAuthorUrl = verifiedAuthorUrl
self.version = version
}
private enum CodingKeys: String, CodingKey {
case applicationId
case author
case creationTime
case description
case homePageUrl
case isVerifiedAuthor
case labels
case licenseUrl
case name
case readmeUrl
case spdxLicenseId
case verifiedAuthorUrl
case version
}
}
public struct CreateApplicationVersionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId")),
AWSMemberEncoding(label: "semanticVersion", location: .uri(locationName: "semanticVersion"))
]
public let applicationId: String
public let semanticVersion: String
public let sourceCodeArchiveUrl: String?
public let sourceCodeUrl: String?
public let templateBody: String?
public let templateUrl: String?
public init(applicationId: String, semanticVersion: String, sourceCodeArchiveUrl: String? = nil, sourceCodeUrl: String? = nil, templateBody: String? = nil, templateUrl: String? = nil) {
self.applicationId = applicationId
self.semanticVersion = semanticVersion
self.sourceCodeArchiveUrl = sourceCodeArchiveUrl
self.sourceCodeUrl = sourceCodeUrl
self.templateBody = templateBody
self.templateUrl = templateUrl
}
private enum CodingKeys: String, CodingKey {
case sourceCodeArchiveUrl
case sourceCodeUrl
case templateBody
case templateUrl
}
}
public struct CreateApplicationVersionResponse: AWSDecodableShape {
public let applicationId: String?
public let creationTime: String?
public let parameterDefinitions: [ParameterDefinition]?
public let requiredCapabilities: [Capability]?
public let resourcesSupported: Bool?
public let semanticVersion: String?
public let sourceCodeArchiveUrl: String?
public let sourceCodeUrl: String?
public let templateUrl: String?
public init(applicationId: String? = nil, creationTime: String? = nil, parameterDefinitions: [ParameterDefinition]? = nil, requiredCapabilities: [Capability]? = nil, resourcesSupported: Bool? = nil, semanticVersion: String? = nil, sourceCodeArchiveUrl: String? = nil, sourceCodeUrl: String? = nil, templateUrl: String? = nil) {
self.applicationId = applicationId
self.creationTime = creationTime
self.parameterDefinitions = parameterDefinitions
self.requiredCapabilities = requiredCapabilities
self.resourcesSupported = resourcesSupported
self.semanticVersion = semanticVersion
self.sourceCodeArchiveUrl = sourceCodeArchiveUrl
self.sourceCodeUrl = sourceCodeUrl
self.templateUrl = templateUrl
}
private enum CodingKeys: String, CodingKey {
case applicationId
case creationTime
case parameterDefinitions
case requiredCapabilities
case resourcesSupported
case semanticVersion
case sourceCodeArchiveUrl
case sourceCodeUrl
case templateUrl
}
}
public struct CreateCloudFormationChangeSetRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId"))
]
public let applicationId: String
public let capabilities: [String]?
public let changeSetName: String?
public let clientToken: String?
public let description: String?
public let notificationArns: [String]?
public let parameterOverrides: [ParameterValue]?
public let resourceTypes: [String]?
public let rollbackConfiguration: RollbackConfiguration?
public let semanticVersion: String?
public let stackName: String
public let tags: [Tag]?
public let templateId: String?
public init(applicationId: String, capabilities: [String]? = nil, changeSetName: String? = nil, clientToken: String? = nil, description: String? = nil, notificationArns: [String]? = nil, parameterOverrides: [ParameterValue]? = nil, resourceTypes: [String]? = nil, rollbackConfiguration: RollbackConfiguration? = nil, semanticVersion: String? = nil, stackName: String, tags: [Tag]? = nil, templateId: String? = nil) {
self.applicationId = applicationId
self.capabilities = capabilities
self.changeSetName = changeSetName
self.clientToken = clientToken
self.description = description
self.notificationArns = notificationArns
self.parameterOverrides = parameterOverrides
self.resourceTypes = resourceTypes
self.rollbackConfiguration = rollbackConfiguration
self.semanticVersion = semanticVersion
self.stackName = stackName
self.tags = tags
self.templateId = templateId
}
private enum CodingKeys: String, CodingKey {
case capabilities
case changeSetName
case clientToken
case description
case notificationArns
case parameterOverrides
case resourceTypes
case rollbackConfiguration
case semanticVersion
case stackName
case tags
case templateId
}
}
public struct CreateCloudFormationChangeSetResponse: AWSDecodableShape {
public let applicationId: String?
public let changeSetId: String?
public let semanticVersion: String?
public let stackId: String?
public init(applicationId: String? = nil, changeSetId: String? = nil, semanticVersion: String? = nil, stackId: String? = nil) {
self.applicationId = applicationId
self.changeSetId = changeSetId
self.semanticVersion = semanticVersion
self.stackId = stackId
}
private enum CodingKeys: String, CodingKey {
case applicationId
case changeSetId
case semanticVersion
case stackId
}
}
public struct CreateCloudFormationTemplateRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId"))
]
public let applicationId: String
public let semanticVersion: String?
public init(applicationId: String, semanticVersion: String? = nil) {
self.applicationId = applicationId
self.semanticVersion = semanticVersion
}
private enum CodingKeys: String, CodingKey {
case semanticVersion
}
}
public struct CreateCloudFormationTemplateResponse: AWSDecodableShape {
public let applicationId: String?
public let creationTime: String?
public let expirationTime: String?
public let semanticVersion: String?
public let status: Status?
public let templateId: String?
public let templateUrl: String?
public init(applicationId: String? = nil, creationTime: String? = nil, expirationTime: String? = nil, semanticVersion: String? = nil, status: Status? = nil, templateId: String? = nil, templateUrl: String? = nil) {
self.applicationId = applicationId
self.creationTime = creationTime
self.expirationTime = expirationTime
self.semanticVersion = semanticVersion
self.status = status
self.templateId = templateId
self.templateUrl = templateUrl
}
private enum CodingKeys: String, CodingKey {
case applicationId
case creationTime
case expirationTime
case semanticVersion
case status
case templateId
case templateUrl
}
}
public struct DeleteApplicationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId"))
]
public let applicationId: String
public init(applicationId: String) {
self.applicationId = applicationId
}
private enum CodingKeys: CodingKey {}
}
public struct GetApplicationPolicyRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId"))
]
public let applicationId: String
public init(applicationId: String) {
self.applicationId = applicationId
}
private enum CodingKeys: CodingKey {}
}
public struct GetApplicationPolicyResponse: AWSDecodableShape {
public let statements: [ApplicationPolicyStatement]?
public init(statements: [ApplicationPolicyStatement]? = nil) {
self.statements = statements
}
private enum CodingKeys: String, CodingKey {
case statements
}
}
public struct GetApplicationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId")),
AWSMemberEncoding(label: "semanticVersion", location: .querystring(locationName: "semanticVersion"))
]
public let applicationId: String
public let semanticVersion: String?
public init(applicationId: String, semanticVersion: String? = nil) {
self.applicationId = applicationId
self.semanticVersion = semanticVersion
}
private enum CodingKeys: CodingKey {}
}
public struct GetApplicationResponse: AWSDecodableShape {
public let applicationId: String?
public let author: String?
public let creationTime: String?
public let description: String?
public let homePageUrl: String?
public let isVerifiedAuthor: Bool?
public let labels: [String]?
public let licenseUrl: String?
public let name: String?
public let readmeUrl: String?
public let spdxLicenseId: String?
public let verifiedAuthorUrl: String?
public let version: Version?
public init(applicationId: String? = nil, author: String? = nil, creationTime: String? = nil, description: String? = nil, homePageUrl: String? = nil, isVerifiedAuthor: Bool? = nil, labels: [String]? = nil, licenseUrl: String? = nil, name: String? = nil, readmeUrl: String? = nil, spdxLicenseId: String? = nil, verifiedAuthorUrl: String? = nil, version: Version? = nil) {
self.applicationId = applicationId
self.author = author
self.creationTime = creationTime
self.description = description
self.homePageUrl = homePageUrl
self.isVerifiedAuthor = isVerifiedAuthor
self.labels = labels
self.licenseUrl = licenseUrl
self.name = name
self.readmeUrl = readmeUrl
self.spdxLicenseId = spdxLicenseId
self.verifiedAuthorUrl = verifiedAuthorUrl
self.version = version
}
private enum CodingKeys: String, CodingKey {
case applicationId
case author
case creationTime
case description
case homePageUrl
case isVerifiedAuthor
case labels
case licenseUrl
case name
case readmeUrl
case spdxLicenseId
case verifiedAuthorUrl
case version
}
}
public struct GetCloudFormationTemplateRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId")),
AWSMemberEncoding(label: "templateId", location: .uri(locationName: "templateId"))
]
public let applicationId: String
public let templateId: String
public init(applicationId: String, templateId: String) {
self.applicationId = applicationId
self.templateId = templateId
}
private enum CodingKeys: CodingKey {}
}
public struct GetCloudFormationTemplateResponse: AWSDecodableShape {
public let applicationId: String?
public let creationTime: String?
public let expirationTime: String?
public let semanticVersion: String?
public let status: Status?
public let templateId: String?
public let templateUrl: String?
public init(applicationId: String? = nil, creationTime: String? = nil, expirationTime: String? = nil, semanticVersion: String? = nil, status: Status? = nil, templateId: String? = nil, templateUrl: String? = nil) {
self.applicationId = applicationId
self.creationTime = creationTime
self.expirationTime = expirationTime
self.semanticVersion = semanticVersion
self.status = status
self.templateId = templateId
self.templateUrl = templateUrl
}
private enum CodingKeys: String, CodingKey {
case applicationId
case creationTime
case expirationTime
case semanticVersion
case status
case templateId
case templateUrl
}
}
public struct ListApplicationDependenciesRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "maxItems")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")),
AWSMemberEncoding(label: "semanticVersion", location: .querystring(locationName: "semanticVersion"))
]
public let applicationId: String
public let maxItems: Int?
public let nextToken: String?
public let semanticVersion: String?
public init(applicationId: String, maxItems: Int? = nil, nextToken: String? = nil, semanticVersion: String? = nil) {
self.applicationId = applicationId
self.maxItems = maxItems
self.nextToken = nextToken
self.semanticVersion = semanticVersion
}
public func validate(name: String) throws {
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 100)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListApplicationDependenciesResponse: AWSDecodableShape {
public let dependencies: [ApplicationDependencySummary]?
public let nextToken: String?
public init(dependencies: [ApplicationDependencySummary]? = nil, nextToken: String? = nil) {
self.dependencies = dependencies
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case dependencies
case nextToken
}
}
public struct ListApplicationVersionsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "maxItems")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
public let applicationId: String
public let maxItems: Int?
public let nextToken: String?
public init(applicationId: String, maxItems: Int? = nil, nextToken: String? = nil) {
self.applicationId = applicationId
self.maxItems = maxItems
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 100)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListApplicationVersionsResponse: AWSDecodableShape {
public let nextToken: String?
public let versions: [VersionSummary]?
public init(nextToken: String? = nil, versions: [VersionSummary]? = nil) {
self.nextToken = nextToken
self.versions = versions
}
private enum CodingKeys: String, CodingKey {
case nextToken
case versions
}
}
public struct ListApplicationsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "maxItems")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
public let maxItems: Int?
public let nextToken: String?
public init(maxItems: Int? = nil, nextToken: String? = nil) {
self.maxItems = maxItems
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 100)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListApplicationsResponse: AWSDecodableShape {
public let applications: [ApplicationSummary]?
public let nextToken: String?
public init(applications: [ApplicationSummary]? = nil, nextToken: String? = nil) {
self.applications = applications
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case applications
case nextToken
}
}
public struct ParameterDefinition: AWSDecodableShape {
/// A regular expression that represents the patterns to allow for String types.
public let allowedPattern: String?
/// An array containing the list of values allowed for the parameter.
public let allowedValues: [String]?
/// A string that explains a constraint when the constraint is violated. For example, without a constraint description,
/// a parameter that has an allowed pattern of [A-Za-z0-9]+ displays the following error message when the user
/// specifies an invalid value:
/// Malformed input-Parameter MyParameter must match pattern [A-Za-z0-9]+
/// By adding a constraint description, such as "must contain only uppercase and lowercase letters and numbers," you can display
/// the following customized error message:
/// Malformed input-Parameter MyParameter must contain only uppercase and lowercase letters and numbers.
///
public let constraintDescription: String?
/// A value of the appropriate type for the template to use if no value is specified when a stack is created.
/// If you define constraints for the parameter, you must specify a value that adheres to those constraints.
public let defaultValue: String?
/// A string of up to 4,000 characters that describes the parameter.
public let description: String?
/// An integer value that determines the largest number of characters that you want to allow for String types.
public let maxLength: Int?
/// A numeric value that determines the largest numeric value that you want to allow for Number types.
public let maxValue: Int?
/// An integer value that determines the smallest number of characters that you want to allow for String types.
public let minLength: Int?
/// A numeric value that determines the smallest numeric value that you want to allow for Number types.
public let minValue: Int?
/// The name of the parameter.
public let name: String
/// Whether to mask the parameter value whenever anyone makes a call that describes the stack. If you set the
/// value to true, the parameter value is masked with asterisks (*****).
public let noEcho: Bool?
/// A list of AWS SAM resources that use this parameter.
public let referencedByResources: [String]
/// The type of the parameter.Valid values: String | Number | List<Number> | CommaDelimitedList
///
/// String: A literal string.For example, users can specify "MyUserName".
/// Number: An integer or float. AWS CloudFormation validates the parameter value as a number. However, when you use the
/// parameter elsewhere in your template (for example, by using the Ref intrinsic function), the parameter value becomes a string.For example, users might specify "8888".
/// List<Number>: An array of integers or floats that are separated by commas. AWS CloudFormation validates the parameter value as numbers. However, when
/// you use the parameter elsewhere in your template (for example, by using the Ref intrinsic function), the parameter value becomes a list of strings.For example, users might specify "80,20", and then Ref results in ["80","20"].
/// CommaDelimitedList: An array of literal strings that are separated by commas. The total number of strings should be one more than the total number of commas.
/// Also, each member string is space-trimmed.For example, users might specify "test,dev,prod", and then Ref results in ["test","dev","prod"].
public let type: String?
public init(allowedPattern: String? = nil, allowedValues: [String]? = nil, constraintDescription: String? = nil, defaultValue: String? = nil, description: String? = nil, maxLength: Int? = nil, maxValue: Int? = nil, minLength: Int? = nil, minValue: Int? = nil, name: String, noEcho: Bool? = nil, referencedByResources: [String], type: String? = nil) {
self.allowedPattern = allowedPattern
self.allowedValues = allowedValues
self.constraintDescription = constraintDescription
self.defaultValue = defaultValue
self.description = description
self.maxLength = maxLength
self.maxValue = maxValue
self.minLength = minLength
self.minValue = minValue
self.name = name
self.noEcho = noEcho
self.referencedByResources = referencedByResources
self.type = type
}
private enum CodingKeys: String, CodingKey {
case allowedPattern
case allowedValues
case constraintDescription
case defaultValue
case description
case maxLength
case maxValue
case minLength
case minValue
case name
case noEcho
case referencedByResources
case type
}
}
public struct ParameterValue: AWSEncodableShape {
/// The key associated with the parameter. If you don't specify a key and value for a particular parameter, AWS CloudFormation
/// uses the default value that is specified in your template.
public let name: String
/// The input value associated with the parameter.
public let value: String
public init(name: String, value: String) {
self.name = name
self.value = value
}
private enum CodingKeys: String, CodingKey {
case name
case value
}
}
public struct PutApplicationPolicyRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId"))
]
public let applicationId: String
public let statements: [ApplicationPolicyStatement]
public init(applicationId: String, statements: [ApplicationPolicyStatement]) {
self.applicationId = applicationId
self.statements = statements
}
private enum CodingKeys: String, CodingKey {
case statements
}
}
public struct PutApplicationPolicyResponse: AWSDecodableShape {
public let statements: [ApplicationPolicyStatement]?
public init(statements: [ApplicationPolicyStatement]? = nil) {
self.statements = statements
}
private enum CodingKeys: String, CodingKey {
case statements
}
}
public struct RollbackConfiguration: AWSEncodableShape {
/// This property corresponds to the content of the same name for the AWS CloudFormation RollbackConfiguration
/// Data Type.
public let monitoringTimeInMinutes: Int?
/// This property corresponds to the content of the same name for the AWS CloudFormation RollbackConfiguration
/// Data Type.
public let rollbackTriggers: [RollbackTrigger]?
public init(monitoringTimeInMinutes: Int? = nil, rollbackTriggers: [RollbackTrigger]? = nil) {
self.monitoringTimeInMinutes = monitoringTimeInMinutes
self.rollbackTriggers = rollbackTriggers
}
private enum CodingKeys: String, CodingKey {
case monitoringTimeInMinutes
case rollbackTriggers
}
}
public struct RollbackTrigger: AWSEncodableShape {
/// This property corresponds to the content of the same name for the AWS CloudFormation RollbackTrigger
/// Data Type.
public let arn: String
/// This property corresponds to the content of the same name for the AWS CloudFormation RollbackTrigger
/// Data Type.
public let type: String
public init(arn: String, type: String) {
self.arn = arn
self.type = type
}
private enum CodingKeys: String, CodingKey {
case arn
case type
}
}
public struct Tag: AWSEncodableShape {
/// This property corresponds to the content of the same name for the AWS CloudFormation Tag
/// Data Type.
public let key: String
/// This property corresponds to the content of the same name for the AWS CloudFormation
/// Tag
///
/// Data Type.
public let value: String
public init(key: String, value: String) {
self.key = key
self.value = value
}
private enum CodingKeys: String, CodingKey {
case key
case value
}
}
public struct UnshareApplicationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId"))
]
public let applicationId: String
public let organizationId: String
public init(applicationId: String, organizationId: String) {
self.applicationId = applicationId
self.organizationId = organizationId
}
private enum CodingKeys: String, CodingKey {
case organizationId
}
}
public struct UpdateApplicationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "applicationId", location: .uri(locationName: "applicationId"))
]
public let applicationId: String
public let author: String?
public let description: String?
public let homePageUrl: String?
public let labels: [String]?
public let readmeBody: String?
public let readmeUrl: String?
public init(applicationId: String, author: String? = nil, description: String? = nil, homePageUrl: String? = nil, labels: [String]? = nil, readmeBody: String? = nil, readmeUrl: String? = nil) {
self.applicationId = applicationId
self.author = author
self.description = description
self.homePageUrl = homePageUrl
self.labels = labels
self.readmeBody = readmeBody
self.readmeUrl = readmeUrl
}
private enum CodingKeys: String, CodingKey {
case author
case description
case homePageUrl
case labels
case readmeBody
case readmeUrl
}
}
public struct UpdateApplicationResponse: AWSDecodableShape {
public let applicationId: String?
public let author: String?
public let creationTime: String?
public let description: String?
public let homePageUrl: String?
public let isVerifiedAuthor: Bool?
public let labels: [String]?
public let licenseUrl: String?
public let name: String?
public let readmeUrl: String?
public let spdxLicenseId: String?
public let verifiedAuthorUrl: String?
public let version: Version?
public init(applicationId: String? = nil, author: String? = nil, creationTime: String? = nil, description: String? = nil, homePageUrl: String? = nil, isVerifiedAuthor: Bool? = nil, labels: [String]? = nil, licenseUrl: String? = nil, name: String? = nil, readmeUrl: String? = nil, spdxLicenseId: String? = nil, verifiedAuthorUrl: String? = nil, version: Version? = nil) {
self.applicationId = applicationId
self.author = author
self.creationTime = creationTime
self.description = description
self.homePageUrl = homePageUrl
self.isVerifiedAuthor = isVerifiedAuthor
self.labels = labels
self.licenseUrl = licenseUrl
self.name = name
self.readmeUrl = readmeUrl
self.spdxLicenseId = spdxLicenseId
self.verifiedAuthorUrl = verifiedAuthorUrl
self.version = version
}
private enum CodingKeys: String, CodingKey {
case applicationId
case author
case creationTime
case description
case homePageUrl
case isVerifiedAuthor
case labels
case licenseUrl
case name
case readmeUrl
case spdxLicenseId
case verifiedAuthorUrl
case version
}
}
public struct Version: AWSDecodableShape {
/// The application Amazon Resource Name (ARN).
public let applicationId: String
/// The date and time this resource was created.
public let creationTime: String
/// An array of parameter types supported by the application.
public let parameterDefinitions: [ParameterDefinition]
/// A list of values that you must specify before you can deploy certain applications.
/// Some applications might include resources that can affect permissions in your AWS
/// account, for example, by creating new AWS Identity and Access Management (IAM) users.
/// For those applications, you must explicitly acknowledge their capabilities by
/// specifying this parameter.The only valid values are CAPABILITY_IAM, CAPABILITY_NAMED_IAM,
/// CAPABILITY_RESOURCE_POLICY, and CAPABILITY_AUTO_EXPAND.The following resources require you to specify CAPABILITY_IAM or
/// CAPABILITY_NAMED_IAM:
/// AWS::IAM::Group,
/// AWS::IAM::InstanceProfile,
/// AWS::IAM::Policy, and
/// AWS::IAM::Role.
/// If the application contains IAM resources, you can specify either CAPABILITY_IAM
/// or CAPABILITY_NAMED_IAM. If the application contains IAM resources
/// with custom names, you must specify CAPABILITY_NAMED_IAM.The following resources require you to specify CAPABILITY_RESOURCE_POLICY:
/// AWS::Lambda::Permission,
/// AWS::IAM:Policy,
/// AWS::ApplicationAutoScaling::ScalingPolicy,
/// AWS::S3::BucketPolicy,
/// AWS::SQS::QueuePolicy, and
/// AWS::SNS::TopicPolicy.Applications that contain one or more nested applications require you to specify
/// CAPABILITY_AUTO_EXPAND.If your application template contains any of the above resources, we recommend that you review
/// all permissions associated with the application before deploying. If you don't specify
/// this parameter for an application that requires capabilities, the call will fail.
public let requiredCapabilities: [Capability]
/// Whether all of the AWS resources contained in this application are supported in the region
/// in which it is being retrieved.
public let resourcesSupported: Bool
/// The semantic version of the application:
/// https://semver.org/
///
public let semanticVersion: String
/// A link to the S3 object that contains the ZIP archive of the source code for this version of your application.Maximum size 50 MB
public let sourceCodeArchiveUrl: String?
/// A link to a public repository for the source code of your application, for example the URL of a specific GitHub commit.
public let sourceCodeUrl: String?
/// A link to the packaged AWS SAM template of your application.
public let templateUrl: String
public init(applicationId: String, creationTime: String, parameterDefinitions: [ParameterDefinition], requiredCapabilities: [Capability], resourcesSupported: Bool, semanticVersion: String, sourceCodeArchiveUrl: String? = nil, sourceCodeUrl: String? = nil, templateUrl: String) {
self.applicationId = applicationId
self.creationTime = creationTime
self.parameterDefinitions = parameterDefinitions
self.requiredCapabilities = requiredCapabilities
self.resourcesSupported = resourcesSupported
self.semanticVersion = semanticVersion
self.sourceCodeArchiveUrl = sourceCodeArchiveUrl
self.sourceCodeUrl = sourceCodeUrl
self.templateUrl = templateUrl
}
private enum CodingKeys: String, CodingKey {
case applicationId
case creationTime
case parameterDefinitions
case requiredCapabilities
case resourcesSupported
case semanticVersion
case sourceCodeArchiveUrl
case sourceCodeUrl
case templateUrl
}
}
public struct VersionSummary: AWSDecodableShape {
/// The application Amazon Resource Name (ARN).
public let applicationId: String
/// The date and time this resource was created.
public let creationTime: String
/// The semantic version of the application:
/// https://semver.org/
///
public let semanticVersion: String
/// A link to a public repository for the source code of your application, for example the URL of a specific GitHub commit.
public let sourceCodeUrl: String?
public init(applicationId: String, creationTime: String, semanticVersion: String, sourceCodeUrl: String? = nil) {
self.applicationId = applicationId
self.creationTime = creationTime
self.semanticVersion = semanticVersion
self.sourceCodeUrl = sourceCodeUrl
}
private enum CodingKeys: String, CodingKey {
case applicationId
case creationTime
case semanticVersion
case sourceCodeUrl
}
}
}
| apache-2.0 | 7e192b92ca15d4f17c0dc9364fefb7e5 | 41.181391 | 424 | 0.6386 | 5.283847 | false | false | false | false |
dpricha89/DrApp | Source/TableCells/IconCell.swift | 1 | 1199 | //
// IconCell.swift
// Venga
//
// Created by David Richards on 6/26/17.
// Copyright © 2017 David Richards. All rights reserved.
//
import UIKit
import SnapKit
open class IconCell: UICollectionViewCell {
var collectionImageView = UIImageView()
var collectionImageTitle = UILabel()
open override func layoutSubviews() {
super.layoutSubviews()
// Setup the image icon size
self.contentView.addSubview(self.collectionImageView)
collectionImageView.snp.makeConstraints { (make) -> Void in
make.center.equalTo(self.contentView)
make.height.equalTo(30)
make.width.equalTo(30)
}
// Setup the icon label right below the image
self.collectionImageTitle.font = .systemFont(ofSize: 12)
self.collectionImageTitle.textAlignment = .center
self.collectionImageTitle.textColor = .white
self.contentView.addSubview(self.collectionImageTitle)
self.collectionImageTitle.snp.makeConstraints { (make) -> Void in
make.centerX.equalTo(self.contentView)
make.top.equalTo(self.collectionImageView.snp.bottom)
}
}
}
| apache-2.0 | 8ae5e695f3d6e58f580e63ff83d40ab2 | 30.526316 | 73 | 0.659432 | 4.607692 | false | false | false | false |
whipsterCZ/WeatherTest | WeatherTest/Classes/Models/Settings.swift | 1 | 5122 | //
// Settings.swift
// WeatherTest
//
// Created by Daniel Kouba on 14/02/15.
// Copyright (c) 2015 Daniel Kouba. All rights reserved.
//
import Foundation
import UIKit
enum LengthUnit: String {
case Metric = "Metric"
case Imperial = "Imperial"
}
enum TempreatureUnit: String {
case Celsius = "Celsius"
case Fahrenheit = "Fahrenheit"
}
enum SettingOptions: String
{
case LengthUnit = "Unit of length"
case TempreatureUnit = "Unit of tempreature"
}
class Settings: NSObject, UITableViewDataSource, UITableViewDelegate
{
var tempreatureUnit:TempreatureUnit?
var lengthUnit: LengthUnit?
var scope = SettingOptions.TempreatureUnit
var tempreatureUnitOptions = [ TempreatureUnit.Celsius, TempreatureUnit.Fahrenheit ]
var lengthUnitOptions = [ LengthUnit.Metric, LengthUnit.Imperial ]
var optionSelectedHandler: (()->Void)?
private let userDefaults: NSUserDefaults
override init () {
self.userDefaults = NSUserDefaults.standardUserDefaults()
super.init()
NSLog("init settings")
loadState()
}
func getSettingForKey(key: SettingOptions) -> String
{
switch key {
case .LengthUnit: return self.lengthUnit!.rawValue
case .TempreatureUnit: return self.tempreatureUnit!.rawValue
}
}
func setSettingForKey(key: SettingOptions, value: String)
{
switch key {
case .LengthUnit: self.lengthUnit = LengthUnit(rawValue: value)
case .TempreatureUnit: self.tempreatureUnit = TempreatureUnit(rawValue: value)
}
}
func loadState() {
if let savedTempreatureUnit = userDefaults.stringForKey(SettingOptions.TempreatureUnit.rawValue) {
tempreatureUnit = TempreatureUnit(rawValue: savedTempreatureUnit )!
} else {
var defaultValue = DI.context.getParameter("default_tempreature_unit", defaultValue: "Celsius")!
tempreatureUnit = TempreatureUnit(rawValue: defaultValue)!
}
if let savedLengthUnit = userDefaults.stringForKey(SettingOptions.LengthUnit.rawValue) {
lengthUnit = LengthUnit(rawValue: savedLengthUnit)!
} else {
var defaultValue = DI.context.getParameter("default_length_unit", defaultValue: "Metric")!
lengthUnit = LengthUnit(rawValue: defaultValue)!
}
}
func saveState() {
userDefaults.setValue(tempreatureUnit?.rawValue, forKey: SettingOptions.TempreatureUnit.rawValue)
userDefaults.setValue(lengthUnit?.rawValue, forKey: SettingOptions.LengthUnit.rawValue)
userDefaults.synchronize();
// NSNotificationCenter.defaultCenter().postNotificationName(RELOAD_NOTIFICATION, object: nil)
}
// Particular Setting View Controller
//MARK: UITableViewDelegate protocol
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch scope {
case .LengthUnit: setSettingForKey(scope, value: lengthUnitOptions[indexPath.item].rawValue)
case .TempreatureUnit: setSettingForKey(scope, value: tempreatureUnitOptions[indexPath.item].rawValue)
}
optionSelectedHandler!()
}
//MARK: UITableViewDatasource protocol
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
switch scope {
case .LengthUnit: cell.textLabel!.text = lengthUnitOptions[indexPath.item].rawValue
case .TempreatureUnit: cell.textLabel!.text = tempreatureUnitOptions[indexPath.item].rawValue
}
cell.textLabel?.font = UIFont(name: FONT_REGULAR, size: 17)
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch scope {
case .LengthUnit: return countElements(lengthUnitOptions)
case .TempreatureUnit: return countElements(tempreatureUnitOptions)
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return scope.rawValue
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50;
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as UITableViewHeaderFooterView //recast your view as a UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor.whiteColor();
header.textLabel.textColor = tableView.tintColor;
header.textLabel.font = UIFont(name: FONT_SEMIBOLD, size: 14)
let headerSize = header.bounds.size
let image = UIImage(named: "Line_forecast")
let border = UIImageView(image: image)
border.frame = CGRectMake(0, headerSize.height-1, headerSize.width, 1)
header.addSubview(border)
}
} | apache-2.0 | 852171b783fd9323c5b5132f5342e9c5 | 33.153333 | 111 | 0.667903 | 4.90613 | false | false | false | false |
witekbobrowski/Stanford-CS193p-Winter-2017 | Faceit/Faceit/BlinkingFaceViewController.swift | 1 | 1492 | //
// BlinkingFaceViewController.swift
// Faceit
//
// Created by Witek on 13/09/2017.
// Copyright © 2017 Witek Bobrowski. All rights reserved.
//
import UIKit
class BlinkingFaceViewController: FaceViewController {
private struct BlinkRate {
static let closedDuration: TimeInterval = 0.4
static let openDuration: TimeInterval = 2.5
}
private var canBlink = false
private var inABlink = false
var blinking = false {
didSet {
blinkIfNeeded()
}
}
private func blinkIfNeeded() {
if blinking && canBlink && !inABlink {
faceView.eyesOpen = false
inABlink = true
Timer.scheduledTimer(withTimeInterval: BlinkRate.closedDuration, repeats: false) { [weak self] timer in
self?.faceView.eyesOpen = true
Timer.scheduledTimer(withTimeInterval: BlinkRate.openDuration, repeats: false) { [weak self] timer in
self?.inABlink = false
self?.blinkIfNeeded()
}
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
canBlink = true
blinkIfNeeded()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
canBlink = false
}
override func updateUI() {
super.updateUI()
blinking = expression.eyes == .squinting
}
}
| mit | 6702b91b4c7df5958f8fafa558101674 | 26.109091 | 117 | 0.59222 | 4.718354 | false | false | false | false |
zapdroid/RXWeather | Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift | 1 | 3188 | //
// RxTableViewReactiveArrayDataSource.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/26/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
// objc monkey business
class _RxTableViewReactiveArrayDataSource
: NSObject
, UITableViewDataSource {
func numberOfSections(in _: UITableView) -> Int {
return 1
}
func _tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _tableView(tableView, numberOfRowsInSection: section)
}
fileprivate func _tableView(_: UITableView, cellForRowAt _: IndexPath) -> UITableViewCell {
rxAbstractMethod()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return _tableView(tableView, cellForRowAt: indexPath)
}
}
class RxTableViewReactiveArrayDataSourceSequenceWrapper<S: Sequence>
: RxTableViewReactiveArrayDataSource<S.Iterator.Element>
, RxTableViewDataSourceType {
typealias Element = S
override init(cellFactory: @escaping CellFactory) {
super.init(cellFactory: cellFactory)
}
func tableView(_ tableView: UITableView, observedEvent: Event<S>) {
UIBindingObserver(UIElement: self) { tableViewDataSource, sectionModels in
let sections = Array(sectionModels)
tableViewDataSource.tableView(tableView, observedElements: sections)
}.on(observedEvent)
}
}
// Please take a look at `DelegateProxyType.swift`
class RxTableViewReactiveArrayDataSource<Element>
: _RxTableViewReactiveArrayDataSource
, SectionedViewDataSourceType {
typealias CellFactory = (UITableView, Int, Element) -> UITableViewCell
var itemModels: [Element]?
func modelAtIndex(_ index: Int) -> Element? {
return itemModels?[index]
}
func model(at indexPath: IndexPath) throws -> Any {
precondition(indexPath.section == 0)
guard let item = itemModels?[indexPath.item] else {
throw RxCocoaError.itemsNotYetBound(object: self)
}
return item
}
let cellFactory: CellFactory
init(cellFactory: @escaping CellFactory) {
self.cellFactory = cellFactory
}
override func _tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return itemModels?.count ?? 0
}
override func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cellFactory(tableView, indexPath.item, itemModels![indexPath.row])
}
// reactive
func tableView(_ tableView: UITableView, observedElements: [Element]) {
self.itemModels = observedElements
tableView.reloadData()
}
}
#endif
| mit | d15f7df0bef9c4d1b9da62c901045571 | 30.245098 | 114 | 0.628491 | 5.773551 | false | false | false | false |
keithrdavis/Camping-Directory | Camping Directory/SearchController.swift | 1 | 9020 | //
// SearchController.swift
// Camping Directory
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Created by Keith Davis on 9/21/16.
// Copyright © 2016 ZuniSoft. All rights reserved.
//
import UIKit
class SearchController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UIScrollViewDelegate, UITextFieldDelegate {
var pickerDataSource: [String] = Constants.stateList
var statePickerValue: String = ""
@IBOutlet weak var optionScroll: UIScrollView!
@IBOutlet weak var viewScroll: UIView!
@IBOutlet weak var statePicker: UIPickerView!
@IBOutlet weak var maxPeopleField: UITextField!
@IBOutlet weak var cgNameField: UITextField!
@IBOutlet weak var rvLengthField: UITextField!
@IBOutlet weak var petsAllowedSwitch: UISwitch!
@IBOutlet weak var waterSwitch: UISwitch!
@IBOutlet weak var sewerSwitch: UISwitch!
@IBOutlet weak var pullThroughSwitch: UISwitch!
@IBOutlet weak var waterFrontSwitch: UISwitch!
@IBOutlet weak var ampsAvailableSegment: UISegmentedControl!
@IBOutlet weak var facilityTypeSegment: UISegmentedControl!
@IBOutlet weak var aboutButton: UIBarButtonItem!
@IBOutlet weak var searchButton: UIButton!
// About Button
@IBAction func aboutButtonClicked(_ sender: UIBarButtonItem) {
let alertMessage = UIAlertController(title: "Camping Directory", message: "", preferredStyle: .alert)
// Application Icon
let image = UIImage(named: "AppIcon40x40")
let imageView = UIImageView(frame: CGRect(x: 115, y: 48, width: 40, height: 40))
imageView.image = image
imageView.layer.cornerRadius = 8.0
imageView.clipsToBounds = true
alertMessage.view.addSubview(imageView)
// Application Version
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
// Description
var message = "\n\n\nVersion " + version! + "\n\n"
message += "This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation.\n\nGitHub: https://github.com/keithrdavis/Camping-Directory\n\nCopyright © 2016 Keith R. Davis"
alertMessage.message = message
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alertMessage .addAction(action)
self.present(alertMessage, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Connect data:
self.statePicker.dataSource = self;
self.statePicker.delegate = self;
self.optionScroll.delegate = self;
self.rvLengthField.delegate = self;
self.maxPeopleField.delegate = self;
// Defaults
self.statePicker.selectRow(0, inComponent: 0, animated: true)
statePickerValue = Constants.stateDictionary[Constants.stateList[statePicker.selectedRow(inComponent: 0)]]!
self.searchButton.layer.cornerRadius = 5
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// The number of columns of data.
func numberOfComponents(in statePicker: UIPickerView) -> Int {
return 1
}
// The number of rows of data.
func pickerView(_ statePicker: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerDataSource.count
}
// The data to return for the row and component (column) that's being passed in.
func pickerView(_ statePicker: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDataSource[row]
}
// The row selected in the picker by the user.
func pickerView(_ statePicker: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
statePickerValue = Constants.stateDictionary[Constants.stateList[row]]!
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Create a variable that you want to send
var newSequeUrl : String
// API url
newSequeUrl = Constants.svcCampgroundURL
// API key
newSequeUrl += "?api_key=" + Constants.svcCampgroundAPIKey
// State
newSequeUrl += "&pstate=" + statePickerValue
// CG name
let cgNameValue = cgNameField.text == "" ? "" : cgNameField.text
if cgNameValue != "" {
newSequeUrl += "&pname=" + cgNameValue!
}
// RV length
let rvLengthValue = rvLengthField.text == "" ? "" : rvLengthField.text
if rvLengthValue != "" {
newSequeUrl += "&eqplen=" + rvLengthValue!
}
// Facility type
var facilityTypeValue: String?
let facilityTypeSelected = facilityTypeSegment.selectedSegmentIndex
switch facilityTypeSelected {
case 0:
facilityTypeValue = ""
case 1:
facilityTypeValue = "2001"
case 2:
facilityTypeValue = "10001"
case 3:
facilityTypeValue = "2003"
case 4:
facilityTypeValue = "2002"
case 5:
facilityTypeValue = "9002"
case 6:
facilityTypeValue = "9001"
case 7:
facilityTypeValue = "3001"
case 8:
facilityTypeValue = "2004"
default: break
}
if (facilityTypeValue != "") {
newSequeUrl += "&siteType=" + facilityTypeValue!
}
// Max people
let maxPeopleValue = maxPeopleField.text == "" ? "" : maxPeopleField.text
if maxPeopleValue != "" {
newSequeUrl += "&Maxpeople=" + maxPeopleValue!
}
// Water
let waterValue = waterSwitch.isOn ? 3007 : 0
if waterValue == 3007 {
newSequeUrl += "&water=" + String(waterValue)
}
// Sewer
let sewerValue = sewerSwitch.isOn ? 3007 : 0
if sewerValue == 3007 {
newSequeUrl += "&sewer=" + String(sewerValue)
}
// Pets allowed
let petsAllowedValue = petsAllowedSwitch.isOn ? 3010 : 0
if petsAllowedValue == 3010 {
newSequeUrl += "&pets=" + String(petsAllowedValue)
}
// Pull through
let pullThroughValue = pullThroughSwitch.isOn ? 3008 : 0
if pullThroughValue == 3008 {
newSequeUrl += "&pull=" + String(pullThroughValue)
}
// Waterfront
let waterFrontValue = waterFrontSwitch.isOn ? 3011 : 0
if waterFrontValue == 3011 {
newSequeUrl += "&waterfront=" + String(waterFrontValue)
}
// Power
var powerValue: String?
let powerSelected = ampsAvailableSegment.selectedSegmentIndex
switch powerSelected {
case 0:
powerValue = ""
case 1:
powerValue = "3002"
case 2:
powerValue = "3003"
case 3:
powerValue = "3004"
case 4:
powerValue = "3005"
default: break
}
if (powerValue != "") {
newSequeUrl += "&hookup=" + powerValue!
}
debugPrint("URL: " + newSequeUrl)
// Create a new variable to store the instance of SearchResultsViewController
let destinationVC = segue.destination as! SearchResultsController
destinationVC.sequeUrl = newSequeUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
}
}
| gpl-2.0 | d0c0f5b7f89ddea00b7481624ec8f7b1 | 35.362903 | 294 | 0.621091 | 4.82246 | false | false | false | false |
freshOS/ws | Sources/ws/WSModelJSONParser.swift | 2 | 1414 | //
// WSModelJSONParser.swift
// ws
//
// Created by Sacha Durand Saint Omer on 06/04/16.
// Copyright © 2016 s4cha. All rights reserved.
//
import Arrow
import Foundation
open class WSModelJSONParser<T> {
public init() { }
fileprivate func resourceData(from json: JSON, keypath: String?) -> JSON {
if let k = keypath, !k.isEmpty, let j = json[k] {
return j
}
return json
}
}
extension WSModelJSONParser where T: ArrowInitializable {
open func toModel(_ json: JSON, keypath: String? = nil) -> T? {
return T.init(resourceData(from: json, keypath: keypath))
}
open func toModels(_ json: JSON, keypath: String? = nil) -> [T]? {
return [T].init(resourceData(from: json, keypath: keypath))
}
}
extension WSModelJSONParser where T: ArrowParsable {
open func toModel(_ json: JSON, keypath: String? = nil) -> T {
let data = resourceData(from: json, keypath: keypath)
return resource(from: data)
}
open func toModels(_ json: JSON, keypath: String? = nil) -> [T] {
guard let array = resourceData(from: json, keypath: keypath).collection else {
return [T]()
}
return array.map { resource(from: $0) }
}
private func resource(from json: JSON) -> T {
var t = T()
t.deserialize(json)
return t
}
}
| mit | 52b219fbe587da067d9cd3c48ee9cb51 | 23.789474 | 86 | 0.585987 | 3.798387 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Controller/LinearEquations/CLinearEquationsPolynomial.swift | 1 | 3692 | import UIKit
class CLinearEquationsPolynomial:CController
{
weak var polynomial:DPolynomial?
weak var viewPolynomial:VLinearEquationsPolynomial!
init(polynomial:DPolynomial)
{
self.polynomial = polynomial
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewPolynomial:VLinearEquationsPolynomial = VLinearEquationsPolynomial(
controller:self)
self.viewPolynomial = viewPolynomial
view = viewPolynomial
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
viewPolynomial.startEdition()
}
//MARK: private
private func confirmTrash()
{
guard
let polynomial:DPolynomial = self.polynomial
else
{
return
}
polynomial.deleteFromEquation()
trashDone()
}
private func trashDone()
{
DManager.sharedInstance?.save
{
DispatchQueue.main.async
{ [weak self] in
self?.parentController.dismissAnimateOver(completion:nil)
}
}
}
//MARK: public
func save()
{
UIApplication.shared.keyWindow!.endEditing(true)
DManager.sharedInstance?.save
{
DispatchQueue.main.async
{ [weak self] in
self?.parentController.dismissAnimateOver(completion:nil)
}
}
viewPolynomial.endEdition()
}
func trash()
{
UIApplication.shared.keyWindow!.endEditing(true)
let alert:UIAlertController = UIAlertController(
title:NSLocalizedString("CLinearEquationsPolynomial_alertTitle", comment:""),
message:nil,
preferredStyle:UIAlertControllerStyle.actionSheet)
let actionCancel:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CLinearEquationsPolynomial_alertCancel", comment:""),
style:
UIAlertActionStyle.cancel)
let actionDelete:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CLinearEquationsPolynomial_alertDelete", comment:""),
style:
UIAlertActionStyle.destructive)
{ [weak self] (action:UIAlertAction) in
self?.viewPolynomial.endEdition()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.confirmTrash()
}
}
alert.addAction(actionDelete)
alert.addAction(actionCancel)
if let popover:UIPopoverPresentationController = alert.popoverPresentationController
{
popover.sourceView = viewPolynomial
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(alert, animated:true, completion:nil)
}
func changeIndeterminate()
{
UIApplication.shared.keyWindow!.endEditing(true)
guard
let polynomial:DPolynomial = self.polynomial
else
{
return
}
let controllerIndeterminate:CLinearEquationsPolynomialIndeterminate = CLinearEquationsPolynomialIndeterminate(
polynomial:polynomial)
parentController.animateOver(controller:controllerIndeterminate)
}
}
| mit | 3ecdefe4017da5624f3a6045e9b691df | 25 | 118 | 0.574215 | 5.983793 | false | false | false | false |
Ryce/flickrpickr | Carthage/Checkouts/judokit/Source/BillingCountryInputField.swift | 2 | 4786 | //
// BillingCountryInputField.swift
// JudoKit
//
// Copyright (c) 2016 Alternative Payments 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
/**
The BillingCountryInputField is an input field configured to select a billing country out of a selected set of countries that we currently support.
*/
open class BillingCountryInputField: JudoPayInputField {
let countryPicker = UIPickerView()
var selectedCountry: BillingCountry = .uk
override func setupView() {
super.setupView()
self.countryPicker.delegate = self
self.countryPicker.dataSource = self
self.textField.placeholder = " "
self.textField.text = "UK"
self.textField.inputView = self.countryPicker
self.setActive(true)
}
// MARK: UITextFieldDelegate Methods
/**
Delegate method implementation
- parameter textField: Text field
- parameter range: Range
- parameter string: String
- returns: boolean to change characters in given range for a text field
*/
open func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return false
}
// MARK: JudoInputType
/**
Check if this inputField is valid
- returns: true if valid input
*/
open override func isValid() -> Bool {
return true
}
/**
Title of the receiver inputField
- returns: a string that is the title of the receiver
*/
open override func title() -> String {
return "Billing country"
}
/**
Width of the title
- returns: width of the title
*/
open override func titleWidth() -> Int {
return 120
}
}
// MARK: UIPickerViewDataSource
extension BillingCountryInputField: UIPickerViewDataSource {
/**
Datasource method for billingCountryPickerView
- parameter pickerView: PickerView that calls its delegate
- returns: the number of components in the pickerView
*/
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
/**
Datasource method for billingCountryPickerView
- parameter pickerView: Picker view
- parameter component: A given component
- returns: number of rows in component
*/
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return BillingCountry.allValues.count
}
}
extension BillingCountryInputField: UIPickerViewDelegate {
// MARK: UIPickerViewDelegate
/**
Delegate method for billingCountryPickerView
- parameter pickerView: The caller
- parameter row: The row
- parameter component: The component
- returns: title of a given component and row
*/
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return BillingCountry.allValues[row].title()
}
/**
Delegate method for billingCountryPickerView that had a given row in a component selected
- parameter pickerView: The caller
- parameter row: The row
- parameter component: The component
*/
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectedCountry = BillingCountry.allValues[row]
self.textField.text = self.selectedCountry.title()
self.delegate?.billingCountryInputDidEnter(self, billingCountry: self.selectedCountry)
}
}
| mit | 6c0d7bbd43a440caa3b3e1c33a850127 | 28.726708 | 148 | 0.672587 | 5.140709 | false | false | false | false |
BellAppLab/AdorableContacts | AdorableContacts/ViewControllers.swift | 1 | 6205 | //
// ViewController.swift
// AdorableContacts
//
// Created by André Abou Chami Campana on 08/12/15.
// Copyright © 2015 Bell App Lab. All rights reserved.
//
import UIKit
import Backgroundable
import CoreData
import UILoader
import Alertable
class ListViewController: BackgroundableTableViewController, AdorableController, UILoader, Alertable
{
//MARK: Consts
private static let itemSegue = "ItemSegue"
private static let listCellId = "ListCell"
//MARK: Adorable Controller
var fetchedResultsController: NSFetchedResultsController!
//MARK: View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
DatabaseController.make(self) { [unowned self] (success) -> Void in
if success {
self.tableView.reloadData()
}
}
}
override func willChangeVisibility() {
if !self.visible && !self.alerting {
self.loadContacts(self.refreshControl!)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
if let controller = segue.destinationViewController as? ItemViewController {
if let contact = sender as? Contact {
controller.contact = contact
}
}
}
//MARK: Loading
@IBAction func loadContacts(sender: UIRefreshControl) {
if self.loading {
return
}
self.loading = true
DatabaseController.loadNewContacts { [unowned self] (success) -> Void in
if !success {
let alert = Alert("Uh oh... Something went wrong", "Adorable alert", self)
self.alert(this: alert)
}
self.refreshControl?.endRefreshing()
self.loading = false
}
}
//MARK: Table View Data Source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.fetchedResultsController?.fetchedObjects?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(ListViewController.listCellId) as? ListCell
if cell == nil {
cell = ListCell()
}
cell!.contact = self.fetchedResultsController.objectAtIndexPath(indexPath) as? Contact
return cell!
}
//MARK: Table View Delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier(ListViewController.itemSegue, sender: (tableView.cellForRowAtIndexPath(indexPath) as? ListCell)?.contact)
}
//MARK: Fetched Results Controller Delegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
{
switch type
{
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Update:
if let contact = anObject as? Contact {
(tableView.cellForRowAtIndexPath(indexPath!) as? ListCell)?.contact = contact
}
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
//MARK: UI Loader
@IBOutlet weak var spinningThing: UIActivityIndicatorView?
func didChangeLoadingStatus(loading: Bool) {
}
}
class ItemViewController: UIViewController, AdorableController
{
//MARK: Data Model
var contact: Contact!
//MARK: Adorable Controller
var fetchedResultsController: NSFetchedResultsController!
//MARK: UI Elements
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var surnameLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var phoneNumberLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var createdAtLabel: UILabel!
@IBOutlet weak var updatedAtLabel: UILabel!
//MARK: View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
DatabaseController.make(self, withItem: self.contact) { [unowned self] (success) -> Void in
self.configure()
}
}
private let dateFormatter: NSDateFormatter = {
let result = NSDateFormatter()
result.dateStyle = .MediumStyle
result.timeStyle = .ShortStyle
return result
}()
private func configure() {
self.firstNameLabel.text = self.contact.firstName
self.surnameLabel.text = self.contact.surname
self.addressLabel.text = self.contact.address
self.phoneNumberLabel.text = self.contact.phoneNumber
self.emailLabel.text = self.contact.email
if let date = self.contact.createdAt {
self.createdAtLabel.text = self.dateFormatter.stringFromDate(date)
}
if let date = self.contact.updatedAt {
self.updatedAtLabel.text = self.dateFormatter.stringFromDate(date)
}
}
//MARK: Fetched Results Controller Delegate
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
{
self.configure()
}
}
| mit | 46cb99862ee009d123e9798be26f854e | 32.896175 | 209 | 0.659358 | 5.479682 | false | false | false | false |
fgengine/quickly | Quickly/Extensions/UIDevice.swift | 1 | 2706 | //
// Quickly
//
public enum QDeviceFamily : Int {
case unknown
case iPhone
case iPad
case iPod
case simulator
}
public enum QDeviceDisplaySize : Int {
case unknown
case iPad
case iPad_10_5
case iPad_12_9
case iPhone_3_5
case iPhone_4
case iPhone_4_7
case iPhone_5_5
case iPhone_5_8
}
public extension UIDevice {
var identifier: String {
get {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
return machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
}
}
var family: QDeviceFamily {
get {
#if targetEnvironment(simulator)
return .simulator
#else
let identifier = self.identifier
if identifier.hasPrefix("iPhone") {
return .iPhone
} else if identifier.hasPrefix("iPad") {
return .iPad
} else if identifier.hasPrefix("iPod") {
return .iPod
}
return .unknown
#endif
}
}
var displaySize: QDeviceDisplaySize {
get {
let screenSize = UIScreen.main.bounds.integral.size
let screenWidth = min(screenSize.width, screenSize.height)
let screenHeight = max(screenSize.width, screenSize.height)
switch self.userInterfaceIdiom {
case .phone:
if screenHeight >= 812 && screenWidth >= 375 {
return .iPhone_5_8
} else if screenHeight >= 736 && screenWidth >= 414 {
return .iPhone_5_5
} else if screenHeight >= 667 && screenWidth >= 375 {
return .iPhone_4_7
} else if screenHeight >= 568 && screenWidth >= 320 {
return .iPhone_4
} else if screenHeight >= 480 && screenWidth >= 320 {
return .iPhone_3_5
}
case .pad:
if screenHeight >= 1366 && screenWidth >= 1024 {
return .iPad_10_5
} else if screenHeight >= 1112 && screenWidth >= 834 {
return .iPad_10_5
} else if screenHeight >= 1024 && screenWidth >= 768 {
return .iPad
}
default:
return .unknown
}
return .unknown
}
}
}
| mit | cfeb60ee0052839d1cc63698389284de | 29.066667 | 95 | 0.504065 | 5.164122 | false | false | false | false |
saeta/penguin | Sources/PenguinCSV/UTF8Iterator.swift | 1 | 3501 | // Copyright 2020 Penguin Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// A Naive UTF8Parser based on Swift iterator protocols.
///
/// TODO: Consider vectorizing the implementation to improve performance.
public struct UTF8Parser<T: IteratorProtocol>: Sequence, IteratorProtocol where T.Element == UInt8 {
var underlying: T
public mutating func next() -> Character? {
guard let first = underlying.next() else {
return nil
}
if first & 0b10000000 == 0 {
// ASCII character
let scalar = Unicode.Scalar(first)
return Character(scalar)
}
// Non-ascii values
if first & 0b00100000 == 0 {
// 2 bytes
guard let second = underlying.next() else {
print("Incomplete (2 byte) unicode value found at end of file.")
return nil
}
let char = UInt32(((first & 0b00011111) << 6) | (second & 0b00111111))
return Character(Unicode.Scalar(char)!)
}
if first & 0b00010000 == 0 {
// 3 bytes
guard let second = underlying.next() else {
print("Incomplete (3 byte; 1 byte found) unicode value found at end of file.")
return nil
}
guard let third = underlying.next() else {
print("Incomplete (3 byte; 2 bytes found) unicode value found at end of file.")
return nil
}
// Workaround for Swift compiler being unable to typecheck the following expression.
// let char = UInt32((first & 0b00011111) << 12 | (second & 0b00111111) << 6 | (third & 0b00111111))
let upper = UInt32((first & 0b00011111) << 12 | (second & 0b00111111) << 6)
let char = upper | UInt32(third & 0b00111111)
return Character(Unicode.Scalar(char)!)
}
if first & 0b00001000 != 0 {
print("Invalid ascii encountered!") // TODO: make a more helpful error message (e.g offset.)
return nil
}
guard let second = underlying.next() else {
print("Incomplete (4 byte; 1 byte found) unicode value found at end of file.")
return nil
}
guard let third = underlying.next() else {
print("Incomplete (4 byte; 2 bytes found) unicode value found at end of file.")
return nil
}
guard let fourth = underlying.next() else {
print("Incomplete (4 byte; 3 bytes found) unicode value found at end of file.")
return nil
}
// Workaround for Swift compiler being unable to typecheck an expression.
let charUpper = UInt32((first & 0b00001111) << 18 | (second & 0b00111111 << 12))
let charLower = UInt32((third & 0b00111111) << 6 | (fourth & 0b00111111))
return Character(Unicode.Scalar(charUpper | charLower)!)
}
}
struct Bits {
let u: UInt32
init(_ u: UInt8) {
self.u = UInt32(u)
}
init(_ u: UInt32) {
self.u = u
}
}
extension Bits: CustomStringConvertible {
var description: String {
var desc = ""
for i in 0..<32 {
desc.append("\(UInt32(((u & UInt32(1 << i)) >> (i))))")
}
return "0b\(String(desc.reversed()))"
}
}
| apache-2.0 | 1d122647d287f7c523255562f790794f | 35.092784 | 106 | 0.642674 | 3.960407 | false | false | false | false |
remlostime/one | one/one/Views/UserInfoViewCell.swift | 1 | 3009 | //
// UserInfoViewCell.swift
// one
//
// Created by Kai Chen on 12/30/16.
// Copyright © 2016 Kai Chen. All rights reserved.
//
import UIKit
import Parse
class UserInfoViewCell: UITableViewCell {
@IBOutlet weak var contentTextField: UITextField!
@IBOutlet weak var iconImageView: UIImageView!
let imageName = "imageName"
let placeholder = "placeholder"
let content = "content"
var userInfo: UserInfo?
// MARK: Helpers
func config(_ indexPath: IndexPath, userInfo: UserInfo) {
self.userInfo = userInfo
if let info = cellInfo(indexPath) {
if let imageName = info[imageName] {
iconImageView.image = UIImage(named: imageName!)
}
if let content = info[content] {
contentTextField.text = content
}
if let placeholder = info[placeholder] {
contentTextField.placeholder = placeholder
}
}
}
private func cellInfo(_ forIndexPath: IndexPath) -> [String: String?]? {
if forIndexPath.section == 0 {
switch forIndexPath.row {
case 1:
return
[
imageName: "user_fullname_icon",
placeholder: "Full Name",
content: userInfo?.fullname
]
case 2:
return
[
imageName: "user_id_icon",
placeholder: "User ID",
content: userInfo?.username
]
case 3:
return
[
imageName: "user_website_icon",
placeholder: "Website",
content: userInfo?.website
]
case 4:
return
[
imageName: "user_bio_icon",
placeholder: "Bio",
content: userInfo?.bio
]
default:
return nil
}
} else {
switch forIndexPath.row {
case 0:
return
[
imageName: "user_email_icon",
placeholder: "Email",
content: userInfo?.email
]
case 1:
return
[
imageName: "user_phone_icon",
placeholder: "Mobile",
content: userInfo?.mobile
]
case 2:
return
[
imageName: "user_gender_icon",
placeholder: "Gender",
content: userInfo?.gender
]
default:
return nil
}
}
}
}
| gpl-3.0 | de9341c973f02a2e626f8656a15f65af | 28.203883 | 76 | 0.412899 | 6.151329 | false | false | false | false |
zouguangxian/VPNOn | VPNOn/LTVPNCreateViewController.swift | 1 | 4566 | //
// LTVPNCreateViewController.swift
// VPN On
//
// Created by Lex Tang on 12/4/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import UIKit
import CoreData
class LTVPNCreateViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var serverTextField: UITextField!
@IBOutlet weak var accountTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var groupTextField: UITextField!
@IBOutlet weak var secretTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBAction func createVPN(sender: AnyObject) {
let success = VPNDataManager.sharedManager.createVPN(
titleTextField.text,
server: serverTextField.text,
account: accountTextField.text,
password: passwordTextField.text,
group: groupTextField.text,
secret: secretTextField.text)
if success {
dismissViewControllerAnimated(true) {}
}
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("textDidChange:"),
name: UITextFieldTextDidChangeNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("keyboardWillShow:"),
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("keyboardWillHide:"),
name: UIKeyboardWillHideNotification,
object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(
self, name: UITextFieldTextDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(
self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(
self, name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
saveButton?.enabled = false
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
switch textField {
case titleTextField:
serverTextField.becomeFirstResponder()
break
case serverTextField:
accountTextField.becomeFirstResponder()
break
case accountTextField:
groupTextField.becomeFirstResponder()
break
case groupTextField:
passwordTextField.becomeFirstResponder()
break
case passwordTextField:
secretTextField.becomeFirstResponder()
break
default:
secretTextField.resignFirstResponder()
}
return true
}
func textDidChange(notification: NSNotification) {
if self.titleTextField.text.isEmpty
|| self.accountTextField.text.isEmpty
|| self.serverTextField.text.isEmpty {
self.saveButton.enabled = false
} else {
self.saveButton.enabled = true
}
}
func keyboardWillShow(notification: NSNotification) {
// Add bottom edge inset so that the last cell is visiable
var bottom: CGFloat = 216
if let userInfo: NSDictionary = notification.userInfo {
if let boundsObject: AnyObject = userInfo.valueForKey("UIKeyboardBoundsUserInfoKey") {
let bounds = boundsObject.CGRectValue()
bottom = bounds.size.height
}
}
var edgeInsets = self.tableView.contentInset
edgeInsets.bottom = bottom
self.tableView.contentInset = edgeInsets
}
func keyboardWillHide(notification: NSNotification) {
var edgeInsets = self.tableView.contentInset
edgeInsets.bottom = 0
self.tableView.contentInset = edgeInsets
}
/*
// 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 | 4bfbc136338324cc4f94a9f2e5f5be40 | 32.086957 | 106 | 0.634034 | 6.079893 | false | false | false | false |
samodom/UIKitSwagger | UIKitSwagger/Dynamics/UIDynamicAnimatorAdditionSyntax.swift | 1 | 1580 | //
// UIDynamicAnimatorAdditionSyntax.swift
// UIKitSwagger
//
// Created by Sam Odom on 12/14/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import UIKit
/**
Convenience operator for adding a dynamic behavior to an animator.
- parameter animator: Dynamic animator to which the behavior should be added.
- parameter behavior: Dynamic behavior to add to the animator.
*/
public func +=(animator: UIDynamicAnimator, behavior: UIDynamicBehavior) {
animator.addBehavior(behavior)
}
/**
Convenience operator for adding an array of dynamic behaviors to an animator.
- parameter animator: Dynamic animator to which the behavior should be added.
- parameter behaviors: Array of dynamic behaviors to add to the animator.
*/
public func +=(animator: UIDynamicAnimator, behaviors: [UIDynamicBehavior]) {
behaviors.forEach { animator += $0 }
}
/**
Convenience operator for removing a dynamic behavior from an animator.
- parameter animator: Dynamic animator from which the behavior should be removed.
- parameter behavior: Dynamic behavior to remove from the animator.
*/
public func -=(animator: UIDynamicAnimator, behavior: UIDynamicBehavior) {
animator.removeBehavior(behavior)
}
/**
Convenience operator for removing an array of dynamic behaviors from an animator.
- parameter animator: Dynamic animator from which the behaviors should be removed.
- parameter behavior: Array of dynamic behaviors to remove from the animator.
*/
public func -=(animator: UIDynamicAnimator, behaviors: [UIDynamicBehavior]) {
behaviors.forEach { animator -= $0 }
}
| mit | d0d9cf3b6e091c62bb7b011de4778607 | 34.111111 | 82 | 0.767089 | 4.674556 | false | false | false | false |
plivesey/BuildTimeAnalyzer-for-Xcode | BuildTimeAnalyzer/CMCompileMeasure.swift | 1 | 1659 | //
// CMCompileMeasure.swift
// BuildTimeAnalyzer
//
// Created by Robert Gummesson on 02/05/2016.
// Copyright © 2016 Robert Gummesson. All rights reserved.
//
import Foundation
struct CMCompileMeasure {
var time: Double
var path: String
var code: String
var filename: String
private var locationArray: [Int]
var fileInfo: String {
return "\(filename):\(locationArray[0]):\(locationArray[1])"
}
var location: Int {
return locationArray[0]
}
var timeString: String {
return "\(time)ms"
}
init?(time: Double, rawPath: String, code: String) {
let untrimmedFilename = rawPath.characters.split("/").map(String.init).last
guard let filepath = rawPath.characters.split(":").map(String.init).first else { return nil }
guard let filename = untrimmedFilename?.characters.split(":").map(String.init).first else { return nil }
let locationString = String(rawPath.substringFromIndex(filepath.endIndex).characters.dropFirst())
let locations = locationString.characters.split(":").flatMap{ Int(String.init($0)) }
guard locations.count == 2 else { return nil }
self.time = time
self.code = code
self.path = filepath
self.filename = filename
self.locationArray = locations
}
subscript(column: Int) -> String {
get {
switch column {
case 0:
return timeString
case 1:
return fileInfo
default:
return code
}
}
}
} | mit | db312afd263a3d3dce66cdcecd769449 | 26.196721 | 112 | 0.582027 | 4.517711 | false | false | false | false |
DuckDeck/GrandTime | GrandTimeDemo/TimerViewController.swift | 1 | 3301 | //
// TimerViewController.swift
// GrandTimeDemo
//
// Created by Stan Hu on 2020/3/17.
//
import UIKit
class TimerViewController: UIViewController {
let lblTImerBlock = UILabel()
let lblTimer = UILabel()
var timer:GrandTimer?
var timer2:GrandTimer?
var seco = 0
var seco2 = 0
var isPause = false
let btnPause = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
lblTimer.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
view.addSubview(lblTimer)
lblTImerBlock.frame = CGRect(x: 100, y: 300, width: 200, height: 50)
view.addSubview(lblTImerBlock)
btnPause.setTitle("暂停", for: .normal)
btnPause.setTitleColor(UIColor.black, for: .normal)
btnPause.frame = CGRect(x: 100, y: 500, width: 100, height: 40)
btnPause.addTarget(self, action: #selector(pauseTimer(_:)), for: .touchUpInside)
view.addSubview(btnPause)
// let dispatch = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT)
// timer = GrandTimer.scheduleTimerWithTimeSpan(TimeSpan.fromSeconds(1), target: self, sel: #selector(TimerViewController.tick), userInfo: nil, repeats: true, dispatchQueue: dispatch)
// timer?.fire()
// GrandTimer.every(TimeSpan.fromSeconds(5)) {
// self.seco2 = self.seco2 + 1
// self.lblTimer.text = "\(self.seco2)"
// }
// timer = GrandTimer.scheduleTimerWithTimeSpan(TimeSpan.fromSeconds(1), block: {
// self.seco2 = self.seco2 + 1
// self.lblTimer.text = "\(self.seco2)"
//
// }, repeats: true, dispatchQueue: dispatch)
//Issue2: I must use a var to receive the GrandTimer static func which is to return a GrandTimer instance. I don't know why
//IF this werid stuff can not fix . I will feel unhappy.
// I know wahy this weill not work .because the when out of the code bound, and there is no strong refrence to this timer. so the system will recycle the
//timer .So it need a var to receive the Timer
weak var weakSelf = self
//使用者要注意,这个timer本身是weak的,所以需要一个外部变量来强引用,
//如果要让timer正确地释放内存,那么要使用weakself
timer = GrandTimer.every(TimeSpan.fromSeconds(1)) {
weakSelf!.seco2 = weakSelf!.seco2 + 1
weakSelf!.lblTimer.text = "\(weakSelf!.seco2)"
}
lblTImerBlock.text = "3秒后变红"
timer?.fire()
timer2 = GrandTimer.after(TimeSpan.fromSeconds(3), block: {
weakSelf?.lblTImerBlock.backgroundColor = UIColor.red
})
timer2?.fire()
}
func tick() {
seco = seco + 1
DispatchQueue.main.async {
self.lblTimer.text = "\(self.seco)"
}
}
@objc func pauseTimer(_ sender: UIButton) {
isPause = !isPause
if isPause{
timer?.pause()
}
else{
timer?.fire()
}
}
}
| mit | 8603a54561b74f75945a3efab0a680ce | 35.329545 | 194 | 0.570848 | 4.036616 | false | false | false | false |
weby/Stencil | Sources/ForTag.swift | 1 | 2548 | public class ForNode : NodeType {
let variable:Variable
let loopVariable:String
let nodes:[NodeType]
let emptyNodes: [NodeType]
public class func parse(parser:TokenParser, token:Token) throws -> NodeType {
let components = token.components()
guard components.count == 4 && components[2] == "in" else {
throw TemplateSyntaxError("'for' statements should use the following 'for x in y' `\(token.contents)`.")
}
let loopVariable = components[1]
let variable = components[3]
var emptyNodes = [NodeType]()
let forNodes = try parser.parse(until: until(tags: ["endfor", "empty"]))
guard let token = parser.nextToken() else {
throw TemplateSyntaxError("`endfor` was not found.")
}
if token.contents == "empty" {
emptyNodes = try parser.parse(until: until(tags: ["endfor"]))
parser.nextToken()
}
return ForNode(variable: variable, loopVariable: loopVariable, nodes: forNodes, emptyNodes:emptyNodes)
}
public init(variable:String, loopVariable:String, nodes:[NodeType], emptyNodes:[NodeType]) {
self.variable = Variable(variable)
self.loopVariable = loopVariable
self.nodes = nodes
self.emptyNodes = emptyNodes
}
public func render(context: Context) throws -> String {
let values = try variable.resolve(context: context)
if let values = values as? [Any] where values.count > 0 {
let count = values.count
#if !swift(>=3.0)
return try values.enumerate().map { index, item in
let forContext: [String: Any] = [
"first": index == 0,
"last": index == (count - 1),
"counter": index + 1,
]
return try context.push([loopVariable: item, "forloop": forContext]) {
try renderNodes(nodes, context)
}
}.joinWithSeparator("")
#else
return try values.enumerated().map { index, item in
let forContext: [String: Any] = [
"first": index == 0,
"last": index == (count - 1),
"counter": index + 1,
]
return try context.push(dictionary: [loopVariable: item, "forloop": forContext]) {
try renderNodes(nodes: nodes, context)
}
}.joined(separator:"")
#endif
}
return try context.push {
try renderNodes(nodes: emptyNodes, context)
}
}
}
| bsd-2-clause | 5ae5b9d0b5a166c5f18c14b672d82cc2 | 32.526316 | 110 | 0.569466 | 4.446771 | false | false | false | false |
bartekchlebek/SwiftHelpers | Example/Pods/Nimble/Sources/Nimble/DSL.swift | 1 | 2467 | import Foundation
/// Make an expectation on a given actual value. The value given is lazily evaluated.
public func expect<T>(_ expression: @autoclosure @escaping () throws -> T?, file: FileString = #file, line: UInt = #line) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Make an expectation on a given actual value. The closure is lazily invoked.
public func expect<T>(_ file: FileString = #file, line: UInt = #line, expression: @escaping () throws -> T?) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Always fails the test with a message and a specified location.
public func fail(_ message: String, location: SourceLocation) {
let handler = NimbleEnvironment.activeInstance.assertionHandler
handler.assert(false, message: FailureMessage(stringValue: message), location: location)
}
/// Always fails the test with a message.
public func fail(_ message: String, file: FileString = #file, line: UInt = #line) {
fail(message, location: SourceLocation(file: file, line: line))
}
/// Always fails the test.
public func fail(_ file: FileString = #file, line: UInt = #line) {
fail("fail() always fails", file: file, line: line)
}
/// Like Swift's precondition(), but raises NSExceptions instead of sigaborts
internal func nimblePrecondition(
_ expr: @autoclosure() -> Bool,
_ name: @autoclosure() -> String,
_ message: @autoclosure() -> String,
file: StaticString = #file,
line: UInt = #line) -> Bool {
let result = expr()
if !result {
#if _runtime(_ObjC)
let e = NSException(
name: NSExceptionName(rawValue: name()),
reason: message(),
userInfo: nil)
e.raise()
#else
preconditionFailure("\(name()) - \(message())", file: file, line: line)
#endif
}
return result
}
internal func internalError(_ msg: String, file: FileString = #file, line: UInt = #line) -> Never {
fatalError(
"Nimble Bug Found: \(msg) at \(file):\(line).\n" +
"Please file a bug to Nimble: https://github.com/Quick/Nimble/issues with the " +
"code snippet that caused this error."
)
}
| mit | fbf89496e5d6feee51ff34794bb5cbc3 | 36.953846 | 141 | 0.634779 | 4.253448 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/Offline methods/PXOfflineMethodsViewController.swift | 1 | 21005 | import Foundation
import MLUI
protocol PXOfflineMethodsViewControllerDelegate: class {
func didEnableUI(enabled: Bool)
}
final class PXOfflineMethodsViewController: MercadoPagoUIViewController {
let viewModel: PXOfflineMethodsViewModel
var callbackConfirm: ((PXPaymentData, Bool) -> Void)
let callbackFinishCheckout: (() -> Void)
var finishButtonAnimation: (() -> Void)
var callbackUpdatePaymentOption: ((PaymentMethodOption) -> Void)
let timeOutPayButton: TimeInterval
var amountOfButtonPress: Int = 0
let tableView = UITableView(frame: .zero, style: .grouped)
var loadingButtonComponent: PXWindowedAnimatedButton?
var inactivityView: UIView?
var inactivityViewAnimationConstraint: NSLayoutConstraint?
weak var delegate: PXOfflineMethodsViewControllerDelegate?
var userDidScroll = false
var strategyTracking: StrategyTrackings = ImpletationStrategy()
private struct Constants {
static let viewBorderWidth: CGFloat = 1.5
static let viewCornerRadius: CGFloat = 10
}
init(viewModel: PXOfflineMethodsViewModel, callbackConfirm: @escaping ((PXPaymentData, Bool) -> Void), callbackUpdatePaymentOption: @escaping ((PaymentMethodOption) -> Void), finishButtonAnimation: @escaping (() -> Void), callbackFinishCheckout: @escaping (() -> Void)) {
self.viewModel = viewModel
self.callbackConfirm = callbackConfirm
self.callbackUpdatePaymentOption = callbackUpdatePaymentOption
self.finishButtonAnimation = finishButtonAnimation
self.callbackFinishCheckout = callbackFinishCheckout
self.timeOutPayButton = 15
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
render()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
self?.showInactivityViewIfNecessary()
}
autoSelectPaymentMethodIfNeeded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
sheetViewController?.scrollView = tableView
trackScreen(event: MercadoPagoUITrackingEvents.offlineMethodds(viewModel.getScreenTrackingProperties()))
strategyTracking.getPropertieFlow(flow: "PXOfflineMethodsViewController")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
trackAbortEvent()
}
func getTopInset() -> CGFloat {
if #available(iOS 13.0, *) {
return 0
} else {
return PXLayout.getStatusBarHeight()
}
}
func render() {
view.layer.borderWidth = Constants.viewBorderWidth
view.layer.borderColor = UIColor.Andes.graySolid070.cgColor
view.layer.cornerRadius = 10
view.backgroundColor = UIColor.Andes.white
tableView.layer.cornerRadius = 10
tableView.layer.masksToBounds = true
if #available(iOS 12.0, *) {
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
tableView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
let footerView = getFooterView()
view.addSubview(footerView)
// Footer view layout
NSLayoutConstraint.activate([
footerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
footerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
footerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
tableView.register(PXPaymentMethodsCell.self, forCellReuseIdentifier: PXPaymentMethodsCell.identifier)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.separatorInset = .init(top: 0, left: PXLayout.S_MARGIN, bottom: 0, right: PXLayout.S_MARGIN)
tableView.separatorColor = UIColor.black.withAlphaComponent(0.1)
tableView.backgroundColor = .white
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: PXLayout.L_MARGIN),
tableView.bottomAnchor.constraint(equalTo: footerView.topAnchor)
])
tableView.reloadData()
// Inactivity View - rendered but hidden
renderInactivityView(text: viewModel.getTitleForLastSection())
view.bringSubviewToFront(footerView)
}
private func autoSelectPaymentMethodIfNeeded() {
guard let indexPath = viewModel.selectedIndexPath else { return }
selectPaymentMethodAtIndexPath(indexPath)
}
private func selectPaymentMethodAtIndexPath(_ indexPath: IndexPath) {
viewModel.selectedIndexPath = indexPath
PXFeedbackGenerator.selectionFeedback()
if viewModel.selectedIndexPath != nil {
loadingButtonComponent?.setEnabled()
} else {
loadingButtonComponent?.setDisabled()
}
if let selectedPaymentOption = viewModel.getSelectedOfflineMethod() {
callbackUpdatePaymentOption(selectedPaymentOption)
}
}
private func getBottomPayButtonMargin() -> CGFloat {
let safeAreaBottomHeight = PXLayout.getSafeAreaBottomInset()
if safeAreaBottomHeight > 0 {
return PXLayout.XXS_MARGIN + safeAreaBottomHeight
}
if UIDevice.isSmallDevice() {
return PXLayout.XS_MARGIN
}
return PXLayout.M_MARGIN
}
private func getFooterView() -> UIView {
let footerContainer = UIView()
footerContainer.translatesAutoresizingMaskIntoConstraints = false
footerContainer.backgroundColor = .white
var displayInfoLabel: UILabel?
if let description = viewModel.getDisplayInfo()?.bottomDescription {
displayInfoLabel = buildLabel()
if let label = displayInfoLabel {
label.text = description.message
if let backgroundColor = description.backgroundColor {
label.backgroundColor = UIColor.fromHex(backgroundColor)
}
if let textColor = description.textColor {
label.textColor = UIColor.fromHex(textColor)
}
footerContainer.addSubview(label)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: footerContainer.leadingAnchor, constant: PXLayout.M_MARGIN),
label.trailingAnchor.constraint(equalTo: footerContainer.trailingAnchor, constant: -PXLayout.M_MARGIN),
label.topAnchor.constraint(equalTo: footerContainer.topAnchor, constant: PXLayout.S_MARGIN)
])
}
}
let loadingButtonComponent = PXWindowedAnimatedButton(normalText: "Pagar".localized, loadingText: "Procesando tu pago".localized, retryText: "Reintentar".localized)
self.loadingButtonComponent = loadingButtonComponent
loadingButtonComponent.animationDelegate = self
loadingButtonComponent.layer.cornerRadius = 4
loadingButtonComponent.add(for: .touchUpInside, { [weak self] in
guard let self = self else { return }
self.confirmPayment()
})
loadingButtonComponent.setTitle("Pagar".localized, for: .normal)
loadingButtonComponent.backgroundColor = ThemeManager.shared.getAccentColor()
loadingButtonComponent.accessibilityIdentifier = "pay_button"
loadingButtonComponent.setDisabled()
footerContainer.addSubview(loadingButtonComponent)
var topConstraint: NSLayoutConstraint
if let label = displayInfoLabel {
topConstraint = loadingButtonComponent.topAnchor.constraint(equalTo: label.bottomAnchor, constant: PXLayout.S_MARGIN)
} else {
topConstraint = loadingButtonComponent.topAnchor.constraint(equalTo: footerContainer.topAnchor, constant: PXLayout.S_MARGIN)
}
topConstraint.isActive = true
NSLayoutConstraint.activate([
loadingButtonComponent.bottomAnchor.constraint(greaterThanOrEqualTo: footerContainer.bottomAnchor, constant: -getBottomPayButtonMargin()),
loadingButtonComponent.leadingAnchor.constraint(equalTo: footerContainer.leadingAnchor, constant: PXLayout.M_MARGIN),
loadingButtonComponent.trailingAnchor.constraint(equalTo: footerContainer.trailingAnchor, constant: -PXLayout.M_MARGIN)
])
PXLayout.setHeight(owner: loadingButtonComponent, height: PXLayout.XXL_MARGIN).isActive = true
footerContainer.dropShadow()
return footerContainer
}
private func buildLabel() -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.font = UIFont.ml_semiboldSystemFont(ofSize: PXLayout.XXXS_FONT)
return label
}
}
// MARK: Inactivity view methods
extension PXOfflineMethodsViewController {
func showInactivityView(animated: Bool = true) {
self.inactivityView?.isHidden = false
let animator = UIViewPropertyAnimator(duration: animated ? 0.3 : 0, dampingRatio: 1) {
self.inactivityViewAnimationConstraint?.constant = -PXLayout.XS_MARGIN
self.inactivityView?.alpha = 1
self.view.layoutIfNeeded()
}
animator.startAnimation()
}
func hideInactivityView(animated: Bool = true) {
let animator = UIViewPropertyAnimator(duration: animated ? 0.3 : 0, dampingRatio: 1) {
self.inactivityViewAnimationConstraint?.constant = PXLayout.M_MARGIN
self.inactivityView?.alpha = 0
self.view.layoutIfNeeded()
}
self.inactivityView?.isHidden = true
animator.startAnimation()
}
func showInactivityViewIfNecessary() {
if let inactivityView = inactivityView, inactivityView.isHidden, !userDidScroll, hasHiddenPaymentTypes() {
showInactivityView()
}
}
func hideInactivityViewIfNecessary() {
if let inactivityView = inactivityView, !inactivityView.isHidden, userDidScroll, !hasHiddenPaymentTypes() {
hideInactivityView()
}
}
func hasHiddenPaymentTypes() -> Bool {
guard let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows else { return false }
let visibleRowsLastSection = indexPathsForVisibleRows.filter { indexPath -> Bool in
return indexPath.section == viewModel.numberOfSections() - 1
}
return visibleRowsLastSection.isEmpty
}
func renderInactivityView(text: String?) {
let viewHeight: CGFloat = 28
let imageSize: CGFloat = 16
let inactivityView = UIView()
inactivityView.translatesAutoresizingMaskIntoConstraints = false
inactivityView.backgroundColor = ThemeManager.shared.navigationBar().backgroundColor
inactivityView.layer.cornerRadius = viewHeight / 2
view.addSubview(inactivityView)
NSLayoutConstraint.activate([
inactivityView.heightAnchor.constraint(equalToConstant: viewHeight),
inactivityView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
let bottomConstraint = inactivityView.bottomAnchor.constraint(equalTo: tableView.bottomAnchor, constant: -PXLayout.XS_MARGIN)
bottomConstraint.isActive = true
self.inactivityView = inactivityView
self.inactivityViewAnimationConstraint = bottomConstraint
let arrowImage = ResourceManager.shared.getImage("inactivity_indicator")?.imageWithOverlayTint(tintColor: ThemeManager.shared.navigationBar().getTintColor())
let imageView = UIImageView(image: arrowImage)
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: inactivityView.leadingAnchor, constant: PXLayout.XS_MARGIN),
imageView.centerYAnchor.constraint(equalTo: inactivityView.centerYAnchor),
imageView.heightAnchor.constraint(equalToConstant: imageSize),
imageView.widthAnchor.constraint(equalToConstant: imageSize)
])
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = ThemeManager.shared.navigationBar().getTintColor()
label.font = UIFont.ml_regularSystemFont(ofSize: PXLayout.XXXS_FONT)
label.text = text
inactivityView.addSubview(label)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: PXLayout.XXS_MARGIN),
label.trailingAnchor.constraint(equalTo: inactivityView.trailingAnchor, constant: -PXLayout.XS_MARGIN),
label.topAnchor.constraint(equalTo: inactivityView.topAnchor, constant: PXLayout.XXS_MARGIN),
label.bottomAnchor.constraint(equalTo: inactivityView.bottomAnchor, constant: -PXLayout.XXS_MARGIN)
])
hideInactivityView(animated: false)
}
}
// MARK: UITableViewDelegate & DataSource
extension PXOfflineMethodsViewController: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRowsInSection(section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: PXPaymentMethodsCell.identifier, for: indexPath) as? PXPaymentMethodsCell {
let data = viewModel.dataForCellAt(indexPath)
cell.render(data: data)
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let title = viewModel.headerTitleForSection(section)
let view = UIView()
view.backgroundColor = UIColor.Andes.white
view.layer.cornerRadius = Constants.viewCornerRadius
if #available(iOS 12.0, *) {
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
if title?.weight == nil {
label.text = title?.message
label.font = UIFont.ml_semiboldSystemFont(ofSize: PXLayout.M_FONT)
label.textColor = UIColor.Andes.gray900
} else {
label.attributedText = title?.getAttributedString(fontSize: PXLayout.M_FONT)
}
view.addSubview(label)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: PXLayout.S_MARGIN),
label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: PXLayout.S_MARGIN),
label.bottomAnchor.constraint(equalTo: view.bottomAnchor),
label.topAnchor.constraint(equalTo: view.topAnchor)
])
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 55
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView(frame: .zero)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return viewModel.heightForRowAt(indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectPaymentMethodAtIndexPath(indexPath)
tableView.reloadData()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
userDidScroll = true
hideInactivityViewIfNecessary()
}
}
// MARK: Payment Button animation delegate
@available(iOS 9.0, *)
extension PXOfflineMethodsViewController: PXAnimatedButtonDelegate {
func shakeDidFinish() {
displayBackButton()
isUIEnabled(true)
unsubscribeFromNotifications()
UIView.animate(withDuration: 0.3, animations: {
self.loadingButtonComponent?.backgroundColor = ThemeManager.shared.getAccentColor()
})
}
func expandAnimationInProgress() {
}
func didFinishAnimation() {
self.dismiss(animated: true, completion: { [weak self] in
self?.loadingButtonComponent?.animatedView?.removeFromSuperview()
})
self.finishButtonAnimation()
}
func progressButtonAnimationTimeOut() {
loadingButtonComponent?.showErrorToast(title: "review_and_confirm_toast_error".localized, actionTitle: nil, type: MLSnackbarType.error(), duration: .short, action: nil)
}
private func confirmPayment() {
isUIEnabled(false)
if viewModel.shouldValidateWithBiometric() {
viewModel.validateWithReauth { [weak self] in
DispatchQueue.main.async {
self?.doPayment()
}
} onError: { [weak self] _ in
self?.isUIEnabled(true)
self?.trackEvent(event: GeneralErrorTrackingEvents.error([:]))
}
} else {
doPayment()
}
}
private func doPayment() {
if shouldAnimateButton() {
subscribeLoadingButtonToNotifications()
loadingButtonComponent?.startLoading(timeOut: self.timeOutPayButton)
disableModalDismiss()
}
if let selectedOfflineMethod = viewModel.getSelectedOfflineMethod(), let newPaymentMethod = viewModel.getOfflinePaymentMethod(targetOfflinePaymentMethod: selectedOfflineMethod) {
let currentPaymentData: PXPaymentData = viewModel.amountHelper.getPaymentData()
currentPaymentData.payerCost = nil
currentPaymentData.paymentMethod = newPaymentMethod
currentPaymentData.issuer = nil
amountOfButtonPress += 1
trackEvent(event: PXOfflineMethodsTrackingEvents.didConfirm(viewModel.getEventTrackingProperties(selectedOfflineMethod)))
let resultTracking = strategyTracking.getPropertiesTrackings(versionLib: "", counter: amountOfButtonPress, paymentMethod: nil, offlinePaymentMethod: selectedOfflineMethod, businessResult: nil)
trackEvent(event: PXPaymentsInfoGeneralEvents.infoGeneral_Follow_Confirm_Payments(resultTracking))
if let payerCompliance = viewModel.getPayerCompliance(), payerCompliance.offlineMethods.isCompliant {
currentPaymentData.payer?.firstName = viewModel.getPayerFirstName()
currentPaymentData.payer?.lastName = viewModel.getPayerLastName()
currentPaymentData.payer?.identification = viewModel.getPayerIdentification()
}
}
let splitPayment = false
hideBackButton()
hideNavBar()
callbackConfirm(viewModel.amountHelper.getPaymentData(), splitPayment)
if shouldShowKyC() {
dismiss(animated: false, completion: nil)
callbackFinishCheckout()
}
}
func isUIEnabled(_ enabled: Bool) {
delegate?.didEnableUI(enabled: enabled)
tableView.isScrollEnabled = enabled
view.isUserInteractionEnabled = enabled
loadingButtonComponent?.isUserInteractionEnabled = enabled
}
private func shouldAnimateButton() -> Bool {
return !shouldShowKyC()
}
private func shouldShowKyC() -> Bool {
if let selectedOfflineMethod = viewModel.getSelectedOfflineMethod(), selectedOfflineMethod.hasAdditionalInfoNeeded,
let compliant = viewModel.getPayerCompliance()?.offlineMethods.isCompliant, !compliant {
return true
}
return false
}
private func disableModalDismiss() {
if #available(iOS 13.0, *) {
isModalInPresentation = true
}
}
}
// MARK: Notifications
extension PXOfflineMethodsViewController {
func subscribeLoadingButtonToNotifications() {
guard let loadingButton = loadingButtonComponent else {
return
}
PXNotificationManager.SuscribeTo.animateButton(loadingButton, selector: #selector(loadingButton.animateFinish))
}
func unsubscribeFromNotifications() {
PXNotificationManager.UnsuscribeTo.animateButton(loadingButtonComponent)
}
}
| mit | 1a4d1d6cbf695ed31bc8956a0ef723bf | 39.786408 | 275 | 0.688931 | 5.406692 | false | false | false | false |
Awalz/ark-ios-monitor | ArkMonitor/SwiftyArk+Extensions.swift | 1 | 6780 | // Copyright (c) 2016 Ark
//
// 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 SwiftyArk
public let _screenWidth = UIScreen.main.bounds.width
public let _screenHeight = UIScreen.main.bounds.height
extension Transaction {
enum TransacionStatus {
case sent
case received
case vote
case unknown
}
func status() -> TransacionStatus {
guard let myAddress = ArkDataManager.manager.settings?.address else {
return .unknown
}
if type == 3 {
return .vote
}
if recipientId == myAddress {
return .received
} else if senderId == myAddress {
return .sent
} else {
return .unknown
}
}
}
extension Double {
func formatString(_ decimalPoints: Int) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = decimalPoints
formatter.maximumFractionDigits = decimalPoints
let number = NSNumber(value: self)
return formatter.string(from: number) ?? "\(self)"
}
}
extension Date {
var fullStyleDateString: String {
let formatterLongDate = DateFormatter()
formatterLongDate.dateStyle = .full
return formatterLongDate.string(from: self)
}
var longStyleDateString: String {
let formatterLongDate = DateFormatter()
formatterLongDate.dateFormat = "MMM dd, hh:mm a"
return formatterLongDate.string(from: self)
}
var shortDateOnlyString: String {
let formatterShortDate = DateFormatter()
formatterShortDate.dateFormat = "dd/MM/yy"
return formatterShortDate.string(from: self)
}
}
func delay(_ delay: Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
extension Array where Element: Comparable {
func containsSameElements(as other: [Element]) -> Bool {
return self.count == other.count && self.sorted() == other.sorted()
}
}
extension UISearchBar {
public func updateColors() {
backgroundColor = ArkPalette.backgroundColor
tintColor = UIColor.white
for subview in self.subviews {
for view in subview.subviews {
if view.isKind(of: NSClassFromString("UISearchBarBackground")!) {
let imageView = view as! UIImageView
imageView.removeFromSuperview()
}
}
}
if let textField = self.value(forKey: "searchField") as? UITextField {
textField.backgroundColor = ArkPalette.secondaryBackgroundColor
textField.textColor = ArkPalette.highlightedTextColor
textField.borderStyle = .roundedRect
searchTextPositionAdjustment = UIOffsetMake(5.0, 0.0)
if let placeholderLabel = textField.value(forKey: "placeholderLabel") as? UILabel {
placeholderLabel.textColor = UIColor.white
}
if let clearButton = textField.value(forKey: "clearButton") as? UIButton {
clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
clearButton.tintColor = UIColor.white
}
}
}
}
extension String {
func isNumeric() -> Bool {
if let _ = range(of: "^[0-9]+$", options: .regularExpression) {
return true
}
return false
}
}
extension UIImage {
func maskWithColor(color: UIColor) -> UIImage? {
let maskLayer = CALayer()
maskLayer.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
maskLayer.backgroundColor = color.cgColor
maskLayer.doMask(by: self)
let maskImage = maskLayer.toImage()
return maskImage
}
}
extension CALayer {
func doMask(by imageMask: UIImage) {
let maskLayer = CAShapeLayer()
maskLayer.bounds = CGRect(x: 0, y: 0, width: imageMask.size.width, height: imageMask.size.height)
bounds = maskLayer.bounds
maskLayer.contents = imageMask.cgImage
maskLayer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
mask = maskLayer
}
func toImage() -> UIImage?
{
UIGraphicsBeginImageContextWithOptions(bounds.size,
isOpaque,
UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension UIButton {
public func title(_ text: String, color: UIColor) {
setTitle(text, for: UIControlState())
setTitleColor(color, for: UIControlState())
}
public func setBackgroundColor(_ color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
| mit | b4f75edde7512692707d70fc594389d4 | 32.073171 | 137 | 0.628024 | 5.113122 | false | false | false | false |
ktatroe/MPA-Horatio | Horatio/Horatio/Classes/JSON/JSONParsing.swift | 2 | 7953 | //
// Copyright © 2016 Kevin Tatroe. All rights reserved.
// See LICENSE.txt for this sample’s licensing information
import Foundation
public typealias JSONObject = [String : Any]
/// Options for parsing and validating JSON using the `JSONParser` class.
public struct JSONParsingOptions: OptionSet {
public let rawValue: Int
/// No options set.
public static let none = JSONParsingOptions(rawValue: 0)
/// Allow empty values (will be converted to a default value when parsed).
public static let allowEmpty = JSONParsingOptions(rawValue: 1)
/// Allow value conversion; for example, if bare literal instead of requested array, convert to an array containing it.
public static let allowConversion = JSONParsingOptions(rawValue: 2)
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
/**
Normalizes values from JSON objects, with options for allowing for conversion from unexpected value
types and missing values.
*/
open class JSONParser {
public static func parseIdentifier(_ value: Any?, options: JSONParsingOptions = .none) -> String? {
if let stringValue = JSONParser.parseString(value) {
return stringValue.lowercased()
}
return nil
}
public static func parseString(_ value: Any?, options: JSONParsingOptions = .none) -> String? {
if let stringValue = value as? String {
return stringValue.stringByDecodingJavascriptEntities()
}
if options.contains(.allowConversion) {
if let numberValue = value as? NSNumber {
return String(describing: numberValue)
}
}
if options.contains(.allowEmpty) {
return ""
}
return nil
}
public static func parseInt(_ value: Any?, options: JSONParsingOptions = .none) -> Int? {
if let intValue = value as? Int {
return intValue
}
if options.contains(.allowConversion) {
if let numberValue = value as? NSNumber {
return Int(truncating: numberValue)
}
if let stringValue = value as? String {
return Int(stringValue)
}
}
if options.contains(.allowEmpty) {
return 0
}
return nil
}
public static func parseDouble(_ value: Any?, options: JSONParsingOptions = .none) -> Double? {
if let doubleValue = value as? Double {
return doubleValue
}
if options.contains(.allowConversion) {
if let numberValue = value as? NSNumber {
return Double(truncating: numberValue)
}
if let stringValue = value as? String {
return Double(stringValue)
}
}
if options.contains(.allowEmpty) {
return 0.0
}
return nil
}
public static func parseBool(_ value: Any?, options: JSONParsingOptions = .none) -> Bool? {
if let boolValue = value as? Bool {
return boolValue
}
if options.contains(.allowConversion) {
if let numberValue = value as? NSNumber {
return Bool(truncating: numberValue)
}
if let stringValue = value as? String {
if stringValue.lowercased() == "true" || stringValue == "1" {
return true
}
return false
}
}
if options.contains(.allowEmpty) {
return false
}
return nil
}
public static func parseArray(_ value: Any?, options: JSONParsingOptions = .none) -> [Any]? {
if let arrayValue = value as? [Any] {
return arrayValue
}
if let value = value {
if let _ = value as? NSNull {
if options.contains(.allowConversion) {
return [Any]()
}
}
if options.contains(.allowConversion) {
return [value]
}
}
if options.contains(.allowEmpty) {
return [Any]()
}
return nil
}
public static func parseObject(_ value: Any?, options: JSONParsingOptions = .none) -> JSONObject? {
if let objectValue = value as? [String : Any] {
return objectValue
}
if let value = value {
if let _ = value as? NSNull {
if options.contains(.allowConversion) {
return [String : Any]()
}
}
}
if options.contains(.allowEmpty) {
return [String : Any]()
}
return nil
}
public static func parseISO8601Date(_ value: Any?, options: JSONParsingOptions = .none) -> Date? {
if let dateString = JSONParser.parseString(value, options: options) {
if let dateValue = Date.dateFromISO8601String(dateString) {
return dateValue
}
}
if options.contains(.allowEmpty) {
return Date()
}
return nil
}
public static func parseDecimalNumber(_ value: Any?, options: JSONParsingOptions = .none) -> NSDecimalNumber? {
if let decimalString = JSONParser.parseString(value, options: options) {
return NSDecimalNumber(string: decimalString, locale: [NSLocale.Key.decimalSeparator: "."])
}
if options.contains(.allowEmpty) {
return NSDecimalNumber.zero
}
return nil
}
}
public protocol JSONParsing {
func updateFromJSONRepresentation(_ data: JSONObject)
static func isValidJSONRepresentation (_ data: JSONObject) -> Bool
}
extension String {
func stringByDecodingJavascriptEntities() -> String {
func decodeHexValue(_ string: String, base: Int32) -> Character? {
let code = UInt32(strtoul(string, nil, base))
return Character(UnicodeScalar(code)!)
}
func decodeEntity(_ entity: String) -> Character? {
if entity.hasPrefix("\\x") || entity.hasPrefix("\\u") {
return decodeHexValue(String(entity[entity.index(entity.startIndex, offsetBy: 2)]), base: 16)
}
return nil
}
var result = ""
var position = startIndex
let entityBeacons = ["\\x", "\\u"]
for beacon in entityBeacons {
while let entityRange = self.range(of: beacon, range: position ..< endIndex) {
result += self[position ..< entityRange.lowerBound]
position = entityRange.lowerBound
let entityLength = (beacon == "\\u") ? 6 : 4
let indexAtEntityEnd = self.index(position, offsetBy: entityLength)
let entity = self[position ..< indexAtEntityEnd]
if let decodedEntity = decodeEntity(String(entity)) {
result.append(decodedEntity)
} else {
result.append(String(entity))
}
position = indexAtEntityEnd
}
}
result += self[position ..< endIndex]
return result
}
}
extension Date {
struct ISO8601Support {
static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}()
}
public static func dateFromISO8601String(_ string: String) -> Date? {
return ISO8601Support.formatter.date(from: string)
}
public var iso8601String: String { return ISO8601Support.formatter.string(from: self) }
}
| mit | c3d744972d91709fe09b64394a3674a8 | 28.014599 | 123 | 0.568176 | 5.009452 | false | false | false | false |
findmybusnj/findmybusnj-swift | findmybusnj-common/Presenter/ETAPresenter.swift | 1 | 3661 | //
// ETAPresenter.swift
// findmybusnj
//
// Created by David Aghassi on 4/19/16.
// Copyright © 2016 David Aghassi. All rights reserved.
//
import UIKit
// Dependecies
import SwiftyJSON
/**
* Base protocol representing a presenter that handles ETA cell formatting
*/
public protocol ETAPresenter {
var sanitizer: JSONSanitizer { get set }
func formatCellForPresentation(_ cell: UITableViewCell, json: JSON)
func assignArrivalTimeForJson(_ cell: UITableViewCell, json: JSON)
func assignBusAndRouteTextForJson(_ cell: UITableViewCell, json: JSON)
}
public extension ETAPresenter {
/**
Based on the json provided, uses the `JSONSanitizer` to check the
`arrivalTime` (an `int`) and the `arrivalString` (a `string` representation of the time).
If we are dealing with `arrivalTime`, we determine if the bus has `"Arrived"`
(meaning it is 0), otherwise we know that it is still coming and return `"Minutes"`.
If we don't have an `arrivalTime` (-1), then we determine if the bus is
`"Arriving"` or `"Delayed"` using `determineNonZeroArrivalString`
- parameter json: A `JSON` object that is returned from the server to be parsed
- returns: A `String` that is either "Arrived", "Minutes", "Arriving", or "Delayed"
*/
func determineArrivalCase(json: JSON) -> String {
let arrivalString = sanitizer.getSanatizedArrivalTimeAsString(json)
let arrivalTime = sanitizer.getSanitizedArrivaleTimeAsInt(json)
if arrivalTime != -1 {
if arrivalTime == NumericArrivals.arrived.rawValue {
return "Arrived"
} else {
return "Minutes"
}
} else {
#if DEBUG
print(arrivalString)
print(json)
#endif
return determineNonZeroArrivalString(arrivalString: arrivalString)
}
}
/**
Determines the background color to be displayed in the cell given the time.
Cases:
- 0: `powderBlue`
- 1...7: `emeraldGreen`
- 8...14: `creamsicleOrange`
- X > 14: `lollipopRed`
See `ColorPalette` for the above colors.
- returns: Any of the above colors depending on the case.
*/
func backgroundColorForTime(_ time: Int) -> UIColor {
let colorPalette = ColorPalette()
switch time {
case 0:
// Blue
return colorPalette.powderBlue()
case 1...7:
// Green
return colorPalette.emeraldGreen()
case 8...14:
// Orange
return colorPalette.creamsicleOrange()
default:
return colorPalette.lollipopRed()
}
}
/**
Used to determine the type of string to be displayed if the incoming buses
provided via the `JSON` response are `"Arriving"` or `"Delayed"`.
- parameter arrivalString: Passed by `determineArrivalCase`.
Compared to `NonNumericalArrivals` enum to determine if `"Arriving"` or `"Delayed"`
- returns: A string of `"Arriving"` or `"Delayed"`. If neither, returns "0".
*/
func determineNonZeroArrivalString(arrivalString: String) -> String {
switch arrivalString {
case NonNumericArrivals.APPROACHING.rawValue:
return "Arriving"
case NonNumericArrivals.DELAYED.rawValue:
return "Delay"
default:
return "0"
}
}
}
/**
Enum representing states of incoming buses that are less than 1 minute
- APPROACHING: The `description` of the incoming bus is "APPROACHING"
- DELAYED: The `description` of the incoming bus is "DELAYED"
*/
public enum NonNumericArrivals: String {
case APPROACHING
case DELAYED
}
/**
Checks the cases that are special for numeric arrivals
- ARRIVED: When the `description` of the incoming bus is `0`
*/
public enum NumericArrivals: Int {
case arrived = 0
}
| gpl-3.0 | 6b348f72ab7fe318f6de099099217fa5 | 28.047619 | 92 | 0.684973 | 4.017563 | false | false | false | false |
DarlingXIe/WeiBoProject | WeiBo/WeiBo/Classes/Tools/Temp/XDLQRToolBarController.swift | 1 | 11780 | //
// XDLTempViewController.swift
// WeiBo
//
// Created by DalinXie on 16/9/11.
// Copyright © 2016年 itcast. All rights reserved.
//
/*
static var token: dispatch_once_t = 0
func whatDoYouHear() {
print("All of this has happened before, and all of it will happen again.")
dispatch_once(&token) {
print("Except this part.")
}
}
*/
import UIKit
import AVFoundation
class XDLQRToolBarController: UIViewController {
var flag = 0
var qrCodeScanCons : Constraint?
var QRScanViewCons: Constraint?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
//MARK: - setupUI()
private func setupUI(){
title = "Scan QR Code"
self.view.backgroundColor = UIColor.white
navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "compose_toolbar_picture", title: "", target: self, action: #selector(pushTestVc))
navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_back", title: " ", target: self, action: #selector(backToPrevious))
//self.navigationController?.navigationBar.barTintColor = UIColor.darkGray
view.addSubview(SQToolBar)
view.addSubview(QRScanView)
SQToolBar.snp_makeConstraints { (make) in
make.left.right.bottom.equalTo(self.view)
make.height.equalTo(49)
}
QRScanView.snp_makeConstraints { (make) in
make.center.equalTo(self.view)
self.QRScanViewCons = make.height.equalTo(300).constraint
//make.height.constraint = self.QRScanViewCons?
make.width.equalTo(300)
}
QRScanView.addSubview(qrCodeView)
qrCodeView.addSubview(qrLineCodeView)
qrCodeView.snp_makeConstraints { (make) in
make.edges.equalTo(self.QRScanView)
}
qrLineCodeView.snp_makeConstraints{(make) in
make.width.equalTo(300)
self.qrCodeScanCons = make.height.equalTo(SQScanCodeWH).constraint
make.top.equalTo(qrCodeView)
make.left.equalTo(qrCodeView)
//make.edges.equalTo(self.qrCodeView)
}
self.SQToolBar.clickSQClosure = {[weak self](type:XDLQRToolBarButtonType) -> () in
print("****clickComposeButtons\(self)")
switch type {
case .SQCode:
print("SQCode")
self?.qrLineCodeView.layer.removeAllAnimations()
self?.QRScanView.snp_updateConstraints{(make) in
make.height.equalTo(SQScanCodeWH)
self?.view.layoutIfNeeded()
}
self?.startAnimation(type: type)
self?.flag = 0
case .SQLongCode:
if(self?.flag == 0){
print("SQLongCode")
self?.qrLineCodeView.layer.removeAllAnimations()
//self?.QRScanViewCons?.uninstall()
self?.QRScanView.snp_updateConstraints{(make) in
self?.QRScanViewCons? = make.height.equalTo(SQScanCodeWH/2).constraint
}
self?.startAnimation(type: .SQLongCode)
self?.flag = 1
}
/****************************************************************/
// self?.qrCodeScanCons?.uninstall()
// self?.qrLineCodeView.snp_updateConstraints{(make) in
// //make.centerY.equalTo(-300)
// self?.qrCodeScanCons = make.height.equalTo(-SQScanCodeWH).constraint
// }
// self?.view.layoutIfNeeded()
// self?.qrCodeScanCons?.uninstall()
// UIView.animate(withDuration: 1.0) {
// UIView.setAnimationRepeatCount(MAXFLOAT)
// self?.qrLineCodeView.snp_updateConstraints{(make) in
// //make.centerY.equalTo(-300)
// SQScanCodeWH = SQScanCodeWH/2
// self?.qrCodeScanCons = make.height.equalTo(SQScanCodeWH).constraint
// }
// self?.view.layoutIfNeeded()
// }
/****************************************************************/
}
}
startScanCode()
}
private func startAnimation(type: XDLQRToolBarButtonType){
qrCodeScanCons?.uninstall()
//QRScanViewCons?.uninstall()
qrLineCodeView.snp_updateConstraints{(make) in
//make.centerY.equalTo(-300)
self.qrCodeScanCons = make.height.equalTo(-SQScanCodeWH).constraint
}
self.view.layoutIfNeeded()
// UIView.animate(withDuration: 1.0) {
// UIView.setAnimationRepeatCount(MAXFLOAT)
// self.qrLineCodeView.snp_updateConstraints{(make) in
// //make.centerY.equalTo(-300)
//// SQScanCodeWH = (type == .SQLongCode) ? (SQScanCodeWH + 10) : SQScanCodeWH/2
// if(type == .SQLongCode){
// SQScanCodeWH = SQScanCodeWH/2
// self.qrCodeScanCons = make.height.equalTo(SQScanCodeWH).constraint
// }else{
// self.qrCodeScanCons = make.height.equalTo(SQScanCodeWH).constraint
// }
// }
// self.view.layoutIfNeeded()
// }
UIView.animate(withDuration: 1.0, animations: {
UIView.setAnimationRepeatCount(MAXFLOAT)
self.qrLineCodeView.snp_updateConstraints{(make) in
//make.centerY.equalTo(-300)
// SQScanCodeWH = (type == .SQLongCode) ? (SQScanCodeWH + 10) : SQScanCodeWH/2
if(type == .SQLongCode){
SQScanCodeWH = SQScanCodeWH/2
self.qrCodeScanCons = make.height.equalTo(SQScanCodeWH).constraint
}else{
self.qrCodeScanCons = make.height.equalTo(SQScanCodeWH).constraint
}
}
self.view.layoutIfNeeded()
}) { (_) in
// self.QRScanView.snp_updateConstraints{(make) in
// self.QRScanViewCons? = make.height.equalTo(SQScanCodeWH).constraint
// }
SQScanCodeWH = 300
self.view.layoutIfNeeded()
}
}
private func startScanCode(){
let videoCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
// 创建 input object.
//let videoInput: AVCaptureDeviceInput?
do {
let videoInput = try! AVCaptureDeviceInput(device: videoCaptureDevice)
//1. input
if session.canAddInput(videoInput) == false{
return
}
//2. output
if session.canAddOutput(deviceOutput) == false{
return
}
//3. add input and output into sesstion
session.addInput(videoInput)
session.addOutput(deviceOutput)
//4. setting output to deal with data
deviceOutput.metadataObjectTypes = deviceOutput.availableMetadataObjectTypes
//5. monitor data from the output
deviceOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
//6. add preScanView
view.layer.insertSublayer(preViewScan, at: 0)
//6. startScan
session.startRunning()
} catch {
return
}
}
//
/* optional public func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)*/
override func viewWillAppear(_ animated: Bool) {
print("qrLineCodeView appear")
qrCodeScanCons?.uninstall()
qrLineCodeView.snp_updateConstraints{(make) in
self.qrCodeScanCons = make.height.equalTo(-SQScanCodeWH).constraint
}
self.view.layoutIfNeeded()
qrCodeScanCons?.uninstall()
UIView.animate(withDuration: 1.0) {
UIView.setAnimationRepeatCount(MAXFLOAT)
self.qrLineCodeView.snp_updateConstraints{(make) in
self.qrCodeScanCons = make.height.equalTo( (SQScanCodeWH + 10)).constraint
}
self.view.layoutIfNeeded()
}
}
//click navigationItemButton
@objc private func pushTestVc(){
print("Album")
}
//click navigationBackItemButton
@objc private func backToPrevious(){
_ = navigationController?.popViewController(animated: true)
// navigationController?.navigationBar.barTintColor = UIColor(red: 247/255.0, green: 247/255.0, blue: 247/250.0, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - lazy var QRScanCode
//1. input
// internal lazy var deviceInput :AVCaptureDeviceInput = {()-> AVCaptureDeviceInput in
//
// let videoCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) ?? ""
//// let deviceInput = AVCaptureDevice.defaultDevice(withDeviceType: nil, mediaType: AVMediaTypeVideo, position: AVCaptureDevicePositionUnspecified)
// //label.textColor = UIcolor.red
// return try AVCaptureDeviceInput.init(device:videoCaptureDevice)
// return AnyObject! = AVCaptureDeviceInput.deviceInputWithDevice(videoCaptureDevice, error: nil)
// //return deviceInput
// }()
//2. session
internal lazy var session :AVCaptureSession = {()-> AVCaptureSession in
let Session = AVCaptureSession()
//label.textColor = UIcolor.red
return Session
}()
//3. output
internal lazy var deviceOutput :AVCaptureMetadataOutput = {()-> AVCaptureMetadataOutput in
let deviceOutput = AVCaptureMetadataOutput()
//label.textColor = UIcolor.red
return deviceOutput
}()
internal lazy var preViewScan :AVCaptureVideoPreviewLayer = {()-> AVCaptureVideoPreviewLayer in
let preViewScan = AVCaptureVideoPreviewLayer(session: self.session)
//label.textColor = UIcolor.red
return preViewScan!
}()
//MARK: - lazy var UI
internal lazy var SQToolBar :XDLQRToolBar = {()-> XDLQRToolBar in
let SQToolBar = XDLQRToolBar()
//label.textColor = UIcolor.red
return SQToolBar
}()
internal lazy var QRScanView :XDLQRScanView = {()-> XDLQRScanView in
let QRScanView = XDLQRScanView()
return QRScanView
}()
internal lazy var qrCodeView :UIImageView = {()-> UIImageView in
let QRScanView = UIImageView(image:UIImage(named:"qrcode_border"))
return QRScanView
}()
internal lazy var qrLineCodeView :UIImageView = {()-> UIImageView in
let QRLineScanView = UIImageView(image: UIImage(named: "qrcode_scanline_qrcode"))
return QRLineScanView
}()
}
extension XDLQRToolBarController:AVCaptureMetadataOutputObjectsDelegate{
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!){
print(metadataObjects.last as! NSString)
}
}
| mit | 22b13c6a5281557fd017d983db6dff8f | 34.248503 | 167 | 0.570543 | 5.014055 | false | false | false | false |
Coderian/SwiftedGPX | SwiftedGPX/Elements/Metadata.swift | 1 | 4952 | //
// Metadata.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX Metadata
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="metadata" type="metadataType" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Metadata about the file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class Metadata : SPXMLElement, HasXMLElementValue {
public static var elementName: String = "metadata"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch self.parent {
case let v as Gpx: v.value.metadata = self
default: break
}
}
}
}
public var value:MetadataType = MetadataType()
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
}
/// GPX MetadataType
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:complexType name="metadataType">
/// <xsd:annotation>
/// <xsd:documentation>
/// Information about the GPX file, author, and copyright restrictions goes in the metadata section. Providing rich,
/// meaningful information about your GPX files allows others to search for and use your GPS data.
/// </xsd:documentation>
/// </xsd:annotation>
/// <xsd:sequence> <!-- elements must appear in this order -->
/// <xsd:element name="name" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// The name of the GPX file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="desc" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// A description of the contents of the GPX file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="author" type="personType" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// The person or organization who created the GPX file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="copyright" type="copyrightType" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Copyright and license information governing use of the file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="link" type="linkType" minOccurs="0" maxOccurs="unbounded">
/// <xsd:annotation>
/// <xsd:documentation>
/// URLs associated with the location described in the file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="time" type="xsd:dateTime" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// The creation date of the file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="keywords" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Keywords associated with the file. Search engines or databases can use this information to classify the data.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="bounds" type="boundsType" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Minimum and maximum coordinates which describe the extent of the coordinates in the file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
///
/// <xsd:element name="extensions" type="extensionsType" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// You can add extend GPX by adding your own elements from another schema here.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// </xsd:sequence>
/// </xsd:complexType>
public class MetadataType {
var name:Name!
var desc:Description!
var author:Author!
var copyright:Copyright!
var link:Link!
var time:Time!
var keywords:Keywords!
var bounds:Bounds!
var extensions:Extensions!
}
| mit | 1e226c51bf2b91ffabb7df506958ac06 | 36.653846 | 128 | 0.550562 | 3.897293 | false | false | false | false |
fedepo/phoneid_iOS | Pod/Classes/ui/views/controls/WebImageView.swift | 2 | 2576 | //
// WebImageView.swift
// phoneid_iOS
//
// Copyright 2015 phone.id - 73 knots, Inc.
//
// 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
class WebImageView: UIImageView {
var activityIndicator:UIActivityIndicatorView!
init(){
super.init(frame:CGRect.zero)
setupSubviews()
}
override init(frame:CGRect)
{
super.init(frame:frame)
setupSubviews()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupSubviews()
}
func setupSubviews(){
activityIndicator = UIActivityIndicatorView()
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(activityIndicator)
addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant:0))
addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant:0))
}
func getDataFromUrl(_ url:String, completion: @escaping ((_ data: Data?) -> Void)) {
if let urlSession = PhoneIdService.sharedInstance.urlSession {
var request = URLRequest(url: URL(string: url)!)
request.cachePolicy = NSURLRequest.CachePolicy.useProtocolCachePolicy
let dataTask = urlSession.dataTask(with: request, completionHandler: { (data, response, error) in
completion(data)
})
dataTask.resume()
}
}
func downloadImage(_ url:String?){
guard url != nil else {
return
}
self.activityIndicator.startAnimating()
getDataFromUrl(url!) { data in
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.image = data != nil ? UIImage(data: data!) : nil
}
}
}
}
| apache-2.0 | f784c8baa0a8dc438c00040a98197059 | 31.607595 | 168 | 0.63354 | 4.878788 | false | false | false | false |
zhxnlai/Emoticon | EmoticonKeyboard/EmoticonKeyboard/EKQueryEmoticonsCollectionViewController.swift | 1 | 1579 | //
// EKRecentEmoticonsCollectionViewController.swift
// EmoticonKeyboard
//
// Created by Zhixuan Lai on 5/10/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
class EKQueryEmoticonsCollectionViewController: UICollectionViewController {
var dataSourceDelegate = EKQueryEmoticonsCollectionViewDataSourceDelegate()
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.registerClass(EKEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView?.registerClass(EKSectionHeaderView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier)
collectionView?.registerClass(UICollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier)
dataSourceDelegate.sectionHeaderTitle = title
dataSourceDelegate.hideSectionHeader = true
dataSourceDelegate.didSelectEmoticon = {emoticon in
let text = emoticon.value
var pasteboard = UIPasteboard.generalPasteboard()
pasteboard.string = text
}
collectionView?.backgroundColor = UIColor.whiteColor()
collectionView?.dataSource = dataSourceDelegate
collectionView?.delegate = dataSourceDelegate
// Do any additional setup after loading the view.
collectionView?.reloadData()
}
}
| mit | 14124c46f5c029b51acd84bce0d39c59 | 38.475 | 184 | 0.732742 | 6.634454 | false | false | false | false |
mkaply/firefox-ios | Client/Frontend/Home/FirefoxHomeViewController.swift | 4 | 49072 | /* 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 Shared
import UIKit
import Storage
import SDWebImage
import XCGLogger
import SyncTelemetry
import SnapKit
private let log = Logger.browserLogger
private let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites"
// MARK: - Lifecycle
struct FirefoxHomeUX {
static let rowSpacing: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 30 : 20
static let highlightCellHeight: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 250 : 200
static let sectionInsetsForSizeClass = UXSizeClasses(compact: 0, regular: 101, other: 20)
static let numberOfItemsPerRowForSizeClassIpad = UXSizeClasses(compact: 3, regular: 4, other: 2)
static let SectionInsetsForIpad: CGFloat = 101
static let SectionInsetsForIphone: CGFloat = 20
static let MinimumInsets: CGFloat = 20
static let TopSitesInsets: CGFloat = 6
static let LibraryShortcutsHeight: CGFloat = 100
static let LibraryShortcutsMaxWidth: CGFloat = 350
}
/*
Size classes are the way Apple requires us to specify our UI.
Split view on iPad can make a landscape app appear with the demensions of an iPhone app
Use UXSizeClasses to specify things like offsets/itemsizes with respect to size classes
For a primer on size classes https://useyourloaf.com/blog/size-classes/
*/
struct UXSizeClasses {
var compact: CGFloat
var regular: CGFloat
var unspecified: CGFloat
init(compact: CGFloat, regular: CGFloat, other: CGFloat) {
self.compact = compact
self.regular = regular
self.unspecified = other
}
subscript(sizeClass: UIUserInterfaceSizeClass) -> CGFloat {
switch sizeClass {
case .compact:
return self.compact
case .regular:
return self.regular
case .unspecified:
return self.unspecified
@unknown default:
fatalError()
}
}
}
protocol HomePanelDelegate: AnyObject {
func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool)
func homePanel(didSelectURL url: URL, visitType: VisitType)
func homePanelDidRequestToOpenLibrary(panel: LibraryPanelType)
}
protocol HomePanel: Themeable {
var homePanelDelegate: HomePanelDelegate? { get set }
}
enum HomePanelType: Int {
case topSites = 0
var internalUrl: URL {
let aboutUrl: URL! = URL(string: "\(InternalURL.baseUrl)/\(AboutHomeHandler.path)")
return URL(string: "#panel=\(self.rawValue)", relativeTo: aboutUrl)!
}
}
protocol HomePanelContextMenu {
func getSiteDetails(for indexPath: IndexPath) -> Site?
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]?
func presentContextMenu(for indexPath: IndexPath)
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?)
}
extension HomePanelContextMenu {
func presentContextMenu(for indexPath: IndexPath) {
guard let site = getSiteDetails(for: indexPath) else { return }
presentContextMenu(for: site, with: indexPath, completionHandler: {
return self.contextMenu(for: site, with: indexPath)
})
}
func contextMenu(for site: Site, with indexPath: IndexPath) -> PhotonActionSheet? {
guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil }
let contextMenu = PhotonActionSheet(site: site, actions: actions)
contextMenu.modalPresentationStyle = .overFullScreen
contextMenu.modalTransitionStyle = .crossDissolve
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
return contextMenu
}
func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [PhotonActionSheetItem]? {
guard let siteURL = URL(string: site.url) else { return nil }
let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { _, _ in
homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false)
}
let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { _, _ in
homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true)
}
return [openInNewTabAction, openInNewPrivateTabAction]
}
}
class FirefoxHomeViewController: UICollectionViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
fileprivate let profile: Profile
fileprivate let pocketAPI = Pocket()
fileprivate let flowLayout = UICollectionViewFlowLayout()
fileprivate lazy var topSitesManager: ASHorizontalScrollCellManager = {
let manager = ASHorizontalScrollCellManager()
return manager
}()
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(longPress))
}()
// Not used for displaying. Only used for calculating layout.
lazy var topSiteCell: ASHorizontalScrollCell = {
let customCell = ASHorizontalScrollCell(frame: CGRect(width: self.view.frame.size.width, height: 0))
customCell.delegate = self.topSitesManager
return customCell
}()
var pocketStories: [PocketStory] = []
init(profile: Profile) {
self.profile = profile
super.init(collectionViewLayout: flowLayout)
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
collectionView?.addGestureRecognizer(longPressRecognizer)
let refreshEvents: [Notification.Name] = [.DynamicFontChanged, .HomePanelPrefsChanged]
refreshEvents.forEach { NotificationCenter.default.addObserver(self, selector: #selector(reload), name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
Section.allValues.forEach { self.collectionView?.register(Section($0.rawValue).cellType, forCellWithReuseIdentifier: Section($0.rawValue).cellIdentifier) }
self.collectionView?.register(ASHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header")
self.collectionView?.register(ASFooterView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "Footer")
collectionView?.keyboardDismissMode = .onDrag
self.profile.panelDataObservers.activityStream.delegate = self
applyTheme()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadAll()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: {context in
//The AS context menu does not behave correctly. Dismiss it when rotating.
if let _ = self.presentedViewController as? PhotonActionSheet {
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
self.collectionViewLayout.invalidateLayout()
self.collectionView?.reloadData()
}, completion: { _ in
// Workaround: label positions are not correct without additional reload
self.collectionView?.reloadData()
})
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.topSitesManager.currentTraits = self.traitCollection
}
@objc func reload(notification: Notification) {
reloadAll()
}
func applyTheme() {
collectionView?.backgroundColor = UIColor.theme.homePanel.topSitesBackground
topSiteCell.collectionView.reloadData()
if let collectionView = self.collectionView, collectionView.numberOfSections > 0, collectionView.numberOfItems(inSection: 0) > 0 {
collectionView.reloadData()
}
}
func scrollToTop(animated: Bool = false) {
collectionView?.setContentOffset(.zero, animated: animated)
}
}
// MARK: - Section management
extension FirefoxHomeViewController {
enum Section: Int {
case topSites
case libraryShortcuts
case pocket
static let count = 3
static let allValues = [topSites, libraryShortcuts, pocket]
var title: String? {
switch self {
case .pocket: return Strings.ASPocketTitle
case .topSites: return Strings.ASTopSitesTitle
case .libraryShortcuts: return Strings.AppMenuLibraryTitleString
}
}
var headerHeight: CGSize {
return CGSize(width: 50, height: 40)
}
var headerImage: UIImage? {
switch self {
case .pocket: return UIImage.templateImageNamed("menu-pocket")
case .topSites: return UIImage.templateImageNamed("menu-panel-TopSites")
case .libraryShortcuts: return UIImage.templateImageNamed("menu-library")
}
}
var footerHeight: CGSize {
switch self {
case .pocket: return .zero
case .topSites, .libraryShortcuts: return CGSize(width: 50, height: 5)
}
}
func cellHeight(_ traits: UITraitCollection, width: CGFloat) -> CGFloat {
switch self {
case .pocket: return FirefoxHomeUX.highlightCellHeight
case .topSites: return 0 //calculated dynamically
case .libraryShortcuts: return FirefoxHomeUX.LibraryShortcutsHeight
}
}
/*
There are edge cases to handle when calculating section insets
- An iPhone 7+ is considered regular width when in landscape
- An iPad in 66% split view is still considered regular width
*/
func sectionInsets(_ traits: UITraitCollection, frameWidth: CGFloat) -> CGFloat {
var currentTraits = traits
if (traits.horizontalSizeClass == .regular && UIScreen.main.bounds.size.width != frameWidth) || UIDevice.current.userInterfaceIdiom == .phone {
currentTraits = UITraitCollection(horizontalSizeClass: .compact)
}
var insets = FirefoxHomeUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass]
switch self {
case .pocket, .libraryShortcuts:
let window = UIApplication.shared.keyWindow
let safeAreaInsets = window?.safeAreaInsets.left ?? 0
insets += FirefoxHomeUX.MinimumInsets + safeAreaInsets
return insets
case .topSites:
insets += FirefoxHomeUX.TopSitesInsets
return insets
}
}
func numberOfItemsForRow(_ traits: UITraitCollection) -> CGFloat {
switch self {
case .pocket:
var numItems: CGFloat = FirefoxHomeUX.numberOfItemsPerRowForSizeClassIpad[traits.horizontalSizeClass]
if UIApplication.shared.statusBarOrientation.isPortrait {
numItems = numItems - 1
}
if traits.horizontalSizeClass == .compact && UIApplication.shared.statusBarOrientation.isLandscape {
numItems = numItems - 1
}
return numItems
case .topSites, .libraryShortcuts:
return 1
}
}
func cellSize(for traits: UITraitCollection, frameWidth: CGFloat) -> CGSize {
let height = cellHeight(traits, width: frameWidth)
let inset = sectionInsets(traits, frameWidth: frameWidth) * 2
switch self {
case .pocket:
let numItems = numberOfItemsForRow(traits)
return CGSize(width: floor(((frameWidth - inset) - (FirefoxHomeUX.MinimumInsets * (numItems - 1))) / numItems), height: height)
case .topSites, .libraryShortcuts:
return CGSize(width: frameWidth - inset, height: height)
}
}
var headerView: UIView? {
let view = ASHeaderView()
view.title = title
return view
}
var cellIdentifier: String {
switch self {
case .topSites: return "TopSiteCell"
case .pocket: return "PocketCell"
case .libraryShortcuts: return "LibraryShortcutsCell"
}
}
var cellType: UICollectionViewCell.Type {
switch self {
case .topSites: return ASHorizontalScrollCell.self
case .pocket: return FirefoxHomeHighlightCell.self
case .libraryShortcuts: return ASLibraryCell.self
}
}
init(at indexPath: IndexPath) {
self.init(rawValue: indexPath.section)!
}
init(_ section: Int) {
self.init(rawValue: section)!
}
}
}
// MARK: - Tableview Delegate
extension FirefoxHomeViewController: UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! ASHeaderView
view.iconView.isHidden = false
view.iconView.image = Section(indexPath.section).headerImage
let title = Section(indexPath.section).title
switch Section(indexPath.section) {
case .pocket:
view.title = title
view.moreButton.isHidden = false
view.moreButton.setTitle(Strings.PocketMoreStoriesText, for: .normal)
view.moreButton.addTarget(self, action: #selector(showMorePocketStories), for: .touchUpInside)
view.titleLabel.textColor = UIColor.Pocket.red
view.titleLabel.accessibilityIdentifier = "pocketTitle"
view.moreButton.setTitleColor(UIColor.Pocket.red, for: .normal)
view.iconView.tintColor = UIColor.Pocket.red
return view
case .topSites:
view.title = title
view.titleLabel.accessibilityIdentifier = "topSitesTitle"
view.moreButton.isHidden = true
return view
case .libraryShortcuts:
view.title = title
view.moreButton.isHidden = false
view.moreButton.setTitle(Strings.AppMenuLibrarySeeAllTitleString, for: .normal)
view.moreButton.addTarget(self, action: #selector(openHistory), for: .touchUpInside)
view.moreButton.accessibilityIdentifier = "libraryMoreButton"
view.titleLabel.accessibilityIdentifier = "libraryTitle"
return view
}
case UICollectionView.elementKindSectionFooter:
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "Footer", for: indexPath) as! ASFooterView
switch Section(indexPath.section) {
case .topSites, .pocket:
return view
case .libraryShortcuts:
view.separatorLineView?.isHidden = true
return view
}
default:
return UICollectionReusableView()
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.longPressRecognizer.isEnabled = false
selectItemAtIndex(indexPath.item, inSection: Section(indexPath.section))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize = Section(indexPath.section).cellSize(for: self.traitCollection, frameWidth: self.view.frame.width)
switch Section(indexPath.section) {
case .topSites:
// Create a temporary cell so we can calculate the height.
let layout = topSiteCell.collectionView.collectionViewLayout as! HorizontalFlowLayout
let estimatedLayout = layout.calculateLayout(for: CGSize(width: cellSize.width, height: 0))
return CGSize(width: cellSize.width, height: estimatedLayout.size.height)
case .pocket:
return cellSize
case .libraryShortcuts:
let numberofshortcuts: CGFloat = 4
let titleSpacing: CGFloat = 10
let width = min(FirefoxHomeUX.LibraryShortcutsMaxWidth, cellSize.width)
return CGSize(width: width, height: (width / numberofshortcuts) + titleSpacing)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
switch Section(section) {
case .pocket:
return pocketStories.isEmpty ? .zero : Section(section).headerHeight
case .topSites:
return Section(section).headerHeight
case .libraryShortcuts:
return UIDevice.current.userInterfaceIdiom == .pad ? CGSize.zero : Section(section).headerHeight
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
switch Section(section) {
case .pocket:
return .zero
case .topSites:
return Section(section).footerHeight
case .libraryShortcuts:
return UIDevice.current.userInterfaceIdiom == .pad ? CGSize.zero : Section(section).footerHeight
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return FirefoxHomeUX.rowSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let insets = Section(section).sectionInsets(self.traitCollection, frameWidth: self.view.frame.width)
return UIEdgeInsets(top: 0, left: insets, bottom: 0, right: insets)
}
fileprivate func showSiteWithURLHandler(_ url: URL) {
let visitType = VisitType.bookmark
homePanelDelegate?.homePanel(didSelectURL: url, visitType: visitType)
}
}
// MARK: - Tableview Data Source
extension FirefoxHomeViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numItems: CGFloat = FirefoxHomeUX.numberOfItemsPerRowForSizeClassIpad[self.traitCollection.horizontalSizeClass]
if UIApplication.shared.statusBarOrientation.isPortrait {
numItems = numItems - 1
}
if self.traitCollection.horizontalSizeClass == .compact && UIApplication.shared.statusBarOrientation.isLandscape {
numItems = numItems - 1
}
switch Section(section) {
case .topSites:
return topSitesManager.content.isEmpty ? 0 : 1
case .pocket:
// There should always be a full row of pocket stories (numItems) otherwise don't show them
return pocketStories.count
case .libraryShortcuts:
// disable the libary shortcuts on the ipad
return UIDevice.current.userInterfaceIdiom == .pad ? 0 : 1
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier = Section(indexPath.section).cellIdentifier
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
switch Section(indexPath.section) {
case .topSites:
return configureTopSitesCell(cell, forIndexPath: indexPath)
case .pocket:
return configurePocketItemCell(cell, forIndexPath: indexPath)
case .libraryShortcuts:
return configureLibraryShortcutsCell(cell, forIndexPath: indexPath)
}
}
func configureLibraryShortcutsCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let libraryCell = cell as! ASLibraryCell
let targets = [#selector(openBookmarks), #selector(openReadingList), #selector(openDownloads), #selector(openSyncedTabs)]
libraryCell.libraryButtons.map({ $0.button }).zip(targets).forEach { (button, selector) in
button.removeTarget(nil, action: nil, for: .allEvents)
button.addTarget(self, action: selector, for: .touchUpInside)
}
libraryCell.applyTheme()
return cell
}
//should all be collectionview
func configureTopSitesCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let topSiteCell = cell as! ASHorizontalScrollCell
topSiteCell.delegate = self.topSitesManager
topSiteCell.setNeedsLayout()
topSiteCell.collectionView.reloadData()
return cell
}
func configurePocketItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let pocketStory = pocketStories[indexPath.row]
let pocketItemCell = cell as! FirefoxHomeHighlightCell
pocketItemCell.configureWithPocketStory(pocketStory)
return pocketItemCell
}
}
// MARK: - Data Management
extension FirefoxHomeViewController: DataObserverDelegate {
// Reloads both highlights and top sites data from their respective caches. Does not invalidate the cache.
// See ActivityStreamDataObserver for invalidation logic.
func reloadAll() {
// If the pocket stories are not availible for the Locale the PocketAPI will return nil
// So it is okay if the default here is true
self.getTopSites().uponQueue(.main) { _ in
// If there is no pending cache update and highlights are empty. Show the onboarding screen
self.collectionView?.reloadData()
self.getPocketSites().uponQueue(.main) { _ in
if !self.pocketStories.isEmpty {
self.collectionView?.reloadData()
}
}
// Refresh the AS data in the background so we'll have fresh data next time we show.
self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: false)
}
}
func getPocketSites() -> Success {
let showPocket = (profile.prefs.boolForKey(PrefsKeys.ASPocketStoriesVisible) ?? Pocket.IslocaleSupported(Locale.current.identifier))
guard showPocket else {
self.pocketStories = []
return succeed()
}
return pocketAPI.globalFeed(items: 10).bindQueue(.main) { pStory in
self.pocketStories = pStory
return succeed()
}
}
@objc func showMorePocketStories() {
showSiteWithURLHandler(Pocket.MoreStoriesURL)
}
func getTopSites() -> Success {
let numRows = max(self.profile.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows, 1)
let maxItems = UIDevice.current.userInterfaceIdiom == .pad ? 32 : 16
return self.profile.history.getTopSitesWithLimit(maxItems).both(self.profile.history.getPinnedTopSites()).bindQueue(.main) { (topsites, pinnedSites) in
guard let mySites = topsites.successValue?.asArray(), let pinned = pinnedSites.successValue?.asArray() else {
return succeed()
}
// How sites are merged together. We compare against the url's base domain. example m.youtube.com is compared against `youtube.com`
let unionOnURL = { (site: Site) -> String in
return URL(string: site.url)?.normalizedHost ?? ""
}
// Fetch the default sites
let defaultSites = self.defaultTopSites()
// create PinnedSite objects. used by the view layer to tell topsites apart
let pinnedSites: [Site] = pinned.map({ PinnedSite(site: $0) })
// Merge default topsites with a user's topsites.
let mergedSites = mySites.union(defaultSites, f: unionOnURL)
// Merge pinnedSites with sites from the previous step
let allSites = pinnedSites.union(mergedSites, f: unionOnURL)
// Favour topsites from defaultSites as they have better favicons. But keep PinnedSites
let newSites = allSites.map { site -> Site in
if let _ = site as? PinnedSite {
return site
}
let domain = URL(string: site.url)?.shortDisplayString
return defaultSites.find { $0.title.lowercased() == domain } ?? site
}
self.topSitesManager.currentTraits = self.view.traitCollection
let maxItems = Int(numRows) * self.topSitesManager.numberOfHorizontalItems()
if newSites.count > Int(ActivityStreamTopSiteCacheSize) {
self.topSitesManager.content = Array(newSites[0..<Int(ActivityStreamTopSiteCacheSize)])
} else {
self.topSitesManager.content = newSites
}
if newSites.count > maxItems {
self.topSitesManager.content = Array(newSites[0..<maxItems])
}
self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in
self.longPressRecognizer.isEnabled = false
self.showSiteWithURLHandler(url as URL)
}
return succeed()
}
}
// Invoked by the ActivityStreamDataObserver when highlights/top sites invalidation is complete.
func didInvalidateDataSources(refresh forced: Bool, topSitesRefreshed: Bool) {
// Do not reload panel unless we're currently showing the highlight intro or if we
// force-reloaded the highlights or top sites. This should prevent reloading the
// panel after we've invalidated in the background on the first load.
if forced {
reloadAll()
}
}
func hideURLFromTopSites(_ site: Site) {
guard let host = site.tileURL.normalizedHost else {
return
}
let url = site.tileURL.absoluteString
// if the default top sites contains the siteurl. also wipe it from default suggested sites.
if defaultTopSites().filter({$0.url == url}).isEmpty == false {
deleteTileForSuggestedSite(url)
}
profile.history.removeHostFromTopSites(host).uponQueue(.main) { result in
guard result.isSuccess else { return }
self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true)
}
}
func pinTopSite(_ site: Site) {
profile.history.addPinnedTopSite(site).uponQueue(.main) { result in
guard result.isSuccess else { return }
self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true)
}
}
func removePinTopSite(_ site: Site) {
profile.history.removeFromPinnedTopSites(site).uponQueue(.main) { result in
guard result.isSuccess else { return }
self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true)
}
}
fileprivate func deleteTileForSuggestedSite(_ siteURL: String) {
var deletedSuggestedSites = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
deletedSuggestedSites.append(siteURL)
profile.prefs.setObject(deletedSuggestedSites, forKey: DefaultSuggestedSitesKey)
}
func defaultTopSites() -> [Site] {
let suggested = SuggestedSites.asArray()
let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
return suggested.filter({deleted.firstIndex(of: $0.url) == .none})
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == .began else { return }
let point = longPressGestureRecognizer.location(in: self.collectionView)
guard let indexPath = self.collectionView?.indexPathForItem(at: point) else { return }
switch Section(indexPath.section) {
case .pocket:
presentContextMenu(for: indexPath)
case .topSites:
let topSiteCell = self.collectionView?.cellForItem(at: indexPath) as! ASHorizontalScrollCell
let pointInTopSite = longPressGestureRecognizer.location(in: topSiteCell.collectionView)
guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItem(at: pointInTopSite) else { return }
presentContextMenu(for: topSiteIndexPath)
case .libraryShortcuts:
return
}
}
fileprivate func fetchBookmarkStatus(for site: Site, with indexPath: IndexPath, forSection section: Section, completionHandler: @escaping () -> Void) {
profile.places.isBookmarked(url: site.url).uponQueue(.main) { result in
let isBookmarked = result.successValue ?? false
site.setBookmarked(isBookmarked)
completionHandler()
}
}
func selectItemAtIndex(_ index: Int, inSection section: Section) {
let site: Site?
switch section {
case .pocket:
site = Site(url: pocketStories[index].url.absoluteString, title: pocketStories[index].title)
let params = ["Source": "Activity Stream", "StoryType": "Article"]
LeanPlumClient.shared.track(event: .openedPocketStory, withParameters: params)
case .topSites:
return
case .libraryShortcuts:
return
}
if let site = site {
showSiteWithURLHandler(URL(string: site.url)!)
}
}
}
extension FirefoxHomeViewController {
@objc func openBookmarks() {
homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .bookmarks)
}
@objc func openHistory() {
homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .history)
}
@objc func openSyncedTabs() {
homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .syncedTabs)
}
@objc func openReadingList() {
homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .readingList)
}
@objc func openDownloads() {
homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .downloads)
}
}
extension FirefoxHomeViewController: HomePanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
fetchBookmarkStatus(for: site, with: indexPath, forSection: Section(indexPath.section)) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
switch Section(indexPath.section) {
case .pocket:
return Site(url: pocketStories[indexPath.row].url.absoluteString, title: pocketStories[indexPath.row].title)
case .topSites:
return topSitesManager.content[indexPath.item]
case .libraryShortcuts:
return nil
}
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
guard let siteURL = URL(string: site.url) else { return nil }
var sourceView: UIView?
switch Section(indexPath.section) {
case .topSites:
if let topSiteCell = self.collectionView?.cellForItem(at: IndexPath(row: 0, section: 0)) as? ASHorizontalScrollCell {
sourceView = topSiteCell.collectionView.cellForItem(at: indexPath)
}
case .pocket:
sourceView = self.collectionView?.cellForItem(at: indexPath)
case .libraryShortcuts:
return nil
}
let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { _, _ in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false)
let source = ["Source": "Activity Stream Long Press Context Menu"]
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: source)
if Section(indexPath.section) == .pocket {
LeanPlumClient.shared.track(event: .openedPocketStory, withParameters: source)
}
}
let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { _, _ in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true)
}
let bookmarkAction: PhotonActionSheetItem
if site.bookmarked ?? false {
bookmarkAction = PhotonActionSheetItem(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { _, _ in
self.profile.places.deleteBookmarksWithURL(url: site.url) >>== {
self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: false)
site.setBookmarked(false)
}
TelemetryWrapper.recordEvent(category: .action, method: .delete, object: .bookmark, value: .activityStream)
})
} else {
bookmarkAction = PhotonActionSheetItem(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { _, _ in
let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon)
_ = self.profile.places.createBookmark(parentGUID: BookmarkRoots.MobileFolderGUID, url: shareItem.url, title: shareItem.title)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: .shared)
site.setBookmarked(true)
self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true)
LeanPlumClient.shared.track(event: .savedBookmark)
TelemetryWrapper.recordEvent(category: .action, method: .add, object: .bookmark, value: .activityStream)
})
}
let shareAction = PhotonActionSheetItem(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { _, _ in
let helper = ShareExtensionHelper(url: siteURL, tab: nil)
let controller = helper.createActivityViewController({ (_, _) in })
if UI_USER_INTERFACE_IDIOM() == .pad, let popoverController = controller.popoverPresentationController {
let cellRect = sourceView?.frame ?? .zero
let cellFrameInSuperview = self.collectionView?.convert(cellRect, to: self.collectionView) ?? .zero
popoverController.sourceView = sourceView
popoverController.sourceRect = CGRect(origin: CGPoint(x: cellFrameInSuperview.size.width/2, y: cellFrameInSuperview.height/2), size: .zero)
popoverController.permittedArrowDirections = [.up, .down, .left]
popoverController.delegate = self
}
self.present(controller, animated: true, completion: nil)
})
let removeTopSiteAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { _, _ in
self.hideURLFromTopSites(site)
})
let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { _, _ in
self.pinTopSite(site)
})
let removePinTopSite = PhotonActionSheetItem(title: Strings.RemovePinTopsiteActionTitle, iconString: "action_unpin", handler: { _, _ in
self.removePinTopSite(site)
})
let topSiteActions: [PhotonActionSheetItem]
if let _ = site as? PinnedSite {
topSiteActions = [removePinTopSite]
} else {
topSiteActions = [pinTopSite, removeTopSiteAction]
}
var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction]
switch Section(indexPath.section) {
case .pocket: break
case .topSites: actions.append(contentsOf: topSiteActions)
case .libraryShortcuts: break
}
return actions
}
}
extension FirefoxHomeViewController: UIPopoverPresentationControllerDelegate {
// Dismiss the popover if the device is being rotated.
// This is used by the Share UIActivityViewController action sheet on iPad
func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) {
popoverPresentationController.presentedViewController.dismiss(animated: false, completion: nil)
}
}
// MARK: - Section Header View
private struct FirefoxHomeHeaderViewUX {
static var SeparatorColor: UIColor { return UIColor.theme.homePanel.separator }
static let TextFont = DynamicFontHelper.defaultHelper.SmallSizeHeavyWeightAS
static let ButtonFont = DynamicFontHelper.defaultHelper.MediumSizeBoldFontAS
static let SeparatorHeight = 0.5
static let Insets: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? FirefoxHomeUX.SectionInsetsForIpad + FirefoxHomeUX.MinimumInsets : FirefoxHomeUX.MinimumInsets
static let TitleTopInset: CGFloat = 5
}
class ASFooterView: UICollectionReusableView {
var separatorLineView: UIView?
var leftConstraint: Constraint? //This constraint aligns content (Titles, buttons) between all sections.
override init(frame: CGRect) {
super.init(frame: frame)
let separatorLine = UIView()
self.backgroundColor = UIColor.clear
addSubview(separatorLine)
separatorLine.snp.makeConstraints { make in
make.height.equalTo(FirefoxHomeHeaderViewUX.SeparatorHeight)
leftConstraint = make.leading.equalTo(self.safeArea.leading).inset(insets).constraint
make.trailing.equalTo(self.safeArea.trailing).inset(insets)
make.top.equalTo(self.snp.top)
}
separatorLineView = separatorLine
applyTheme()
}
var insets: CGFloat {
return UIScreen.main.bounds.size.width == self.frame.size.width && UIDevice.current.userInterfaceIdiom == .pad ? FirefoxHomeHeaderViewUX.Insets : FirefoxHomeUX.MinimumInsets
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
separatorLineView?.isHidden = false
}
override func layoutSubviews() {
super.layoutSubviews()
// update the insets every time a layout happens.Insets change depending on orientation or size (ipad split screen)
leftConstraint?.update(offset: insets)
}
}
extension ASFooterView: Themeable {
func applyTheme() {
separatorLineView?.backgroundColor = FirefoxHomeHeaderViewUX.SeparatorColor
}
}
class ASHeaderView: UICollectionReusableView {
static let verticalInsets: CGFloat = 4
lazy fileprivate var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.text = self.title
titleLabel.textColor = UIColor.theme.homePanel.activityStreamHeaderText
titleLabel.font = FirefoxHomeHeaderViewUX.TextFont
titleLabel.minimumScaleFactor = 0.6
titleLabel.numberOfLines = 1
titleLabel.adjustsFontSizeToFitWidth = true
return titleLabel
}()
lazy var moreButton: UIButton = {
let button = UIButton()
button.isHidden = true
button.titleLabel?.font = FirefoxHomeHeaderViewUX.ButtonFont
button.contentHorizontalAlignment = .right
button.setTitleColor(UIConstants.SystemBlueColor, for: .normal)
button.setTitleColor(UIColor.Photon.Grey50, for: .highlighted)
return button
}()
lazy fileprivate var iconView: UIImageView = {
let imageView = UIImageView()
imageView.tintColor = UIColor.Photon.Grey50
imageView.isHidden = true
return imageView
}()
var title: String? {
willSet(newTitle) {
titleLabel.text = newTitle
}
}
var leftConstraint: Constraint?
var rightConstraint: Constraint?
var titleInsets: CGFloat {
get {
return UIScreen.main.bounds.size.width == self.frame.size.width && UIDevice.current.userInterfaceIdiom == .pad ? FirefoxHomeHeaderViewUX.Insets : FirefoxHomeUX.MinimumInsets
}
}
override func prepareForReuse() {
super.prepareForReuse()
moreButton.isHidden = true
moreButton.setTitle(nil, for: .normal)
moreButton.accessibilityIdentifier = nil;
titleLabel.text = nil
moreButton.removeTarget(nil, action: nil, for: .allEvents)
iconView.isHidden = true
iconView.tintColor = UIColor.theme.homePanel.activityStreamHeaderText
titleLabel.textColor = UIColor.theme.homePanel.activityStreamHeaderText
moreButton.setTitleColor(UIConstants.SystemBlueColor, for: .normal)
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
addSubview(moreButton)
addSubview(iconView)
moreButton.snp.makeConstraints { make in
make.top.equalTo(self.snp.top).offset(ASHeaderView.verticalInsets)
make.bottom.equalToSuperview().offset(-ASHeaderView.verticalInsets)
self.rightConstraint = make.trailing.equalTo(self.safeArea.trailing).inset(-titleInsets).constraint
}
moreButton.setContentCompressionResistancePriority(.required, for: .horizontal)
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(iconView.snp.trailing).offset(5)
make.trailing.equalTo(moreButton.snp.leading).inset(-FirefoxHomeHeaderViewUX.TitleTopInset)
make.top.equalTo(self.snp.top).offset(ASHeaderView.verticalInsets)
make.bottom.equalToSuperview().offset(-ASHeaderView.verticalInsets)
}
iconView.snp.makeConstraints { make in
self.leftConstraint = make.leading.equalTo(self.safeArea.leading).inset(titleInsets).constraint
make.centerY.equalTo(self.snp.centerY)
make.size.equalTo(16)
}
}
override func layoutSubviews() {
super.layoutSubviews()
leftConstraint?.update(offset: titleInsets)
rightConstraint?.update(offset: -titleInsets)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class LibraryShortcutView: UIView {
static let spacing: CGFloat = 15
var button = UIButton()
var title = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(button)
addSubview(title)
button.snp.makeConstraints { make in
make.top.equalToSuperview()
make.centerX.equalToSuperview()
make.width.equalTo(self).offset(-LibraryShortcutView.spacing)
make.height.equalTo(self.snp.width).offset(-LibraryShortcutView.spacing)
}
title.adjustsFontSizeToFitWidth = true
title.minimumScaleFactor = 0.7
title.lineBreakMode = .byTruncatingTail
title.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS
title.textAlignment = .center
title.snp.makeConstraints { make in
make.top.equalTo(button.snp.bottom).offset(5)
make.leading.trailing.equalToSuperview()
}
button.imageView?.contentMode = .scaleToFill
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsets(equalInset: LibraryShortcutView.spacing)
button.tintColor = .white
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
button.layer.cornerRadius = (self.frame.width - LibraryShortcutView.spacing) / 2
super.layoutSubviews()
}
}
class ASLibraryCell: UICollectionViewCell, Themeable {
var mainView = UIStackView()
struct LibraryPanel {
let title: String
let image: UIImage?
let color: UIColor
}
var libraryButtons: [LibraryShortcutView] = []
let bookmarks = LibraryPanel(title: Strings.AppMenuBookmarksTitleString, image: UIImage.templateImageNamed("menu-Bookmark"), color: UIColor.Photon.Blue50)
let history = LibraryPanel(title: Strings.AppMenuHistoryTitleString, image: UIImage.templateImageNamed("menu-panel-History"), color: UIColor.Photon.Orange50)
let readingList = LibraryPanel(title: Strings.AppMenuReadingListTitleString, image: UIImage.templateImageNamed("menu-panel-ReadingList"), color: UIColor.Photon.Teal60)
let downloads = LibraryPanel(title: Strings.AppMenuDownloadsTitleString, image: UIImage.templateImageNamed("menu-panel-Downloads"), color: UIColor.Photon.Magenta60)
let syncedTabs = LibraryPanel(title: Strings.AppMenuSyncedTabsTitleString, image: UIImage.templateImageNamed("menu-sync"), color: UIColor.Photon.Purple70)
override init(frame: CGRect) {
super.init(frame: frame)
mainView.distribution = .fillEqually
mainView.spacing = 10
addSubview(mainView)
mainView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
[bookmarks, readingList, downloads, syncedTabs].forEach { item in
let view = LibraryShortcutView()
view.button.setImage(item.image, for: .normal)
view.title.text = item.title
let words = view.title.text?.components(separatedBy: NSCharacterSet.whitespacesAndNewlines).count
view.title.numberOfLines = words == 1 ? 1 :2
view.button.backgroundColor = item.color
view.button.setTitleColor(UIColor.theme.homePanel.topSiteDomain, for: .normal)
view.accessibilityLabel = item.title
mainView.addArrangedSubview(view)
libraryButtons.append(view)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func applyTheme() {
libraryButtons.forEach { button in
button.title.textColor = UIColor.theme.homePanel.activityStreamCellTitle
}
}
override func prepareForReuse() {
super.prepareForReuse()
applyTheme()
}
}
open class PinnedSite: Site {
let isPinnedSite = true
init(site: Site) {
super.init(url: site.url, title: site.title, bookmarked: site.bookmarked)
self.icon = site.icon
self.metadata = site.metadata
}
}
| mpl-2.0 | dc4513ee09f3342753e42967c40f92ad | 42.197183 | 218 | 0.667957 | 5.299924 | false | false | false | false |
JunDang/SwiftFoundation | Sources/SwiftFoundation/RegularExpressionCompileOption.swift | 1 | 2281 | //
// RegularExpressionCompileOption.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 8/9/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin.C
#elseif os(Linux)
import Glibc
#endif
public extension RegularExpression {
/// POSIX Regular Expression Compilation Options
public enum CompileOption: Int32, BitMaskOption {
/// Do not differentiate case.
case CaseInsensitive
/// Use POSIX Extended Regular Expression syntax when interpreting regular expression.
/// If not set, POSIX Basic Regular Expression syntax is used.
case ExtendedSyntax
/// Report only success/fail.
case NoSub
/// Treat a newline in string as dividing string into multiple lines, so that ```$``` can match before the newline and ```^``` can match after. Also, don’t permit ```.``` to match a newline, and don’t permit ```[^…]``` to match a newline.
///
/// Otherwise, newline acts like any other ordinary character.
case NewLine
public init?(rawValue: POSIXRegularExpression.FlagBitmask) {
switch rawValue {
case REG_ICASE: self = CaseInsensitive
case REG_EXTENDED: self = ExtendedSyntax
case REG_NOSUB: self = NoSub
case REG_NEWLINE: self = NewLine
default: return nil
}
}
public var rawValue: POSIXRegularExpression.FlagBitmask {
switch self {
case .CaseInsensitive: return REG_ICASE
case .ExtendedSyntax: return REG_EXTENDED
case .NoSub: return REG_NOSUB
case .NewLine: return REG_NEWLINE
}
}
}
}
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
#elseif os(Linux)
public let REG_EXTENDED: Int32 = 1
public let REG_ICASE: Int32 = (REG_EXTENDED << 1)
public let REG_NEWLINE: Int32 = (REG_ICASE << 1)
public let REG_NOSUB: Int32 = (REG_NEWLINE << 1)
#endif
| mit | ed681957e662ca6d9c0a4bc97c662ea2 | 29.72973 | 246 | 0.558047 | 4.640816 | false | false | false | false |
larcus94/ImagePickerSheetController | ImagePickerSheetController/ImagePickerSheetController/Sheet/Preview/PreviewCollectionView.swift | 2 | 1752 | //
// PreviewCollectionView.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 07/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
class PreviewCollectionView: UICollectionView {
var bouncing: Bool {
if contentOffset.x < -contentInset.left { return true }
if contentOffset.x + frame.width > contentSize.width + contentInset.right { return true }
return false
}
var imagePreviewLayout: PreviewCollectionViewLayout {
return collectionViewLayout as! PreviewCollectionViewLayout
}
// MARK: - Initialization
init() {
super.init(frame: .zero, collectionViewLayout: PreviewCollectionViewLayout())
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
panGestureRecognizer.addTarget(self, action: #selector(PreviewCollectionView.handlePanGesture(gestureRecognizer:)))
}
// MARK: - Panning
@objc private func handlePanGesture(gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .ended {
let translation = gestureRecognizer.translation(in: self)
if translation == CGPoint() {
if !bouncing {
let possibleIndexPath = indexPathForItem(at: gestureRecognizer.location(in: self))
if let indexPath = possibleIndexPath {
selectItem(at: indexPath, animated: false, scrollPosition: [])
delegate?.collectionView?(self, didSelectItemAt: indexPath)
}
}
}
}
}
}
| mit | 61f6cd1260636a0f839b73971559bd11 | 29.736842 | 123 | 0.618721 | 5.440994 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Contacts/ViewPlaceholder.swift | 1 | 3743 | //
// ViewPlaceholder.swift
// Pigeon-project
//
// Created by Roman Mizin on 11/6/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
enum ViewPlaceholderPriority: CGFloat {
case low = 0.1
case medium = 0.5
case high = 1.0
}
enum ViewPlaceholderPosition {
case top
case center
}
enum ViewPlaceholderTitle: String {
case denied = "Falcon doesn't have access to your contacts"
case empty = "You don't have any Falcon Users yet."
case emptyChat = "You don't have any active conversations yet."
case emptySharedMedia = "You don't have any shared media yet."
}
enum ViewPlaceholderSubtitle: String {
case denied = "Please go to your iPhone Settings –– Privacy –– Contacts. Then select ON for Falcon."
case empty = "You can invite your friends to Flacon Messenger at the Contacts tab "
case emptyChat = "You can select somebody in Contacts, and send your first message."
case emptyString = ""
}
class ViewPlaceholder: UIView {
var title = UILabel()
var subtitle = UILabel()
var placeholderPriority: ViewPlaceholderPriority = .low
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
translatesAutoresizingMaskIntoConstraints = false
title.font = .systemFont(ofSize: 18)
title.textColor = ThemeManager.currentTheme().generalSubtitleColor
title.textAlignment = .center
title.numberOfLines = 0
title.translatesAutoresizingMaskIntoConstraints = false
subtitle.font = .systemFont(ofSize: 13)
subtitle.textColor = ThemeManager.currentTheme().generalSubtitleColor
subtitle.textAlignment = .center
subtitle.numberOfLines = 0
subtitle.translatesAutoresizingMaskIntoConstraints = false
addSubview(title)
title.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true
title.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true
title.heightAnchor.constraint(equalToConstant: 45).isActive = true
addSubview(subtitle)
subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 5).isActive = true
subtitle.leftAnchor.constraint(equalTo: leftAnchor, constant: 35).isActive = true
subtitle.rightAnchor.constraint(equalTo: rightAnchor, constant: -35).isActive = true
subtitle.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func add(for view: UIView, title: ViewPlaceholderTitle, subtitle: ViewPlaceholderSubtitle,
priority: ViewPlaceholderPriority, position: ViewPlaceholderPosition) {
guard priority.rawValue >= placeholderPriority.rawValue else { return }
placeholderPriority = priority
self.title.text = title.rawValue
self.subtitle.text = subtitle.rawValue
if position == .center {
self.title.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
}
if position == .top {
self.title.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true
}
DispatchQueue.main.async {
view.addSubview(self)
self.topAnchor.constraint(equalTo: view.topAnchor, constant: 135).isActive = true
self.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
self.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -20).isActive = true
}
}
func remove(from view: UIView, priority: ViewPlaceholderPriority) {
guard priority.rawValue >= placeholderPriority.rawValue else { return }
for subview in view.subviews where subview is ViewPlaceholder {
DispatchQueue.main.async {
subview.removeFromSuperview()
}
}
}
}
| gpl-3.0 | bbf0c1b44cb99c670b56f148d6bf7572 | 33.256881 | 102 | 0.732994 | 4.526061 | false | false | false | false |
lxcid/LXStateMachine | LXStateMachine/LXStateMachine/StateMachine.swift | 1 | 2063 | //
// StateMachine.swift
// LXStateMachine
//
// Created by Stan Chang Khin Boon on 29/9/15.
// Copyright © 2015 lxcid. All rights reserved.
//
import Foundation
public protocol EventType {
}
public protocol StateType {
typealias Event: EventType
}
public struct Transition<State: StateType> {
public let event: State.Event
public let fromState: State
public let toState: State
public init(event: State.Event, fromState: State, toState: State) {
self.event = event
self.fromState = fromState
self.toState = toState
}
}
public protocol StateMachineDelegate: class {
typealias State: StateType
// FIXME: (me@lxcid.com) Define `stateMachine` type as `AnyObject` instead of `StateMachine<Self>` to prevent requiring the conforming class to be final.
func stateMachine(stateMachine: AnyObject, nextStateForEvent event: State.Event, inCurrentState currentState: State) -> State?
func stateMachine(stateMachine: AnyObject, willPerformTransition transition: Transition<State>?)
func stateMachine(stateMachine: AnyObject, didPerformTransition transition: Transition<State>?)
}
public class StateMachine<Delegate: StateMachineDelegate> {
public var currentState: Delegate.State
public weak var delegate: Delegate?
public init(initialState: Delegate.State) {
self.currentState = initialState
}
public func sendEvent(event: Delegate.State.Event) {
guard let nextState = self.delegate?.stateMachine(self, nextStateForEvent: event, inCurrentState: self.currentState) else {
return
}
let transition = Transition(event: event, fromState: self.currentState, toState: nextState)
self.performTransition(transition)
}
public func performTransition(transition: Transition<Delegate.State>) {
self.delegate?.stateMachine(self, willPerformTransition: transition)
self.currentState = transition.toState
self.delegate?.stateMachine(self, didPerformTransition: transition)
}
}
| mit | e004557a9387e82d274e5de0ab8aaf28 | 32.803279 | 157 | 0.71969 | 4.697039 | false | false | false | false |
umer-hai/xiniuzhujia-swift | xiniuzhujia/CustomViews/KindView.swift | 1 | 2168 | //
// KindView.swift
// xiniuzhujia
//
// Created by 海广盼 on 16/5/22.
// Copyright © 2016年 22. All rights reserved.
//
import UIKit
///1.声明一个协议 :NSObjectProtocol, 只有这样才能在设置代理的时候前面添加weak
protocol KindViewDelegate : NSObjectProtocol{
//2.在协议中声明一个代理方法
func buttonClick(_ btn : UIButton)
}
class KindView: UIView {
//3.设置代理属性
weak var delegate : KindViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
let width = self.frame.width/4.0
let height = self.frame.height/2.0
let btnTitles = ["特色小吃","水果","夜宵","炒菜/火锅","山鲜花/蛋糕","粉/面","便利店","客服电话",]
for idx in 0..<8{
let x = CGFloat(idx%4)*width
let y = CGFloat(idx/4)*height
//按钮
let btn = UIButton.init(type: UIButtonType.custom)
btn.tag = idx+100
btn.frame = CGRect(x: x, y: y, width: width, height: height)
btn.layer.borderColor = UIColor.green.cgColor
btn.layer.borderWidth = 1
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btn.setTitleColor(UIColor.black, for: UIControlState())
btn.setImage(UIImage.init(named: "11_\(idx+1)"), for: UIControlState())
btn.addTarget(self, action: #selector(KindView.btnClick(_:)), for: UIControlEvents.touchUpInside)
self.addSubview(btn)
//按钮下标题
let label = UILabel.init(frame: CGRect(x: 0, y: btn.frame.height-20, width: btn.frame.width, height: 20))
label.font = UIFont.systemFont(ofSize: 12)
label.text = btnTitles[idx]
label.textAlignment = NSTextAlignment.center
btn.addSubview(label)
}
}
func btnClick(_ btn: UIButton){
//4.使用代理
self.delegate?.buttonClick(btn);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 4082cf7344b6ba3f320ae06ca3845a6c | 27.585714 | 117 | 0.573713 | 3.747191 | false | false | false | false |
curiousurick/BluetoothBackupSensor-iOS | CSS427Bluefruit_Connect/BLE Test/BLEDevice.swift | 4 | 7425 | //
// BLEDevice.swift
// Adafruit Bluefruit LE Connect
//
// Used to represent an unconnected peripheral in scanning/discovery list
//
// Created by Collin Cunningham on 10/17/14.
// Copyright (c) 2014 Adafruit Industries. All rights reserved.
//
import Foundation
import CoreBluetooth
class BLEDevice {
var peripheral: CBPeripheral!
var isUART:Bool = false
// var isDFU:Bool = false
private var advertisementData: [NSObject : AnyObject]
var RSSI:NSNumber {
didSet {
self.deviceCell?.updateSignalImage(RSSI)
}
}
private let nilString = "nil"
var connectableBool:Bool {
let num = advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber
if num != nil {
return num!.boolValue
}
else {
return false
}
}
var name:String = ""
var deviceCell:DeviceCell? {
didSet {
deviceCell?.nameLabel.text = self.name
deviceCell?.connectButton.hidden = !(self.connectableBool)
deviceCell?.updateSignalImage(RSSI)
deviceCell?.uartCapableLabel.hidden = !self.isUART
}
}
var localName:String {
var nameString = advertisementData[CBAdvertisementDataLocalNameKey] as? NSString
if nameString == nil {
nameString = nilString
}
return nameString! as String
}
var manufacturerData:String {
let newData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? NSData
if newData == nil {
return nilString
}
let dataString = newData?.hexRepresentation()
return dataString!
}
var serviceData:String {
let dict = advertisementData[CBAdvertisementDataServiceDataKey] as? NSDictionary
if dict == nil {
return nilString
}
else {
return dict!.description
}
}
var serviceUUIDs:[String] {
let svcIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? NSArray
if svcIDs == nil {
return [nilString]
}
return self.stringsFromUUIDs(svcIDs!)
}
var overflowServiceUUIDs:[String] {
let ovfIDs = advertisementData[CBAdvertisementDataOverflowServiceUUIDsKey] as? NSArray
if ovfIDs == nil {
return [nilString]
}
return self.stringsFromUUIDs(ovfIDs!)
}
var txPowerLevel:String {
let txNum = advertisementData[CBAdvertisementDataTxPowerLevelKey] as? NSNumber
if txNum == nil {
return nilString
}
return txNum!.stringValue
}
var isConnectable:String {
let num = advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber
if num == nil {
return nilString
}
let verdict = num!.boolValue
//Enable connect button according to connectable value
if self.deviceCell?.connectButton != nil {
deviceCell?.connectButton.enabled = verdict
}
return verdict.description
}
var solicitedServiceUUIDs:[String] {
let ssIDs = advertisementData[CBAdvertisementDataSolicitedServiceUUIDsKey] as? NSArray
if ssIDs == nil {
return [nilString]
}
return self.stringsFromUUIDs(ssIDs!)
}
var RSSString:String {
return RSSI.stringValue
}
var identifier:NSUUID? {
if self.peripheral == nil {
printLog(self, funcName: "identifier", logString: "attempting to retrieve peripheral ID before peripheral set")
return nil
}
else {
return self.peripheral.identifier
}
}
var UUIDString:String {
let str = self.identifier?.UUIDString
if str != nil {
return str!
}
else {
return nilString
}
}
var advertisementArray:[[String]] = []
init(peripheral:CBPeripheral!, advertisementData:[NSObject : AnyObject]!, RSSI:NSNumber!) {
self.peripheral = peripheral
self.advertisementData = advertisementData
self.RSSI = RSSI
var array:[[String]] = []
var entry:[String] = ["Local Name", self.localName]
if entry[1] != nilString {
array.append(entry)
}
// entry = ["UUID", UUIDString]
// if entry[1] != nilString { array.append(entry) }
entry = ["Manufacturer Data", manufacturerData]
if entry[1] != nilString { array.append(entry) }
entry = ["Service Data", serviceData]
if entry[1] != nilString { array.append(entry) }
var completServiceUUIDs:[String] = serviceUUIDs
if overflowServiceUUIDs[0] != nilString { completServiceUUIDs += overflowServiceUUIDs }
entry = ["Service UUIDs"] + completServiceUUIDs
if entry[1] != nilString { array.append(entry) }
entry = ["TX Power Level", txPowerLevel]
if entry[1] != nilString { array.append(entry) }
entry = ["Connectable", isConnectable]
if entry[1] != nilString { array.append(entry) }
entry = ["Solicited Service UUIDs"] + solicitedServiceUUIDs
if entry[1] != nilString { array.append(entry) }
advertisementArray = array
var nameString = peripheral.name
//FOR SCREENSHOTS v
// if nameString == "Apple TV" {
// var rand:String = "\(random())"
// rand = rand.stringByPaddingToLength(2, withString: " ", startingAtIndex: 0)
// nameString = "UP_\(rand)"
// }
// else if nameString == "UART" {
// var rand:String = "\(random())"
// rand = rand.stringByPaddingToLength(1, withString: " ", startingAtIndex: 2)
// nameString = nameString + "-\(rand)"
// }
//FOR SCREENSHOTS ^
if nameString == nil || nameString == "" {
nameString = "N/A"
}
self.name = nameString!
//Check for UART & DFU services
for id in completServiceUUIDs {
if uartServiceUUID().equalsString(id, caseSensitive: false, omitDashes: true) {
isUART = true
}
// else if dfuServiceUUID().equalsString(id, caseSensitive: false, omitDashes: true) {
// isDFU = true
// }
}
}
func stringsFromUUIDs(idArray:NSArray)->[String] {
var idStringArray = [String](count: idArray.count, repeatedValue: "")
idArray.enumerateObjectsUsingBlock({ (obj:AnyObject!, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
let objUUID = obj as? CBUUID
let idStr = objUUID!.UUIDString
idStringArray[idx] = idStr
})
return idStringArray
}
func printAdData(){
if LOGGING {
print("- - - -")
for a in advertisementArray {
print(a)
}
print("- - - -")
}
}
} | mit | 09ecded97e6378f4805fdb65352a7e54 | 29.064777 | 123 | 0.55165 | 5.064802 | false | false | false | false |
LoganWright/vapor | Tests/Vapor/RouteTests.swift | 1 | 3894 | //
// RouteTests.swift
// Vapor
//
// Created by Matthew on 20/02/2016.
// Copyright © 2016 Tanner Nelson. All rights reserved.
//
import XCTest
@testable import Vapor
class RouteTests: XCTestCase {
static var allTests: [(String, RouteTests -> () throws -> Void)] {
return [
("testNestedRouteScopedPrefixPopsCorrectly", testNestedRouteScopedPrefixPopsCorrectly),
("testRoute", testRoute),
("testRouteScopedPrefix", testRouteScopedPrefix)
]
}
func testRoute() {
let app = Application()
app.get("foo") { request in
return ""
}
app.post("bar") { request in
return ""
}
app.host("google.com") {
app.put("baz") { request in
return ""
}
}
assertRouteExists(at: "foo", method: .get, host: "*", inRoutes: app.routes)
assertRouteExists(at: "bar", method: .post, host: "*", inRoutes: app.routes)
assertRouteExists(at: "baz", method: .put, host: "google.com", inRoutes: app.routes)
}
func testRouteScopedPrefix() {
let app = Application()
app.group("group/path") {
app.get("1") { request in
return ""
}
app.options("2") { request in
return ""
}
}
assertRouteExists(at: "group/path/1", method: .get, host: "*", inRoutes: app.routes)
assertRouteExists(at: "group/path/2", method: .options, host: "*", inRoutes: app.routes)
}
func testNestedRouteScopedPrefixPopsCorrectly() {
let app = Application()
app.group("group") {
app.group("subgroup") {
app.get("1") { request in
return ""
}
}
app.options("2") { request in
return ""
}
}
assertRouteExists(at: "group/subgroup/1", method: .get, host: "*", inRoutes: app.routes)
assertRouteExists(at: "group/2", method: .options, host: "*", inRoutes: app.routes)
}
func testRouteAbort() {
let app = Application()
app.get("400") { request in
print("from 400")
throw Abort.badRequest
}
app.bootRoutes()
print(app.routes)
let request = Request(method: .get, uri: URI(path: "400"), headers: [:], body: [])
guard var handler = app.router.route(request)?.handler else {
XCTFail("No handler found")
return
}
do {
let response = try handler.respond(to: request)
print(response)
var body = response.body
let data = try body.becomeBuffer()
let string = try String(data: data)
print(string)
XCTFail("Handler did not throw error")
} catch Abort.badRequest {
//pass
} catch {
XCTFail("Handler threw incorrect error")
}
handler = AbortMiddleware().chain(to: handler)
do {
let request = try handler.respond(to: request)
XCTAssert(request.status.statusCode == 400, "Incorrect response status")
} catch {
XCTFail("Middleware did not handle abort")
}
}
}
/**
Global functions because any function that takes an argument on an XCTest class fails on Linux.
*/
internal func assertRouteExists(at path: String,
method: Request.Method,
host: String,
inRoutes routes: [Route]) {
var found = false
for route in routes {
if route.path == path && route.method == method && route.hostname == host {
found = true
}
}
if !found {
XCTFail("\(method) \(path) was not found")
}
}
| mit | a52228eaa9d97c5f5e812b9e062e0538 | 25.304054 | 98 | 0.521449 | 4.39887 | false | true | false | false |
couchbase/couchbase-lite-ios | Swift/ArrayExpressionSatisfies.swift | 1 | 2766 | //
// ArrayExpressionSatisfies.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc 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
/* internal */ enum QuantifiesType {
case any, anyAndEvery, every
}
/// The Satisfies class represents the SATISFIES clause object in a quantified operator
/// (ANY/ANY AND EVERY/EVERY <variable name> IN <expr> SATISFIES <expr>). The SATISFIES clause
/// is used for specifying an expression that will be used to evaluate each item in the array.
public final class ArrayExpressionSatisfies {
/// Creates a complete quantified operator with the given satisfies expression.
///
/// - Parameter expression: The satisfies expression used for evaluating each item in the array.
/// - Returns: The quantified expression.
public func satisfies(_ expression: ExpressionProtocol) -> ExpressionProtocol {
let impl = ArrayExpressionSatisfies.toImpl(
type: self.type,
variable: self.variable,
inExpression: self.inExpression,
satisfies: expression)
return QueryExpression(impl)
}
// MARK: Internal
let type: QuantifiesType
let variable: VariableExpressionProtocol
let inExpression: ExpressionProtocol
init(type: QuantifiesType, variable: VariableExpressionProtocol, inExpression: ExpressionProtocol) {
self.type = type
self.variable = variable
self.inExpression = inExpression
}
static func toImpl(type: QuantifiesType,
variable: VariableExpressionProtocol,
inExpression: ExpressionProtocol,
satisfies: ExpressionProtocol) -> CBLQueryExpression
{
let v = variable.toImpl() as! CBLQueryVariableExpression
let i = inExpression.toImpl()
let s = satisfies.toImpl()
switch type {
case .any:
return CBLQueryArrayExpression.any(v, in: i, satisfies: s)
case .anyAndEvery:
return CBLQueryArrayExpression.anyAndEvery(v, in: i, satisfies: s)
case .every:
return CBLQueryArrayExpression.every(v, in: i, satisfies: s)
}
}
}
| apache-2.0 | bf7013234ce8a8d621f2881c20a7ecaf | 35.394737 | 104 | 0.673897 | 4.564356 | false | false | false | false |
ecaselles/GameOfLife | GameOfLifeTests/CellSpec.swift | 1 | 2300 | //
// CellSpec.swift
// GameOfLifeTests
//
// Created by Edu Caselles on 10/8/16.
// Copyright © 2016 Edu Caselles. All rights reserved.
//
import Quick
import Nimble
@testable import GameOfLife
class CellSpec: QuickSpec {
override func spec() {
describe(".nextEvolution") {
context("when the cell is live") {
let cell = Cell.Live
context("and it has less than 2 neighbours") {
it("will be dead") {
let result = cell.nextEvolution(forNeighboursCount: 1)
expect(result).to(equal(Cell.Dead))
}
}
context("and it has 2 neighbours") {
it("will be live") {
let result = cell.nextEvolution(forNeighboursCount: 2)
expect(result).to(equal(Cell.Live))
}
}
context("and it has 3 neighbours") {
it("will be live") {
let result = cell.nextEvolution(forNeighboursCount: 3)
expect(result).to(equal(Cell.Live))
}
}
context("and it has more than 3 neighbours") {
it("will be dead") {
let result = cell.nextEvolution(forNeighboursCount: 4)
expect(result).to(equal(Cell.Dead))
}
}
}
context("when the cell is dead") {
let cell = Cell.Dead
context("and it has 3 neighbours") {
it("will be live") {
let result = cell.nextEvolution(forNeighboursCount: 3)
expect(result).to(equal(Cell.Live))
}
}
context("and it does not have 3 neighbours") {
it("will be dead") {
let result = cell.nextEvolution(forNeighboursCount: 2)
expect(result).to(equal(Cell.Dead))
}
}
}
}
}
}
| mit | d90fee76051777c804b11c57d2ae2c24 | 32.808824 | 78 | 0.419313 | 5.334107 | false | false | false | false |
dleonard00/firebase-user-signup | Pods/Material/Sources/MenuViewController.swift | 1 | 6648 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* 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 Material 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
public extension UIViewController {
/**
A convenience property that provides access to the MenuViewController.
This is the recommended method of accessing the MenuViewController
through child UIViewControllers.
*/
public var menuViewController: MenuViewController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is MenuViewController {
return viewController as? MenuViewController
}
viewController = viewController?.parentViewController
}
return nil
}
}
public class MenuViewController: UIViewController {
/// Reference to the MenuView.
public private(set) lazy var menuView: MenuView = MenuView()
/**
A Boolean property used to enable and disable interactivity
with the mainViewController.
*/
public var userInteractionEnabled: Bool {
get {
return mainViewController.view.userInteractionEnabled
}
set(value) {
mainViewController.view.userInteractionEnabled = value
}
}
/**
A UIViewController property that references the active
main UIViewController. To swap the mainViewController, it
is recommended to use the transitionFromMainViewController
helper method.
*/
public private(set) var mainViewController: UIViewController!
/**
An initializer for the MenuViewController.
- Parameter mainViewController: The main UIViewController.
*/
public convenience init(mainViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
prepareView()
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layoutSubviews()
}
/**
A method to swap mainViewController objects.
- Parameter toViewController: The UIViewController to swap
with the active mainViewController.
- Parameter duration: A NSTimeInterval that sets the
animation duration of the transition.
- Parameter options: UIViewAnimationOptions thst are used
when animating the transition from the active mainViewController
to the toViewController.
- Parameter animations: An animation block that is executed during
the transition from the active mainViewController
to the toViewController.
- Parameter completion: A completion block that is execited after
the transition animation from the active mainViewController
to the toViewController has completed.
*/
public func transitionFromMainViewController(toViewController: UIViewController, duration: NSTimeInterval = 0.5, options: UIViewAnimationOptions = [], animations: (() -> Void)? = nil, completion: ((Bool) -> Void)? = nil) {
mainViewController.willMoveToParentViewController(nil)
addChildViewController(toViewController)
toViewController.view.frame = mainViewController.view.frame
transitionFromViewController(mainViewController,
toViewController: toViewController,
duration: duration,
options: options,
animations: animations,
completion: { [unowned self] (result: Bool) in
toViewController.didMoveToParentViewController(self)
self.mainViewController.removeFromParentViewController()
self.mainViewController = toViewController
self.view.sendSubviewToBack(self.mainViewController.view)
completion?(result)
})
}
/**
Opens the menu with a callback.
- Parameter completion: An Optional callback that is executed when
all menu items have been opened.
*/
public func openMenu(completion: (() -> Void)? = nil) {
if true == userInteractionEnabled {
userInteractionEnabled = false
mainViewController.view.alpha = 0.5
menuView.open(completion)
}
}
/**
Closes the menu with a callback.
- Parameter completion: An Optional callback that is executed when
all menu items have been closed.
*/
public func closeMenu(completion: (() -> Void)? = nil) {
if false == userInteractionEnabled {
mainViewController.view.alpha = 1
menuView.close({ [weak self] in
self?.userInteractionEnabled = true
completion?()
})
}
}
/// A method that generally prepares the MenuViewController.
private func prepareView() {
prepareMenuView()
prepareMainViewController()
}
/// Prepares the MenuView.
private func prepareMenuView() {
menuView.zPosition = 1000
view.addSubview(menuView)
}
/// A method that prepares the mainViewController.
private func prepareMainViewController() {
prepareViewControllerWithinContainer(mainViewController, container: view)
}
/**
A method that adds the passed in controller as a child of
the MenuViewController within the passed in
container view.
- Parameter viewController: A UIViewController to add as a child.
- Parameter container: A UIView that is the parent of the
passed in controller view within the view hierarchy.
*/
private func prepareViewControllerWithinContainer(viewController: UIViewController?, container: UIView) {
if let v: UIViewController = viewController {
addChildViewController(v)
container.insertSubview(v.view, atIndex: 0)
v.didMoveToParentViewController(self)
}
}
/// Layout subviews.
private func layoutSubviews() {
mainViewController.view.frame = view.bounds
}
}
| mit | d53c2c050ebe542b163b57e640ce3ddb | 33.989474 | 223 | 0.772413 | 4.613463 | false | false | false | false |
moyazi/SwiftDayList | SwiftDayList/Days/Day6/InterestCollectionViewCell.swift | 1 | 1222 | //
// InterestCollectionViewCell.swift
// SwiftDayList
//
// Created by leoo on 2017/6/27.
// Copyright © 2017年 Het. All rights reserved.
//
import UIKit
class InterestCollectionViewCell: UICollectionViewCell {
var imageView:UIImageView!
var title:UILabel!
var interest: Interest! {
didSet {
updateUI()
}
}
fileprivate func updateUI() {
if !(imageView != nil) {
self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.height-40))
self.contentView .addSubview(self.imageView)
}
self.imageView.image = interest.featuredImage
if !(title != nil) {
self.title = UILabel(frame: CGRect(x: 0, y: self.imageView.frame.maxY, width: self.bounds.width, height: 40))
}
self.contentView.addSubview(self.title)
self.title.text = interest.title
self.title.textColor = UIColor.red
self.title.textAlignment = NSTextAlignment.center
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = 5.0
self.clipsToBounds = true
}
}
| mit | a4e5a534ec69506a6854896cbec8ec61 | 26.088889 | 129 | 0.609516 | 4.247387 | false | false | false | false |
listen-li/DYZB | DYZB/DYZB/Classes/Home/Controller/GameViewController.swift | 1 | 4713 | //
// GameViewController.swift
// DYZB
//
// Created by admin on 17/8/16.
// Copyright © 2017年 smartFlash. All rights reserved.
//
import UIKit
private let kEdgeMargin :CGFloat = 30
private let kItemW :CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH :CGFloat = kItemW * 6 / 5
private let kHeaderViewH :CGFloat = 50
private let kGameView : CGFloat = 90
class GameViewController: UIViewController {
//Mark:- 懒加载属性
fileprivate lazy var gameVM : GameViewModel = GameViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
//1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
//创建UIcolletionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.register(UINib(nibName:"CollectionViewGameCell", bundle:nil), forCellWithReuseIdentifier: "kGameCellID")
collectionView.register(UINib(nibName:"CollectionHeaderView", bundle:nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.white
return collectionView
}()
fileprivate lazy var topHeaderView : CollectionHeaderView = {
let headerView = CollectionHeaderView.collectionHeaderView()
headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameView), width: kScreenW, height: kHeaderViewH)
headerView.iconImageView.image = UIImage(named: "dyla_bg_plane_gift")
headerView.moreBtn.isHidden = true
headerView.titleLabel.text = "常用"
return headerView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameView, width: kScreenW, height: kGameView)
return gameView
}()
//Mark:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
//1.
setupUI()
//2.
loadData()
}
}
//Mark:- 设置UI界面
extension GameViewController{
fileprivate func setupUI() {
//1.添加UIcollectionView
view.addSubview(collectionView)
//2.添加顶部的headerView
collectionView.addSubview(topHeaderView)
//3.将gameView添加到collectionView
collectionView.addSubview(gameView)
//4.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameView, left: 0, bottom: 0, right: 0)
}
}
//Mark:- 请求数据
extension GameViewController {
fileprivate func loadData(){
gameVM.loadAllGameData {
//1.展示全部游戏
self.collectionView.reloadData()
//2.展示常用游戏
self.gameView.groups = Array(self.gameVM.games[0..<10])
}
}
}
//Mark:- 遵守UIcolletionView的数据源代理
extension GameViewController : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameVM.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.获取cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "kGameCellID", for: indexPath) as! CollectionViewGameCell
//2.
let gameModel = gameVM.games[indexPath.item]
cell.baseGame = gameModel
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1.取出headView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId", for: indexPath) as! CollectionHeaderView
//2.给headerView设置属性
headerView.titleLabel.text = "全部";
headerView.iconImageView.image = UIImage(named: "dyla_bg_plane_gift")
headerView.moreBtn.isHidden = true
return headerView
}
}
| mit | db674e75ca6efc0af7a23ec6854f3294 | 35.806452 | 192 | 0.682954 | 5.252014 | false | false | false | false |
jum/Charts | Source/Charts/Renderers/AxisRendererBase.swift | 8 | 6939 | //
// AxisRendererBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(ChartAxisRendererBase)
open class AxisRendererBase: Renderer
{
/// base axis this axis renderer works with
@objc open var axis: AxisBase?
/// transformer to transform values to screen pixels and return
@objc open var transformer: Transformer?
@objc public init(viewPortHandler: ViewPortHandler, transformer: Transformer?, axis: AxisBase?)
{
super.init(viewPortHandler: viewPortHandler)
self.transformer = transformer
self.axis = axis
}
/// Draws the axis labels on the specified context
@objc open func renderAxisLabels(context: CGContext)
{
fatalError("renderAxisLabels() cannot be called on AxisRendererBase")
}
/// Draws the grid lines belonging to the axis.
@objc open func renderGridLines(context: CGContext)
{
fatalError("renderGridLines() cannot be called on AxisRendererBase")
}
/// Draws the line that goes alongside the axis.
@objc open func renderAxisLine(context: CGContext)
{
fatalError("renderAxisLine() cannot be called on AxisRendererBase")
}
/// Draws the LimitLines associated with this axis to the screen.
@objc open func renderLimitLines(context: CGContext)
{
fatalError("renderLimitLines() cannot be called on AxisRendererBase")
}
/// Computes the axis values.
///
/// - Parameters:
/// - min: the minimum value in the data object for this axis
/// - max: the maximum value in the data object for this axis
@objc open func computeAxis(min: Double, max: Double, inverted: Bool)
{
var min = min, max = max
if let transformer = self.transformer
{
// calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds)
if viewPortHandler.contentWidth > 10.0 && !viewPortHandler.isFullyZoomedOutY
{
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
if !inverted
{
min = Double(p2.y)
max = Double(p1.y)
}
else
{
min = Double(p1.y)
max = Double(p2.y)
}
}
}
computeAxisValues(min: min, max: max)
}
/// Sets up the axis values. Computes the desired number of labels between the two given extremes.
@objc open func computeAxisValues(min: Double, max: Double)
{
guard let axis = self.axis else { return }
let yMin = min
let yMax = max
let labelCount = axis.labelCount
let range = abs(yMax - yMin)
if labelCount == 0 || range <= 0 || range.isInfinite
{
axis.entries = [Double]()
axis.centeredEntries = [Double]()
return
}
// Find out how much spacing (in y value space) between axis values
let rawInterval = range / Double(labelCount)
var interval = rawInterval.roundedToNextSignficant()
// If granularity is enabled, then do not allow the interval to go below specified granularity.
// This is used to avoid repeated values when rounding values for display.
if axis.granularityEnabled
{
interval = interval < axis.granularity ? axis.granularity : interval
}
// Normalize interval
let intervalMagnitude = pow(10.0, Double(Int(log10(interval)))).roundedToNextSignficant()
let intervalSigDigit = Int(interval / intervalMagnitude)
if intervalSigDigit > 5
{
// Use one order of magnitude higher, to avoid intervals like 0.9 or 90
// if it's 0.0 after floor(), we use the old value
interval = floor(10.0 * intervalMagnitude) == 0.0 ? interval : floor(10.0 * intervalMagnitude)
}
var n = axis.centerAxisLabelsEnabled ? 1 : 0
// force label count
if axis.isForceLabelsEnabled
{
interval = Double(range) / Double(labelCount - 1)
// Ensure stops contains at least n elements.
axis.entries.removeAll(keepingCapacity: true)
axis.entries.reserveCapacity(labelCount)
var v = yMin
for _ in 0 ..< labelCount
{
axis.entries.append(v)
v += interval
}
n = labelCount
}
else
{
// no forced count
var first = interval == 0.0 ? 0.0 : ceil(yMin / interval) * interval
if axis.centerAxisLabelsEnabled
{
first -= interval
}
let last = interval == 0.0 ? 0.0 : (floor(yMax / interval) * interval).nextUp
if interval != 0.0 && last != first
{
for _ in stride(from: first, through: last, by: interval)
{
n += 1
}
}
else if last == first && n == 0
{
n = 1
}
// Ensure stops contains at least n elements.
axis.entries.removeAll(keepingCapacity: true)
axis.entries.reserveCapacity(labelCount)
var f = first
var i = 0
while i < n
{
if f == 0.0
{
// Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0)
f = 0.0
}
axis.entries.append(Double(f))
f += interval
i += 1
}
}
// set decimals
if interval < 1
{
axis.decimals = Int(ceil(-log10(interval)))
}
else
{
axis.decimals = 0
}
if axis.centerAxisLabelsEnabled
{
axis.centeredEntries.reserveCapacity(n)
axis.centeredEntries.removeAll()
let offset: Double = interval / 2.0
for i in 0 ..< n
{
axis.centeredEntries.append(axis.entries[i] + offset)
}
}
}
}
| apache-2.0 | 4ee641d52278c9fb0251aa65b0189af7 | 30.830275 | 130 | 0.529903 | 5.162946 | false | false | false | false |
chenms-m2/M7Kit | Example/M7Kit/AppDelegate.swift | 1 | 3166 | //
// AppDelegate.swift
// M7Kit
//
// Created by chenms-m2 on 12/02/2016.
// Copyright (c) 2016 chenms-m2. All rights reserved.
//
import UIKit
import M7Kit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var tabBarViewController: M7TabBarViewController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
tabBarViewController = M7TabBarViewController(tabBarHeight: 250)
let sub0 = SubViewController()
let sub1 = SubViewController()
let sub2 = SubViewController()
tabBarViewController?.viewControllers = [sub0, sub1, sub2]
let tabBarView = Bundle.main.loadNibNamed("DemoTabBarView", owner: nil, options: nil)?.first as! DemoTabBarView
tabBarView.delegate = self
tabBarViewController?.tabBarView = tabBarView
window = UIWindow()
window?.rootViewController = tabBarViewController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension AppDelegate: DemoTabBarViewProtocol {
func onTapLeft() {
tabBarViewController?.selectedIndex = 0
}
func onTapMiddle() {
tabBarViewController?.selectedIndex = 1
}
func onTapRight() {
tabBarViewController?.selectedIndex = 2
}
}
| mit | d8fea6f1ccf2f763c3edcfed4b019e39 | 39.589744 | 285 | 0.718572 | 5.60354 | false | false | false | false |
sadawi/PrimarySource | Pod/iOS/BooleanCell.swift | 1 | 1134 | //
// BooleanCell.swift
// Pods
//
// Created by Sam Williams on 11/30/15.
//
//
import UIKit
open class BooleanCell:FieldCell<Bool> {
}
open class SwitchCell:BooleanCell, TappableTableCell {
var switchControl:UISwitch?
override open func buildView() {
super.buildView()
let control = UISwitch(frame: self.controlView!.bounds)
self.addControl(control, alignment:.right)
control.addTarget(self, action: #selector(SwitchCell.switchChanged), for: UIControlEvents.valueChanged)
self.switchControl = control
}
open func switchChanged() {
self.value = self.switchControl?.isOn
}
open func toggle(animated:Bool=true) {
let newValue = (self.value != true)
self.switchControl?.setOn(newValue, animated: animated)
self.value = newValue
}
open override func update() {
super.update()
self.switchControl?.isOn = (self.value == true)
self.switchControl?.isUserInteractionEnabled = !self.isReadonly
}
public func handleTap() {
self.toggle(animated: true)
}
}
| mit | 389135cc368a059bbbb731f6d464b80c | 24.2 | 111 | 0.637566 | 4.311787 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Extensions/UIImageView+SiteIcon.swift | 1 | 9682 | import AlamofireImage
import Alamofire
import AutomatticTracks
import Foundation
import Gridicons
/// UIImageView Helper Methods that allow us to download a SiteIcon, given a website's "Icon Path"
///
extension UIImageView {
/// Default Settings
///
struct SiteIconDefaults {
/// Default SiteIcon's Image Size, in points.
///
static let imageSize = CGSize(width: 40, height: 40)
}
/// Downloads the SiteIcon Image, hosted at the specified path. This method will attempt to optimize the URL, so that
/// the download Image Size matches `imageSize`.
///
/// TODO: This is a convenience method. Nuke me once we're all swifted.
///
/// - Parameter path: SiteIcon's url (string encoded) to be downloaded.
///
@objc
func downloadSiteIcon(at path: String) {
downloadSiteIcon(at: path, placeholderImage: .siteIconPlaceholder)
}
/// Downloads the SiteIcon Image, hosted at the specified path. This method will attempt to optimize the URL, so that
/// the download Image Size matches `imageSize`.
///
/// - Parameters:
/// - path: SiteIcon's url (string encoded) to be downloaded.
/// - imageSize: Request site icon in the specified image size.
/// - placeholderImage: Yes. It's the "place holder image", Sherlock.
///
@objc
func downloadSiteIcon(
at path: String,
imageSize: CGSize = SiteIconDefaults.imageSize,
placeholderImage: UIImage?
) {
guard let siteIconURL = optimizedURL(for: path, imageSize: imageSize) else {
image = placeholderImage
return
}
logURLOptimization(from: path, to: siteIconURL)
let request = URLRequest(url: siteIconURL)
downloadSiteIcon(with: request, imageSize: imageSize, placeholderImage: placeholderImage)
}
/// Downloads a SiteIcon image, using a specified request.
///
/// - Parameters:
/// - request: The request for the SiteIcon.
/// - imageSize: Request site icon in the specified image size.
/// - placeholderImage: Yes. It's the "place holder image".
///
private func downloadSiteIcon(
with request: URLRequest,
imageSize expectedSize: CGSize = SiteIconDefaults.imageSize,
placeholderImage: UIImage?
) {
af_setImage(withURLRequest: request, placeholderImage: placeholderImage, completion: { [weak self] dataResponse in
switch dataResponse.result {
case .success(let image):
guard let self = self else {
return
}
// In `MediaRequesAuthenticator.authenticatedRequestForPrivateAtomicSiteThroughPhoton` we're
// having to replace photon URLs for Atomic Private Sites, with a call to the Atomic Media Proxy
// endpoint. The downside of calling that endpoint is that it doesn't always return images of
// the requested size.
//
// The following lines of code ensure that we resize the image to the default Site Icon size, to
// ensure there is no UI breakage due to having larger images set here.
//
if image.size != expectedSize {
self.image = image.resizedImage(with: .scaleAspectFill, bounds: expectedSize, interpolationQuality: .default)
} else {
self.image = image
}
self.removePlaceholderBorder()
case .failure(let error):
if case .requestCancelled = (error as? AFIError) {
// Do not log intentionally cancelled requests as errors.
} else {
DDLogError(error.localizedDescription)
}
}
})
}
/// Downloads the SiteIcon Image, associated to a given Blog. This method will attempt to optimize the URL, so that
/// the download Image Size matches `imageSize`.
///
/// - Parameters:
/// - blog: reference to the source blog
/// - placeholderImage: Yes. It's the "place holder image".
///
@objc func downloadSiteIcon(
for blog: Blog,
imageSize: CGSize = SiteIconDefaults.imageSize,
placeholderImage: UIImage? = .siteIconPlaceholder
) {
guard let siteIconPath = blog.icon, let siteIconURL = optimizedURL(for: siteIconPath, imageSize: imageSize) else {
if blog.isWPForTeams() && placeholderImage == .siteIconPlaceholder {
image = UIImage.gridicon(.p2, size: imageSize)
return
}
image = placeholderImage
return
}
logURLOptimization(from: siteIconPath, to: siteIconURL, for: blog)
let host = MediaHost(with: blog) { error in
// We'll log the error, so we know it's there, but we won't halt execution.
DDLogError(error.localizedDescription)
}
let mediaRequestAuthenticator = MediaRequestAuthenticator()
mediaRequestAuthenticator.authenticatedRequest(
for: siteIconURL,
from: host,
onComplete: { [weak self] request in
self?.downloadSiteIcon(with: request, imageSize: imageSize, placeholderImage: placeholderImage)
}) { error in
DDLogError(error.localizedDescription)
}
}
}
// MARK: - Private Methods
//
extension UIImageView {
/// Returns the Size Optimized URL for a given Path.
///
func optimizedURL(for path: String, imageSize: CGSize = SiteIconDefaults.imageSize) -> URL? {
if isPhotonURL(path) || isDotcomURL(path) {
return optimizedDotcomURL(from: path, imageSize: imageSize)
}
if isBlavatarURL(path) {
return optimizedBlavatarURL(from: path, imageSize: imageSize)
}
return optimizedPhotonURL(from: path, imageSize: imageSize)
}
// MARK: - Private Helpers
/// Returns the download URL for a square icon with a size of `imageSize` in pixels.
///
/// - Parameter path: SiteIcon URL (string encoded).
///
private func optimizedDotcomURL(from path: String, imageSize: CGSize = SiteIconDefaults.imageSize) -> URL? {
let size = imageSize.toPixels()
let query = String(format: "w=%d&h=%d", Int(size.width), Int(size.height))
return parseURL(path: path, query: query)
}
/// Returns the icon URL corresponding to the provided path
///
/// - Parameter path: Blavatar URL (string encoded).
///
private func optimizedBlavatarURL(from path: String, imageSize: CGSize = SiteIconDefaults.imageSize) -> URL? {
let size = imageSize.toPixels()
let query = String(format: "d=404&s=%d", Int(max(size.width, size.height)))
return parseURL(path: path, query: query)
}
/// Returs the photon URL for the provided path
///
/// - Parameter siteIconPath: SiteIcon URL (string encoded).
///
private func optimizedPhotonURL(from path: String, imageSize: CGSize = SiteIconDefaults.imageSize) -> URL? {
guard let url = URL(string: path) else {
return nil
}
return PhotonImageURLHelper.photonURL(with: imageSize, forImageURL: url)
}
/// Indicates if the received URL is hosted at WordPress.com
///
private func isDotcomURL(_ path: String) -> Bool {
return path.contains(".files.wordpress.com")
}
/// Indicates if the received URL is hosted at Gravatar.com
///
private func isBlavatarURL(_ path: String) -> Bool {
return path.contains("gravatar.com/blavatar")
}
/// Indicates if the received URL is a Photon Endpoint
/// Possible matches are "i0.wp.com", "i1.wp.com" & "i2.wp.com" -> https://developer.wordpress.com/docs/photon/
///
private func isPhotonURL(_ path: String) -> Bool {
return path.contains(".wp.com")
}
/// Attempts to parse the URL contained within a Path, with a given query. Returns nil on failure.
///
private func parseURL(path: String, query: String) -> URL? {
guard var components = URLComponents(string: path) else {
return nil
}
components.query = query
return components.url
}
}
// MARK: - Border handling
@objc
extension UIImageView {
func removePlaceholderBorder() {
layer.borderColor = UIColor.clear.cgColor
}
}
// MARK: - Logging Support
/// This is just a temporary extension to try and narrow down the caused behind this issue: https://sentry.io/share/issue/3da4662c65224346bb3a731c131df13d/
///
private extension UIImageView {
private func logURLOptimization(from original: String, to optimized: URL) {
DDLogInfo("URL optimized from \(original) to \(optimized.absoluteString)")
}
private func logURLOptimization(from original: String, to optimized: URL, for blog: Blog) {
let blogInfo: String
if blog.isAccessibleThroughWPCom() {
blogInfo = "dot-com-accessible: \(blog.url ?? "unknown"), id: \(blog.dotComID ?? 0)"
} else {
blogInfo = "self-hosted with url: \(blog.url ?? "unknown")"
}
DDLogInfo("URL optimized from \(original) to \(optimized.absoluteString) for blog \(blogInfo)")
}
}
// MARK: - CGFloat Extension
private extension CGSize {
func toPixels() -> CGSize {
return CGSize(width: width.toPixels(), height: height.toPixels())
}
}
private extension CGFloat {
func toPixels() -> CGFloat {
return self * UIScreen.main.scale
}
}
| gpl-2.0 | 6f2be3f66575d8ef051501bf0b4f3fdd | 33.091549 | 155 | 0.623838 | 4.625896 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/PledgePaymentMethods/Views/Cells/PledgePaymentMethodAddCell.swift | 1 | 3567 | import KsApi
import Library
import Prelude
import UIKit
final class PledgePaymentMethodAddCell: UITableViewCell, ValueCell {
// MARK: - Properties
private lazy var selectionView: UIView = { UIView(frame: .zero) }()
private lazy var addButton: UIButton = { UIButton(type: .custom) }()
private lazy var containerView: UIStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var activityIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
indicator.startAnimating()
return indicator
}()
private let viewModel: PledgePaymentMethodAddCellViewModelType = PledgePaymentMethodAddCellViewModel()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.configureSubviews()
self.setupConstraints()
self.bindViewModel()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View model
override func bindViewModel() {
self.activityIndicator.rac.animating = self.viewModel.outputs.showLoading
self.addButton.rac.hidden = self.viewModel.outputs.showLoading
}
// MARK: - Configuration
private func configureSubviews() {
_ = (self.containerView, self.contentView)
|> ksr_addSubviewToParent()
}
private func setupConstraints() {
_ = ([self.activityIndicator, self.addButton], self.containerView)
|> ksr_addArrangedSubviewsToStackView()
_ = (self.containerView, self.contentView)
|> ksr_constrainViewToEdgesInParent()
|> ksr_constrainViewToCenterInParent()
NSLayoutConstraint.activate([
self.activityIndicator.widthAnchor.constraint(equalToConstant: Styles.grid(9)),
self.containerView.heightAnchor.constraint(equalToConstant: Styles.grid(9))
])
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self.selectionView
|> selectionViewStyle
_ = self
|> \.selectedBackgroundView .~ self.selectionView
_ = self.addButton
|> addButtonStyle
_ = self.activityIndicator
|> activityIndicatorStyle
_ = self.containerView
|> stackViewStyle
}
func configureWith(value flag: Bool) {
self.viewModel.inputs.configureWith(value: flag)
}
}
// MARK: - Styles
private let addButtonStyle: ButtonStyle = { button in
button
|> UIButton.lens.titleLabel.font .~ UIFont.boldSystemFont(ofSize: 15)
|> UIButton.lens.image(for: .normal) .~ Library.image(named: "icon-add-round-green")
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.New_payment_method() }
|> UIButton.lens.isUserInteractionEnabled .~ false
|> UIButton.lens.titleColor(for: .normal) .~ .ksr_create_700
|> UIButton.lens.tintColor .~ .ksr_create_700
|> UIButton.lens.titleEdgeInsets .~ UIEdgeInsets(left: Styles.grid(3))
}
private let selectionViewStyle: ViewStyle = { view in
view
|> \.backgroundColor .~ .ksr_support_100
}
private let activityIndicatorStyle: ActivityIndicatorStyle = { activityIndicator in
activityIndicator
|> \.color .~ UIColor.ksr_support_400
|> \.hidesWhenStopped .~ true
}
private let stackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ .horizontal
|> \.alignment .~ .center
|> \.spacing .~ Styles.grid(0)
|> \.isLayoutMarginsRelativeArrangement .~ true
}
| apache-2.0 | a6940c9d27d881f262466d7b46fe911a | 27.766129 | 104 | 0.702832 | 4.712021 | false | false | false | false |
pdx-ios/watchkit-workshop | RoShamBo/RoShamBo/Game.swift | 1 | 3198 | //
// Choice.swift
// RoShamBo
//
// Created by Ryan Arana on 3/26/15.
// Copyright (c) 2015 PDX-iOS. All rights reserved.
//
import Foundation
public enum Choice: Int {
case Rock = 1
case Paper
case Scissors
case Spock
case Lizard
public var name: String {
switch self {
case .Rock:
return "rock"
case .Paper:
return "paper"
case .Scissors:
return "scissors"
case .Spock:
return "spock"
case .Lizard:
return "lizard"
}
}
public static func all() -> [Choice] {
return [.Rock, .Paper, .Scissors, .Spock, .Lizard]
}
public static func random() -> Choice {
var c = Int(arc4random_uniform(UInt32(5))) + 1
return Choice(rawValue: c)!
}
public func verb(other: Choice) -> String {
if other == self {
return ""
}
switch self {
case .Rock:
switch other {
case .Scissors, .Lizard:
return "crushes"
default:
return other.verb(self)
}
case .Paper:
switch other {
case .Spock:
return "disproves"
case .Rock:
return "covers"
default:
return other.verb(self)
}
case .Scissors:
switch other {
case .Paper:
return "cuts"
case .Lizard:
return "decapitates"
default:
return other.verb(self)
}
case .Spock:
switch other {
case .Rock, .Scissors:
return "vaporizes"
default:
return other.verb(self)
}
case .Lizard:
switch other {
case .Paper:
return "eats"
case .Spock:
return "poisons"
default:
return other.verb(self)
}
}
}
}
public struct Result {
public let winner: Choice!
public let loser: Choice!
public let draw: Bool = false
public init(choices p1: Choice, p2: Choice) {
draw = p1 == p2
if !draw {
let higher = p1.rawValue > p2.rawValue ? p1 : p2
let lower = higher == p1 ? p2 : p1
if p1.rawValue % 2 == p2.rawValue % 2 {
// If both are odd or both are even, the lower one wins
winner = lower
loser = higher
} else {
// Otherwise the higher one wins
winner = higher
loser = lower
}
}
}
public var summary: String {
return "\(winner.name.capitalizedString) \(winner.verb(loser)) \(loser.name.capitalizedString)."
}
}
public struct Game {
public let player1: Choice
public let player2: Choice
public init(player1: Choice, player2: Choice) {
self.player1 = player1
self.player2 = player2
}
public func play() -> Result {
return Result(choices: player1, p2: player2)
}
}
| mit | b2ad08a9bcdb52be7192a1e41804f42b | 22.865672 | 104 | 0.476861 | 4.32747 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/maximum-product-of-splitted-binary-tree.swift | 2 | 1277 | /**
* https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/
*
*
*/
// Date: Thu Aug 19 10:42:57 PDT 2021
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func maxProduct(_ root: TreeNode?) -> Int {
var sumList = [UInt]()
func getSum(_ root: TreeNode?) -> UInt {
guard let root = root else { return 0 }
var sum = UInt(root.val)
sum += getSum(root.left)
sum += getSum(root.right)
sumList.append(sum)
return sum
}
let sum = getSum(root)
sumList = sumList.sorted()
var result: UInt = 0
for index in 0 ..< sumList.count - 1 {
result = max(result, (sumList[index] * (sum - sumList[index])))
}
return Int(result % 1000000007)
}
} | mit | 8843efe0db333d977412edbf7be19fda | 30.170732 | 85 | 0.534064 | 3.517906 | false | false | false | false |
narner/AudioKit | Examples/iOS/Particles/AudioKitParticles/ViewController.swift | 1 | 5521 | //
// ViewController.swift
// AudioKitParticles
//
// Created by Simon Gladman on 28/12/2015.
// Copyright © 2015 Simon Gladman. All rights reserved.
//
import AudioKit
import UIKit
class ViewController: UIViewController {
let statusLabel = UILabel()
let floatPi = Float.pi
var gravityWellAngle: Float = 0
var particleLab: ParticleLab!
var fft: AKFFTTap!
var amplitudeTracker: AKAmplitudeTracker!
var amplitude: Float = 0
var lowMaxIndex: Float = 0
var hiMaxIndex: Float = 0
var hiMinIndex: Float = 0
override func viewDidLoad() {
super.viewDidLoad()
let mic = AKMicrophone()
fft = AKFFTTap(mic)
amplitudeTracker = AKAmplitudeTracker(mic)
// Turn the volume all the way down on the output of amplitude tracker
let noAudioOutput = AKMixer(amplitudeTracker)
noAudioOutput.volume = 0
AudioKit.output = noAudioOutput
AudioKit.start()
let _ = Loop(every: 1 / 60) {
let fftData = self.fft.fftData
let count = 250
let lowMax = fftData[0 ... (count / 2) - 1].max() ?? 0
let hiMax = fftData[count / 2 ... count - 1].max() ?? 0
let hiMin = fftData[count / 2 ... count - 1].min() ?? 0
let lowMaxIndex = fftData.index(of: lowMax) ?? 0
let hiMaxIndex = fftData.index(of: hiMax) ?? 0
let hiMinIndex = fftData.index(of: hiMin) ?? 0
self.amplitude = Float(self.amplitudeTracker.amplitude * 25)
self.lowMaxIndex = Float(lowMaxIndex)
self.hiMaxIndex = Float(hiMaxIndex - count / 2)
self.hiMinIndex = Float(hiMinIndex - count / 2)
}
// ----
view.backgroundColor = UIColor.white
let numParticles = ParticleCount.twoMillion
if view.frame.height < view.frame.width {
particleLab = ParticleLab(width: UInt(view.frame.width),
height: UInt(view.frame.height),
numParticles: numParticles)
particleLab.frame = CGRect(x: 0,
y: 0,
width: view.frame.width,
height: view.frame.height)
} else {
particleLab = ParticleLab(width: UInt(view.frame.height),
height: UInt(view.frame.width),
numParticles: numParticles)
particleLab.frame = CGRect(x: 0,
y: 0,
width: view.frame.height,
height: view.frame.width)
}
particleLab.particleLabDelegate = self
particleLab.dragFactor = 0.9
particleLab.clearOnStep = false
particleLab.respawnOutOfBoundsParticles = true
view.addSubview(particleLab)
statusLabel.textColor = UIColor.darkGray
statusLabel.text = "AudioKit Particles"
view.addSubview(statusLabel)
}
func particleLabStep() {
gravityWellAngle += 0.01
let radiusLow = 0.1 + (lowMaxIndex / 256)
particleLab.setGravityWellProperties(
gravityWell: .one,
normalisedPositionX: 0.5 + radiusLow * sin(gravityWellAngle),
normalisedPositionY: 0.5 + radiusLow * cos(gravityWellAngle),
mass: (lowMaxIndex * amplitude),
spin: -(lowMaxIndex * amplitude))
particleLab.setGravityWellProperties(
gravityWell: .four,
normalisedPositionX: 0.5 + radiusLow * sin((gravityWellAngle + floatPi)),
normalisedPositionY: 0.5 + radiusLow * cos((gravityWellAngle + floatPi)),
mass: (lowMaxIndex * amplitude),
spin: -(lowMaxIndex * amplitude))
let radiusHi = 0.1 + (0.25 + (hiMaxIndex / 1_024))
particleLab.setGravityWellProperties(
gravityWell: .two,
normalisedPositionX: particleLab.getGravityWellNormalisedPosition(gravityWell: .one).x +
(radiusHi * sin(gravityWellAngle * 3)),
normalisedPositionY: particleLab.getGravityWellNormalisedPosition(gravityWell: .one).y +
(radiusHi * cos(gravityWellAngle * 3)),
mass: (hiMaxIndex * amplitude),
spin: (hiMinIndex * amplitude))
particleLab.setGravityWellProperties(
gravityWell: .three,
normalisedPositionX: particleLab.getGravityWellNormalisedPosition(gravityWell: .four).x +
(radiusHi * sin((gravityWellAngle + floatPi) * 3)),
normalisedPositionY: particleLab.getGravityWellNormalisedPosition(gravityWell: .four).y +
(radiusHi * cos((gravityWellAngle + floatPi) * 3)),
mass: (hiMaxIndex * amplitude),
spin: (hiMinIndex * amplitude))
}
// MARK: Layout
override func viewDidLayoutSubviews() {
statusLabel.frame = CGRect(x: 5,
y: view.frame.height - statusLabel.intrinsicContentSize.height,
width: view.frame.width,
height: statusLabel.intrinsicContentSize.height)
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscape
}
override var prefersStatusBarHidden: Bool {
return true
}
}
extension ViewController: ParticleLabDelegate {
func particleLabMetalUnavailable() {
// handle metal unavailable here
}
func particleLabDidUpdate(_ status: String) {
statusLabel.text = status
particleLab.resetGravityWells()
particleLabStep()
}
}
| mit | 09eef7c25e6b1d995ad58fc11aa8824f | 30.907514 | 101 | 0.610326 | 4.419536 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Effects/Distortion/Complex Distortion/AKDistortion.swift | 1 | 9460 | //
// AKDistortion.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// AudioKit version of Apple's Distortion Audio Unit
///
open class AKDistortion: AKNode, AKToggleable, AUEffect, AKInput {
// MARK: - Properties
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(appleEffect: kAudioUnitSubType_Distortion)
private var au: AUWrapper
private var lastKnownMix: Double = 0.5
/// Delay (Milliseconds) ranges from 0.1 to 500 (Default: 0.1)
@objc open dynamic var delay: Double = 0.1 {
didSet {
delay = (0.1...500).clamp(delay)
au[kDistortionParam_Delay] = delay
}
}
/// Decay (Rate) ranges from 0.1 to 50 (Default: 1.0)
@objc open dynamic var decay: Double = 1.0 {
didSet {
decay = (0.1...50).clamp(decay)
au[kDistortionParam_Decay] = decay
}
}
/// Delay Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var delayMix: Double = 0.5 {
didSet {
delayMix = (0...1).clamp(delayMix)
au[kDistortionParam_DelayMix] = delayMix * 100
}
}
/// Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var decimation: Double = 0.5 {
didSet {
decimation = (0...1).clamp(decimation)
au[kDistortionParam_Decimation] = decimation * 100
}
}
/// Rounding (Normalized Value) ranges from 0 to 1 (Default: 0.0)
@objc open dynamic var rounding: Double = 0.0 {
didSet {
rounding = (0...1).clamp(rounding)
au[kDistortionParam_Rounding] = rounding * 100
}
}
/// Decimation Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var decimationMix: Double = 0.5 {
didSet {
decimationMix = (0...1).clamp(decimationMix)
au[kDistortionParam_DecimationMix] = decimationMix * 100
}
}
/// Linear Term (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var linearTerm: Double = 0.5 {
didSet {
linearTerm = (0...1).clamp(linearTerm)
au[kDistortionParam_LinearTerm] = linearTerm * 100
}
}
/// Squared Term (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var squaredTerm: Double = 0.5 {
didSet {
squaredTerm = (0...1).clamp(squaredTerm)
au[kDistortionParam_SquaredTerm] = squaredTerm * 100
}
}
/// Cubic Term (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var cubicTerm: Double = 0.5 {
didSet {
cubicTerm = (0...1).clamp(cubicTerm)
au[kDistortionParam_CubicTerm] = cubicTerm * 100
}
}
/// Polynomial Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var polynomialMix: Double = 0.5 {
didSet {
polynomialMix = (0...1).clamp(polynomialMix)
au[kDistortionParam_PolynomialMix] = polynomialMix * 100
}
}
/// Ring Mod Freq1 (Hertz) ranges from 0.5 to 8000 (Default: 100)
@objc open dynamic var ringModFreq1: Double = 100 {
didSet {
ringModFreq1 = (0.5...8_000).clamp(ringModFreq1)
au[kDistortionParam_RingModFreq1] = ringModFreq1
}
}
/// Ring Mod Freq2 (Hertz) ranges from 0.5 to 8000 (Default: 100)
@objc open dynamic var ringModFreq2: Double = 100 {
didSet {
ringModFreq2 = (0.5...8_000).clamp(ringModFreq2)
au[kDistortionParam_RingModFreq2] = ringModFreq2
}
}
/// Ring Mod Balance (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var ringModBalance: Double = 0.5 {
didSet {
ringModBalance = (0...1).clamp(ringModBalance)
au[kDistortionParam_RingModBalance] = ringModBalance * 100
}
}
/// Ring Mod Mix (Normalized Value) ranges from 0 to 1 (Default: 0.0)
@objc open dynamic var ringModMix: Double = 0.0 {
didSet {
ringModMix = (0...1).clamp(ringModMix)
au[kDistortionParam_RingModMix] = ringModMix * 100
}
}
/// Soft Clip Gain (dB) ranges from -80 to 20 (Default: -6)
@objc open dynamic var softClipGain: Double = -6 {
didSet {
softClipGain = (-80...20).clamp(softClipGain)
au[kDistortionParam_SoftClipGain] = softClipGain
}
}
/// Final Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var finalMix: Double = 0.5 {
didSet {
finalMix = (0...1).clamp(finalMix)
au[kDistortionParam_FinalMix] = finalMix * 100
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted = true
// MARK: - Initialization
/// Initialize the distortion node
///
/// - Parameters:
/// - input: Input node to process
/// - delay: Delay (Milliseconds) ranges from 0.1 to 500 (Default: 0.1)
/// - decay: Decay (Rate) ranges from 0.1 to 50 (Default: 1.0)
/// - delayMix: Delay Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0.0)
/// - decimationMix: Decimation Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - linearTerm: Linear Term (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - squaredTerm: Squared Term (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - cubicTerm: Cubic Term (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - polynomialMix: Polynomial Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - ringModFreq1: Ring Mod Freq1 (Hertz) ranges from 0.5 to 8000 (Default: 100)
/// - ringModFreq2: Ring Mod Freq2 (Hertz) ranges from 0.5 to 8000 (Default: 100)
/// - ringModBalance: Ring Mod Balance (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - ringModMix: Ring Mod Mix (Normalized Value) ranges from 0 to 1 (Default: 0.0)
/// - softClipGain: Soft Clip Gain (dB) ranges from -80 to 20 (Default: -6)
/// - finalMix: Final Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5)
///
@objc public init(
_ input: AKNode? = nil,
delay: Double = 0.1,
decay: Double = 1.0,
delayMix: Double = 0.5,
decimation: Double = 0.5,
rounding: Double = 0.0,
decimationMix: Double = 0.5,
linearTerm: Double = 0.5,
squaredTerm: Double = 0.5,
cubicTerm: Double = 0.5,
polynomialMix: Double = 0.5,
ringModFreq1: Double = 100,
ringModFreq2: Double = 100,
ringModBalance: Double = 0.5,
ringModMix: Double = 0.0,
softClipGain: Double = -6,
finalMix: Double = 0.5) {
self.delay = delay
self.decay = decay
self.delayMix = delayMix
self.decimation = decimation
self.rounding = rounding
self.decimationMix = decimationMix
self.linearTerm = linearTerm
self.squaredTerm = squaredTerm
self.cubicTerm = cubicTerm
self.polynomialMix = polynomialMix
self.ringModFreq1 = ringModFreq1
self.ringModFreq2 = ringModFreq2
self.ringModBalance = ringModBalance
self.ringModMix = ringModMix
self.softClipGain = softClipGain
self.finalMix = finalMix
let effect = _Self.effect
au = AUWrapper(effect)
super.init(avAudioNode: effect, attach: true)
input?.connect(to: self)
au[kDistortionParam_Delay] = delay
au[kDistortionParam_Decay] = decay
au[kDistortionParam_DelayMix] = delayMix * 100
au[kDistortionParam_Decimation] = decimation * 100
au[kDistortionParam_Rounding] = rounding * 100
au[kDistortionParam_DecimationMix] = decimationMix * 100
au[kDistortionParam_LinearTerm] = linearTerm * 100
au[kDistortionParam_SquaredTerm] = squaredTerm * 100
au[kDistortionParam_CubicTerm] = cubicTerm * 100
au[kDistortionParam_PolynomialMix] = polynomialMix * 100
au[kDistortionParam_RingModFreq1] = ringModFreq1
au[kDistortionParam_RingModFreq2] = ringModFreq2
au[kDistortionParam_RingModBalance] = ringModBalance * 100
au[kDistortionParam_RingModMix] = ringModMix * 100
au[kDistortionParam_SoftClipGain] = softClipGain
au[kDistortionParam_FinalMix] = finalMix * 100
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
if isStopped {
finalMix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
if isPlaying {
lastKnownMix = finalMix
finalMix = 0
isStarted = false
}
}
/// Disconnect the node
override open func disconnect() {
stop()
AudioKit.detach(nodes: [self.avAudioNode])
}
}
| mit | e773e130e5feded53fa0fd0c3334c112 | 35.380769 | 113 | 0.605667 | 4.146865 | false | false | false | false |
planvine/Line-Up-iOS-SDK | Pod/Classes/PaymentViewController/ViewTableCellPaymentCheckout.swift | 1 | 3186 | /**
* Copyright (c) 2016 Line-Up
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
class PaymentCheckoutTableViewCell : UITableViewCell {
lazy var typeLabel : UILabel = {
var temp : UILabel = UILabel(frame: CGRectIntegral(CGRectZero))
temp.translatesAutoresizingMaskIntoConstraints = false
return temp
}()
lazy var priceLabel : UILabel = {
var temp : UILabel = UILabel(frame: CGRectIntegral(CGRectZero))
temp.translatesAutoresizingMaskIntoConstraints = false
return temp
}()
var didSetupContraints : Bool = false
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup () {
typeLabel.font = PVFont.mainRegular(13)
typeLabel.textColor = UIColor.grayColor()
addSubview(typeLabel)
priceLabel.font = PVFont.mainRegular(13)
priceLabel.textColor = UIColor.grayColor()
addSubview(priceLabel)
setNeedsUpdateConstraints()
}
override func updateConstraints() {
if didSetupContraints != true {
let views: NSDictionary = ["typeLabel": typeLabel, "priceLabel":priceLabel]
addConstraint(NSLayoutConstraint(item:typeLabel, attribute:.CenterY, relatedBy:.Equal, toItem: self, attribute:.CenterY, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item:priceLabel, attribute:.CenterY, relatedBy:.Equal, toItem: self, attribute:.CenterY, multiplier: 1, constant: 0))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-padMedium-[typeLabel]->=padMedium-[priceLabel]-padMedium-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: NSDictionary(dictionary:PVMetric.pads()) as? [String: AnyObject], views: views as! [String : AnyObject]))
didSetupContraints = true
}
super.updateConstraints()
}
}
| mit | 770f103dcdaaf1c10280a55c129bbe9f | 42.054054 | 302 | 0.700565 | 5.105769 | false | false | false | false |
itaen/30DaysSwift | 003_PlayLocalVideo/PlayLocalVideo/PlayLocalVideo/ViewController.swift | 1 | 2468 | //
// ViewController.swift
// PlayLocalVideo
//
// Created by itaen on 17/07/2017.
// Copyright © 2017 itaen. All rights reserved.
//
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var videoTableView: UITableView!
var data = [
video(image: "videoScreenshot01", title: "Introduce 3DS Mario", source: "Youtube - 06:32"),
video(image: "videoScreenshot02", title: "Emoji Among Us", source: "Vimeo - 3:34"),
video(image: "videoScreenshot03", title: "Seals Documentary", source: "Vine - 00:06"),
video(image: "videoScreenshot04", title: "Adventure Time", source: "Youtube - 02:39"),
video(image: "videoScreenshot05", title: "Facebook HQ", source: "Facebook - 10:20"),
video(image: "videoScreenshot06", title: "Lijiang Lugu Lake", source: "Allen - 20:30")
]
var playViewController = AVPlayerViewController()
var playerView = AVPlayer()
@IBAction func playVideoButtonDidTouch(_ sender: UIButton) {
let path = Bundle.main.path(forResource: "emoji zone", ofType: "mp4")
playerView = AVPlayer(url: URL(fileURLWithPath: path!))
playViewController.player = playerView
self.present(playViewController, animated: true) {
self.playViewController.player?.play()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 220
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = videoTableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! VideoCell
let video = data[indexPath.row]
cell.videoScreenshot.image = UIImage(named: video.image)
cell.videoTitleLabel.text = video.title
cell.videoSourceLabel.text = video.source
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
videoTableView.dataSource = self
videoTableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | ecb443a5e2dff514e584a41998179b29 | 33.263889 | 112 | 0.656668 | 4.690114 | false | false | false | false |
kharrison/CodeExamples | RefreshScroll/RefreshScroll/SignUpViewController.swift | 1 | 2791 | //
// SignUpViewController.swift
//
// Created by Keith Harrison http://useyourloaf.com
// Copyright (c) 2016 Keith Harrison. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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
class SignUpViewController: UIViewController {
@IBOutlet private var scrollView: AdaptiveScrollView!
@IBOutlet private var orangeLabel: UILabel!
@IBOutlet private var orangeButton: UIButton!
private var orangeAvailable = true {
didSet {
orangeLabel.isHidden = !orangeAvailable
orangeButton.isHidden = !orangeAvailable
}
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10.0, *) {
let refreshControl = UIRefreshControl()
let title = NSLocalizedString("PullToRefresh", comment: "Pull to refresh")
refreshControl.attributedTitle = NSAttributedString(string: title)
refreshControl.addTarget(self,
action: #selector(refreshOptions(sender:)),
for: .valueChanged)
scrollView.refreshControl = refreshControl
}
}
@objc private func refreshOptions(sender: UIRefreshControl) {
orangeAvailable = !orangeAvailable
sender.endRefreshing()
}
}
| bsd-3-clause | 0fc29602a0e9da19cb663b8f0eddaba3 | 41.938462 | 86 | 0.707273 | 4.992844 | false | false | false | false |
SteveBarnegren/SBSwiftUtils | SBSwiftUtils/Extensions/Array/Array+SortBySteps.swift | 1 | 2757 | //
// Array+SortBySteps.swift
// SBSwiftUtils
//
// Created by Steve Barnegren on 11/02/2018.
// Copyright © 2018 SteveBarnegren. All rights reserved.
//
import Foundation
public extension Array {
class SortStep<Input> {
public enum Result {
case ascending
case descending
case equal
}
private let sortClosure: (Input, Input) -> Result
public init(sortClosure: @escaping (Input, Input) -> Result) {
self.sortClosure = sortClosure
}
public convenience init<Output: Comparable>(ascending transform: @escaping (Input) -> Output) {
self.init { (lhs, rhs) -> Result in
let lhsComparable = transform(lhs)
let rhsComparable = transform(rhs)
if lhsComparable == rhsComparable {
return .equal
} else {
return rhsComparable > lhsComparable ? .ascending : .descending
}
}
}
public convenience init<Output: Comparable>(descending transform: @escaping (Input) -> Output) {
self.init { (lhs, rhs) -> Result in
let lhsComparable = transform(lhs)
let rhsComparable = transform(rhs)
if lhsComparable == rhsComparable {
return .equal
} else {
return rhsComparable < lhsComparable ? .ascending : .descending
}
}
}
fileprivate func sort(lhs: Input, rhs: Input) -> Result {
return sortClosure(lhs, rhs)
}
}
mutating func sortBySteps(_ steps: [SortStep<Element>]) {
if steps.isEmpty {
return
}
sort { (lhs, rhs) -> Bool in
var index = 0
while let step = steps[maybe: index] {
let result = step.sort(lhs: lhs, rhs: rhs)
switch result {
case .ascending: return true
case .descending: return false
case .equal: break
}
index += 1
}
return true
}
}
mutating func sortBySteps(_ steps: SortStep<Element>...) {
sortBySteps(steps)
}
func sortedBySteps(_ steps: SortStep<Element>...) -> [Element] {
return sortedBySteps(steps)
}
func sortedBySteps(_ steps: [SortStep<Element>]) -> [Element] {
var sortedArray = self
sortedArray.sortBySteps(steps)
return sortedArray
}
}
| mit | 8f4905d0ec6ca2243386ffea778dfb8b | 27.708333 | 104 | 0.489115 | 5.259542 | false | false | false | false |
Bunn/firefox-ios | Client/Frontend/Settings/ThemeSettingsController.swift | 1 | 8827 | /* 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 Shared
class ThemeSettingsController: ThemedTableViewController {
struct UX {
static var rowHeight: CGFloat = 70
static var moonSunIconSize: CGFloat = 18
static var footerFontSize: CGFloat = 12
static var sliderLeftRightInset: CGFloat = 16
static var spaceBetweenTableSections: CGFloat = 20
}
enum Section: Int {
case automaticOnOff
case lightDarkPicker
}
// A non-interactable slider is underlaid to show the current screen brightness indicator
private var slider: (control: UISlider, deviceBrightnessIndicator: UISlider)?
// TODO decide if this is themeable, or if it is being replaced by a different style of slider
private let deviceBrightnessIndicatorColor = UIColor(white: 182/255, alpha: 1.0)
var isAutoBrightnessOn: Bool {
return ThemeManager.instance.automaticBrightnessIsOn
}
init() {
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.SettingsDisplayThemeTitle
tableView.accessibilityIdentifier = "DisplayTheme.Setting.Options"
tableView.backgroundColor = UIColor.theme.tableView.headerBackground
let headerFooterFrame = CGRect(width: self.view.frame.width, height: SettingsUX.TableViewHeaderFooterHeight)
let headerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
tableView.tableHeaderView = headerView
headerView.titleLabel.text = Strings.DisplayThemeSectionHeader
NotificationCenter.default.addObserver(self, selector: #selector(brightnessChanged), name: UIScreen.brightnessDidChangeNotification, object: nil)
}
@objc func brightnessChanged() {
guard ThemeManager.instance.automaticBrightnessIsOn else { return }
ThemeManager.instance.updateCurrentThemeBasedOnScreenBrightness()
applyTheme()
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard isAutoBrightnessOn else { return nil }
let footer = UIView()
let label = UILabel()
footer.addSubview(label)
label.text = Strings.DisplayThemeSectionFooter
label.numberOfLines = 0
label.snp.makeConstraints { make in
make.top.equalToSuperview().inset(4)
make.left.right.equalToSuperview().inset(16)
}
label.font = UIFont.systemFont(ofSize: UX.footerFontSize)
label.textColor = UIColor.theme.tableView.headerTextLight
return footer
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard isAutoBrightnessOn else {
return section == Section.automaticOnOff.rawValue ? UX.spaceBetweenTableSections : 1
}
// When auto is on, make footer arbitrarily large enough to handle large block of text.
return 120
}
@objc func switchValueChanged(control: UISwitch) {
ThemeManager.instance.automaticBrightnessIsOn = control.isOn
// Switch animation must begin prior to scheduling table view update animation (or the switch will be auto-synchronized to the slower tableview animation and makes the switch behaviour feel slow and non-standard).
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
UIView.transition(with: self.tableView, duration: 0.2, options: .transitionCrossDissolve, animations: { self.tableView.reloadData() })
}
}
@objc func sliderValueChanged(control: UISlider, event: UIEvent) {
guard let touch = event.allTouches?.first, touch.phase == .ended else {
return
}
ThemeManager.instance.automaticBrightnessValue = control.value
brightnessChanged()
}
private func makeSlider(parent: UIView) -> UISlider {
let slider = UISlider()
parent.addSubview(slider)
let size = CGSize(width: UX.moonSunIconSize, height: UX.moonSunIconSize)
let images = ["menu-NightMode", "themeBrightness"].map { name in
UIImage(imageLiteralResourceName: name).createScaled(size).tinted(withColor: UIColor.theme.browser.tint)
}
slider.minimumValueImage = images[0]
slider.maximumValueImage = images[1]
slider.snp.makeConstraints { make in
make.top.bottom.equalToSuperview()
make.left.right.equalToSuperview().inset(UX.sliderLeftRightInset)
}
return slider
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ThemedTableViewCell(style: .subtitle, reuseIdentifier: nil)
cell.selectionStyle = .none
let section = Section(rawValue: indexPath.section) ?? .automaticOnOff
switch section {
case .automaticOnOff:
if indexPath.row == 0 {
cell.textLabel?.text = Strings.DisplayThemeAutomaticSwitchTitle
cell.detailTextLabel?.text = Strings.DisplayThemeAutomaticSwitchSubtitle
cell.detailTextLabel?.numberOfLines = 2
cell.detailTextLabel?.minimumScaleFactor = 0.5
cell.detailTextLabel?.adjustsFontSizeToFitWidth = true
let control = UISwitchThemed()
control.accessibilityIdentifier = "DisplaySwitchValue"
control.onTintColor = UIColor.theme.tableView.controlTint
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.isOn = ThemeManager.instance.automaticBrightnessIsOn
cell.accessoryView = control
} else {
let deviceBrightnessIndicator = makeSlider(parent: cell.contentView)
let slider = makeSlider(parent: cell.contentView)
slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)
slider.value = Float(ThemeManager.instance.automaticBrightnessValue)
deviceBrightnessIndicator.value = Float(UIScreen.main.brightness)
deviceBrightnessIndicator.isUserInteractionEnabled = false
deviceBrightnessIndicator.minimumTrackTintColor = .clear
deviceBrightnessIndicator.maximumTrackTintColor = .clear
deviceBrightnessIndicator.thumbTintColor = deviceBrightnessIndicatorColor
self.slider = (slider, deviceBrightnessIndicator)
}
case .lightDarkPicker:
if indexPath.row == 0 {
cell.textLabel?.text = Strings.DisplayThemeOptionLight
} else {
cell.textLabel?.text = Strings.DisplayThemeOptionDark
}
let theme = BuiltinThemeName(rawValue: ThemeManager.instance.current.name) ?? .normal
if (indexPath.row == 0 && theme == .normal) ||
(indexPath.row == 1 && theme == .dark) {
cell.accessoryType = .checkmark
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
} else {
cell.accessoryType = .none
}
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return isAutoBrightnessOn ? 1 : 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isAutoBrightnessOn ? 2 : (section == Section.automaticOnOff.rawValue ? 1 : 2)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.section == Section.automaticOnOff.rawValue ? UX.rowHeight : super.tableView(tableView, heightForRowAt: indexPath)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section > 0 else { return }
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
ThemeManager.instance.current = indexPath.row == 0 ? NormalTheme() : DarkTheme()
applyTheme()
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return indexPath.section != Section.automaticOnOff.rawValue
}
}
| mpl-2.0 | 92e896c8700fda024e52e787196fcfc4 | 43.135 | 221 | 0.674975 | 5.320675 | false | false | false | false |
beeth0ven/CKSIncrementalStore | CKSIncrementalStore/CKSIncrementalStoreSyncOperationTokenHandler.swift | 1 | 2597 | // CKSIncrementalStoreSyncOperationTokenHandler.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Nofel Mahmood (https://twitter.com/NofelMahmood)
//
// 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 CloudKit
class CKSIncrementalStoreSyncOperationTokenHandler
{
static let defaultHandler = CKSIncrementalStoreSyncOperationTokenHandler()
private var newToken: CKServerChangeToken?
func token()->CKServerChangeToken?
{
if NSUserDefaults.standardUserDefaults().objectForKey(CKSIncrementalStoreSyncOperationFetchChangeTokenKey) != nil
{
let fetchTokenKeyArchived = NSUserDefaults.standardUserDefaults().objectForKey(CKSIncrementalStoreSyncOperationFetchChangeTokenKey) as! NSData
return NSKeyedUnarchiver.unarchiveObjectWithData(fetchTokenKeyArchived) as? CKServerChangeToken
}
return nil
}
func save(serverChangeToken serverChangeToken:CKServerChangeToken)
{
self.newToken = serverChangeToken
}
func commit()
{
if self.newToken != nil
{
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(self.newToken!), forKey: CKSIncrementalStoreSyncOperationFetchChangeTokenKey)
}
}
func delete()
{
if self.token() != nil
{
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: CKSIncrementalStoreSyncOperationFetchChangeTokenKey)
}
}
}
| mit | a802f874b7f051c12ba7c2011694543d | 38.953846 | 180 | 0.721987 | 5.003854 | false | false | false | false |
slimpp/CocoaSLIMPP | CocoaMQTT/CocoaMQTTMessage.swift | 1 | 1237 | //
// CocoaMQTTMessage.swift
// CocoaMQTT
//
// Created by Feng Lee<feng.lee@nextalk.im> on 14/8/3.
// Copyright (c) 2014年 slimpp.io. All rights reserved.
//
import Foundation
/**
* MQTT Messgae
*/
class CocoaMQTTMessage {
var topic: String
var payload: [Byte]
//utf8 bytes array to string
var string: String? {
get {
return String.stringWithBytes(payload,
length: payload.count,
encoding: NSUTF8StringEncoding)
}
}
var qos: CocoaMQTTQOS = .QOS1
var retain: Bool = false
var dup: Bool = false
init(topic: String, string: String, qos: CocoaMQTTQOS = .QOS1) {
self.topic = topic
self.payload = [Byte](string.utf8)
self.qos = qos
}
init(topic: String, payload: [Byte], qos: CocoaMQTTQOS = .QOS1, retain: Bool = false, dup: Bool = false) {
self.topic = topic
self.payload = payload
self.qos = qos
self.retain = retain
self.dup = dup
}
}
/**
* MQTT Will Message
**/
class CocoaMQTTWill: CocoaMQTTMessage {
init(topic: String, message: String) {
super.init(topic: topic, payload: message.bytesWithLength)
}
}
| mit | eefe3575430ac6925f1e6225e3a7dcaf | 19.245902 | 110 | 0.582186 | 3.664688 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Wallet/ViewControllers/ImportMainWalletViewController.swift | 1 | 4741 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import UIKit
import Eureka
import QRCodeReaderViewController
import TrustCore
protocol ImportMainWalletViewControllerDelegate: class {
func didImportWallet(wallet: WalletInfo, in controller: ImportMainWalletViewController)
func didSkipImport(in controller: ImportMainWalletViewController)
}
final class ImportMainWalletViewController: FormViewController {
let keystore: Keystore
struct Values {
static let mnemonic = "mnemonic"
static let password = "password"
}
private var mnemonicRow: TextAreaRow? {
return form.rowBy(tag: Values.mnemonic)
}
private var passwordRow: TextFloatLabelRow? {
return form.rowBy(tag: Values.password)
}
weak var delegate: ImportMainWalletViewControllerDelegate?
init(
keystore: Keystore
) {
self.keystore = keystore
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
title = R.string.localizable.importMainWallet()
navigationItem.rightBarButtonItems = [
UIBarButtonItem(title: R.string.localizable.skip(), style: .plain, target: self, action: #selector(skip)),
UIBarButtonItem(image: R.image.qr_code_icon(), style: .done, target: self, action: #selector(openReader)),
]
form +++ Section()
// Mnemonic
+++ Section(footer: ImportSelectionType.mnemonic.footerTitle)
<<< AppFormAppearance.textArea(tag: Values.mnemonic) {
$0.placeholder = R.string.localizable.backupPhrase()
$0.textAreaHeight = .fixed(cellHeight: 140)
$0.add(rule: RuleRequired())
$0.cell.textView?.autocapitalizationType = .none
}
+++ Section()
<<< ButtonRow(R.string.localizable.importWalletImportButtonTitle()) {
$0.title = $0.tag
}.onCellSelection { [weak self] _, _ in
self?.importWallet()
}
}
func didImport(account: WalletInfo) {
delegate?.didImportWallet(wallet: account, in: self)
}
func importWallet() {
let validatedError = mnemonicRow?.section?.form?.validate()
guard let errors = validatedError, errors.isEmpty else { return }
let password = ""//passwordRow?.value ?? ""
let mnemonicInput = mnemonicRow?.value?.trimmed ?? ""
let words = mnemonicInput.components(separatedBy: " ").map { $0.trimmed.lowercased() }
displayLoading(text: R.string.localizable.importWalletImportingIndicatorLabelTitle(), animated: false)
let importType = ImportType.mnemonic(words: words, password: password, derivationPath: Coin.ethereum.derivationPath(at: 0))
DispatchQueue.global(qos: .userInitiated).async {
self.keystore.importWallet(type: importType, coin: .ethereum) { result in
switch result {
case .success(let account):
self.addWallets(wallet: account)
DispatchQueue.main.async {
self.hideLoading(animated: false)
self.didImport(account: account)
}
case .failure(let error):
DispatchQueue.main.async {
self.hideLoading(animated: false)
self.displayError(error: error)
}
}
}
}
}
@discardableResult
func addWallets(wallet: WalletInfo) -> Bool {
// Create coins based on supported networks
guard let w = wallet.currentWallet else {
return false
}
let derivationPaths = Config.current.servers.map { $0.derivationPath(at: 0) }
let _ = keystore.addAccount(to: w, derivationPaths: derivationPaths)
return true
}
@objc func openReader() {
let controller = QRCodeReaderViewController()
controller.delegate = self
present(controller, animated: true, completion: nil)
}
@objc private func skip() {
self.delegate?.didSkipImport(in: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ImportMainWalletViewController: QRCodeReaderDelegate {
func readerDidCancel(_ reader: QRCodeReaderViewController!) {
reader.stopScanning()
reader.dismiss(animated: true, completion: nil)
}
func reader(_ reader: QRCodeReaderViewController!, didScanResult result: String!) {
reader.stopScanning()
mnemonicRow?.value = result
mnemonicRow?.reload()
reader.dismiss(animated: true)
}
}
| gpl-3.0 | 3306087bd18ff565520ab26b4a29d1af | 32.864286 | 131 | 0.629192 | 4.892673 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureWalletConnect/Sources/FeatureWalletConnectData/Services/WalletConnectService.swift | 1 | 11361 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Combine
import DIKit
import EthereumKit
import FeatureWalletConnectDomain
import Foundation
import PlatformKit
import ToolKit
import WalletConnectSwift
final class WalletConnectService {
// MARK: - Private Properties
private var server: Server!
private var cancellables = [AnyCancellable]()
private var sessionLinks = Atomic<[WCURL: Session]>([:])
private let sessionEventsSubject = PassthroughSubject<WalletConnectSessionEvent, Never>()
private let userEventsSubject = PassthroughSubject<WalletConnectUserEvent, Never>()
private let analyticsEventRecorder: AnalyticsEventRecorderAPI
private let sessionRepository: SessionRepositoryAPI
private let publicKeyProvider: WalletConnectPublicKeyProviderAPI
private let featureFlagService: FeatureFlagsServiceAPI
// MARK: - Init
init(
analyticsEventRecorder: AnalyticsEventRecorderAPI = resolve(),
publicKeyProvider: WalletConnectPublicKeyProviderAPI = resolve(),
sessionRepository: SessionRepositoryAPI = resolve(),
featureFlagService: FeatureFlagsServiceAPI = resolve()
) {
self.analyticsEventRecorder = analyticsEventRecorder
self.publicKeyProvider = publicKeyProvider
self.sessionRepository = sessionRepository
self.featureFlagService = featureFlagService
server = Server(delegate: self)
configureServer()
}
// MARK: - Private Methods
private func configureServer() {
let sessionEvent: (WalletConnectSessionEvent) -> Void = { [sessionEventsSubject] sessionEvent in
sessionEventsSubject.send(sessionEvent)
}
let userEvent: (WalletConnectUserEvent) -> Void = { [userEventsSubject] userEvent in
userEventsSubject.send(userEvent)
}
let responseEvent: (WalletConnectResponseEvent) -> Void = { [weak server] responseEvent in
switch responseEvent {
case .empty(let request):
server?.send(.create(string: nil, for: request))
case .rejected(let request):
server?.send(.reject(request))
case .invalid(let request):
server?.send(.invalid(request))
case .signature(let signature, let request):
server?.send(.create(string: signature, for: request))
case .transactionHash(let transactionHash, let request):
server?.send(.create(string: transactionHash, for: request))
}
}
let getSession: (WCURL) -> Session? = { [sessionLinks] url in
sessionLinks.value[url]
}
// personal_sign, eth_sign, eth_signTypedData
server.register(
handler: SignRequestHandler(
getSession: getSession,
responseEvent: responseEvent,
userEvent: userEvent
)
)
// eth_sendTransaction, eth_signTransaction
server.register(
handler: TransactionRequestHandler(
getSession: getSession,
responseEvent: responseEvent,
userEvent: userEvent
)
)
// eth_sendRawTransaction
server.register(
handler: RawTransactionRequestHandler(
getSession: getSession,
responseEvent: responseEvent,
userEvent: userEvent
)
)
// wallet_switchEthereumChain
server.register(
handler: SwitchRequestHandler(
getSession: getSession,
responseEvent: responseEvent,
sessionEvent: sessionEvent
)
)
publicKeyProvider
.publicKey(network: .ethereum)
.ignoreFailure(setFailureType: Never.self)
.zip(sessionRepository.retrieve())
.map { publicKey, sessions -> [Session] in
print(sessions)
return sessions
.compactMap { session in
session.session(address: publicKey)
}
}
.handleEvents(
receiveOutput: { [server, sessionLinks] sessions in
print(sessions)
sessions
.forEach { session in
sessionLinks.mutate {
$0[session.url] = session
}
try? server?.reconnect(to: session)
}
}
)
.subscribe()
.store(in: &cancellables)
}
private func addOrUpdateSession(session: Session) {
sessionLinks.mutate {
$0[session.url] = session
}
}
}
extension WalletConnectService: ServerDelegateV2 {
// MARK: - ServerDelegate
func server(_ server: Server, didFailToConnect url: WCURL) {
guard let session = sessionLinks.value[url] else {
return
}
sessionEventsSubject.send(.didFailToConnect(session))
}
func server(_ server: Server, shouldStart session: Session, completion: @escaping (Session.WalletInfo) -> Void) {
// Method not called on `ServerDelegateV2`.
}
func server(_ server: Server, didReceiveConnectionRequest requestId: RequestID, for session: Session) {
addOrUpdateSession(session: session)
let completion: (Session.WalletInfo) -> Void = { [server] walletInfo in
server.sendCreateSessionResponse(
for: requestId,
session: session,
walletInfo: walletInfo
)
}
sessionEventsSubject.send(.shouldStart(session, completion))
}
func server(_ server: Server, willReconnect session: Session) {
// NOOP
}
func server(_ server: Server, didConnect session: Session) {
addOrUpdateSession(session: session)
sessionRepository
.contains(session: session)
.flatMap { [sessionRepository] containsSession in
sessionRepository
.store(session: session)
.map { containsSession }
}
.sink { [sessionEventsSubject] containsSession in
if !containsSession {
sessionEventsSubject.send(.didConnect(session))
}
}
.store(in: &cancellables)
}
func server(_ server: Server, didDisconnect session: Session) {
sessionRepository
.remove(session: session)
.sink { [sessionEventsSubject] _ in
sessionEventsSubject.send(.didDisconnect(session))
}
.store(in: &cancellables)
}
func server(_ server: Server, didUpdate session: Session) {
addOrUpdateSession(session: session)
sessionRepository
.store(session: session)
.sink { [sessionEventsSubject] _ in
sessionEventsSubject.send(.didUpdate(session))
}
.store(in: &cancellables)
}
}
extension WalletConnectService: WalletConnectServiceAPI {
// MARK: - WalletConnectServiceAPI
var userEvents: AnyPublisher<WalletConnectUserEvent, Never> {
userEventsSubject.eraseToAnyPublisher()
}
var sessionEvents: AnyPublisher<WalletConnectSessionEvent, Never> {
sessionEventsSubject.eraseToAnyPublisher()
}
func acceptConnection(
session: Session,
completion: @escaping (Session.WalletInfo) -> Void
) {
guard let network = EVMNetwork(int: session.dAppInfo.chainId) else {
if BuildFlag.isInternal {
let chainID = session.dAppInfo.chainId
let meta = session.dAppInfo.peerMeta
fatalError("Unsupported ChainID: '\(chainID ?? 0)' ,'\(meta.name)', '\(meta.url.absoluteString)'")
}
return
}
publicKeyProvider
.publicKey(network: network)
.map { publicKey in
Session.WalletInfo(
approved: true,
accounts: [publicKey],
chainId: Int(network.chainID),
peerId: UUID().uuidString,
peerMeta: .blockchain
)
}
.sink { [completion] walletInfo in
completion(walletInfo)
}
.store(in: &cancellables)
}
func denyConnection(
session: Session,
completion: @escaping (Session.WalletInfo) -> Void
) {
let walletInfo = Session.WalletInfo(
approved: false,
accounts: [],
chainId: session.dAppInfo.chainId ?? EVMNetwork.defaultChainID,
peerId: UUID().uuidString,
peerMeta: .blockchain
)
completion(walletInfo)
}
func connect(_ url: String) {
featureFlagService.isEnabled(.walletConnectEnabled)
.sink { [weak self] isEnabled in
guard isEnabled,
let wcUrl = WCURL(url)
else {
return
}
try? self?.server.connect(to: wcUrl)
}
.store(in: &cancellables)
}
func disconnect(_ session: Session) {
try? server.disconnect(from: session)
}
func respondToChainIDChangeRequest(
session: Session,
request: Request,
network: EVMNetwork,
approved: Bool
) {
guard approved else {
server?.send(.reject(request))
return
}
// Create new session information.
guard let oldWalletInfo = sessionLinks.value[session.url]?.walletInfo else {
server?.send(.reject(request))
return
}
let walletInfo = Session.WalletInfo(
approved: oldWalletInfo.approved,
accounts: oldWalletInfo.accounts,
chainId: Int(network.chainID),
peerId: oldWalletInfo.peerId,
peerMeta: oldWalletInfo.peerMeta
)
let newSession = Session(
url: session.url,
dAppInfo: session.dAppInfo,
walletInfo: walletInfo
)
// Update local cache.
addOrUpdateSession(session: newSession)
// Update session repository.
sessionRepository
.store(session: newSession)
.subscribe()
.store(in: &cancellables)
// Request session update.
try? server.updateSession(session, with: walletInfo)
// Respond accepting change.
server?.send(.create(string: nil, for: request))
}
}
extension Response {
/// Response for any 'sign'/'send' method that sends back a single string as result.
fileprivate static func create(string: String?, for request: Request) -> Response {
guard let response = try? Response(url: request.url, value: string, id: request.id!) else {
fatalError("Wallet Connect Response Failed: \(request.method)")
}
return response
}
}
extension EVMNetwork {
fileprivate static var defaultChainID: Int {
Int(EVMNetwork.ethereum.chainID)
}
}
| lgpl-3.0 | 82c43882492114df6c5c79194d74b07a | 31.927536 | 117 | 0.581778 | 5.325832 | false | false | false | false |
farion/eloquence | Eloquence/Core/EloConnections.swift | 1 | 1112 | import Foundation
import CoreData
import XMPPFramework
@objc
protocol EloConnectionsDelegate: NSObjectProtocol {
}
class EloConnections: MulticastDelegateContainer {
static let sharedInstance = EloConnections();
typealias DelegateType = EloConnectionsDelegate;
var multicastDelegate = [EloConnectionsDelegate]()
var connections = [EloAccountJid:EloConnection]();
//TODO threadsafe
func connectAllAccounts(){
let accounts = DataController.sharedInstance.getAccounts();
NSLog("%@","connectall");
NSLog("accountcount: %d",accounts.count);
for account in accounts {
let accountJid = account.getJid()
connections[accountJid] = EloConnection(account: account);
if(account.isAutoConnect()){
connections[accountJid]!.connect();
}
}
}
func getConnection(accountJid:EloAccountJid) -> EloConnection {
return connections[accountJid]! ; //otherwise it is a bad bug
}
}
// invokeDelegate { $0.method() } | apache-2.0 | 5a9d96c777edd3d29b112478f306f80a | 24.295455 | 70 | 0.632194 | 5.077626 | false | false | false | false |
nathantannar4/InputBarAccessoryView | Sources/Views/InputTextView.swift | 1 | 16807 | //
// InputTextView.swift
// InputBarAccessoryView
//
// Copyright © 2017-2020 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 8/18/17.
//
import Foundation
import UIKit
/**
A UITextView that has a UILabel embedded for placeholder text
## Important Notes ##
1. Changing the font, textAlignment or textContainerInset automatically performs the same modifications to the placeholderLabel
2. Intended to be used in an `InputBarAccessoryView`
3. Default placeholder text is "Aa"
4. Will pass a pasted image it's `InputBarAccessoryView`'s `InputPlugin`s
*/
open class InputTextView: UITextView {
// MARK: - Properties
open override var text: String! {
didSet {
postTextViewDidChangeNotification()
}
}
open override var attributedText: NSAttributedString! {
didSet {
postTextViewDidChangeNotification()
}
}
/// The images that are currently stored as NSTextAttachment's
open var images: [UIImage] {
return parseForAttachedImages()
}
open var components: [Any] {
return parseForComponents()
}
open var isImagePasteEnabled: Bool = true
/// A UILabel that holds the InputTextView's placeholder text
public let placeholderLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
if #available(iOS 13, *) {
label.textColor = .systemGray2
} else {
label.textColor = .lightGray
}
label.text = "Aa"
label.backgroundColor = .clear
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The placeholder text that appears when there is no text
open var placeholder: String? = "Aa" {
didSet {
placeholderLabel.text = placeholder
}
}
/// The placeholderLabel's textColor
open var placeholderTextColor: UIColor? = .lightGray {
didSet {
placeholderLabel.textColor = placeholderTextColor
}
}
/// The UIEdgeInsets the placeholderLabel has within the InputTextView
open var placeholderLabelInsets: UIEdgeInsets = UIEdgeInsets(top: 8, left: 4, bottom: 8, right: 4) {
didSet {
updateConstraintsForPlaceholderLabel()
}
}
/// The font of the InputTextView. When set the placeholderLabel's font is also updated
open override var font: UIFont! {
didSet {
placeholderLabel.font = font
}
}
/// The textAlignment of the InputTextView. When set the placeholderLabel's textAlignment is also updated
open override var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment = textAlignment
}
}
/// The textContainerInset of the InputTextView. When set the placeholderLabelInsets is also updated
open override var textContainerInset: UIEdgeInsets {
didSet {
placeholderLabelInsets = textContainerInset
}
}
open override var scrollIndicatorInsets: UIEdgeInsets {
didSet {
// When .zero a rendering issue can occur
if scrollIndicatorInsets == .zero {
scrollIndicatorInsets = UIEdgeInsets(top: .leastNonzeroMagnitude,
left: .leastNonzeroMagnitude,
bottom: .leastNonzeroMagnitude,
right: .leastNonzeroMagnitude)
}
}
}
/// A weak reference to the InputBarAccessoryView that the InputTextView is contained within
open weak var inputBarAccessoryView: InputBarAccessoryView?
/// The constraints of the placeholderLabel
private var placeholderLabelConstraintSet: NSLayoutConstraintSet?
// MARK: - Initializers
public convenience init() {
self.init(frame: .zero)
}
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Setup
/// Sets up the default properties
open func setup() {
backgroundColor = .clear
font = UIFont.preferredFont(forTextStyle: .body)
isScrollEnabled = false
scrollIndicatorInsets = UIEdgeInsets(top: .leastNonzeroMagnitude,
left: .leastNonzeroMagnitude,
bottom: .leastNonzeroMagnitude,
right: .leastNonzeroMagnitude)
setupPlaceholderLabel()
setupObservers()
}
/// Adds the placeholderLabel to the view and sets up its initial constraints
private func setupPlaceholderLabel() {
addSubview(placeholderLabel)
placeholderLabelConstraintSet = NSLayoutConstraintSet(
top: placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: placeholderLabelInsets.top),
bottom: placeholderLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -placeholderLabelInsets.bottom),
left: placeholderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: placeholderLabelInsets.left),
right: placeholderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -placeholderLabelInsets.right),
centerX: placeholderLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
centerY: placeholderLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
)
placeholderLabelConstraintSet?.centerX?.priority = .defaultLow
placeholderLabelConstraintSet?.centerY?.priority = .defaultLow
placeholderLabelConstraintSet?.activate()
}
/// Adds a notification for .UITextViewTextDidChange to detect when the placeholderLabel
/// should be hidden or shown
private func setupObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(InputTextView.redrawTextAttachments),
name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(InputTextView.textViewTextDidChange),
name: UITextView.textDidChangeNotification, object: nil)
}
/// Updates the placeholderLabels constraint constants to match the placeholderLabelInsets
private func updateConstraintsForPlaceholderLabel() {
placeholderLabelConstraintSet?.top?.constant = placeholderLabelInsets.top
placeholderLabelConstraintSet?.bottom?.constant = -placeholderLabelInsets.bottom
placeholderLabelConstraintSet?.left?.constant = placeholderLabelInsets.left
placeholderLabelConstraintSet?.right?.constant = -placeholderLabelInsets.right
}
// MARK: - Notifications
private func postTextViewDidChangeNotification() {
NotificationCenter.default.post(name: UITextView.textDidChangeNotification, object: self)
}
@objc
private func textViewTextDidChange() {
let isPlaceholderHidden = !text.isEmpty
placeholderLabel.isHidden = isPlaceholderHidden
// Adjust constraints to prevent unambiguous content size
if isPlaceholderHidden {
placeholderLabelConstraintSet?.deactivate()
} else {
placeholderLabelConstraintSet?.activate()
}
}
// MARK: - Image Paste Support
open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == NSSelectorFromString("paste:") && UIPasteboard.general.hasImages {
return isImagePasteEnabled
}
return super.canPerformAction(action, withSender: sender)
}
open override func paste(_ sender: Any?) {
guard isImagePasteEnabled, let image = UIPasteboard.general.image else {
return super.paste(sender)
}
for plugin in inputBarAccessoryView?.inputPlugins ?? [] {
if plugin.handleInput(of: image) {
return
}
}
pasteImageInTextContainer(with: image)
}
/// Addes a new UIImage to the NSTextContainer as an NSTextAttachment
///
/// - Parameter image: The image to add
private func pasteImageInTextContainer(with image: UIImage) {
// Add the new image as an NSTextAttachment
let attributedImageString = NSAttributedString(attachment: textAttachment(using: image))
let isEmpty = attributedText.length == 0
// Add a new line character before the image, this is what iMessage does
let newAttributedStingComponent = isEmpty ? NSMutableAttributedString(string: "") : NSMutableAttributedString(string: "\n")
newAttributedStingComponent.append(attributedImageString)
// Add a new line character after the image, this is what iMessage does
newAttributedStingComponent.append(NSAttributedString(string: "\n"))
// The attributes that should be applied to the new NSAttributedString to match the current attributes
let defaultTextColor: UIColor
if #available(iOS 13, *) {
defaultTextColor = .label
} else {
defaultTextColor = .black
}
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: font ?? UIFont.preferredFont(forTextStyle: .body),
NSAttributedString.Key.foregroundColor: textColor ?? defaultTextColor
]
newAttributedStingComponent.addAttributes(attributes, range: NSRange(location: 0, length: newAttributedStingComponent.length))
textStorage.beginEditing()
// Paste over selected text
textStorage.replaceCharacters(in: selectedRange, with: newAttributedStingComponent)
textStorage.endEditing()
// Advance the range to the selected range plus the number of characters added
let location = selectedRange.location + (isEmpty ? 2 : 3)
selectedRange = NSRange(location: location, length: 0)
// Broadcast a notification to recievers such as the MessageInputBar which will handle resizing
postTextViewDidChangeNotification()
}
/// Returns an NSTextAttachment the provided image that will fit inside the NSTextContainer
///
/// - Parameter image: The image to create an attachment with
/// - Returns: The formatted NSTextAttachment
private func textAttachment(using image: UIImage) -> NSTextAttachment {
guard let cgImage = image.cgImage else { return NSTextAttachment() }
let scale = image.size.width / (frame.width - 2 * (textContainerInset.left + textContainerInset.right))
let textAttachment = NSTextAttachment()
textAttachment.image = UIImage(cgImage: cgImage, scale: scale, orientation: image.imageOrientation)
return textAttachment
}
/// Returns all images that exist as NSTextAttachment's
///
/// - Returns: An array of type UIImage
private func parseForAttachedImages() -> [UIImage] {
var images = [UIImage]()
let range = NSRange(location: 0, length: attributedText.length)
attributedText.enumerateAttribute(.attachment, in: range, options: [], using: { value, range, _ -> Void in
if let attachment = value as? NSTextAttachment {
if let image = attachment.image {
images.append(image)
} else if let image = attachment.image(forBounds: attachment.bounds,
textContainer: nil,
characterIndex: range.location) {
images.append(image)
}
}
})
return images
}
/// Returns an array of components (either a String or UIImage) that makes up the textContainer in
/// the order that they were typed
///
/// - Returns: An array of objects guaranteed to be of UIImage or String
private func parseForComponents() -> [Any] {
var components = [Any]()
var attachments = [(NSRange, UIImage)]()
let length = attributedText.length
let range = NSRange(location: 0, length: length)
attributedText.enumerateAttribute(.attachment, in: range) { (object, range, _) in
if let attachment = object as? NSTextAttachment {
if let image = attachment.image {
attachments.append((range, image))
} else if let image = attachment.image(forBounds: attachment.bounds,
textContainer: nil,
characterIndex: range.location) {
attachments.append((range,image))
}
}
}
var curLocation = 0
if attachments.count == 0 {
let text = attributedText.string.trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty {
components.append(text)
}
}
else {
attachments.forEach { (attachment) in
let (range, image) = attachment
if curLocation < range.location {
let textRange = NSMakeRange(curLocation, range.location - curLocation)
let text = attributedText.attributedSubstring(from: textRange).string.trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty {
components.append(text)
}
}
curLocation = range.location + range.length
components.append(image)
}
if curLocation < length - 1 {
let text = attributedText.attributedSubstring(from: NSMakeRange(curLocation, length - curLocation)).string.trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty {
components.append(text)
}
}
}
return components
}
/// Redraws the NSTextAttachments in the NSTextContainer to fit the current bounds
@objc
private func redrawTextAttachments() {
guard images.count > 0 else { return }
let range = NSRange(location: 0, length: attributedText.length)
attributedText.enumerateAttribute(.attachment, in: range, options: [], using: { value, _, _ -> Void in
if let attachment = value as? NSTextAttachment, let image = attachment.image {
// Calculates a new width/height ratio to fit the image in the current frame
let newWidth = frame.width - 2 * (textContainerInset.left + textContainerInset.right)
let ratio = image.size.height / image.size.width
attachment.bounds.size = CGSize(width: newWidth, height: ratio * newWidth)
}
})
layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
}
}
| mit | d3a8bc2135854ee9d39619fed0aa205c | 40.191176 | 170 | 0.6268 | 5.755479 | false | false | false | false |
xivol/Swift-CS333 | playgrounds/uiKit/uiKitCatalog/UIKitCatalog/SearchBarEmbeddedInNavigationBarViewController.swift | 3 | 1739 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to present a search controller's search bar within a navigation bar.
*/
import UIKit
class SearchBarEmbeddedInNavigationBarViewController: SearchControllerBaseViewController {
// MARK: - Properties
// `searchController` is set in viewDidLoad(_:).
var searchController: UISearchController!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Create the search results view controller and use it for the `UISearchController`.
let searchResultsController = storyboard!.instantiateViewController(withIdentifier: SearchResultsViewController.StoryboardConstants.identifier) as! SearchResultsViewController
// Create the search controller and make it perform the results updating.
searchController = UISearchController(searchResultsController: searchResultsController)
searchController.searchResultsUpdater = searchResultsController
searchController.hidesNavigationBarDuringPresentation = false
/*
Configure the search controller's search bar. For more information on
how to configure search bars, see the "Search Bar" group under "Search".
*/
searchController.searchBar.searchBarStyle = .minimal
searchController.searchBar.placeholder = NSLocalizedString("Search", comment: "")
// Include the search bar within the navigation bar.
navigationItem.titleView = searchController.searchBar
definesPresentationContext = true
}
}
| mit | 5b4d250e1648cda57cf904c42018a5c7 | 40.357143 | 183 | 0.71848 | 6.579545 | false | false | false | false |
Peyotle/CircularControl | Example/CircularControl/ViewController.swift | 1 | 1164 | //
// ViewController.swift
// CircularControl
//
// Created by Peyotle on 06/28/2017.
// Copyright (c) 2017 Peyotle. All rights reserved.
//
import UIKit
import CircularControl
class ViewController: UIViewController {
let valueLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
addCircularControl()
setupLabel()
}
func addCircularControl() {
let control = CircularControl(radius: 150 , lineWidth: 20)
control.center = view.center
control.minimumValue = 0
control.maximumValue = 10
control.trackColor = .darkGray
control.value = 5
control.startAngle = 90
control.addTarget(self, action: #selector(trackValueChanged(sender:)), for: .valueChanged)
view.addSubview(control)
}
func setupLabel() {
valueLabel.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
valueLabel.center = view.center
view.addSubview(valueLabel)
}
func trackValueChanged(sender: CircularControl) {
let valueString = String(format: "%.2f", sender.value)
valueLabel.text = valueString
}
}
| mit | 1197110e1f1b49c41f3250d9427dacef | 24.304348 | 98 | 0.638316 | 4.37594 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/ArticleLocationController.swift | 2 | 2238 | import Foundation
@objc class ArticleLocationController: NSObject {
let migrationKey = "WMFDidCompleteQuadKeyMigration"
@objc func needsMigration(managedObjectContext: NSManagedObjectContext) -> Bool {
do {
let keyValueRequest = WMFKeyValue.fetchRequest()
keyValueRequest.predicate = NSPredicate(format: "key == %@", migrationKey)
let keyValueResult = try managedObjectContext.fetch(keyValueRequest)
return keyValueResult.isEmpty || (keyValueResult[0].value == nil)
} catch {
return true
}
}
@objc func migrate(managedObjectContext: NSManagedObjectContext, completion: @escaping (Error?) -> Void) {
do {
let request = WMFArticle.fetchRequest()
request.predicate = NSPredicate(format: "latitude != NULL && latitude != 0 && longitude != NULL && longitude != 0 && signedQuadKey == NULL")
request.fetchLimit = 500
let results = try managedObjectContext.fetch(request)
if results.isEmpty, let entity = NSEntityDescription.entity(forEntityName: "WMFKeyValue", in: managedObjectContext) {
let kv = WMFKeyValue(entity: entity, insertInto: managedObjectContext)
kv.key = migrationKey
kv.value = NSNumber(value: true)
try managedObjectContext.save()
completion(nil)
return
}
for result in results {
let lat = QuadKeyDegrees(result.latitude)
let lon = QuadKeyDegrees(result.longitude)
if lat != 0 && lon != 0 {
let quadKey = QuadKey(latitude: lat, longitude: lon)
let signedQuadKey = Int64(quadKey: quadKey)
result.signedQuadKey = NSNumber(value: signedQuadKey)
}
}
try managedObjectContext.save()
} catch let error {
completion(error)
return
}
DispatchQueue.main.async {
self.migrate(managedObjectContext: managedObjectContext, completion: completion)
}
}
}
| mit | 07ec62433486163bf5ddb3ebbac83511 | 38.964286 | 152 | 0.573727 | 5.595 | false | false | false | false |
Raizlabs/BonMot | Tests/Helpers.swift | 1 | 7776 | //
// Helpers.swift
// BonMot
//
// Created by Brian King on 8/29/16.
// Copyright © 2016 Rightpoint. All rights reserved.
//
@testable import BonMot
import XCTest
#if os(OSX)
#else
import UIKit
let titleTextStyle = UIFont.TextStyle.title1
let differentTextStyle = UIFont.TextStyle.title2
@available(iOS 10.0, tvOS 10.0, *)
let largeTraitCollection = UITraitCollection(preferredContentSizeCategory: .large)
#endif
class DummyClassForTests {}
let testBundle = Bundle(for: DummyClassForTests.self)
extension BONColor {
static var colorA: BONColor {
return red
}
static var colorB: BONColor {
return blue
}
static var colorC: BONColor {
return purple
}
}
extension BONColor {
typealias RGBAComponents = (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)
var rgbaComponents: RGBAComponents {
var comps: RGBAComponents = (0, 0, 0, 0)
getRed(&comps.r, green: &comps.g, blue: &comps.b, alpha: &comps.a)
return comps
}
}
extension BONFont {
static var fontA: BONFont {
return BONFont(name: "Avenir-Roman", size: 30)!
}
static var fontB: BONFont {
return BONFont(name: "Avenir-Roman", size: 20)!
}
}
let styleA = StringStyle(
.font(.fontA),
.color(.colorA)
)
let styleB = StringStyle(
.font(.fontB),
.color(.colorB),
.headIndent(10),
.tailIndent(10)
)
#if os(OSX)
#else
let adaptiveStyle = StringStyle(
.font(.fontA),
.color(.colorA),
.adapt(.body)
)
#endif
let styleBz = StringStyle(
.font(.fontB),
.color(.colorB),
.headIndent(10),
.tailIndent(10)
)
/// A fully populated style object that is updated to ensure that `update`
/// overwrites all values correctly. Values in this style object should not be
/// used by any test using `checks(for:)` to ensure no false positives.
let fullStyle: StringStyle = {
let terribleValue = CGFloat(1000000)
var fullStyle = StringStyle()
fullStyle.font = BONFont(name: "Copperplate", size: 20)
fullStyle.link = URL(string: "http://www.rightpoint.com/")
fullStyle.backgroundColor = .colorC
fullStyle.color = .colorC
fullStyle.underline = (.byWord, .colorC)
fullStyle.strikethrough = (.byWord, .colorC)
fullStyle.baselineOffset = terribleValue
#if os(iOS) || os(tvOS) || os(watchOS)
fullStyle.speaksPunctuation = true
fullStyle.speakingLanguage = "pt-BR" // Brazilian Portuguese
fullStyle.speakingPitch = 1.5
fullStyle.speakingPronunciation = "ˈɡɪər"
fullStyle.shouldQueueSpeechAnnouncement = false
fullStyle.headingLevel = .two
#endif
fullStyle.ligatures = .disabled // not the default value
fullStyle.lineSpacing = terribleValue
fullStyle.paragraphSpacingAfter = terribleValue
fullStyle.alignment = .left
fullStyle.firstLineHeadIndent = terribleValue
fullStyle.headIndent = terribleValue
fullStyle.tailIndent = terribleValue
fullStyle.lineBreakMode = .byTruncatingMiddle
fullStyle.minimumLineHeight = terribleValue
fullStyle.maximumLineHeight = terribleValue
fullStyle.baseWritingDirection = .rightToLeft
fullStyle.lineHeightMultiple = terribleValue
fullStyle.paragraphSpacingBefore = terribleValue
fullStyle.hyphenationFactor = Float(terribleValue)
fullStyle.allowsDefaultTighteningForTruncation = true
#if os(iOS) || os(tvOS) || os(OSX)
fullStyle.fontFeatureProviders = [NumberCase.upper, NumberSpacing.proportional, VerticalPosition.superscript]
fullStyle.numberCase = .upper
fullStyle.numberSpacing = .proportional
fullStyle.fractions = .diagonal
fullStyle.superscript = true
fullStyle.`subscript` = true
fullStyle.ordinals = true
fullStyle.scientificInferiors = true
fullStyle.smallCaps = [.fromUppercase]
fullStyle.stylisticAlternates = .three(on: true)
fullStyle.contextualAlternates = .contextualSwashAlternates(on: true)
#endif
#if os(iOS) || os(tvOS)
fullStyle.adaptations = [.preferred, .control, .body]
#endif
fullStyle.tracking = .adobe(terribleValue)
return fullStyle
}()
/// Utility to load the EBGaramond font if needed.
class EBGaramondLoader: NSObject {
static func loadFontIfNeeded() {
_ = loadFont
}
// Can't include font the normal (Plist) way for logic tests, so load it the hard way
// Source: http://stackoverflow.com/questions/14735522/can-i-embed-a-custom-font-in-a-bundle-and-access-it-from-an-ios-framework
// Method: https://marco.org/2012/12/21/ios-dynamic-font-loading
private static var loadFont: Void = {
guard let path = Bundle(for: EBGaramondLoader.self).path(forResource: "EBGaramond12-Regular", ofType: "otf"),
let data = NSData(contentsOfFile: path)
else {
fatalError("Can not load EBGaramond12")
}
guard let provider = CGDataProvider(data: data) else {
fatalError("Can not create provider")
}
let fontRef = CGFont(provider)
var error: Unmanaged<CFError>?
CTFontManagerRegisterGraphicsFont(fontRef!, &error)
if let error = error {
fatalError("Unable to load font: \(error)")
}
}()
}
extension NSAttributedString {
func rangesFor<T>(attribute name: String) -> [String: T] {
var attributesByRange: [String: T] = [:]
enumerateAttribute(NSAttributedString.Key(name), in: NSRange(location: 0, length: length), options: []) { value, range, _ in
if let object = value as? T {
attributesByRange["\(range.location):\(range.length)"] = object
}
}
return attributesByRange
}
func snapshotForTesting() -> BONImage? {
let bigSize = CGSize(width: 10_000, height: 10_000)
// Bug: on macOS, attached images are not taken into account
// when measuring attributed strings: http://www.openradar.me/28639290
let rect = boundingRect(with: bigSize, options: .usesLineFragmentOrigin, context: nil)
guard !rect.isEmpty else {
return nil
}
#if os(OSX)
let image = NSImage(size: rect.size)
let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(rect.size.width),
pixelsHigh: Int(rect.size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: .deviceRGB,
bytesPerRow: 0,
bitsPerPixel: 0
)!
image.addRepresentation(rep)
image.lockFocus()
draw(with: rect, options: .usesLineFragmentOrigin, context: nil)
image.unlockFocus()
return image
#else
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
draw(with: rect, options: .usesLineFragmentOrigin, context: nil)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
#endif
}
}
extension BONView {
func testingSnapshot() -> BONImage {
#if os(OSX)
let dataOfView = dataWithPDF(inside: bounds)
let image = NSImage(data: dataOfView)!
return image
#else
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
#endif
}
}
| mit | 63f61fdbb23e3947a6803075946fc018 | 29.120155 | 132 | 0.642517 | 4.471231 | false | false | false | false |
Brightify/Cuckoo | Source/Initialization/ThreadLocal.swift | 2 | 1185 | //
// ThreadLocal.swift
// Cuckoo
//
// Created by Tadeas Kriz on 7/6/18.
//
import Foundation
internal class ThreadLocal<T> {
private let dictionaryKey = "ThreadLocal.\(UUID().uuidString)"
internal var value: T? {
get {
let dictionary = Thread.current.threadDictionary
if let storedValue = dictionary[dictionaryKey] {
guard let typedStoredValue = storedValue as? T else {
fatalError("Thread dictionary has been tampered with or UUID confict has occured. Thread dictionary contained different type than \(T.self) for key \(dictionaryKey).")
}
return typedStoredValue
} else {
return nil
}
}
set {
guard let newValue = newValue else {
delete()
return
}
let dictionary = Thread.current.threadDictionary
dictionary[dictionaryKey] = newValue
}
}
internal init() {
}
internal func delete() {
let dictionary = Thread.current.threadDictionary
dictionary.removeObject(forKey: dictionaryKey)
}
}
| mit | da8e890d403decab873c009ee10deca9 | 25.931818 | 187 | 0.571308 | 5.152174 | false | false | false | false |
justinhester/hacking-with-swift | src/Project28/Project28/ViewController.swift | 1 | 5607 | //
// ViewController.swift
// Project28
//
// Created by Justin Lawrence Hester on 2/17/16.
// Copyright © 2016 Justin Lawrence Hester. All rights reserved.
//
import LocalAuthentication
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var secret: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
/* Let this view controller know when interaction with the keyboard occurs. */
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(
self,
selector: "adjustForKeyboard:",
name: UIKeyboardWillHideNotification,
object: nil
)
notificationCenter.addObserver(
self,
selector: "adjustForKeyboard:",
name: UIKeyboardWillChangeFrameNotification,
object: nil
)
title = "Nothing to see here"
/* Add observers for saving data. */
notificationCenter.addObserver(
self,
selector: "saveSecretMessage",
name: UIApplicationWillResignActiveNotification,
object: nil
)
}
func adjustForKeyboard(notification: NSNotification) {
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let keyboardViewEndFrame = view
.convertRect(
keyboardScreenEndFrame,
fromView: view.window
)
if notification.name == UIKeyboardWillHideNotification {
secret.contentInset = UIEdgeInsetsZero
} else {
secret.contentInset = UIEdgeInsets(
top: 0,
left: 0,
bottom: keyboardViewEndFrame.height,
right: 0
)
}
secret.scrollIndicatorInsets = secret.contentInset
let selectedRange = secret.selectedRange
secret.scrollRangeToVisible(selectedRange)
}
@IBAction func authenticateUser(sender: AnyObject) {
let context = LAContext()
var error: NSError?
/* Check where the device is capable of supporting biometric authentication. */
if context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
/*
If so, request that the Touch ID begin a check now,
giving it a string containing the reason why we're asking.
*/
let reason = "Identify yourself!"
context.evaluatePolicy(
.DeviceOwnerAuthenticationWithBiometrics,
localizedReason: reason) { [unowned self] (success: Bool, authenticationError: NSError?) in
/*
If we get success back from Touch ID it means this is
the device's owner so we can unlock the app,
otherwise we show a failur message.
NOTE: this might no be on the main thread.
*/
dispatch_async(dispatch_get_main_queue()) {
if success {
self.unlockSecretMessage()
} else {
if let error = authenticationError {
/* User asked to input fallback password. */
if error.code == LAError.UserFallback.rawValue {
let ac = UIAlertController(
title: "Passcode? Ha!",
message: "It's Touch ID or nothing - sorry!",
preferredStyle: .Alert
)
ac.addAction(
UIAlertAction(
title: "OK",
style: .Default,
handler: nil
)
)
self.presentViewController(ac, animated: true, completion: nil)
return
}
}
}
}
}
} else {
let ac = UIAlertController(
title: "Touch ID not available",
message: "Your device is not configured for Touch ID.",
preferredStyle: .Alert
)
ac.addAction(
UIAlertAction(
title: "OK",
style: .Default,
handler: nil
)
)
presentViewController(ac, animated: true, completion: nil)
}
}
func unlockSecretMessage() {
secret.hidden = false
title = "Secret stuff!"
if let text = KeychainWrapper.stringForKey("SecretMessage") {
secret.text = text
}
}
func saveSecretMessage() {
if !secret.hidden {
KeychainWrapper.setString(secret.text, forKey: "SecretMessage")
secret.resignFirstResponder()
secret.hidden = true
title = "Nothing to see here"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 7b2558637e194b8d7d7309c4bbffac80 | 33.604938 | 107 | 0.499643 | 6.518605 | false | false | false | false |
malcommac/SwiftRichString | Sources/SwiftRichString/Extensions/AttributedString+Attachments.swift | 1 | 4580 | //
// SwiftRichString
// Elegant Strings & Attributed Strings Toolkit for Swift
//
// Created by Daniele Margutti.
// Copyright © 2018 Daniele Margutti. All rights reserved.
//
// Web: http://www.danielemargutti.com
// Email: hello@danielemargutti.com
// Twitter: @danielemargutti
//
//
// 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
#if os(OSX)
import AppKit
#else
import UIKit
#endif
public extension AttributedString {
#if os(iOS)
/// Initialize a new text attachment with a remote image resource.
/// Image will be loaded asynchronously after the text appear inside the control.
///
/// - Parameters:
/// - imageURL: url of the image. If url is not valid resource will be not downloaded.
/// - bounds: set a non `nil` value to express set the rect of attachment.
convenience init?(imageURL: String?, bounds: String? = nil) {
guard let imageURL = imageURL, let url = URL(string: imageURL) else {
return nil
}
let attachment = AsyncTextAttachment()
attachment.imageURL = url
if let bounds = CGRect(string: bounds) {
attachment.bounds = bounds
}
self.init(attachment: attachment)
}
#endif
#if os(iOS) || os(OSX)
/// Initialize a new text attachment with local image contained into the assets.
///
/// - Parameters:
/// - imageNamed: name of the image into the assets; if `nil` resource will be not loaded.
/// - bounds: set a non `nil` value to express set the rect of attachment.
convenience init?(imageNamed: String?, bounds: String? = nil) {
guard let imageNamed = imageNamed else {
return nil
}
let image = Image(named: imageNamed)
self.init(image: image, bounds: bounds)
}
/// Initialize a new attributed string from an image.
///
/// - Parameters:
/// - image: image to use.
/// - bounds: location and size of the image, if `nil` the default bounds is applied.
convenience init?(image: Image?, bounds: String? = nil) {
guard let image = image else {
return nil
}
#if os(OSX)
let attachment = NSTextAttachment(data: image.pngData()!, ofType: "png")
#else
var attachment: NSTextAttachment!
if #available(iOS 13.0, *) {
// Due to a bug (?) in UIKit we should use two methods to allocate the text attachment
// in order to render the image as template or original. If we use the
// NSTextAttachment(image: image) with a .alwaysOriginal rendering mode it will be
// ignored.
if image.renderingMode == .alwaysTemplate {
attachment = NSTextAttachment(image: image)
} else {
attachment = NSTextAttachment()
attachment.image = image.withRenderingMode(.alwaysOriginal)
}
} else {
// It does not work on iOS12, return empty set.s
// attachment = NSTextAttachment(data: image.pngData()!, ofType: "png")
attachment = NSTextAttachment()
attachment.image = image.withRenderingMode(.alwaysOriginal)
}
#endif
if let boundsRect = CGRect(string: bounds) {
attachment.bounds = boundsRect
}
self.init(attachment: attachment)
}
#endif
}
| mit | 8b843abf27b0a5499f0a87160f3789d1 | 35.927419 | 98 | 0.627211 | 4.710905 | false | false | false | false |
ydi-core/nucleus-ios | Nucleus/LoginController.swift | 1 | 22972 | //
// LoginController.swift
// Nucleus
//
// Created by Bezaleel Ashefor on 27/10/2017.
// Copyright © 2017 Ephod. All rights reserved.
//
import UIKit
import Alamofire
import ImagePicker
class LoginController: UIViewController, UITextFieldDelegate, ImagePickerDelegate {
let mainStoryBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
guard images.count > 0 else { return }
avatarImage = images[0]
let imageData:NSData = UIImagePNGRepresentation(avatarImage)! as NSData
UserDefaults.standard.set(imageData, forKey: "savedImage")
imagePicker.dismiss(animated: true, completion: nil)
let nextController = mainStoryBoard.instantiateViewController(withIdentifier: "profileView") as! ProfileController
self.present(nextController, animated: true, completion: nil)
}
func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
guard images.count > 0 else { return }
avatarImage = images[0]
let imageData:NSData = UIImagePNGRepresentation(avatarImage)! as NSData
UserDefaults.standard.set(imageData, forKey: "savedImage")
imagePicker.dismiss(animated: true, completion: nil)
let nextController = mainStoryBoard.instantiateViewController(withIdentifier: "profileView") as! ProfileController
self.present(nextController, animated: true, completion: nil)
}
func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
imagePicker.dismiss(animated: true, completion: nil)
}
var avatarImage : UIImage!
@IBOutlet weak var chooseButton: UIButton!
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var signInPanel: UIView!
@IBOutlet weak var registerBtn: UIButton!
@IBOutlet weak var avatarPanel: UIView!
@IBOutlet weak var surnameText: CustomEditText!
@IBOutlet weak var genderText: CustomEditText!
@IBOutlet weak var phoneText: CustomEditText!
@IBOutlet weak var emailText: CustomEditText!
@IBOutlet weak var hearText: CustomEditText!
@IBOutlet weak var careerText: CustomEditText!
@IBOutlet weak var firstTimeText: CustomEditText!
@IBAction func chooseBtnClick(_ sender: Any) {
selectImage()
}
@IBAction func regSubmitButtonClick(_ sender: Any) {
registerParticipant()
}
@IBAction func signSubmitButtonClick(_ sender: Any) {
signInParticipant()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
// Try to find next responder
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
// Do not add a line break
return false
}
let this_headers: HTTPHeaders = [
//"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
//"Accept": "application/json"
"TOK": "blah"
]
@IBAction func registerClick(_ sender: Any) {
startPanel.isHidden = true
registerPanel.isHidden = false
signInPanel.isHidden = true
//self.view.endEditing(true)
}
@IBAction func signInClick(_ sender: Any) {
startPanel.isHidden = true
registerPanel.isHidden = true
signInPanel.isHidden = false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
@IBAction func signInBackBtnClick(_ sender: Any) {
startPanel.isHidden = false
signInPanel.isHidden = true
registerPanel.isHidden = true
self.view.endEditing(true)
}
@IBOutlet weak var regSubmitButton: UIButton!
@IBOutlet weak var signInSubmitBtn: UIButton!
@IBOutlet weak var registerPanel: UIView!
@IBOutlet weak var startPanel: UIView!
@IBAction func regBackBtnClick(_ sender: Any) {
startPanel.isHidden = false
signInPanel.isHidden = true
registerPanel.isHidden = true
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
registerPanel.isHidden = true
signInPanel.isHidden = true
avatarPanel.isHidden = true
// Do any additional setup after loading the view, typically from a nib.
setBg()
setButtons()
surnameText.delegate = self
surnameText.tag = 1
genderText.delegate = self
genderText.tag = 2
phoneText.delegate = self
phoneText.tag = 3
emailText.delegate = self
emailText.tag = 4
hearText.delegate = self
hearText.tag = 5
careerText.delegate = self
careerText.tag = 6
firstTimeText.delegate = self
firstTimeText.tag = 7
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
@IBOutlet weak var emailSignText: CustomEditText!
func signInParticipant(){
if(emailSignText.text == ""){
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out your email yet. Expecting magic?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else {
self.signInPanel.isHidden = true
self.view.endEditing(true)
let spinner = ALThreeCircleSpinner(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
spinner.tintColor = UIColor.white
spinner.hidesWhenStopped = false
view.addSubview(spinner)
spinner.center = view.center
spinner.startAnimating()
let parameters: Parameters = [
"email": emailSignText.text!
]
Alamofire.request("http://campjoseph.ydiworld.org/api/register/participant", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
if let status = response.response?.statusCode {
switch(status){
case 200:
spinner.removeFromSuperview()
if let result = response.result.value {
let JSON = result as! NSDictionary
let statusText: Bool = JSON.object(forKey: "success")! as! Bool
//print(JSON)
if (statusText == true){
//let tribe = JSON.object(forKey: "tribe") as! String!
let participant = JSON.object(forKey: "participant") as! NSDictionary
let events = JSON.object(forKey: "events") as! NSArray
let officials = JSON.object(forKey: "officials") as! NSArray
let name = participant.object(forKey: "Fullname")! as! String
let id = participant.object(forKey: "ID")! as! Int
let tribe = participant.object(forKey: "Tribe")! as! String
let career = participant.object(forKey: "Career")! as! String
let email = participant.object(forKey: "Email")! as! String
let phone = participant.object(forKey: "Phone")! as! String
let gender = participant.object(forKey: "Gender")! as! String
let hear = participant.object(forKey: "Hear about Camp")! as! String
let first = participant.object(forKey: "First time at Camp")! as! String
//print(name)
UserDefaults.standard.set(name, forKey: "savedName")
UserDefaults.standard.set(id, forKey: "savedID")
UserDefaults.standard.set(tribe, forKey: "savedTribe")
UserDefaults.standard.set(career, forKey: "savedCareer")
UserDefaults.standard.set(email, forKey: "savedEmail")
UserDefaults.standard.set(phone, forKey: "savedPhone")
UserDefaults.standard.set(gender, forKey: "savedGender")
UserDefaults.standard.set(hear, forKey: "savedHear")
UserDefaults.standard.set(first, forKey: "savedFirst")
UserDefaults.standard.set(events, forKey: "savedEvents")
UserDefaults.standard.set(officials, forKey: "savedOfficials")
self.avatarPanel.isHidden = false
//UserDefaults.standard.set(tribe, forKey: "savedTribe")
//UserDefaults.standard.set(self.firstTimeText.text, forKey: "savedFirst")
} else if (statusText == false){
let reason = JSON.object(forKey: "reason")! as! String
if (reason == "no exist"){
let alert = UIAlertController(title: "Account not found", message: "No registration data was found with this email.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
self.signInPanel.isHidden = false
}
}
}
//print("Data: \(String(describing: utf8Text))")
//print("example success")
default:
spinner.removeFromSuperview()
print("error with response status: \(status)")
}
}
}
}
}
func registerParticipant(){
if (surnameText.text == ""){
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out your name yet.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else if (genderText.text == "") {
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out your gender yet. Hope all is well?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else if (phoneText.text == ""){
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out your phone number.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else if (emailText.text == ""){
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out your email yet.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else if (hearText.text == ""){
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out how you heard about Camp Joseph.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else if (careerText.text == ""){
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out what you do for a living.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else if (firstTimeText.text == ""){
let alert = UIAlertController(title: "Field empty", message: "You haven't filled out if this is your first time.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
} else {
registerPanel.isHidden = true
self.view.endEditing(true)
let spinner = ALThreeCircleSpinner(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
spinner.tintColor = UIColor.white
spinner.hidesWhenStopped = false
view.addSubview(spinner)
spinner.center = view.center
spinner.startAnimating()
let _: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
//self.appDelegate.api_url
//let rating_int = Int64(ratingVC.cosmosStarRating.rating)
//let comment = ""
let parameters: Parameters = [
"name": surnameText.text!, "phone" : phoneText.text!, "email": emailText.text!, "hear" : hearText.text!, "career" : careerText.text!, "first" : firstTimeText.text!, "gender" : genderText.text!
]
Alamofire.request("http://campjoseph.ydiworld.org/api/register/new", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
//print("Request: \(response.request)")
//print("Response: \(response.response)")
//print("Error: \(response.error)")
if let status = response.response?.statusCode {
switch(status){
case 200:
spinner.removeFromSuperview()
if let result = response.result.value {
let JSON = result as! NSDictionary
let statusText: Bool = JSON.object(forKey: "success")! as! Bool
//print(JSON)
if (statusText == true){
let id = JSON.object(forKey: "last_insert_id") as! Int!
let tribe = JSON.object(forKey: "tribe") as! String!
let events = JSON.object(forKey: "events") as! NSArray
let officials = JSON.object(forKey: "officials") as! NSArray
self.avatarPanel.isHidden = false
UserDefaults.standard.set(self.surnameText.text, forKey: "savedName")
UserDefaults.standard.set(id, forKey: "savedID")
UserDefaults.standard.set(tribe, forKey: "savedTribe")
UserDefaults.standard.set(self.careerText.text, forKey: "savedCareer")
UserDefaults.standard.set(self.emailText.text, forKey: "savedEmail")
UserDefaults.standard.set(self.phoneText.text, forKey: "savedPhone")
UserDefaults.standard.set(self.genderText.text, forKey: "savedGender")
UserDefaults.standard.set(self.hearText.text, forKey: "savedHear")
UserDefaults.standard.set(self.firstTimeText.text, forKey: "savedFirst")
UserDefaults.standard.set(events, forKey: "savedEvents")
UserDefaults.standard.set(officials, forKey: "savedOfficials")
//UserDefaults.standard.set(self.firstTimeText.text, forKey: "savedFirst")
} else if (statusText == false){
let reason = JSON.object(forKey: "reason")! as! String
if (reason == "exists"){
let alert = UIAlertController(title: "Account exists", message: "This email has already been registered for this event. Sign in with this email or use another email.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
self.present(alert, animated: true)
self.registerPanel.isHidden = false
}
}
}
//print("Data: \(String(describing: utf8Text))")
//print("example success")
default:
spinner.removeFromSuperview()
print("error with response status: \(status)")
}
}
/*if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}*/
}
}
}
func selectImage(){
let imagePickerController = ImagePickerController()
imagePickerController.delegate = self
imagePickerController.imageLimit = 1
present(imagePickerController, animated: true, completion: nil)
}
func setButtons(){
chooseButton.layer.shadowColor = UIColor.black.cgColor
chooseButton.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
chooseButton.layer.shadowRadius = 20
chooseButton.layer.shadowOpacity = 0.3
chooseButton.layer.cornerRadius = 5
registerBtn.layer.shadowColor = UIColor.black.cgColor
registerBtn.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
registerBtn.layer.shadowRadius = 20
registerBtn.layer.shadowOpacity = 0.3
registerBtn.layer.cornerRadius = 5
regSubmitButton.layer.shadowColor = UIColor.black.cgColor
regSubmitButton.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
regSubmitButton.layer.shadowRadius = 20
regSubmitButton.layer.shadowOpacity = 0.3
regSubmitButton.layer.cornerRadius = 5
signInSubmitBtn.layer.shadowColor = UIColor.black.cgColor
signInSubmitBtn.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
signInSubmitBtn.layer.shadowRadius = 20
signInSubmitBtn.layer.shadowOpacity = 0.3
signInSubmitBtn.layer.cornerRadius = 5
}
func setBg(){
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
if DeviceType.IS_IPHONE_X {
backgroundImage.image = UIImage(named: "iPhoneX")
//print("== ()")
} else if DeviceType.IS_IPHONE_6P {
backgroundImage.image = UIImage(named: "iphone_6p")
} else if DeviceType.IS_IPHONE_6 {
backgroundImage.image = UIImage(named: "iphone_6")
} else if DeviceType.IS_IPHONE_5 {
backgroundImage.image = UIImage(named: "iphone_5")
} else if DeviceType.IS_IPHONE_4_OR_LESS {
backgroundImage.image = UIImage(named: "iphone_4")
}
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
}
enum UIUserInterfaceIdiom : Int
{
case Unspecified
case Phone
case Pad
}
struct ScreenSize
{
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType
{
//4, 4s and below
static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
//covers 5, 5s, 5c, SE
static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
//covers 6, 6s, 7, 8
static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
//covers 6p, 6sp, 7p, 8p
static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
static let IS_IPHONE_X = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 812.0
static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
}
}
| bsd-2-clause | aea274106b7c56ed5ca88ca35d83abe9 | 42.178571 | 227 | 0.526838 | 5.422805 | false | false | false | false |
TMTBO/TTAImagePickerController | TTAImagePickerController/Classes/Views/TTAPreviewNavigationBar.swift | 1 | 5764 | //
// TTAPreviewNavigationBar.swift
// Pods-TTAImagePickerController_Example
//
// Created by TobyoTenma on 02/07/2017.
//
import Photos
protocol TTAPreviewNavigationBarDelegate: class {
func previewNavigationBar(_ navigationBar: TTAPreviewNavigationBar, didClickBack button: UIButton)
func canOperate() -> (canOperate: Bool, asset: PHAsset?)
func previewNavigationBar(_ navigationBar: TTAPreviewNavigationBar, asset: PHAsset, isSelected: Bool)
}
class TTAPreviewNavigationBar: UIView {
weak var delegate: TTAPreviewNavigationBarDelegate?
var selectItemTintColor: UIColor? {
didSet {
selectButton.selectItemTintColor = selectItemTintColor
}
}
fileprivate let backButton = UIButton(type: .system)
fileprivate let selectButton = TTASelectButton()
fileprivate let timeLabel = UILabel()
fileprivate let bgView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutViews()
}
}
// MARK: - UI
extension TTAPreviewNavigationBar {
func setupUI() {
func _createViews() {
addSubview(bgView)
bgView.contentView.addSubview(backButton)
bgView.contentView.addSubview(selectButton)
bgView.contentView.addSubview(timeLabel)
}
func _configViews() {
backgroundColor = UIColor.clear
bgView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
timeLabel.textColor = .white
timeLabel.font = UIFont.systemFont(ofSize: 16)
timeLabel.adjustsFontSizeToFitWidth = true
timeLabel.textAlignment = .center
timeLabel.numberOfLines = 2
backButton.addTarget(self, action: #selector(didClickBackButton(_:)), for: .touchUpInside)
backButton.setTitle(UIFont.IconFont.backMark.rawValue, for: .normal)
backButton.titleLabel?.font = UIFont.iconfont(size: UIFont.IconFontSize.backMark)
backButton.setTitleColor(selectItemTintColor, for: .normal)
selectButton.addTarget(self, action: #selector(didClickSelectButton(_:)), for: .touchUpInside)
}
_createViews()
_configViews()
}
func layoutViews() {
var layoutY: CGFloat = 20
var layoutHeight: CGFloat = bounds.height
var layoutMaxX: CGFloat = bounds.width
if #available(iOS 11.0, *) {
let rect = safeAreaLayoutGuide.layoutFrame
layoutY = rect.minY
layoutHeight = rect.height
layoutMaxX = rect.maxX
if UIApplication.shared.isStatusBarHidden && UIApplication.shared.statusBarOrientation.isLandscape { // Adjust iPhoneX hidden status bar when Landscape
backButton.contentHorizontalAlignment = .trailing
backButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 30)
} else {
backButton.contentHorizontalAlignment = .leading
backButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 6, bottom: 0, right: 0)
}
} else {
backButton.contentHorizontalAlignment = .left
backButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 6, bottom: 0, right: 0)
}
bgView.frame = bounds
backButton.frame = CGRect(x: 0, y: layoutY, width: 100, height: layoutHeight)
selectButton.frame = CGRect(x: layoutMaxX - 26 - 10, y: layoutY + (layoutHeight - 26) / 2, width: 26, height: 26)
timeLabel.frame = CGRect(x: backButton.frame.maxX + 10, y: backButton.frame.minY, width: bounds.width - 2 * (backButton.frame.width + 10), height: backButton.frame.height)
}
func updateImageInfo(with creationDate: Date?) {
guard let creationDate = creationDate else { return }
if !hasConfigedDateFormatter {
dateFormatter.timeStyle = .medium
dateFormatter.dateStyle = .medium
hasConfigedDateFormatter = true
}
timeLabel.text = dateFormatter.string(from: creationDate)
}
func configNavigationBar(isSelected: Bool) {
guard selectButton.isSelected != isSelected else { return }
selectButton.selectState = isSelected ? .selected : .default
}
func configHideSelectButton(_ isHidden: Bool) {
selectButton.isHidden = isHidden
}
}
// MARK: - Actions
extension TTAPreviewNavigationBar {
@objc func didClickBackButton(_ button: UIButton) {
delegate?.previewNavigationBar(self, didClickBack: button)
}
@objc func didClickSelectButton(_ button: TTASelectButton) {
guard let (canOperate, asset) = delegate?.canOperate(),
canOperate == true,
let operateAsset = asset else { return }
selectButton.selectState = selectButton.selectState == .selected ? .default : .selected
delegate?.previewNavigationBar(self, asset: operateAsset, isSelected: selectButton.isSelected)
}
}
// MARK: - Const
extension TTAPreviewNavigationBar {
static func height(with addition: CGFloat) -> CGFloat {
let orientation = UIApplication.shared.statusBarOrientation
if UIApplication.shared.isStatusBarHidden { // Adjust iPhoneX hidden status bar when Landscape
return orientation.isLandscape ? 32 : (44 + addition)
} else {
return orientation.isLandscape ? 52 : (44 + addition)
}
}
}
| mit | e285de4f535815ad886439d3fa3760e9 | 36.673203 | 179 | 0.648334 | 5.034061 | false | false | false | false |
b0oh/mal | swift/env.swift | 1 | 2246 | //******************************************************************************
// MAL - env
//******************************************************************************
import Foundation
typealias EnvironmentVars = [MalSymbol: MalVal]
let kSymbolAmpersand = MalSymbol(symbol: "&")
class Environment {
init(outer: Environment?) {
self.outer = outer
}
func set_bindings(binds: MalSequence, with_exprs exprs: MalSequence) -> MalVal {
for var index = 0; index < binds.count; ++index {
if !is_symbol(binds[index]) { return MalError(message: "an entry in binds was not a symbol: index=\(index), binds[index]=\(binds[index])") }
let sym = binds[index] as MalSymbol
if sym != kSymbolAmpersand {
if index < exprs.count {
set(sym, exprs[index])
} else {
set(sym, MalNil())
}
continue
}
// I keep getting messed up by the following, so here's an
// explanation. We are iterating over two lists, and are at this
// point:
//
// index
// |
// v
// binds: (... & name)
// exprs: (... a b c d e ...)
//
// In the following, we increment index to get to "name", and then
// later decrement it to get to (a b c d e ...)
if ++index >= binds.count { return MalError(message: "found & but no symbol") }
if !is_symbol(binds[index]) { return MalError(message: "& was not followed by a symbol: index=\(index), binds[index]=\(binds[index])") }
let rest_sym = binds[index--] as MalSymbol
let rest = exprs[index..<exprs.count]
set(rest_sym, MalList(slice: rest))
break
}
return MalNil()
}
func set(sym: MalSymbol, _ value: MalVal) -> MalVal {
data[sym] = value
return value
}
func get(sym: MalSymbol) -> MalVal? {
if let val = data[sym] { return val }
return outer?.get(sym)
}
private var outer: Environment?
private var data = EnvironmentVars()
}
| mpl-2.0 | a14cc7593246cc40d981f7c3cdb192d7 | 35.225806 | 152 | 0.475957 | 4.659751 | false | false | false | false |
ello/ello-ios | Sources/Model/Regions/Asset.swift | 1 | 6629 | ////
/// Asset.swift
//
import SwiftyJSON
let AssetVersion = 1
@objc(Asset)
final class Asset: Model {
enum AttachmentType {
case optimized
case mdpi
case hdpi
case xhdpi
case original
case large
case regular
}
let id: String
var optimized: Attachment?
var mdpi: Attachment?
var hdpi: Attachment?
var xhdpi: Attachment?
var original: Attachment?
var large: Attachment?
var regular: Attachment?
var allAttachments: [(AttachmentType, Attachment)] {
let possibles: [(AttachmentType, Attachment?)] = [
(.optimized, optimized),
(.mdpi, mdpi),
(.hdpi, hdpi),
(.xhdpi, xhdpi),
(.original, original),
(.large, large),
(.regular, regular),
]
return possibles.compactMap { type, attachment in
return attachment.map { (type, $0) }
}
}
var isGif: Bool {
return original?.isGif == true || optimized?.isGif == true
}
var isLargeGif: Bool {
if isGif, let size = optimized?.size {
return size >= 3_145_728
}
return false
}
var isSmallGif: Bool {
if isGif, let size = optimized?.size {
return size <= 1_000_000
}
return false
}
var largeOrBest: Attachment? {
if isGif, let original = original {
return original
}
if DeviceScreen.isRetina {
if let large = large { return large }
if let xhdpi = xhdpi { return xhdpi }
if let optimized = optimized { return optimized }
}
if let hdpi = hdpi { return hdpi }
if let regular = regular { return regular }
return nil
}
var oneColumnAttachment: Attachment? {
return Window.isWide(Window.width) && DeviceScreen.isRetina ? xhdpi : hdpi
}
var gridLayoutAttachment: Attachment? {
return Window.isWide(Window.width) && DeviceScreen.isRetina ? hdpi : mdpi
}
var aspectRatio: CGFloat {
var attachment: Attachment?
if let tryAttachment = oneColumnAttachment {
attachment = tryAttachment
}
else if let tryAttachment = optimized {
attachment = tryAttachment
}
if let attachment = attachment,
let width = attachment.width,
let height = attachment.height
{
return CGFloat(width) / CGFloat(height)
}
return 4.0 / 3.0
}
convenience init(url: URL) {
self.init(id: UUID().uuidString)
let attachment = Attachment(url: url)
self.optimized = attachment
self.mdpi = attachment
self.hdpi = attachment
self.xhdpi = attachment
self.original = attachment
self.large = attachment
self.regular = attachment
}
convenience init(url: URL, gifData: Data, posterImage: UIImage) {
self.init(id: UUID().uuidString)
let optimized = Attachment(url: url)
optimized.type = "image/gif"
optimized.size = gifData.count
optimized.width = Int(posterImage.size.width)
optimized.height = Int(posterImage.size.height)
self.optimized = optimized
let hdpi = Attachment(url: url)
hdpi.width = Int(posterImage.size.width)
hdpi.height = Int(posterImage.size.height)
hdpi.image = posterImage
self.hdpi = hdpi
}
convenience init(url: URL, image: UIImage) {
self.init(id: UUID().uuidString)
let optimized = Attachment(url: url)
optimized.width = Int(image.size.width)
optimized.height = Int(image.size.height)
optimized.image = image
self.optimized = optimized
}
init(id: String) {
self.id = id
super.init(version: AssetVersion)
}
required init(coder: NSCoder) {
let decoder = Coder(coder)
self.id = decoder.decodeKey("id")
self.optimized = decoder.decodeOptionalKey("optimized")
self.mdpi = decoder.decodeOptionalKey("mdpi")
self.hdpi = decoder.decodeOptionalKey("hdpi")
self.xhdpi = decoder.decodeOptionalKey("xhdpi")
self.original = decoder.decodeOptionalKey("original")
// optional avatar
self.large = decoder.decodeOptionalKey("large")
self.regular = decoder.decodeOptionalKey("regular")
super.init(coder: coder)
}
override func encode(with encoder: NSCoder) {
let coder = Coder(encoder)
coder.encodeObject(id, forKey: "id")
coder.encodeObject(optimized, forKey: "optimized")
coder.encodeObject(mdpi, forKey: "mdpi")
coder.encodeObject(hdpi, forKey: "hdpi")
coder.encodeObject(xhdpi, forKey: "xhdpi")
coder.encodeObject(original, forKey: "original")
// optional avatar
coder.encodeObject(large, forKey: "large")
coder.encodeObject(regular, forKey: "regular")
super.encode(with: coder.coder)
}
class func fromJSON(_ data: [String: Any]) -> Asset {
let json = JSON(data)
return parseAsset(json["id"].idValue, node: data["attachment"] as? [String: Any])
}
class func parseAsset(_ id: String, node: [String: Any]?) -> Asset {
let asset = Asset(id: id)
guard let node = node else { return asset }
let attachments: [(String, AttachmentType)] = [
("optimized", .optimized),
("mdpi", .mdpi),
("hdpi", .hdpi),
("xhdpi", .xhdpi),
("original", .original),
("large", .large),
("regular", .regular),
]
for (name, type) in attachments {
guard let attachment = node[name] as? [String: Any],
let url = attachment["url"] as? String,
url != ""
else { continue }
asset.replace(attachmentType: type, with: Attachment.fromJSON(attachment))
}
return asset
}
}
extension Asset {
func replace(attachmentType: AttachmentType, with attachment: Attachment?) {
switch attachmentType {
case .optimized: optimized = attachment
case .mdpi: mdpi = attachment
case .hdpi: hdpi = attachment
case .xhdpi: xhdpi = attachment
case .original: original = attachment
case .large: large = attachment
case .regular: regular = attachment
}
}
}
extension Asset: JSONSaveable {
var uniqueId: String? { return "Asset-\(id)" }
var tableId: String? { return id }
}
| mit | 2883e94747b428977b9ec74cd4e1ceb7 | 28.331858 | 89 | 0.579122 | 4.285068 | false | false | false | false |
wxxsw/GSRefresh | Sources/Observer.swift | 1 | 5569 | //
// Observer.swift
// GSRefresh
// https://github.com/wxxsw/GSRefresh
//
// Created by Gesen on 2017/5/20.
//
// Copyright © 2017 Gesen <i@gesen.me>
//
// 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
protocol ObserverDelegate {
func observerStateChanged(previous: Observer.ObserverState,
newState: Observer.ObserverState)
}
public class Observer: UIView {
enum KeyPath {
static let contentOffset = "contentOffset"
static let contentSize = "contentSize"
static let state = "state"
}
struct ObserverState {
var offset: Offset = .zero
var size: Size = .zero
var insets: Insets = .zero
var dragState: DragState = .possible
var isObserving: Bool = false
}
// MARK: Properties
var scrollView: UIScrollView? { return superview as? UIScrollView }
var view: UIView? {
didSet {
view?.isHidden = true
view != nil ? startObserver() : stopObserver()
}
}
var handler: (() -> Void)?
var observerState = ObserverState() {
didSet {
guard observerState != oldValue else { return }
(self as? ObserverDelegate)?
.observerStateChanged(previous: oldValue,
newState: observerState)
}
}
private var pan: UIPanGestureRecognizer?
// MARK: Initialization
init(scrollView: UIScrollView) {
super.init(frame: .zero)
scrollView.addSubview(self)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
handler = nil
}
public override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if newSuperview == nil, superview is UIScrollView {
stopObserver()
}
}
public override func didMoveToSuperview() {
super.didMoveToSuperview()
if superview is UIScrollView {
startObserver()
}
}
// MARK: KVO
override public func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
guard scrollView != nil, view != nil,
let keyPath = keyPath,
let change = change
else { return }
switch keyPath {
case KeyPath.contentOffset:
guard let newValue = change[.newKey] as? Offset else { return }
observerState.offset = newValue
case KeyPath.contentSize:
guard let newValue = change[.newKey] as? Size else { return }
observerState.size = newValue
case KeyPath.state:
guard let newRawValue = change[.newKey] as? Int,
let newValue = DragState(rawValue: newRawValue)
else { return }
observerState.dragState = newValue
default: break
}
}
}
// MARK: - Private Functions
private extension Observer {
func startObserver() {
guard !observerState.isObserving else { return }
observerState.isObserving = true
scrollView?.addObserver(self, forKeyPath: KeyPath.contentOffset, options: [.new], context: nil)
scrollView?.addObserver(self, forKeyPath: KeyPath.contentSize, options: [.new], context: nil)
pan = scrollView?.panGestureRecognizer
pan?.addObserver(self, forKeyPath: KeyPath.state, options: [.new], context: nil)
}
func stopObserver() {
guard observerState.isObserving else { return }
observerState.isObserving = false
scrollView?.removeObserver(self, forKeyPath: KeyPath.contentOffset)
scrollView?.removeObserver(self, forKeyPath: KeyPath.contentSize)
pan?.removeObserver(self, forKeyPath: KeyPath.state)
pan = nil
}
}
// MARK: - Equatable
extension Observer.ObserverState: Equatable {}
func ==(lhs: Observer.ObserverState, rhs: Observer.ObserverState) -> Bool {
return lhs.dragState == rhs.dragState &&
lhs.offset == rhs.offset &&
lhs.size == rhs.size
}
| mit | 0d256630945fea7c6f4ba2562dd84590 | 29.26087 | 103 | 0.604705 | 5.043478 | false | false | false | false |
BillZong/OneProgramOneDay | D44_FoodPin/FoodPin/DetailViewController.swift | 1 | 3774 | //
// DetailViewController.swift
// FoodPin
//
// Created by BillZong on 15-1-23.
// Copyright (c) 2015年 BillZong. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var restaurantImageView: UIImageView!
var restaurant: Restaurant!
override func viewDidLoad() {
super.viewDidLoad()
restaurantImageView.image = UIImage(named: restaurant.image)
tableView.backgroundColor = UIColor(red: 240.0 / 255.0, green: 240.0 / 255.0, blue: 240.0 / 255.0, alpha: 0.2)
tableView.tableFooterView = UIView(frame: CGRect.zeroRect)
tableView.separatorColor = UIColor(red: 240.0 / 255.0, green: 240.0 / 255.0, blue: 240.0 / 255.0, alpha: 0.8)
self.navigationItem.title = restaurant.name
// set autosize cell
tableView.estimatedRowHeight = 36.0
tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: tableViewDataSource protocol functions
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("restaurantDetailCell", forIndexPath: indexPath) as DetailTableViewCell
switch indexPath.row {
case 0:
cell.fieldLabel.text = "Name"
cell.valueLabel.text = restaurant.name
case 1:
cell.fieldLabel.text = "Type"
cell.valueLabel.text = restaurant.type
case 2:
cell.fieldLabel.text = "Location"
cell.mapButton.hidden = false
cell.valueLabel.text = restaurant.location
case 3:
cell.fieldLabel.text = "Been here"
cell.valueLabel.text = (restaurant.isVisited) ? "Yes, I’ve been here before" : "No"
default:
cell.fieldLabel.text = ""
cell.valueLabel.text = ""
}
cell.backgroundColor = UIColor.clearColor()
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showReview" {
let vc = segue.destinationViewController as ReviewViewController
vc.restaurant = restaurant
} else if segue.identifier == "showMap" {
let vc = segue.destinationViewController as MapViewController
vc.restaurant = restaurant
}
}
@IBAction func close(segue: UIStoryboardSegue) {
}
}
| lgpl-3.0 | d704514003961f5bc13ab618bd2cb181 | 36.7 | 188 | 0.655703 | 5.026667 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift | 3 | 8590 | //
// URLSession+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.URL
import struct Foundation.URLRequest
import struct Foundation.Data
import struct Foundation.Date
import struct Foundation.TimeInterval
import class Foundation.HTTPURLResponse
import class Foundation.URLSession
import class Foundation.URLResponse
import class Foundation.JSONSerialization
import class Foundation.NSError
import var Foundation.NSURLErrorCancelled
import var Foundation.NSURLErrorDomain
#if os(Linux)
// don't know why
import Foundation
#endif
import RxSwift
/// RxCocoa URL errors.
public enum RxCocoaURLError
: Swift.Error {
/// Unknown error occurred.
case unknown
/// Response is not NSHTTPURLResponse
case nonHTTPResponse(response: URLResponse)
/// Response is not successful. (not in `200 ..< 300` range)
case httpRequestFailed(response: HTTPURLResponse, data: Data?)
/// Deserialization error.
case deserializationError(error: Swift.Error)
}
extension RxCocoaURLError
: CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error has occurred."
case let .nonHTTPResponse(response):
return "Response is not NSHTTPURLResponse `\(response)`."
case let .httpRequestFailed(response, _):
return "HTTP request failed with `\(response.statusCode)`."
case let .deserializationError(error):
return "Error during deserialization of the response: \(error)"
}
}
}
private func escapeTerminalString(_ value: String) -> String {
return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil)
}
fileprivate func convertURLRequestToCurlCommand(_ request: URLRequest) -> String {
let method = request.httpMethod ?? "GET"
var returnValue = "curl -X \(method) "
if let httpBody = request.httpBody, request.httpMethod == "POST" {
let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8)
if let body = maybeBody {
returnValue += "-d \"\(escapeTerminalString(body))\" "
}
}
for (key, value) in request.allHTTPHeaderFields ?? [:] {
let escapedKey = escapeTerminalString(key as String)
let escapedValue = escapeTerminalString(value as String)
returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" "
}
let URLString = request.url?.absoluteString ?? "<unknown url>"
returnValue += "\n\"\(escapeTerminalString(URLString))\""
returnValue += " -i -v"
return returnValue
}
private func convertResponseToString(_ response: URLResponse?, _ error: NSError?, _ interval: TimeInterval) -> String {
let ms = Int(interval * 1000)
if let response = response as? HTTPURLResponse {
if 200 ..< 300 ~= response.statusCode {
return "Success (\(ms)ms): Status \(response.statusCode)"
}
else {
return "Failure (\(ms)ms): Status \(response.statusCode)"
}
}
if let error = error {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return "Canceled (\(ms)ms)"
}
return "Failure (\(ms)ms): NSError > \(error)"
}
return "<Unhandled response from server>"
}
extension Reactive where Base: URLSession {
/**
Observable sequence of responses for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
- parameter request: URL request.
- returns: Observable sequence of URL responses.
*/
public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> {
return Observable.create { observer in
// smart compiler should be able to optimize this out
let d: Date?
if Logging.URLRequests(request) {
d = Date()
}
else {
d = nil
}
let task = self.base.dataTask(with: request) { data, response, error in
if Logging.URLRequests(request) {
let interval = Date().timeIntervalSince(d ?? Date())
print(convertURLRequestToCurlCommand(request))
#if os(Linux)
print(convertResponseToString(response, error.flatMap { $0 as? NSError }, interval))
#else
print(convertResponseToString(response, error.map { $0 as NSError }, interval))
#endif
}
guard let response = response, let data = data else {
observer.on(.error(error ?? RxCocoaURLError.unknown))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response)))
return
}
observer.on(.next((httpResponse, data)))
observer.on(.completed)
}
task.resume()
return Disposables.create(with: task.cancel)
}
}
/**
Observable sequence of response data for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
- parameter request: URL request.
- returns: Observable sequence of response data.
*/
public func data(request: URLRequest) -> Observable<Data> {
return self.response(request: request).map { pair -> Data in
if 200 ..< 300 ~= pair.0.statusCode {
return pair.1
}
else {
throw RxCocoaURLError.httpRequestFailed(response: pair.0, data: pair.1)
}
}
}
/**
Observable sequence of response JSON for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter request: URL request.
- returns: Observable sequence of response JSON.
*/
public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable<Any> {
return self.data(request: request).map { data -> Any in
do {
return try JSONSerialization.jsonObject(with: data, options: options)
} catch let error {
throw RxCocoaURLError.deserializationError(error: error)
}
}
}
/**
Observable sequence of response JSON for GET request with `URL`.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter url: URL of `NSURLRequest` request.
- returns: Observable sequence of response JSON.
*/
public func json(url: Foundation.URL) -> Observable<Any> {
return self.json(request: URLRequest(url: url))
}
}
| apache-2.0 | 4061f1be3f71ee3ce2d7f3f83d216c6d | 34.345679 | 119 | 0.63919 | 5.275799 | false | false | false | false |