repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jeffellin/VideoPlayer
|
refs/heads/master
|
VideoPlayer/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// VideoPlayer
//
// Created by Jeffrey Ellin on 11/2/15.
// Copyright © 2015 Jeffrey Ellin. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doSomething() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(paths)!
print (paths)
var file:String = ""
while let element = enumerator.nextObject() as? String {
file = element
}
let url = NSURL.fileURLWithPath("\(paths)/\(file)")
let player = AVPlayer(URL: url.absoluteURL)
print(url.absoluteURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.addChildViewController(playerViewController)
self.view.addSubview(playerViewController.view)
playerViewController.view.frame = self.view.frame
player.play()
}
}
|
89aa45398efeec1023d1f159c5e66dab
| 23.688525 | 111 | 0.644754 | false | false | false | false |
onmyway133/Github.swift
|
refs/heads/master
|
Sources/Classes/Notification/Notification.swift
|
mit
|
1
|
//
// Notification.swift
// GithubSwift
//
// Created by Khoa Pham on 02/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import Tailor
import Sugar
// A notification of some type of activity.
public class Notification: Object {
// The type of the notification.
//
// OCTNotificationTypeUnknown - An unknown type of notification.
// OCTNotificationTypeIssue - A new issue, or a new comment on one.
// OCTNotificationTypePullRequest - A new pull request, or a new comment on one.
// OCTNotificationTypeCommit - A new comment on a commit.
public enum Kind: String {
case Unknown = ""
case Issue = "Issue"
case PullRequest = "PullRequest"
case Commit = "Commit"
}
// The title of the notification.
public private(set) var title: String = ""
// The API URL to the notification's thread.
public private(set) var threadURL: NSURL?
// The API URL to the subject that the notification was generated for (e.g., the
// issue or pull request).
public private(set) var subjectURL: NSURL?
// The API URL to the latest comment in the thread.
//
// If the notification does not represent a comment, this will be the same as
// the subjectURL.
public private(set) var latestCommentURL: NSURL?
// The notification type.
public private(set) var kind: Kind = .Unknown
// The repository to which the notification belongs.
public private(set) var repository: Repository?
// The date on which the notification was last updated.
public private(set) var lastUpdatedDate: NSDate?
// Whether this notification has yet to be read.
public private(set) var isUnread: Bool = false
public required init(_ map: JSONDictionary) {
super.init(map)
let subject = map.dictionary("subject")
self.title <- subject?.property("title")
self.threadURL <- map.transform("url", transformer: NSURL.init(string: ))
self.subjectURL <- subject?.transform("url", transformer: NSURL.init(string: ))
self.latestCommentURL <- subject?.transform("latest_comment_url", transformer: NSURL.init(string: ))
self.kind = subject?.`enum`("type") ?? .Unknown
self.repository = map.relation("repository")
self.lastUpdatedDate = map.transform("updated_at", transformer: Transformer.stringToDate)
}
}
|
796979a4ae4719e18b93252d197c286d
| 32.4 | 104 | 0.695466 | false | true | false | false |
ZhaoBingDong/EasySwifty
|
refs/heads/master
|
EasySwifty/Classes/Easy+UIImage.swift
|
apache-2.0
|
1
|
//
// Easy+UIImage.swift
// EaseSwifty
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIImage
extension UIImage {
/// 调整图片的方向
func normalizedImage() -> UIImage {
if self.imageOrientation == UIImage.Orientation.up {
return self
}
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
self.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img!
}
// func cirleImage() -> UIImage {
//
// // NO代表透明
// UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
// // 获得上下文
// let ctx = UIGraphicsGetCurrentContext()
//
// // 添加一个圆
// let rect = CGRect(x: 0, y : 0, width : self.size.width, height: self.size.height);
// ctx!.addEllipse(in: rect);
//
// // 裁剪
// ctx?.clip();
//
// // 将图片画上去
// self.draw(in: rect)
//
// let cirleImage = UIGraphicsGetImageFromCurrentImageContext();
//
// UIGraphicsEndImageContext();
//
// return cirleImage!
//
//
// }
/// 通过一个 UIColor 生成一个 UIImage
@discardableResult
class func imageWithColor(_ color: UIColor) -> UIImage {
let rect:CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext()
return image
}
}
|
4a9114224264e2e7107be9c7cfc588f1
| 23.876712 | 95 | 0.594714 | false | false | false | false |
PaulWoodIII/tipski
|
refs/heads/master
|
TipskyiOS/Tipski/Appearance.swift
|
mit
|
1
|
//
// Appearance.swift
// Tipski
//
// Created by Paul Wood on 10/14/16.
// Copyright © 2016 Paul Wood. All rights reserved.
//
import UIKit
class Appearance {
private struct Cache {
static let Label30Font = UIFont(name: "OpenSans", size:30)
}
class func setAppearance () {
UIView.appearance().tintColor = TipskiIcons.orangeHighlight
UINavigationBar.appearance().barStyle = .black
UINavigationBar.appearance().barTintColor = TipskiIcons.orangeHighlight
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
UISlider.appearance().minimumTrackTintColor = TipskiIcons.orange
UISlider.appearance().maximumTrackTintColor = TipskiIcons.foreground3
UIButton.appearance(whenContainedInInstancesOf: [UINavigationBar.self])
.tintColor = UIColor.white
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self])
.tintColor = UIColor.white
}
class func reloadViewsFrom(windows : [UIWindow]){
for window in windows {
for view in window.subviews {
view.removeFromSuperview()
window.addSubview(view)
}
}
}
class func createWellFromView(view : UIView){
view.backgroundColor = TipskiIcons.foreground4
view.layer.cornerRadius = 10.0
view.layer.masksToBounds = true
view.layer.borderWidth = 1
view.layer.borderColor = TipskiIcons.foreground2.cgColor
}
class func createInput(textField : UITextField){
textField.backgroundColor = TipskiIcons.foreground3
textField.layer.cornerRadius = 3.0
textField.layer.masksToBounds = true
textField.layer.borderWidth = 1
textField.layer.borderColor = TipskiIcons.foreground1.cgColor
}
class func createSubmitButton(button : UIButton){
button.backgroundColor = TipskiIcons.greenHighlight
button.layer.cornerRadius = 22.0
button.layer.masksToBounds = true
button.layer.borderWidth = 1
button.layer.borderColor = TipskiIcons.green.cgColor
}
}
|
204be4ffa79e930d27cc4f2c61837c83
| 32.536232 | 107 | 0.659032 | false | false | false | false |
JohnBehnke/RPI_Tours_iOS
|
refs/heads/master
|
RPI Tours/RPI Tours/InfoViewController.swift
|
mit
|
2
|
//
// InfoViewController.swift
// RPI Tours
//
// Created by Jacob Speicher on 8/1/16.
// Copyright © 2016 RPI Web Tech. All rights reserved.
//
import UIKit
import ReachabilitySwift
import CoreLocation
import ImageSlideshow
import AlamofireImage
class InfoViewController: UITableViewController {
// MARK: IBOutlets
@IBOutlet var landmarkDescriptionLabel: UILabel!
@IBOutlet var descriptionCell: UITableViewCell!
// MARK: Global Variables
var landmarkName: String = ""
var landmarkDesc: String = ""
var landmarkInformation: [Landmark] = []
@IBOutlet weak var slideShow: ImageSlideshow!
var cameFromMap: Bool = false
// MARK: Segues
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// if segue.identifier == "imageSlider" {
// }
// }
// MARK: System Functions
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = self.landmarkName
let chosenLandmark = searchForLandmark()
self.landmarkDescriptionLabel.text = chosenLandmark.desc
var images: [InputSource] = []
for imageURL in chosenLandmark.urls {
images.append(AlamofireSource(urlString: imageURL)!)
}
slideShow.setImageInputs(images)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Helper Functions
func searchForLandmark() -> Landmark {
for landmark in self.landmarkInformation {
if landmark.name == self.landmarkName && !landmark.desc.isEmpty {
return landmark
}
}
let blankLandmark = Landmark(name: "Unknown Landmark",
desc: "I'm sorry, there is no information yet for this landmark.",
lat: 0.0,
long: 0.0, urls:[])
return blankLandmark
}
// MARK: TableView Functions
override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return CGFloat(Constants.CellHeights.InfoHeights.tall)
}
return CGFloat(Constants.CellHeights.InfoHeights.short)
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return CGFloat(Constants.CellHeights.InfoHeights.tall)
}
return CGFloat(Constants.CellHeights.InfoHeights.short)
}
}
|
d489a37cba0b5e815547553c13de6931
| 26.393617 | 112 | 0.632621 | false | false | false | false |
Frainbow/ShaRead.frb-swift
|
refs/heads/master
|
ShaRead/ShaRead/ShaStore.swift
|
mit
|
1
|
//
// ShaStore.swift
// ShaRead
//
// Created by martin on 2016/5/14.
// Copyright © 2016年 Frainbow. All rights reserved.
//
import Foundation
import SwiftyJSON
enum ShaAdminStoreItem: Int {
case ShaAdminStoreName = 0
case ShaAdminStoreDescription
case ShaAdminStorePosition
}
class ShaStorePosition {
var address: String = ""
var longitude: Float = 0
var latitude: Float = 0
}
class ShaStore {
var id: Int = 0
var name: String = ""
var image: NSURL?
var description: String = ""
var avatar: NSURL?
var owner: ShaUser?
var position = ShaStorePosition()
var books: [ShaBook] = []
init() {
}
init (data: JSON) {
self.id = data["store_id"].intValue
self.name = data["store_name"].stringValue
self.description = data["description"].stringValue
self.position.address = data["position"]["address"].stringValue
if data["store_image"].error == nil {
self.image = NSURL(string: data["store_image"].stringValue)
}
if data["owner"].error == nil {
self.owner = ShaUser(jsonData: data["owner"])
}
if data["avatar"].error == nil {
self.avatar = NSURL(string: data["avatar"].stringValue)
}
for book in data["books"].arrayValue {
self.books.append(ShaBook(data: book))
}
}
}
extension ShaManager {
func newAdminStore(store: ShaStore, success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodPost,
path: "/stores?auth_token=\(authToken)",
param: [ "store_name": store.name ],
success: { code, data in
store.id = data["store_id"].intValue
self.adminStores.append(store)
success()
},
failure: { code, data in
failure()
}
)
}
func getAdminStore(success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores",
param: ["auth_token": self.authToken],
success: { code, data in
let storeList = data["data"].arrayValue
self.adminStores.removeAll()
for store in storeList {
let adminStore = ShaStore(data: store)
self.adminStores.append(adminStore)
}
success()
},
failure: { code, data in
failure()
}
)
}
func updateAdminStore(store: ShaStore, column: [ShaAdminStoreItem],
success: () -> Void, failure: () -> Void) {
var param = [String: AnyObject]()
for item in column {
switch item {
case .ShaAdminStoreName:
param["store_name"] = store.name
case .ShaAdminStoreDescription:
param["description"] = store.description
case .ShaAdminStorePosition:
param["address"] = store.position.address
param["longitude"] = store.position.longitude
param["latitude"] = store.position.latitude
}
}
HttpManager.sharedInstance.request(
.HttpMethodPut,
path: "/stores/\(store.id)?auth_token=\(authToken)",
param: param,
success: { code, data in
success()
},
failure: { code, data in
failure()
}
)
}
func uploadAdminStoreImage(store: ShaStore, image: UIImage, success: (url: NSURL) -> Void, failure: () -> Void) {
let resizedImage = resizeImage(image, newWidth: 200)
if let data = UIImageJPEGRepresentation(resizedImage, 0.1) {
HttpManager.sharedInstance.uploadData(
"/stores/\(store.id)/images?auth_token=\(authToken)",
name: "store_image",
data: data,
success: { (code, data) in
if let url = NSURL(string: data["image_path"].stringValue) {
success(url: url)
} else {
failure()
}
},
failure: { (code, data) in
failure()
}
)
} else {
failure()
}
}
}
extension ShaManager {
func getPopularStore(complete: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores",
param: ["order": "popular"],
success: { code, data in
self.popularStores.removeAll()
for store in data["data"].arrayValue {
self.popularStores.append(ShaStore(data: store))
}
},
complete: {
complete()
}
)
}
func getLatestStore(complete: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores",
param: ["order": "latest"],
success: { code, data in
self.latestStores.removeAll()
for store in data["data"].arrayValue {
self.latestStores.append(ShaStore(data: store))
}
},
complete: {
complete()
}
)
}
func getStoreByID(id: Int, success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores/\(id)",
param: [:],
success: { code, data in
self.stores[id] = ShaStore(data: data["data"])
success()
},
failure: { code, data in
failure()
}
)
}
func getStoreBooks(store: ShaStore, success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores/\(store.id)/books",
param: [:],
success: { code, data in
store.books.removeAll()
for book in data["data"].arrayValue {
store.books.append(ShaBook(data: book))
}
success()
},
failure: { code, data in
failure()
}
)
}
}
|
24393c0b13b762d447953600283e582d
| 27.608333 | 117 | 0.464171 | false | false | false | false |
mssun/pass-ios
|
refs/heads/master
|
passKit/Crypto/ObjectivePGPInterface.swift
|
mit
|
2
|
//
// ObjectivePGPInterface.swift
// passKit
//
// Created by Danny Moesch on 08.09.19.
// Copyright © 2019 Bob Sun. All rights reserved.
//
import ObjectivePGP
struct ObjectivePGPInterface: PGPInterface {
private let keyring = ObjectivePGP.defaultKeyring
init(publicArmoredKey: String, privateArmoredKey: String) throws {
guard let publicKeyData = publicArmoredKey.data(using: .ascii), let privateKeyData = privateArmoredKey.data(using: .ascii) else {
throw AppError.keyImport
}
let publicKeys = try ObjectivePGP.readKeys(from: publicKeyData)
let privateKeys = try ObjectivePGP.readKeys(from: privateKeyData)
keyring.import(keys: publicKeys)
keyring.import(keys: privateKeys)
guard publicKeys.first != nil, privateKeys.first != nil else {
throw AppError.keyImport
}
}
func decrypt(encryptedData: Data, keyID _: String?, passphrase: String) throws -> Data? {
try ObjectivePGP.decrypt(encryptedData, andVerifySignature: false, using: keyring.keys) { _ in passphrase }
}
func encrypt(plainData: Data, keyID _: String?) throws -> Data {
let encryptedData = try ObjectivePGP.encrypt(plainData, addSignature: false, using: keyring.keys, passphraseForKey: nil)
if Defaults.encryptInArmored {
return Armor.armored(encryptedData, as: .message).data(using: .ascii)!
}
return encryptedData
}
func containsPublicKey(with keyID: String) -> Bool {
keyring.findKey(keyID)?.isPublic ?? false
}
func containsPrivateKey(with keyID: String) -> Bool {
keyring.findKey(keyID)?.isSecret ?? false
}
var keyID: [String] {
keyring.keys.map(\.keyID.longIdentifier)
}
var shortKeyID: [String] {
keyring.keys.map(\.keyID.shortIdentifier)
}
}
|
5b1d8b2c697d92eadd9c38b8313bf76e
| 33.444444 | 137 | 0.67043 | false | false | false | false |
ICTFractal/IF_FirebaseFollowHelperKit
|
refs/heads/master
|
IF_FirebaseFollowHelperKit/IF_FirebaseFollowHelper.swift
|
mit
|
1
|
//
// IF_FirebaseFollowHelper.swift
// IF_FirebaseFollowHelper
//
// Created by 久保島 祐磨 on 2016/04/21.
// Copyright © 2016年 ICT Fractal Inc. All rights reserved.
//
import UIKit
import Firebase
/*
Firebaseデータ構造
root
+IFFollowHelper
+Follow (フォロー情報ノード)
+autoID
-uid (ログインユーザのuid)
-followID (フォロー対象ユーザのuid)
-notifiedUser (ログインユーザに通知したか)
-notifiedFollower (フォロー対象ユーザに通知したか)
-timestamp (レコードを作成したサーバー日時)
+autoID
...
+Block (ブロック情報ノード)
+autoID
-uid (ログインユーザのuid)
-blockID (ブロック対象ユーザのuid)
-notifiedUser (ログインユーザに通知したか)
-notifiedBlockUser (ブロック対象ユーザに通知したか)
-timestamp (レコードを作成したサーバー日時)
+autoID
...
*/
/// IF_FirebaseFollowHelper間でやり取りされるユーザ情報Tupleの別名定義
public typealias IF_FirebaseFollowHelperBasicUserInfo = (uid: String, timestamp: NSDate)
/**
IF_FirebaseFollowHelperからNSNotificationCenterへ発行されるメッセージ
notification.userInfoから詳細な情報を得る事ができます。
*/
public struct IF_FirebaseFollowHelperMessage {
/**
ログインユーザが他ユーザをフォローした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(server)
*/
public static let AddedFollow = "IF_FirebaseFollowHelperMessage_AddedFollow"
/**
フォロー追加処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedFollow = "IF_FirebaseFollowHelperMessage_FailedFollow"
/**
フォロー追加処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidAddFollowProc = "IF_FirebaseFollowHelperMessage_DidAddFollowProc"
/**
ログインユーザが他ユーザのフォローを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: フォロー日時
*/
public static let RemovedFollow = "IF_FirebaseFollowHelperMessage_RemovedFollow"
/**
フォロー解除処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedRemoveFollow = "IF_FirebaseFollowHelperMessage_FailedRemoveFollow"
/**
フォロー解除処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidRemoveFollowProc = "IF_FirebaseFollowHelperMessage_DidRemoveFollowProc"
/**
他ユーザがログインユーザをフォローした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: フォロー日時
*/
public static let AddedFollower = "IF_FirebaseFollowHelperMessage_AddedFollower"
/**
他ユーザがログインユーザのフォローを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: フォロー日時
*/
public static let RemovedFollower = "IF_FirebaseFollowHelperMessage_RemovedFollower"
/**
ログインユーザが他ユーザをブロックした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(server)
*/
public static let AddedBlock = "IF_FirebaseFollowHelperMessage_AddedBlock"
/**
ブロック追加処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedBlock = "IF_FirebaseFollowHelperMessage_FailedBlock"
/**
ブロック追加処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidAddBlockProc = "IF_FirebaseFollowHelperMessage_DidAddBlockProc"
/**
ログインユーザが他ユーザのブロックを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: ブロック日時
*/
public static let RemovedBlock = "IF_FirebaseFollowHelperMessage_RemovedBlock"
/**
ブロック解除処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedRemoveBlock = "IF_FirebaseFollowHelperMessage_FailedRemoveBlock"
/**
ブロック解除処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidRemoveBlockProc = "IF_FirebaseFollowHelperMessage_DidRemoveBlockProc"
/**
他ユーザがログインユーザをブロックした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: ブロック日時
*/
public static let BlockedFromSomeone = "IF_FirebaseFollowHelperMessage_BlockedFromSomeone"
/**
他ユーザがログインユーザのブロックを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: ブロック日時
*/
public static let RemoveBlockFromSomeone = "IF_FirebaseFollowHelperMessage_RemoveBlockFromSomeone"
}
/**
Firebaseにフォロー/フォロワー管理機能を追加すヘルパークラス
主な特徴は次の通りです。
1. Firebaseのデータ構造を意識せずに、フォロー関連の機能を利用できます
2. 他ユーザがログインユーザに関わる操作を行った場合、リアルタイムに通知を受け取る事ができます
- important: イベントはリアルタイムにNSNotificationCenterから通知されます。
通知は1つのイベントにつき1回のみです。
すべての通知を受け取りたい場合は初回インスタンス生成以降、常にいずれかのインスタンスにオブザーバを設定してください。
*/
public class IF_FirebaseFollowHelper {
/**
共有インスタンス
こちらからIF_FirebaseFollowHelperの各機能をコールしてください。
*/
public static let sharedHelper = IF_FirebaseFollowHelper()
private var firebaseRef: FIRDatabaseReference!
private var followRef: FIRDatabaseReference!
private var blockRef: FIRDatabaseReference!
private let followHelperPath = "IFFollowHelper"
private let followPath = "Follow"
private let blockPath = "Block"
// firebase項目
private let item_uid = "uid"
private let item_followID = "followID"
private let item_notifiedUser = "notifiedUser"
private let item_notifiedFollower = "notifiedFollower"
private let item_timestamp = "timestamp"
private let item_blockID = "blockID"
private let item_notifiedBlockUser = "notifiedBlockUser"
// オブザーバ登録
private var observeUID: String? = nil
private var observeHandles = [(FIRDatabaseQuery, UInt)]()
// NSNotification.userInfo項目
private let notifyInfo_uid = "uid"
private let notifyInfo_timestamp = "timestamp"
private let notifyInfo_error = "error"
/// error domain
public static let errorDomain = "IF_FirebaseFollowHelper"
/// error code
public enum errorCode: Int {
/// 不明
case Unknown = 0
/// ブロック由来の処理失敗
case FailureByBlock
/// サインインしていない事による処理失敗
case NotSignedIn
}
/// デバッグ情報出力設定
public static var outputDebug = true
private init() {
self.firebaseRef = FIRDatabase.database().reference()
self.followRef = self.firebaseRef.child(self.followHelperPath).child(self.followPath)
self.blockRef = self.firebaseRef.child(self.followHelperPath).child(self.blockPath)
self.observeUID = FIRAuth.auth()?.currentUser?.uid
if self.observeUID != nil {
self.observe()
}
// ユーザ切り替えに対応
FIRAuth.auth()!.addAuthStateDidChangeListener() { auth, user in
if let user = user {
self.debugLog("User is signed in with [\(user.uid)]")
if self.observeUID != user.uid {
self.observeUID = user.uid
self.observe()
}
} else {
self.debugLog("No user is signed in. remove all observer.")
self.observeUID = nil
self.observeHandles.forEach() {
$0.removeObserverWithHandle($1)
}
self.observeHandles.removeAll()
}
}
}
/**
オブザーバ登録
*/
private func observe() {
if self.observeUID == nil {
return
}
self.debugLog("add observe [\(self.observeUID!)]")
self.observeHandles.forEach() {
$0.removeObserverWithHandle($1)
}
self.observeHandles.removeAll()
// Followノードの監視対象
let targetFollowRef = self.followRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!)
let targetFollowerRef = self.followRef.queryOrderedByChild(item_followID).queryEqualToValue(self.observeUID!)
// フォロー追加の監視
self.observeHandles.append((targetFollowRef,
targetFollowRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedUser] as? Bool {
if isNotified == false {
let updateRef = self.followRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedUser: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_followID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.AddedFollow, object: self, userInfo: userInfo)
}
}
}
}
})))
// フォロー削除の監視
self.observeHandles.append((targetFollowRef,
targetFollowRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_followID] as? String,
let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemovedFollow, object: self, userInfo: userInfo)
}
}
})))
// フォロワー追加の監視
self.observeHandles.append((targetFollowerRef,
targetFollowerRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedFollower] as? Bool {
if isNotified == false {
let updateRef = self.followRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedFollower: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.AddedFollower, object: self, userInfo: userInfo)
}
}
}
}
})))
// フォロワー削除の監視
self.observeHandles.append((targetFollowerRef,
targetFollowerRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_uid] as? String,
let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemovedFollower, object: self, userInfo: userInfo)
}
}
})))
// Blockノードの監視対象
let targetBlockRef = self.blockRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!)
let targetBlockerRef = self.blockRef.queryOrderedByChild(item_blockID).queryEqualToValue(self.observeUID!)
// ブロック追加の監視
self.observeHandles.append((targetBlockRef,
targetBlockRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedUser] as? Bool {
if isNotified == false {
let updateRef = self.blockRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedUser: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_blockID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.AddedBlock, object: self, userInfo: userInfo)
}
}
}
}
})))
// ブロック削除の監視
self.observeHandles.append((targetBlockRef,
targetBlockRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_blockID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemovedBlock, object: self, userInfo: userInfo)
}
}
})))
// 被ブロック追加の監視
self.observeHandles.append((targetBlockerRef,
targetBlockerRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedBlockUser] as? Bool {
if isNotified == false {
let updateRef = self.blockRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedBlockUser: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.BlockedFromSomeone, object: self, userInfo: userInfo)
}
}
}
}
})))
// 被ブロック削除の監視
self.observeHandles.append((targetBlockerRef,
targetBlockerRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemoveBlockFromSomeone, object: self, userInfo: userInfo)
}
}
})))
}
/**
Firebase.TimeStampをNSDateに変換する
- parameter timestamp: タイムスタンプ
- returns: NSDateインスタンス
*/
private func convertToNSDate(timestamp: NSTimeInterval) -> NSDate {
return NSDate(timeIntervalSince1970: timestamp / 1000)
}
/**
NSErrorインスタンスを得る
- parameter code: エラーコード
- parameter message: エラーメッセージ
- returns: NSErrorインスタンス
*/
private func error(code: errorCode, message: String) -> NSError {
let userInfo: [String: AnyObject] = [NSLocalizedDescriptionKey: message]
return NSError(domain: IF_FirebaseFollowHelper.errorDomain, code: code.rawValue, userInfo: userInfo)
}
/**
デバッグログの出力
- parameter message: メッセージ
*/
private func debugLog(message: String) {
if IF_FirebaseFollowHelper.outputDebug == true {
print("IF_FirebaseFollowHelper debug: \(message)")
}
}
/**
ログインユーザがフォローしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getFollowList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.followRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var followList = [IF_FirebaseFollowHelperBasicUserInfo]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let followID = value[self.item_followID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
followList.append((followID, self.convertToNSDate(timestamp)))
}
}
}
// 最新順に並び替える
followList = followList.sort() { $0.1.timeIntervalSince1970 > $1.1.timeIntervalSince1970 }
completion?(followList)
})
}
/**
ログインユーザをフォローしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getFollowerList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.followRef.queryOrderedByChild(item_followID).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var followerList = [IF_FirebaseFollowHelperBasicUserInfo]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let followerID = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
followerList.append((followerID, self.convertToNSDate(timestamp)))
}
}
}
completion?(followerList)
})
}
/**
ログインユーザがブロックしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getBlockList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.blockRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var blockList = [(uid: String, timestamp: NSDate)]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let blockID = value[self.item_blockID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
blockList.append((blockID, self.convertToNSDate(timestamp)))
}
}
}
// 最新順に並び替える
blockList = blockList.sort() { $0.1.timeIntervalSince1970 > $1.1.timeIntervalSince1970 }
completion?(blockList)
})
}
/**
ログインユーザをブロックしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getBlockerList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.blockRef.queryOrderedByChild(item_blockID).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var blockerList = [(uid: String, timestamp: NSDate)]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let blockerID = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
blockerList.append((blockerID, self.convertToNSDate(timestamp)))
}
}
}
completion?(blockerList)
})
}
/**
対象ユーザをフォローします
- parameter userID: 対象ユーザのuid
フォローに成功した場合、*IF_FirebaseFollowHelperMessage.AddedFollow*が通知されます。
フォローに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedFollow*が通知されます。
すでにフォロー済みかフォローに失敗した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidAddFollowProc*が通知されます。
*/
public func follow(userID: String) {
self.follow([userID])
}
/**
対象ユーザ(複数)をフォローします
- parameter userIDs: 対象ユーザのuid一覧
フォローに成功した場合、*IF_FirebaseFollowHelperMessage.AddedFollow*が通知されます。
フォローに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedFollow*が通知されます。
すでにフォロー済みかフォローに失敗した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidAddFollowProc*が通知されます。
*/
public func follow(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedFollow, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddFollowProc, object: self, userInfo: nil)
return
}
self.getFollowList() { followList in
let addList = userIDs.filter() { !followList.map() { $0.0 }.contains($0) }
var procCount = 0
addList.forEach() {
let userRef = self.followRef.childByAutoId()
let followID = $0
let dic: [String: AnyObject] = [self.item_uid: self.observeUID!, self.item_followID: followID, self.item_notifiedUser: false, self.item_notifiedFollower: false, self.item_timestamp: FIRServerValue.timestamp()]
userRef.updateChildValues(dic, withCompletionBlock: { error, firebaseRef in
if let error = error {
self.debugLog("follow failed [\(followID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: followID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedFollow, object: self, userInfo: userInfo)
}
else {
self.debugLog("following [\(followID)]")
}
procCount += 1
if procCount >= addList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddFollowProc, object: self, userInfo: nil)
}
})
}
if addList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddFollowProc, object: self, userInfo: nil)
}
}
}
/**
対象ユーザのフォローを解除します
- parameter userID: 対象ユーザのuid
フォロー解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedFollow*が通知されます。
フォロー解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveFollow*が通知されます。
フォローしていないユーザをフォロー解除した場合かフォロー解除に失敗した場合、何も通知されません。
処理完了時に*IF_FirebaseFollowHelperMessage.DidRemoveFollowProc*が通知されます。
*/
public func unFollow(userID: String) {
self.unFollow([userID])
}
/**
対象ユーザ(複数)のフォローを解除します
- parameter userIDs: 対象ユーザのuid一覧
フォロー解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedFollow*が通知されます。
フォロー解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveFollow*が通知されます。
フォローしていないユーザをフォロー解除した場合かフォロー解除に失敗した場合、何も通知されません。
処理完了時に*IF_FirebaseFollowHelperMessage.DidRemoveFollowProc*が通知されます。
*/
public func unFollow(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveFollow, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveFollowProc, object: self, userInfo: nil)
return
}
self.followRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var removeList = [FIRDataSnapshot]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let followID = value[self.item_followID] as? String {
if userIDs.contains(followID) {
removeList.append(user)
}
}
}
}
var procCount = 0
removeList.forEach() {
if let value = $0.value as? [String: AnyObject] {
if let followID = value[self.item_followID] as? String {
let removeRef = self.followRef.child($0.key)
removeRef.removeValueWithCompletionBlock({ error, firebaseRef in
if let error = error {
self.debugLog("remove follow failed [\(followID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: followID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveFollow, object: self, userInfo: userInfo)
}
else {
self.debugLog("remove follow [\(followID)]")
}
procCount += 1
if procCount >= removeList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveFollowProc, object: self, userInfo: nil)
}
})
}
}
}
if removeList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveFollowProc, object: self, userInfo: nil)
}
})
}
/**
対象ユーザをブロックします
- parameter userID: 対象ユーザのuid
ブロックに成功した場合、*IF_FirebaseFollowHelperMessage.AddedBlock*が通知されます。
ブロックに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedBlock*が通知されます。
すでにブロック済みのuidを指定した場合、何も通知されません。
処理完了時に、*DIF_FirebaseFollowHelperMessage.idAddBlockProc*が通知されます。
*/
public func block(userID: String) {
self.block([userID])
}
/**
対象ユーザ(複数)をブロックします
- parameter userIDs: 対象ユーザのuid一覧
ブロックに成功した場合、*IF_FirebaseFollowHelperMessage.AddedBlock*が通知されます。
ブロックに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedBlock*が通知されます。
すでにブロック済みのuidを指定した場合、何も通知されません。
処理完了時に、*DIF_FirebaseFollowHelperMessage.DidAddBlockProc*が通知されます。
*/
public func block(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedBlock, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddBlockProc, object: self, userInfo: nil)
return
}
self.getBlockList() { blockList in
let addList = userIDs.filter() { !blockList.map() { $0.0 }.contains($0) }
var procCount = 0
addList.forEach() {
let userRef = self.blockRef.childByAutoId()
let blockID = $0
let dic: [String: AnyObject] = [self.item_uid: self.observeUID!, self.item_blockID: blockID, self.item_notifiedUser: false, self.item_notifiedBlockUser:false, self.item_timestamp: FIRServerValue.timestamp()]
userRef.updateChildValues(dic, withCompletionBlock: { error, firebaseRef in
if let error = error {
self.debugLog("blocking failed [\(blockID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: blockID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedBlock, object: self, userInfo: userInfo)
}
else {
self.debugLog("blocking [\(blockID)]")
}
procCount += 1
if procCount >= addList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddBlockProc, object: self, userInfo: nil)
}
})
}
if addList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddBlockProc, object: self, userInfo: nil)
}
}
}
/**
対象ユーザのブロックを解除します
- parameter userID: 対象ユーザのuid一覧
ブロックの解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedBlock*が通知されます。
ブロックの解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveBlock*が通知されます。
ブロックしていないユーザをブロック解除した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidRemoveBlockProc*が通知されます。
*/
public func unBlock(userID: String) {
self.unBlock([userID])
}
/**
対象ユーザ(複数)のブロックを解除します
- parameter userIDs: 対象ユーザのuid一覧
ブロックの解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedBlock*が通知されます。
ブロックの解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveBlock*が通知されます。
ブロックしていないユーザをブロック解除した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidRemoveBlockProc*が通知されます。
*/
public func unBlock(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveBlock, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveBlockProc, object: self, userInfo: nil)
return
}
self.blockRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var removeList = [FIRDataSnapshot]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let blockID = value[self.item_blockID] as? String {
if userIDs.contains(blockID) {
removeList.append(user)
}
}
}
}
var procCount = 0
removeList.forEach() {
if let value = $0.value as? [String: AnyObject] {
if let blockID = value[self.item_blockID] as? String {
let removeRef = self.blockRef.child($0.key)
removeRef.removeValueWithCompletionBlock() { error, firebaseRef in
if let error = error {
self.debugLog("remove block failed [\(blockID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: blockID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveBlock, object: self, userInfo: userInfo)
}
else {
self.debugLog("remove block [\(blockID)]")
}
procCount += 1
if procCount >= removeList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveBlockProc, object: self, userInfo: nil)
}
}
}
}
}
if removeList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveBlockProc, object: self, userInfo: nil)
}
})
}
}
|
d7fb41654b767b923c07fecfb783d24c
| 32.837626 | 213 | 0.729325 | false | false | false | false |
Eric217/-OnSale
|
refs/heads/master
|
打折啦/打折啦/UploadController.swift
|
apache-2.0
|
1
|
//
// UploadView.swift
// 打折啦
//
// Created by Eric on 7/26/17.
// Copyright © 2017 INGStudio. All rights reserved.
//
import Foundation
import Alamofire
//upload 时候,picRatio是 长:宽的值1|2,都是 float
//这个扩展包括 texfield, texview, scrollview
extension UpLoadViewController: UITextFieldDelegate, UITextViewDelegate {
//MARK: - @objc functions
@objc func fabu() {
let bigImgArr: [UIImage]
let smaImgArr: [UIImage]
if txf.text!.len() <= 1 {
hud.showError(withStatus: "标题过短"); return
}
if location.textLabel?.text == chooseLoca {
hud.showError(withStatus: "请选择地点"); return
}
if type == -1 {
hud.showError(withStatus: "请选择种类"); return
}else if business.status {
type += 100
}
if l3 == "" {
hud.showError(withStatus: "")
}
bigImgArr = getBigImageArray() as! [UIImage]
smaImgArr = getSmallImageArray() as! [UIImage]
let dict = ["type": type, "title": (txf.text)!, "description": (txv.text)!,
"l1": l1, "l2": l2, "l3": l3, "location": locaStr, "longitude": lon,
"latitude": lat, "deadline": deadLine] as [String : Any]
let data1 = Data()
let imageData1 = Data()
let imageSmallData1 = Data()
Alamofire.upload(multipartFormData: { multi in
/*
//这几个是那几个string或int,double的属性的数据的拼接,name一会写接口里的,
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
//下面是 大图数据.其中第三个参数是 扩展名,是个可选参数,
multi.append(imageData1, withName: "pic1")
multi.append(imageData1, withName: "pic2", mimeType: "jpg")
multi.append(imageData1, withName: "pic3")
//下面是 小图数据
multi.append(imageSmallData1, withName: "picSmall1", mimeType: "jpg")
multi.append(imageSmallData1, withName: "picSmall")
multi.append(imageSmallData1, withName: "picSmall")
multi.append(<#T##data: Data##Data#>, withName: <#T##String#>, fileName: <#T##String#>, mimeType: <#T##String#>)
*/
}, with: Router.upGood, encodingCompletion: { encodeResult in
switch encodeResult {
case .success(let upload, _, _): upload
.uploadProgress { progress in
print(progress.fractionCompleted)
}
.responseJSON { response in
}
case .failure(let error):
print(dk+"\(error)")
}
})
}
@objc func didClick(_ sender: RoundButton) {
let ta = sender.tag
if ta != 201 {
if ta == 202 || ta == 203 {
sender.changeStatus(true)
}else {
sender.changeStatus()
}
}else{
print("😄弹出视图")
}
}
@objc func cancel(){
print(hh+"是否保存草稿 ")
dismiss(animated: true, completion: nil)
}
@objc func showtip() {
print("😄弹出视图")
}
@objc func didTap(_ sender: UITapGestureRecognizer) {
let temp = sender.view
if temp == location {
let controller = LocationChooser()
controller.delegate = self
navigationController?.pushViewController(controller, animated: true)
}else if temp == kind {
let controller = TypeChooser()
controller.delegate = self
navigationController?.pushViewController(controller, animated: true)
}else if temp == time {
BRStringPickerView.showStringPicker(withTitle: "", dataSource: timeArr, defaultSelValue: time.rightLabel.text!, isAutoSelect: false, tintColor: Config.themeColor, resultBlock: { result in
self.time.setRightText(result as! String)
for i in 0..<self.timeArr.count {
if self.timeArr[i] == (result as! String) {
self.deadLine = self.dateArr[i]
break
}
}
})
}
}
//MARK: - 回调与重要的几个方法
///value: y值。x值是屏幕宽度.dir默认0,如果不是0,就是变化量
func updateContentSize(value: CGFloat = 0, dir: CGFloat = 0) {
if dir == 0 {
scrollView.contentSize = CGSize(width: ScreenWidth, height: value)
}else {
let h = scrollView.contentSize.height
scrollView.contentSize = CGSize(width: ScreenWidth, height: h + dir)
}
}
override func pickerViewFrameChanged() {
let pickH = pickerCollectionView.frame.height
if pickH != currPickerHeight {
updateContentSize(dir: pickH - currPickerHeight)
currPickerHeight = pickH
}
}
func textViewDidBeginEditing(_ textView: UITextView) {
updateScrollFrameY(true)
}
func textViewDidEndEditing(_ textView: UITextView) {
updateScrollFrameY()
}
///默认值为false 原位置
func updateScrollFrameY(_ drag: Bool = false) {
UIView.animate(withDuration: 0.2, animations: {
if drag {
self.scrollView.contentOffset = CGPoint(x: 0, y: self.scrollView.contentSize.height - self.scrollView.frame.height)
}
}) { finished in
if finished && drag {
self.txv.becomeFirstResponder()
}
}
}
//MARK: - some methods not that important
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.endEditing(true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
scrollView.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard textField.text!.len() < 25 else {
return false
}
return true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
///如果不设置这个,在推出地址选择器再回来时,出发didBeginEditing的动画,类似QQ。
scrollView.endEditing(true)
}
}
//MARK: - 实现了回调传值
extension UpLoadViewController : ValueRecaller {
func transferLocation(_ value: [Any]) {
}
func transferType(_ value: String, position: Int) {
kind.setRightText(value)
type = position
}
}
/*
class UpLoadView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
//alpha = 0.5
// let view2 = UIScrollView(frame: CGRect(x: 0, y: 30, width: view.bounds.width, height: view.bounds.height))
// view2.backgroundColor = UIColor.white
// let maskPath = UIBezierPath(roundedRect: view2.bounds, byRoundingCorners:
// [UIRectCorner.topRight, UIRectCorner.topLeft], cornerRadii: CGSize(width: 8, height: 8))
// let maskLayer = CAShapeLayer()
// maskLayer.frame = view2.bounds
// maskLayer.path = maskPath.cgPath
//
// view2.layer.mask = maskLayer
//
// view.addSubview(view2)
//
// view2.isUserInteractionEnabled = true
// let gesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
// view2.addGestureRecognizer(gesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
*/
|
aa5221bd9c0dd527bc76c56fa98bd71b
| 27.964158 | 199 | 0.548199 | false | false | false | false |
Alienson/Bc
|
refs/heads/master
|
source-code/Cell-old.swift
|
apache-2.0
|
1
|
//
// Cell-old.swift
// Parketovanie
//
// Created by Adam Turna on 12.1.2016.
// Copyright © 2016 Adam Turna. All rights reserved.
//
import Foundation
import SpriteKit
class Cell-old: SKSpriteNode {
var row: Int = Int()
var collumn: Int = Int()
var reserved: Bool = Bool()
init(row: Int, collumn: Int, isEmpty: Bool = true) {
if isEmpty {
super.init(texture: nil, color: UIColor.whiteColor(), size: CGSize(width: 50, height: 50))
reserved = true
}
else {
let imageNamed = "stvorec-50x50"
let cellTexture = SKTexture(imageNamed: imageNamed)
super.init(texture: cellTexture, color: UIColor.whiteColor(), size: cellTexture.size())
reserved = false
}
self.name = "cell"
self.row = row
self.collumn = collumn
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.zPosition = CGFloat(2.0)
}
func reserve(reserved: Bool) {
self.reserved = reserved
}
func isReserved() -> Bool {
return reserved
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
}
|
046f4808170c9fce43a99afaf0c47aff
| 25.688889 | 102 | 0.577852 | false | false | false | false |
rastogigaurav/mTV
|
refs/heads/master
|
mTV/mTV/Views/MovieDetailsViewController.swift
|
mit
|
1
|
//
// MovieDetailsViewController.swift
// mTV
//
// Created by Gaurav Rastogi on 6/25/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import UIKit
import SDWebImage
class MovieDetailsViewController: UIViewController,UITableViewDataSource {
let repository:MovieDetailsRepository = MovieDetailsRepository()
var displayMovieDetails:DisplayMovieDetails?
var viewModel:MovieDetailsViewModel?
@IBOutlet weak var movieDetailsTableView:UITableView!
var movieId:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
movieDetailsTableView.rowHeight = UITableViewAutomaticDimension
movieDetailsTableView.estimatedRowHeight = 140
self.setupViewModel()
self.viewModel?.fetchDetailAndPopulate(forMovieWith: self.movieId, reload:{[unowned self] _ in
self.movieDetailsTableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: IBActions
@IBAction func onTapping(back sender: UIBarButtonItem) {
self.navigationController?.popViewController(animated: true)
}
//Private Methods
func setupViewModel(){
self.displayMovieDetails = DisplayMovieDetails(with: self.repository)
self.viewModel = MovieDetailsViewModel(with: self.displayMovieDetails!)
}
//TableView Datasource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.viewModel?.numberOfRowsInSection(section: section))!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MovieDetailCustomCell = tableView.dequeueReusableCell(withIdentifier: MovieDetailCustomCell.reuseIdentifier) as! MovieDetailCustomCell
self.configure(cell:cell, forRowAt:indexPath)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func configure(cell:MovieDetailCustomCell, forRowAt indexPath:IndexPath){
if let posterImage = self.viewModel?.movie?.posterPathURL(){
cell.posterImageView.sd_setImage(with: URL(string: posterImage), placeholderImage: UIImage(named: "movie-poster-default"))
}
else{
cell.posterImageView.image = nil
}
if let movieTitle = self.viewModel?.movie?.title{
cell.movieTitleLabel.text = movieTitle
}
if let tagline = self.viewModel?.movie?.tagline{
cell.taglineLabel.text = tagline
}
if let releaseYear = self.viewModel?.movie?.releaseYear{
cell.releaseYearLabel.text = String(releaseYear)
}
if let language = self.viewModel?.spokenLanguagesString(){
cell.languageLabel.text = language
}
if let companiesNames = self.viewModel?.namesOfProductionCompanies(){
cell.productionCompanyLabel.text = companiesNames
}
if let movieOverview = self.viewModel?.movie?.overview{
cell.movieOverviewLabel.text = movieOverview
}
}
}
|
829b54134c226ae3a63f56e1290e7960
| 34.552083 | 151 | 0.674187 | false | false | false | false |
dmrschmidt/DSWaveformImage
|
refs/heads/main
|
Sources/DSWaveformImage/WaveformImageDrawer+iOS.swift
|
mit
|
1
|
#if os(iOS)
import Foundation
import AVFoundation
import UIKit
import CoreGraphics
public extension WaveformImageDrawer {
/// Renders a DSImage of the provided waveform samples.
///
/// Samples need to be normalized within interval `(0...1)`.
func waveformImage(from samples: [Float], with configuration: Waveform.Configuration, renderer: WaveformRenderer) -> DSImage? {
guard samples.count > 0, samples.count == Int(configuration.size.width * configuration.scale) else {
print("ERROR: samples: \(samples.count) != \(configuration.size.width) * \(configuration.scale)")
return nil
}
let format = UIGraphicsImageRendererFormat()
format.scale = configuration.scale
let imageRenderer = UIGraphicsImageRenderer(size: configuration.size, format: format)
let dampenedSamples = configuration.shouldDampen ? dampen(samples, with: configuration) : samples
return imageRenderer.image { renderContext in
draw(on: renderContext.cgContext, from: dampenedSamples, with: configuration, renderer: renderer)
}
}
}
#endif
|
fe9199b6ea5c1d0858c418006e11e712
| 40.740741 | 131 | 0.699201 | false | true | false | false |
Igor-Palaguta/YoutubeEngine
|
refs/heads/master
|
Tests/YoutubeEngineTests/DateComponents+EasyConstruction.swift
|
mit
|
1
|
import Foundation
extension DateComponents {
static func makeComponents(year: Int? = nil,
month: Int? = nil,
weekOfYear: Int? = nil,
day: Int? = nil,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil) -> DateComponents {
var components = DateComponents()
_ = year.map { components.year = $0 }
_ = month.map { components.month = $0 }
_ = day.map { components.day = $0 }
_ = weekOfYear.map { components.weekOfYear = $0 }
_ = hour.map { components.hour = $0 }
_ = minute.map { components.minute = $0 }
_ = second.map { components.second = $0 }
return components
}
}
|
ef59ef800b4689308e1dda23b3e14554
| 38.857143 | 70 | 0.446834 | false | false | false | false |
liuxianghong/SmartLight
|
refs/heads/master
|
Code/SmartLight/SmartLight/AppUIKIt/LoadingView.swift
|
apache-2.0
|
1
|
//
// LoadingView.swift
// Drone
//
// Created by BC600 on 16/1/19.
// Copyright © 2016年 fimi. All rights reserved.
//
import UIKit
class LoadingView: UIView {
fileprivate var delayHideTimer: Timer?
fileprivate var isShow = true
fileprivate var activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initView()
}
deinit {
}
fileprivate func initView() {
self.backgroundColor = UIColor(white: 0, alpha: 0.5)
self.addSubview(activity)
activity.snp.makeConstraints { (make) -> Void in
make.center.equalToSuperview()
}
show(false)
}
func show(_ animated: Bool) {
delayHideTimer?.invalidate()
delayHideTimer = nil
guard !isShow else {return}
isShow = true
self.activity.startAnimating()
superview?.bringSubview(toFront: self)
alpha = 0
UIView.animate(withDuration: animated ? 0.3 : 0, animations: {
self.alpha = 1
})
}
func hide(_ animated: Bool) {
delayHideTimer?.invalidate()
delayHideTimer = nil
isShow = false
UIView.animate(
withDuration: animated ? 0.3 : 0,
animations: { () -> Void in
self.alpha = 0
},
completion: { (finished) -> Void in
// 隐藏中才需要停止动画
if !self.isShow {
self.activity.stopAnimating()
}
}
)
}
func hide(_ animated: Bool, afterDelay delay: Foundation.TimeInterval) {
delayHideTimer?.invalidate()
delayHideTimer = Timer.scheduledTimer(
timeInterval: delay,
target: self,
selector: #selector(delayHideTimerTimeout(_:)),
userInfo: ["animated": animated],
repeats: false
)
}
func delayHideTimerTimeout(_ sender: Timer) {
guard let animated = (sender.userInfo as? [String: Any])?["animated"] as? Bool else {
return
}
hide(animated)
}
}
|
09e230faefd035c94c4d32c58c5bebc6
| 23.186275 | 119 | 0.522497 | false | false | false | false |
BeitIssieShapira/IssieBoard
|
refs/heads/master
|
ConfigurableKeyboard/KeyboardModel.swift
|
apache-2.0
|
2
|
import Foundation
var counter = 0
class Keyboard {
var pages: [Page]
init() {
self.pages = []
}
func addKey(_ key: Key, row: Int, page: Int) {
if self.pages.count <= page {
for _ in self.pages.count...page {
self.pages.append(Page())
}
}
self.pages[page].addKey(key, row: row)
}
}
class Page {
var rows: [[Key]]
init() {
self.rows = []
}
func addKey(_ key: Key, row: Int) {
if self.rows.count <= row {
for _ in self.rows.count...row {
self.rows.append([])
}
}
self.rows[row].append(key)
}
/*
Keyboard Pages
0 - Hebrew
1 - Numbers
2 - Symbols
3 - English Lower
4 - English Upper
5 - Numbers
6 - Symbols
*/
enum PagesIndex : Int {
case hebrewLetters = 0
case hebrewNumbers
case hebrewSymbols
case englishLower
case englishUpper
case englishNumbers
case englishSymbols
case arabicLetters
case arabicNumbers
case arabicSymbols
}
}
class Key: Hashable {
enum KeyType {
case character
case backspace
case modeChange
case keyboardChange
case space
case shift
case `return`
case undo
case restore
case dismissKeyboard
case customCharSetOne
case customCharSetTwo
case customCharSetThree
case specialKeys
case hiddenKey
case punctuation
case other
}
var type: KeyType
var keyTitle : String?
var keyOutput : String?
var pageNum: Int
var toMode: Int? //if type is ModeChange toMode holds the page it links to
var hasOutput : Bool {return (keyOutput != nil)}
var hasTitle : Bool {return (keyTitle != nil)}
var isCharacter: Bool {
get {
switch self.type {
case
.character,
.customCharSetOne,
.customCharSetTwo,
.customCharSetThree,
.hiddenKey,
.specialKeys:
return true
default:
return false
}
}
}
var isSpecial: Bool {
get {
switch self.type {
case
.backspace,
.modeChange,
.keyboardChange,
.space,
.punctuation,
.shift,
.dismissKeyboard,
.return,
.undo,
.restore :
return true
default:
return false
}
}
}
var hashValue: Int
init(_ type: KeyType) {
self.type = type
self.hashValue = counter
counter += 1
pageNum = -1
}
convenience init(_ key: Key) {
self.init(key.type)
self.keyTitle = key.keyTitle
self.keyOutput = key.keyOutput
self.toMode = key.toMode
self.pageNum = key.getPage()
}
func setKeyTitle(_ keyTitle: String) {
self.keyTitle = keyTitle
}
func getKeyTitle () -> String {
if (keyTitle != nil) {
return keyTitle!
}
else {
return ""
}
}
func setKeyOutput(_ keyOutput: String) {
self.keyOutput = keyOutput
}
func getKeyOutput () -> String {
if (keyOutput != nil) {
return keyOutput!
}
else {
return ""
}
}
func setPage(_ pageNum : Int) {
self.pageNum = pageNum
}
func getPage() -> Int {
return self.pageNum
}
}
func ==(lhs: Key, rhs: Key) -> Bool {
return lhs.hashValue == rhs.hashValue
}
|
793e6b47f0e19a405e7d7889106c85c7
| 19.436842 | 78 | 0.480556 | false | false | false | false |
ZJJeffery/PhotoBrowser
|
refs/heads/master
|
PhotoBrowser/PhotoBrowser/DemoTableViewController.swift
|
mit
|
1
|
//
// DemoTableViewController.swift
// 照片查看器
//
// Created by Jiajun Zheng on 15/5/24.
// Copyright (c) 2015年 hgProject. All rights reserved.
//
import UIKit
private let reusedId = "demoCell"
class DemoTableViewController: UITableViewController {
lazy var heightCache : NSCache = {
return NSCache()
}()
/// 图片资源
lazy var photoes : [Picture] = {
let pList = Picture.picturesList()
return pList
}()
/// 测试数组
lazy var dataList : [[Picture]] = {
var result = [[Picture]]()
for i in 0..<10 {
var list = [Picture]()
for x in 0..<i {
list.append(self.photoes[x])
}
result.append(list)
}
return result
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reusedId, forIndexPath: indexPath) as! DemoCell
if !(childViewControllers as NSArray).containsObject(cell.photoVC!) {
addChildViewController(cell.photoVC!)
}
cell.photoes = self.dataList[indexPath.row] as [Picture]
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if heightCache.objectForKey(indexPath.row) == nil {
let photoes = self.dataList[indexPath.row] as [Picture]
let cell = tableView.dequeueReusableCellWithIdentifier(reusedId) as! DemoCell
let rowHeight = cell.rowHeight(photoes)
heightCache.setObject(rowHeight, forKey: indexPath.row)
return rowHeight
}
return heightCache.objectForKey(indexPath.row) as! CGFloat
}
}
|
5890d245e65b4d0515ccd432beb4c312
| 31.144928 | 118 | 0.63165 | false | false | false | false |
NUKisZ/MyTools
|
refs/heads/master
|
MyTools/MyTools/ThirdLibrary/ProgressHUD/ProgressHUD.swift
|
mit
|
1
|
//
// ProgressHUD.swift
// LimitFree1606
//
// Created by gaokunpeng on 16/7/28.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
public let kProgressImageName = "提示底.png"
public let kProgressHUDTag = 10000
public let kProgressActivityTag = 20000
class ProgressHUD: UIView {
var textLabel: UILabel?
init(center: CGPoint){
super.init(frame: CGRect.zero)
let bgImage = UIImage(named: kProgressImageName)
self.bounds = CGRect(x: 0, y: 0, width: bgImage!.size.width, height: bgImage!.size.height)
self.center = center
let imageView = UIImageView(image: bgImage)
imageView.frame = self.bounds
self.addSubview(imageView)
//self.backgroundColor = UIColor.grayColor()
self.layer.cornerRadius = 6
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func show(){
let uaiView = UIActivityIndicatorView(activityIndicatorStyle: .white)
uaiView.tag = kProgressActivityTag
uaiView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
uaiView.backgroundColor = UIColor.clear
uaiView.startAnimating()
self.addSubview(uaiView)
self.textLabel = UILabel(frame: CGRect.zero)
self.textLabel!.backgroundColor = UIColor.clear
self.textLabel!.textColor = UIColor.white
self.textLabel!.text = "加载中..."
self.textLabel!.font = UIFont.systemFont(ofSize: 15)
self.textLabel?.sizeToFit()
self.textLabel!.center = CGPoint(x: uaiView.center.x, y: uaiView.frame.origin.y+uaiView.frame.size.height+5+self.textLabel!.bounds.size.height/2)
self.addSubview(self.textLabel!)
}
fileprivate func hideActivityView(){
let tmpView = self.viewWithTag(kProgressActivityTag)
if tmpView != nil {
let uiaView = tmpView as! UIActivityIndicatorView
uiaView.stopAnimating()
uiaView.removeFromSuperview()
}
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}, completion: { (finished) in
self.superview?.isUserInteractionEnabled = true
self.removeFromSuperview()
})
}
fileprivate func hideAfterSuccess(){
let successImage = UIImage(named: "保存成功.png")
let successImageView = UIImageView(image: successImage)
successImageView.sizeToFit()
successImageView.center = CGPoint(x: self.frame.size.width/2,
y: self.frame.size.height/2)
self.addSubview(successImageView)
self.textLabel!.text = "加载成功"
self.textLabel!.sizeToFit()
self.hideActivityView()
}
fileprivate func hideAfterFail(){
self.textLabel?.text = "加载失败"
self.textLabel?.sizeToFit()
self.hideActivityView()
}
class func showOnView(_ view: UIView){
let oldHud = view.viewWithTag(kProgressHUDTag)
if (oldHud != nil) {
oldHud?.removeFromSuperview()
}
let hud = ProgressHUD(center: view.center)
hud.tag = kProgressHUDTag
hud.show()
view.isUserInteractionEnabled = false
view.addSubview(hud)
}
class func hideAfterSuccessOnView(_ view: UIView){
let tmpView = view.viewWithTag(kProgressHUDTag)
if tmpView != nil {
let hud = tmpView as! ProgressHUD
hud.hideAfterSuccess()
}
}
class func hideAfterFailOnView(_ view: UIView){
let tmpView = view.viewWithTag(kProgressHUDTag)
if tmpView != nil {
let hud = tmpView as! ProgressHUD
hud.hideAfterFail()
}
}
fileprivate class func hideOnView(_ view: UIView){
let tmpView = view.viewWithTag(kProgressHUDTag)
if tmpView != nil {
let hud = tmpView as! ProgressHUD
hud.hideActivityView()
}
}
}
|
361ff445c4bbf0d0380f379e9634c553
| 24.142045 | 153 | 0.567232 | false | false | false | false |
zachwaugh/GIFKit
|
refs/heads/master
|
GIFKit/DataStream.swift
|
mit
|
1
|
//
// DataStream.swift
// GIFKit
//
// Created by Zach Waugh on 11/5/15.
// Copyright © 2015 Zach Waugh. All rights reserved.
//
import Foundation
struct DataStream {
let data: NSData
var position: Int = 0
var bytesRemaining: Int {
return data.length - position
}
var atEndOfStream: Bool {
return position == data.length
}
init(data: NSData) {
self.data = data
}
mutating func takeBool() -> Bool? {
guard hasAvailableBytes(1) else {
return nil
}
var value: Bool = false
let length = sizeof(Bool)
data.getBytes(&value, range: NSRange(location: position, length: length))
position += length
return value
}
mutating func takeUInt8() -> UInt8? {
guard hasAvailableBytes(1) else {
return nil
}
var value: UInt8 = 0
let length = sizeof(UInt8)
data.getBytes(&value, range: NSRange(location: position, length: length))
position += length
return value
}
mutating func takeUInt16() -> UInt16? {
guard hasAvailableBytes(2) else {
return nil
}
var value: UInt16 = 0
let length = sizeof(UInt16)
data.getBytes(&value, range: NSRange(location: position, length: length))
position += length
return value
}
mutating func takeByte() -> Byte? {
return takeUInt8()
}
mutating func takeBytes(length: Int) -> NSData? {
guard let bytes = peekBytes(length) else {
print("[gif decoder] invalid number of bytes!")
return nil
}
position += length
return bytes
}
mutating func takeBytes(length: Int) -> [Byte]? {
guard hasAvailableBytes(length) else {
print("[gif decoder] invalid number of bytes!")
return nil
}
let bytes = nextBytes(length)
position += length
return bytes
}
// MARK: - Peek
func peekBytes(length: Int) -> NSData? {
return peekBytesWithRange(NSRange(location: position, length: length))
}
func peekBytesWithRange(range: NSRange) -> NSData? {
guard range.location + range.length <= data.length else {
print("[gif decoder] invalid range! \(range), bytes: \(data.length)")
return nil
}
return data.subdataWithRange(range)
}
func nextBytes(count: Int) -> [Byte] {
return nextBytes(NSRange(location: position, length: count))
}
func nextBytes(range: NSRange) -> [Byte] {
var bytes = [Byte](count: range.length, repeatedValue: 0)
data.getBytes(&bytes, range: range)
return bytes
}
func hasAvailableBytes(count: Int) -> Bool {
return bytesRemaining >= count
}
}
|
f33906fbfb1cce47dadf44c97654ae9d
| 23.801653 | 81 | 0.545667 | false | false | false | false |
dn-m/Collections
|
refs/heads/master
|
Collections/SortedArray.swift
|
mit
|
1
|
//
// SortedArray.swift
// Collections
//
// Created by James Bean on 12/10/16.
//
//
import Algebra
/// `Array` that keeps itself sorted.
public struct SortedArray <Element: Comparable>:
RandomAccessCollectionWrapping,
SortedCollectionWrapping
{
public var base: [Element] = []
// MARK: - Initializers
/// Create an empty `SortedArray`.
public init() { }
/// Create a `SortedArray` with the given sequence of `elements`.
public init <S> (_ elements: S) where S: Sequence, S.Iterator.Element == Element {
self.base = Array(elements).sorted()
}
// MARK: - Instance Methods
/// Remove the given `element`, if it is contained herein.
///
/// - TODO: Make `throws` instead of returning silently.
public mutating func remove(_ element: Element) {
guard let index = base.index(of: element) else { return }
base.remove(at: index)
}
/// Insert the given `element`.
///
/// - Complexity: O(_n_)
public mutating func insert(_ element: Element) {
let index = self.index(for: element)
base.insert(element, at: index)
}
/// Insert the contents of another sequence of `T`.
public mutating func insert <S: Sequence> (contentsOf elements: S)
where S.Iterator.Element == Element
{
elements.forEach { insert($0) }
}
/// - Returns: Index for the given `element`, if it exists. Otherwise, `nil`.
public func index(of element: Element) -> Int? {
let index = self.index(for: element)
guard index < count, base[index] == element else { return nil }
return index
}
/// Binary search to find insertion point
///
// FIXME: Move to extension on `BidirectionCollection where Element: Comparable`.
// FIXME: Add to `SortedCollection`
private func index(for element: Element) -> Int {
var start = 0
var end = base.count
while start < end {
let middle = start + (end - start) / 2
if element > base[middle] {
start = middle + 1
} else {
end = middle
}
}
return start
}
}
extension SortedArray: Equatable {
// MARK: - Equatable
/// - returns: `true` if all elements in both arrays are equivalent. Otherwise, `false`.
public static func == <T> (lhs: SortedArray<T>, rhs: SortedArray<T>) -> Bool {
return lhs.base == rhs.base
}
}
extension SortedArray: Additive {
// MARK: - Additive
/// - Returns: Empty `SortedArray`.
public static var zero: SortedArray<Element> {
return SortedArray()
}
/// - returns: `SortedArray` with the contents of two `SortedArray` values.
public static func + <T> (lhs: SortedArray<T>, rhs: SortedArray<T>) -> SortedArray<T> {
var result = lhs
result.insert(contentsOf: rhs)
return result
}
}
extension SortedArray: Monoid {
// MARK: - Monoid
/// - Returns: Empty `SortedArray`.
public static var identity: SortedArray<Element> {
return .zero
}
/// - Returns: Composition of two of the same `Semigroup` type values.
public static func <> (lhs: SortedArray<Element>, rhs: SortedArray<Element>)
-> SortedArray<Element>
{
return lhs + rhs
}
}
extension SortedArray: ExpressibleByArrayLiteral {
// MARK: - ExpressibleByArrayLiteral
/// - returns: Create a `SortedArray` with an array literal.
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
|
8418a1df11ffec8ed9d193685943a56a
| 26.113636 | 92 | 0.604359 | false | false | false | false |
Caiflower/SwiftWeiBo
|
refs/heads/master
|
花菜微博/花菜微博/Classes/Tools(工具)/CFAddition(Swift)/UIKit/UIView-Layer.swift
|
apache-2.0
|
1
|
//
// UIView-Layer.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/20.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import UIKit
// MARK: - layer相关属性
extension UIView {
@IBInspectable var borderColor: UIColor {
get {
return UIColor(cgColor: self.layer.borderColor ?? UIColor.white.cgColor)
}
set {
self.layer.borderColor = newValue.cgColor
}
}
@IBInspectable var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.masksToBounds = true;
// 栅格化优化性能
self.layer.rasterizationScale = UIScreen.main.scale;
self.layer.shouldRasterize = true;
self.layer.cornerRadius = newValue
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
}
extension UIView {
}
|
15e9aaa0ba1ee53e7ec946b9d00961be
| 19.64 | 84 | 0.556202 | false | false | false | false |
krevis/MIDIApps
|
refs/heads/main
|
Frameworks/SnoizeMIDI/Endpoint.swift
|
bsd-3-clause
|
1
|
/*
Copyright (c) 2021, Kurt Revis. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
import Foundation
import CoreMIDI
public class Endpoint: MIDIObject {
required init(context: CoreMIDIContext, objectRef: MIDIObjectRef) {
super.init(context: context, objectRef: objectRef)
}
private lazy var cachedManufacturer = cacheProperty(kMIDIPropertyManufacturer, String.self)
public var manufacturer: String? {
get { self[cachedManufacturer] }
set { self[cachedManufacturer] = newValue }
}
private lazy var cachedModel = cacheProperty(kMIDIPropertyModel, String.self)
public var model: String? {
get { self[cachedModel] }
set { self[cachedModel] = newValue }
}
private lazy var cachedDisplayName = cacheProperty(kMIDIPropertyDisplayName, String.self)
public var displayName: String? {
get { self[cachedDisplayName] }
set { self[cachedDisplayName] = newValue }
}
public var device: Device? {
midiContext.findObject(midiObjectRef: deviceRef)
}
public var isVirtual: Bool {
deviceRef == 0
}
public var isOwnedByThisProcess: Bool {
isVirtual && ownerPID == getpid()
}
public var connectedExternalDevices: [ExternalDevice] {
uniqueIDsOfConnectedThings.compactMap { uniqueID -> ExternalDevice? in
if let deviceRef = deviceRefFromConnectedUniqueID(uniqueID) {
return midiContext.findObject(midiObjectRef: deviceRef)
}
else {
return nil
}
}
}
public var endpointRef: MIDIEndpointRef {
midiObjectRef
}
// MARK: Internal
func setPrivateToThisProcess() {
self[kMIDIPropertyPrivate as CFString] = Int32(1)
}
func setOwnedByThisProcess() {
// We have a chicken-egg problem. When setting values of properties, we want
// to make sure that the endpoint is owned by this process. However, there's
// no way to tell if the endpoint is owned by this process until it gets a
// property set on it. So we'll say that this property should be set first,
// before any other setters are called.
guard isVirtual else { fatalError("Endpoint is not virtual, so it can't be owned by this process") }
ownerPID = getpid()
}
// MARK: Private
// We set this property on the virtual endpoints that we create,
// so we can query them to see if they're ours.
private static let propertyOwnerPID = "SMEndpointPropertyOwnerPID"
private var ownerPID: Int32 {
get { self[Endpoint.propertyOwnerPID as CFString] ?? 0 }
set { self[Endpoint.propertyOwnerPID as CFString] = newValue }
}
private var cachedDeviceRef: MIDIDeviceRef?
private var deviceRef: MIDIDeviceRef {
switch cachedDeviceRef {
case .none:
let value: MIDIDeviceRef = {
var entityRef: MIDIEntityRef = 0
var deviceRef: MIDIDeviceRef = 0
if midiContext.interface.endpointGetEntity(endpointRef, &entityRef) == noErr,
midiContext.interface.entityGetDevice(entityRef, &deviceRef) == noErr {
return deviceRef
}
else {
return 0
}
}()
cachedDeviceRef = .some(value)
return value
case .some(let value):
return value
}
}
var uniqueIDsOfConnectedThings: [MIDIUniqueID] {
// Connected things may be external devices, endpoints, or who knows what.
// The property for kMIDIPropertyConnectionUniqueID may be an integer or a data object.
// Try getting it as data first. (The data is an array of big-endian MIDIUniqueIDs, aka Int32s.)
if let data: Data = self[kMIDIPropertyConnectionUniqueID] {
// Make sure the data size makes sense
guard data.count > 0, data.count % MemoryLayout<Int32>.size == 0 else { return [] }
return data.withUnsafeBytes {
$0.bindMemory(to: Int32.self).map { MIDIUniqueID(bigEndian: $0) }
}
}
// Now try getting the property as an integer. (It is only valid if nonzero.)
if let oneUniqueID: MIDIUniqueID = self[kMIDIPropertyConnectionUniqueID],
oneUniqueID != 0 {
return [oneUniqueID]
}
// Give up
return []
}
private func deviceRefFromConnectedUniqueID(_ connectedUniqueID: MIDIUniqueID) -> MIDIDeviceRef? {
var foundDeviceRef: MIDIDeviceRef?
var connectedObjectRef: MIDIObjectRef = 0
var connectedObjectType: MIDIObjectType = .other
var status = midiContext.interface.objectFindByUniqueID(connectedUniqueID, &connectedObjectRef, &connectedObjectType)
var done = false
while status == noErr && !done {
switch connectedObjectType {
case .device, .externalDevice:
// We've got the device
foundDeviceRef = connectedObjectRef as MIDIDeviceRef
done = true
case .entity, .externalEntity:
// Get the entity's device
status = midiContext.interface.entityGetDevice(connectedObjectRef as MIDIEntityRef, &connectedObjectRef)
connectedObjectType = .device
case .source, .destination, .externalSource, .externalDestination:
// Get the endpoint's entity
status = midiContext.interface.endpointGetEntity(connectedObjectRef as MIDIEndpointRef, &connectedObjectRef)
connectedObjectType = .entity
default:
// Give up
done = true
}
}
return foundDeviceRef
}
}
|
82ef4f94e9b9bfc604908826b20c00b9
| 34.622754 | 125 | 0.626156 | false | false | false | false |
123kyky/SteamReader
|
refs/heads/master
|
SteamReader/SteamReader/CoreData/NewsItem.swift
|
mit
|
1
|
import Foundation
import SwiftyJSON
@objc(NewsItem)
public class NewsItem: _NewsItem, JSONImportNSManagedObjectProtocol {
// MARK: - JSONImportNSManagedObjectProtocol
class func importDictionaryFromJSON(json: JSON, app: App?) -> [NSObject: AnyObject] {
return [
"appId" : app!.appId!,
"gId" : json["gid"].stringValue,
"title" : json["title"].stringValue,
"author" : json["author"].stringValue,
"contents" : json["contents"].stringValue,
"url" : json["url"].stringValue,
"isExternalURL" : json["is_external_url"].boolValue,
"feedLabel" : json["feedlabel"].stringValue,
"feedName" : json["feedname"].stringValue,
"date" : NSDate(timeIntervalSince1970: json["date"].doubleValue)
]
}
class func importDictionaryMatches(dictionary: [NSObject : AnyObject], app: App?) -> ImportDictionaryMatchingState {
let newsItem: NewsItem? = CoreDataInterface.singleton.newsItemForId(dictionary["gId"] as! String)
if newsItem == nil {
return .NewObject
} else if newsItem!.app?.appId == (dictionary["appId"] as! String) &&
newsItem!.gId == (dictionary["gId"] as! String) &&
newsItem!.title == (dictionary["title"] as! String) &&
newsItem!.author == (dictionary["author"] as! String) &&
newsItem!.contents == (dictionary["contents"] as! String) &&
newsItem!.url == (dictionary["url"] as! String) &&
newsItem!.isExternalURL == dictionary["isExternalURL"] as! Bool &&
newsItem!.feedLabel == (dictionary["feedLabel"] as! String) &&
newsItem!.feedName == (dictionary["feedName"] as! String) &&
newsItem!.date?.compare((dictionary["date"] as? NSDate)!) == .OrderedSame {
return .Matches
} else if dictionary["appId"] != nil &&
dictionary["gId"] != nil &&
dictionary["title"] != nil &&
dictionary["author"] != nil &&
dictionary["contents"] != nil &&
dictionary["url"] != nil &&
dictionary["isExternalURL"] != nil &&
dictionary["feedLabel"] != nil &&
dictionary["feedName"] != nil &&
dictionary["date"] != nil {
return .Updated
} else {
return .Invalid
}
}
}
|
511ac4577a2ab1d58e7c75d3d5346c37
| 43.740741 | 120 | 0.5625 | false | false | false | false |
polok/UICheckbox.Swift
|
refs/heads/master
|
UICheckbox/Classes/UICheckbox.swift
|
mit
|
1
|
//
// UICheckbox.swift
// UICheckbox
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Marcin Polak. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@IBDesignable open class UICheckbox: UIButton {
/*
* Variable describes UICheckbox padding
*/
@IBInspectable open var padding: CGFloat = CGFloat(15)
/*
* Variable describes UICheckbox border width
*/
@IBInspectable open var borderWidth: CGFloat = 2.0 {
didSet {
layer.borderWidth = borderWidth
}
}
/*
* Variable stores UICheckbox border color
*/
@IBInspectable open var borderColor: UIColor = UIColor.lightGray {
didSet {
layer.borderColor = borderColor.cgColor
}
}
/*
* Variable stores UICheckbox border radius
*/
@IBInspectable open var cornerRadius: CGFloat = 5.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
/*
* Variable to store current UICheckbox select status
*/
override open var isSelected: Bool {
didSet {
super.isSelected = isSelected
onSelectStateChanged?(self, isSelected)
}
}
/*
* Callback for handling checkbox status change
*/
open var onSelectStateChanged: ((_ checkbox: UICheckbox, _ selected: Bool) -> Void)?
// MARK: Init
/*
* Create a new instance of a UICheckbox
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initDefaultParams()
}
/*
* Create a new instance of a UICheckbox
*/
override init(frame: CGRect) {
super.init(frame: frame)
initDefaultParams()
}
/*
* Increase UICheckbox 'clickability' area for better UX
*/
override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let newBound = CGRect(
x: self.bounds.origin.x - padding,
y: self.bounds.origin.y - padding,
width: self.bounds.width + 2 * padding,
height: self.bounds.width + 2 * padding
)
return newBound.contains(point)
}
override open func prepareForInterfaceBuilder() {
setTitle("", for: UIControlState())
}
}
// MARK: Private methods
public extension UICheckbox {
fileprivate func initDefaultParams() {
addTarget(self, action: #selector(UICheckbox.checkboxTapped), for: .touchUpInside)
setTitle(nil, for: UIControlState())
clipsToBounds = true
setCheckboxImage()
}
fileprivate func setCheckboxImage() {
let frameworkBundle = Bundle(for: UICheckbox.self)
let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("UICheckbox.bundle")
let resourceBundle = Bundle(url: bundleURL!)
let image = UIImage(named: "ic_check_3x", in: resourceBundle, compatibleWith: nil)
imageView?.contentMode = .scaleAspectFit
setImage(nil, for: UIControlState())
setImage(image, for: .selected)
setImage(image, for: .highlighted)
}
@objc fileprivate func checkboxTapped(_ sender: UICheckbox) {
isSelected = !isSelected
}
}
|
5f84e85a6a82b6a9a5046a3dc6b9a586
| 28.190476 | 96 | 0.6488 | false | false | false | false |
byu-oit-appdev/ios-byuSuite
|
refs/heads/dev
|
byuSuite/Apps/YTime/controller/YTimeRootViewController.swift
|
apache-2.0
|
1
|
//
// YTimeRootViewController.swift
// byuSuite
//
// Created by Eric Romrell on 5/18/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import CoreLocation
private let TIMESHEETS_SEGUE_ID = "showTimesheets"
private let CALENDAR_SEGUE_ID = "showCalendar"
class YTimeRootViewController: ByuViewController2, UITableViewDataSource, CLLocationManagerDelegate, YTimePunchDelegate {
private struct UI {
static var fadeDuration = 0.25
}
//MARK: Outlets
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var spinner: UIActivityIndicatorView!
@IBOutlet private weak var viewTimesheetButton: UIBarButtonItem!
//MARK: Properties
private var refreshControl = UIRefreshControl()
private var timesheet: YTimeTimesheet?
private var punch: YTimePunch?
private var readyToPunch = false
private var punchLocation: CLLocation?
private var locationManager: CLLocationManager?
private var loadingView: LoadingView?
override func viewDidLoad() {
super.viewDidLoad()
tableView.hideEmptyCells()
refreshControl = tableView.addDefaultRefreshControl(target: self, action: #selector(loadData))
loadData()
}
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(hideAndLoadTable), name: .UIApplicationWillEnterForeground, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == TIMESHEETS_SEGUE_ID, let vc = segue.destination.childViewControllers.first as? YTimeJobsViewController, let jobs = timesheet?.jobs {
vc.jobs = jobs
} else if segue.identifier == CALENDAR_SEGUE_ID, let vc = segue.destination.childViewControllers.first as? YTimeCalendarViewController, let job = timesheet?.jobs.first {
//Use the first job, as this segue will only ever happen when the user only has one job
vc.job = job
}
}
deinit {
locationManager?.delegate = nil
}
//MARK: UITableViewDataSource/Delegate callbacks
func numberOfSections(in tableView: UITableView) -> Int {
//The first section contains all of the jobs, the second contains the hour summaries
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//Return 2 for the weekly and period summaries
return section == 0 ? timesheet?.jobs.count ?? 0 : 2
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
tableView.estimatedRowHeight = 100
return UITableViewAutomaticDimension
} else {
return 45
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0, let cell = tableView.dequeueReusableCell(for: indexPath, identifier: "jobCell") as? YTimeJobTableViewCell {
cell.delegate = self //We added the delegate so that we could allow the view controller to handle the punch logic rather than each cell
cell.job = timesheet?.jobs[indexPath.row]
return cell
} else {
let cell = tableView.dequeueReusableCell(for: indexPath, identifier: "paySummary")
if indexPath.row == 0 {
cell.textLabel?.text = "Week Total:"
cell.detailTextLabel?.text = timesheet?.weeklyTotal
} else {
cell.textLabel?.text = "Pay Period Total:"
cell.detailTextLabel?.text = timesheet?.periodTotal
}
return cell
}
}
//MARK: CLLocationMangerDelegate callbacks
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
YTimeRootViewController.yTimeLocationManager(manager, didChangeAuthorization: status, for: self, deniedCompletionHandler: {
self.loadData()
//If attempted to punch without location services, remove the loadingView and enable interaction again on table.
self.loadingView?.removeFromSuperview()
self.tableView.isUserInteractionEnabled = true
//Remove any saved punches to prevent them being used without location services enabled.
self.punch = nil
})
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
punchLocation = locations.last
manager.stopUpdatingLocation()
loadingView?.setMessage("Processing Punch...")
punchIfReady()
}
//MARK: YTimePunchDelegate callback
func createPunch(punchIn: Bool, job: YTimeJob, sender: Any) {
if let employeeRecord = job.employeeRecord {
punch = YTimePunch(employeeRecord: employeeRecord, clockingIn: punchIn)
if punchIn == job.clockedIn {
//Verify that they want to double punch
let status = punchIn ? "in" : "out"
displayActionSheet(from: sender, title: "You are already clocked \(status). Please confirm that you would like to clock \(status) again.", actions: [
UIAlertAction(title: "Confirm", style: .default, handler: { (_) in
self.startRequest()
})
])
} else {
startRequest()
}
}
}
//MARK: Listeners
@objc func hideAndLoadTable() {
spinner.startAnimating()
tableView.isUserInteractionEnabled = false
tableView.alpha = 0
loadData()
}
@objc func loadData() {
YTimeClient.getTimesheet { (sheet, error) in
//If refreshing the table, end the refresh control. If loading view for first time, stop the spinner and make the table visible.
self.refreshControl.endRefreshing()
self.spinner.stopAnimating()
UIView.animate(withDuration: UI.fadeDuration) {
self.tableView.isUserInteractionEnabled = true
self.tableView.alpha = 1
}
if let sheet = sheet {
self.timesheet = sheet
if sheet.jobs.count == 0 {
super.displayAlert(title: "No Jobs", message: "You are not listed as a BYU employee in the Y-Time system. Contact your supervisor if you believe this notice is in error.")
}
self.viewTimesheetButton.isEnabled = true
} else {
super.displayAlert(error: error, alertHandler: nil)
}
self.tableView.reloadData()
}
}
@IBAction func didTapTimesheetButton(_ sender: Any) {
if timesheet?.jobs.count ?? 0 > 1 {
performSegue(withIdentifier: TIMESHEETS_SEGUE_ID, sender: sender)
} else {
performSegue(withIdentifier: CALENDAR_SEGUE_ID, sender: sender)
}
}
//MARK: Private functions
private func startRequest() {
loadingView = self.displayLoadingView(message: "Determining Location...")
//Disable the table to prevent inadvertent multiple taps
tableView.isUserInteractionEnabled = false
//Request a location
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestWhenInUseAuthorization()
//We are now ready to punch whenever a location has been found
readyToPunch = true
punchIfReady()
}
private func punchIfReady() {
if readyToPunch, let location = punchLocation, let punch = punch {
readyToPunch = false
punch.location = location
YTimeClient.createPunch(punch) { (sheet, error) in
self.loadingView?.removeFromSuperview()
self.tableView.isUserInteractionEnabled = true
//Clear punchLocation after we pass it to the method, to prevent it being saved and sending later. Set to nil here, because LocationManager still resets location right after we stop it updating.
self.punchLocation = nil
if let sheet = sheet {
self.timesheet = sheet
self.showToast(message: "Your punch was submitted successfully.\nIt may take a few minutes for these changes to reflect in your timesheet.", dismissDelay: 5)
self.viewTimesheetButton.isEnabled = true
} else {
super.displayAlert(error: error, alertHandler: nil)
}
self.tableView.reloadData()
}
}
}
//MARK: Static Methods
static func yTimeLocationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus, for viewController: ByuViewController2, deniedCompletionHandler: (() -> Void)? = nil ) {
if status == .denied || status == .restricted {
manager.stopUpdatingLocation()
let alert = UIAlertController(title: "Location Services Required", message: "In order to create punches, location services must be enabled. Please change your settings to allow for this.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (_) in
if let url = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.open(url: url)
}
}))
viewController.present(alert, animated: true, completion: deniedCompletionHandler)
} else {
manager.startUpdatingLocation()
}
}
}
|
763e78e08dfac3dcdc1ad15630be098e
| 36.479839 | 215 | 0.686498 | false | false | false | false |
devpunk/velvet_room
|
refs/heads/master
|
Source/View/SaveData/VSaveData.swift
|
mit
|
1
|
import UIKit
final class VSaveData:ViewMain
{
private(set) weak var viewBar:VSaveDataBar!
private weak var viewList:VSaveDataList!
private weak var viewBack:VSaveDataBarBack!
override var panBack:Bool
{
get
{
return true
}
}
required init(controller:UIViewController)
{
super.init(controller:controller)
guard
let controller:CSaveData = controller as? CSaveData
else
{
return
}
factoryViews(controller:controller)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
super.layoutSubviews()
let barHeight:CGFloat = viewBar.bounds.height
let backRemainHeight:CGFloat = barHeight - viewBack.kHeight
let backMarginBottom:CGFloat = backRemainHeight / -2.0
viewBack.layoutBottom.constant = backMarginBottom
}
//MARK: private
private func factoryViews(controller:CSaveData)
{
let viewList:VSaveDataList = VSaveDataList(
controller:controller)
self.viewList = viewList
let viewBar:VSaveDataBar = VSaveDataBar(
controller:controller)
self.viewBar = viewBar
let viewBack:VSaveDataBarBack = VSaveDataBarBack(
controller:controller)
self.viewBack = viewBack
addSubview(viewBar)
addSubview(viewList)
addSubview(viewBack)
NSLayoutConstraint.topToTop(
view:viewBar,
toView:self)
viewBar.layoutHeight = NSLayoutConstraint.height(
view:viewBar,
constant:viewList.kMinBarHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBar,
toView:self)
NSLayoutConstraint.equals(
view:viewList,
toView:self)
viewBack.layoutBottom = NSLayoutConstraint.bottomToBottom(
view:viewBack,
toView:viewBar)
NSLayoutConstraint.height(
view:viewBack,
constant:viewBack.kHeight)
NSLayoutConstraint.width(
view:viewBack,
constant:viewBack.kWidth)
NSLayoutConstraint.leftToLeft(
view:viewBack,
toView:self)
}
}
|
06e93858e548c2f445eae94f640efb28
| 24.494737 | 67 | 0.580099 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
KsApi/models/graphql/adapters/Project+FetchProjectFriendsQueryDataTests.swift
|
apache-2.0
|
1
|
import Apollo
@testable import KsApi
import XCTest
final class Project_FetchProjectFriendsQueryDataTests: XCTestCase {
/// `FetchProjectFriendsQueryBySlug` returns identical data.
func testFetchProjectFriendsQueryData_Success() {
let producer = Project.projectFriendsProducer(from: FetchProjectFriendsQueryTemplate.valid.data)
guard let projectFriendsById = MockGraphQLClient.shared.client.data(from: producer) else {
XCTFail()
return
}
self.testProjectFriendsProperties_Success(projectFriends: projectFriendsById)
}
private func testProjectFriendsProperties_Success(projectFriends: [User]) {
XCTAssertEqual(projectFriends.count, 2)
XCTAssertEqual(projectFriends[0].id, decompose(id: "VXNlci0xNzA1MzA0MDA2"))
XCTAssertEqual(
projectFriends[0].avatar.large,
"https://ksr-qa-ugc.imgix.net/assets/033/090/101/8667751e512228a62d426c77f6eb8a0b_original.jpg?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1618227451&auto=format&frame=1&q=92&s=36de925b6797139e096d7b6219f743d0"
)
}
}
|
9a5bb51f7a2c7c051ea585c1ecd42574
| 39.423077 | 223 | 0.778306 | false | true | false | false |
SPECURE/rmbt-ios-client
|
refs/heads/main
|
Sources/AbstractBasicRequestBuilder.swift
|
apache-2.0
|
1
|
/*****************************************************************************************************
* Copyright 2016 SPECURE GmbH
*
* 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
///
class AbstractBasicRequestBuilder {
///
class func addBasicRequestValues(_ basicRequest: BasicRequest) {
let infoDictionary = Bundle.main.infoDictionary! // !
if RMBTConfig.sharedInstance.RMBT_USE_MAIN_LANGUAGE == true {
basicRequest.language = RMBTConfig.sharedInstance.RMBT_MAIN_LANGUAGE
} else {
basicRequest.language = PREFFERED_LANGUAGE
}
basicRequest.product = "" // always null on iOS...
Log.logger.debug("ADDING PREVIOUS TEST STATUS: \(String(describing: RMBTSettings.sharedSettings.previousTestStatus))")
basicRequest.previousTestStatus = RMBTSettings.sharedSettings.previousTestStatus
basicRequest.softwareRevision = RMBTBuildInfoString()
basicRequest.softwareVersion = infoDictionary["CFBundleShortVersionString"] as? String
basicRequest.softwareVersionCode = infoDictionary["CFBundleVersion"] as? Int
basicRequest.softwareVersionName = "0.3" // ??
basicRequest.clientVersion = "0.3" // TODO: fix this on server side
basicRequest.timezone = TimeZone.current.identifier
}
}
|
ed8e38f0958a7160a71997d21d442ee0
| 41.369565 | 126 | 0.643407 | false | true | false | false |
Za1006/TIY-Assignments
|
refs/heads/master
|
The Grail Diary/The Grail Diary/FamousSitesTableViewController.swift
|
cc0-1.0
|
1
|
//
// FamousSitesTableViewController.swift
// The Grail Diary
//
// Created by Elizabeth Yeh on 10/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class FamousSitesTableViewController: UITableViewController
{
var place = Array<FamousPlaces>()
var name: String = ""
var location: String = ""
var history: String = ""
var attribute: String = ""
override func viewDidLoad()
{
super.viewDidLoad()
title = "Famouse Places"
loadSITEList()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return place.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("SiteNameCell", forIndexPath: indexPath) as! SiteNameCell
let placeSite = place[indexPath.row]
cell.nameOfSite.text = placeSite.siteName
cell.locationOfSite.text = "location: " + placeSite.siteLocation
cell.historyOfSite.text = "history: " + placeSite.siteHistory
cell.attributeOfSite.text = "attribute: " + placeSite.siteAttribute
return cell
}
func loadSITEList()
{
do
{
let filePath = NSBundle.mainBundle().pathForResource("SITE", ofType: "json")
let dataFromFile = NSData(contentsOfFile: filePath!)
let placeData: NSArray! = try NSJSONSerialization.JSONObjectWithData(dataFromFile!, options: []) as! NSArray
for placeDictionay in placeData
{
let placeSite = FamousPlaces(dictionary: placeDictionay as! NSDictionary)
place.append(placeSite)
}
// catch let error as NSError
// {
// print(error)
// }
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
}
}
|
ad1d02eb7720a3df9468258c09b5133f
| 32.733333 | 157 | 0.645147 | false | false | false | false |
editfmah/AeonAPI
|
refs/heads/master
|
Sources/Mutex.swift
|
mit
|
1
|
//
// Mutex.swift
// scale
//
// Created by Adrian Herridge on 06/02/2017.
//
//
import Foundation
import Dispatch
import SWSQLite
class Mutex {
private var thread: Thread? = nil;
private var lock: DispatchQueue
init() {
lock = DispatchQueue(label: uuid())
}
func mutex(_ closure: ()->()) {
if thread != Thread.current {
lock.sync {
thread = Thread.current
closure()
thread = nil
}
} else {
closure()
}
}
}
|
6d89d3514de1d14756d552870e532619
| 15.823529 | 45 | 0.480769 | false | false | false | false |
onmyway133/Github.swift
|
refs/heads/master
|
Carthage/Checkouts/Tailor/Sources/Shared/Protocols/PathAccessible.swift
|
mit
|
1
|
import Sugar
public protocol PathAccessible {
/**
- Parameter name: The array of path, can be index or key
- Returns: A child dictionary for that path, otherwise it returns nil
*/
func path(path: [SubscriptKind]) -> JSONDictionary?
/**
- Parameter name: The key path, separated by dot
- Returns: A child dictionary for that path, otherwise it returns nil
*/
func path(keyPath: String) -> JSONDictionary?
}
public extension PathAccessible {
func path(path: [SubscriptKind]) -> JSONDictionary? {
var castedPath = path.dropFirst()
castedPath.append(.Key(""))
let pairs = zip(path, Array(castedPath))
var result: Any = self
for (kind, castedKind) in pairs {
switch (kind, castedKind) {
case (let .Key(name), .Key):
result = (result as? JSONDictionary)?.dictionary(name)
case (let .Key(name), .Index):
result = (result as? JSONDictionary)?.array(name)
case (let .Index(index), .Key):
result = (result as? JSONArray)?.dictionary(index)
case (let .Index(index), .Index):
result = (result as? JSONArray)?.array(index)
}
}
return result as? JSONDictionary
}
func path(keyPath: String) -> JSONDictionary? {
let kinds: [SubscriptKind] = keyPath.componentsSeparatedByString(".").map {
if let index = Int($0) {
return .Index(index)
} else {
return .Key($0)
}
}
return path(kinds)
}
}
extension Dictionary: PathAccessible {}
extension Array: PathAccessible {}
|
194a607a8827f284a3e5897a2f66d4f3
| 26.357143 | 79 | 0.63577 | false | false | false | false |
iosClassForBeginner/VacationPlanner_en
|
refs/heads/master
|
Vacation Planner Complete/Vacation Planner/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Vacation Planner
//
// Created by Sam on 2017-03-13.
// Copyright © 2017 Sam. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: IB outlets
@IBOutlet weak var usernameButton: UITextField!
@IBOutlet weak var passwordButton: UITextField!
@IBOutlet weak var loginButton: UIButton!
// MARK: further UI
let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
// MARK: IB actions
@IBAction func login(_ sender: Any) {
spinner.isHidden = !spinner.isHidden
}
// MARK: view controller methods
// Gets called once during loading of the view
override func viewDidLoad() {
super.viewDidLoad()
//set up the UI
loginButton.layer.cornerRadius = 8.0
loginButton.layer.masksToBounds = true
spinner.frame = CGRect(x: -20.0, y: 6.0, width: 20.0, height: 20.0)
spinner.startAnimating()
spinner.center = CGPoint(x: spinner.bounds.midX + 5.0,
y: loginButton.bounds.midY)
loginButton.addSubview(spinner)
}
// Gets called every time before view appears
override func viewWillAppear(_ animated: Bool) {
usernameButton.center.x -= view.bounds.width
passwordButton.center.x -= view.bounds.width
loginButton.center.x -= view.bounds.width
}
// Gets called right after the view apears
override func viewDidAppear(_ animated: Bool) {
spinner.isHidden = true
UIView.animate(withDuration: 0.5, animations: {
self.usernameButton.center.x += self.view.bounds.width
})
UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: {
self.passwordButton.center.x += self.view.bounds.width
}, completion: nil)
UIView.animate(withDuration: 0.5, delay: 0.4, options: [], animations: {
self.loginButton.center.x += self.view.bounds.width
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
8a2a5d62b9bae2c94d0f5593ca21727b
| 26.255814 | 101 | 0.606655 | false | false | false | false |
noahemmet/FingerPaint
|
refs/heads/master
|
FingerPaint/Shape.swift
|
apache-2.0
|
1
|
//
// Shapes.swift
// FingerPaint
//
// Created by Noah Emmet on 4/21/16.
// Copyright © 2016 Sticks. All rights reserved.
//
import Foundation
public enum Border {
case None
case SingleLine
}
public enum Fill {
case Empty
case Solid
case Checkered
case Stripes(rows: Int, columns: Int, offset: Int)
}
public struct Shape {
public let points: [CGPoint]
public let border: Border
public let fill: Fill
public init(points: [CGPoint], border: Border = .SingleLine, fill: Fill = .Empty) {
self.points = points
self.border = border
self.fill = fill
}
}
|
e4b623de392aa332478406e22fdf0bcc
| 16.90625 | 84 | 0.69459 | false | false | false | false |
AckeeCZ/ACKategories
|
refs/heads/master
|
ACKategories-iOS/Base/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ACKategories
//
// Created by Jan Misar on 02/04/2019.
// Copyright © 2019 Ackee, s.r.o. All rights reserved.
//
import UIKit
import os.log
extension Base {
/// Turn on/off logging of init/deinit of all VCs
/// ⚠️ Has no effect when Base.memoryLoggingEnabled is true
public static var viewControllerMemoryLoggingEnabled: Bool = true
/// Base class for all view controllers
open class ViewController: UIViewController {
/// Navigation bar is shown/hidden in viewWillAppear according to this flag
open var hasNavigationBar: Bool = true
public init() {
super.init(nibName: nil, bundle: nil)
if Base.memoryLoggingEnabled && Base.viewControllerMemoryLoggingEnabled {
if #available(iOS 10.0, *) {
os_log("📱 👶 %@", log: Logger.lifecycleLog(), type: .info, self)
} else {
NSLog("📱 👶 \(self)")
}
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var firstWillAppearOccurred = false
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !firstWillAppearOccurred {
viewWillFirstAppear(animated)
firstWillAppearOccurred = true
}
navigationController?.setNavigationBarHidden(!hasNavigationBar, animated: animated)
}
private var firstDidAppearOccurred = false
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !firstDidAppearOccurred {
viewDidFirstAppear(animated)
firstDidAppearOccurred = true
}
}
/// Method is called when `viewWillAppear(_:)` is called for the first time
open func viewWillFirstAppear(_ animated: Bool) {
// to be overridden
}
/// Method is called when `viewDidAppear(_:)` is called for the first time
open func viewDidFirstAppear(_ animated: Bool) {
// to be overridden
}
deinit {
if Base.memoryLoggingEnabled && Base.viewControllerMemoryLoggingEnabled {
if #available(iOS 10.0, *) {
os_log("📱 ⚰️ %@", log: Logger.lifecycleLog(), type: .info, self)
} else {
NSLog("📱 ⚰️ \(self)")
}
}
}
}
}
|
f381daf973563574695744eef7490b5d
| 29.809524 | 95 | 0.568006 | false | false | false | false |
corchwll/amos-ss15-proj5_ios
|
refs/heads/master
|
MobileTimeAccounting/UserInterface/Dashboard/DashboardTableViewController.swift
|
agpl-3.0
|
1
|
/*
Mobile Time Accounting
Copyright (C) 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import MessageUI
class DashboardTableViewController: UITableViewController
{
@IBOutlet weak var overtimeLabel: UILabel!
@IBOutlet weak var vacationDaysLabel: UILabel!
@IBOutlet weak var vacationExpiringWarningLabel: UILabel!
/*
iOS life-cycle function, called when view did appear. Sets up labels.
@methodtype Hook
@pre -
@post Labels are set up
*/
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
setUpOvertimeLabel()
setUpVacationDaysLabel()
}
/*
Sets up overtime label.
@methodtype Command
@pre OvertimeHelper is initialized
@post Overtime label is set up
*/
func setUpOvertimeLabel()
{
let currentDate = NSDate()
overtimeLabel.text = overtimeHelper.getCurrentOvertime(currentDate).description
}
/*
Sets up vacation days label, displaying vacation days left and total vacation days.
@methodtype Command
@pre VacationTimeHelper is initialized
@post Vacation days label is set up
*/
func setUpVacationDaysLabel()
{
let currentDate = NSDate()
let vacationDaysLeft = vacationTimeHelper.getCurrentVacationDaysLeft(currentDate).description
let totalVacationDays = profileDAO.getProfile()!.totalVacationTime
if vacationTimeHelper.isExpiring(currentDate)
{
vacationExpiringWarningLabel.hidden = false
vacationDaysLabel.textColor = UIColor.redColor()
}
else
{
vacationExpiringWarningLabel.hidden = true
vacationDaysLabel.textColor = UIColor.blackColor()
}
vacationDaysLabel.text = "\(vacationDaysLeft) / \(totalVacationDays)"
}
}
|
857bf7dc8a02e47f75b43853e5f2ddb1
| 29.588235 | 101 | 0.666923 | false | false | false | false |
miracl/amcl
|
refs/heads/master
|
version22/swift/BenchtestEC.swift
|
apache-2.0
|
3
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
//
// TestECDH.swift
//
// Created by Michael Scott on 02/07/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
import Foundation
//import amcl // comment out for Xcode
public func BenchtestEC()
{
let pub=rsa_public_key(Int(ROM.FFLEN))
let priv=rsa_private_key(Int(ROM.HFLEN))
var C=[UInt8](repeating: 0,count: RSA.RFS)
var P=[UInt8](repeating: 0,count: RSA.RFS)
var M=[UInt8](repeating: 0,count: RSA.RFS)
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
var RAW=[UInt8](repeating: 0,count: 100)
let rng=RAND()
rng.clean();
for i in 0 ..< 100 {RAW[i]=UInt8(i&0xff)}
rng.seed(100,RAW)
if ROM.CURVETYPE==ROM.WEIERSTRASS {
print("Weierstrass parameterisation")
}
if ROM.CURVETYPE==ROM.EDWARDS {
print("Edwards parameterisation")
}
if ROM.CURVETYPE==ROM.MONTGOMERY {
print("Montgomery representation")
}
if ROM.MODTYPE==ROM.PSEUDO_MERSENNE {
print("Pseudo-Mersenne Modulus")
}
if ROM.MODTYPE==ROM.MONTGOMERY_FRIENDLY {
print("Montgomery Friendly Modulus")
}
if ROM.MODTYPE==ROM.GENERALISED_MERSENNE {
print("Generalised-Mersenne Modulus")
}
if ROM.MODTYPE==ROM.NOT_SPECIAL {
print("Not special Modulus")
}
print("Modulus size \(ROM.MODBITS) bits")
print("\(ROM.CHUNK) bit build")
let gx=BIG(ROM.CURVE_Gx);
var s:BIG
var G:ECP
if ROM.CURVETYPE != ROM.MONTGOMERY
{
let gy=BIG(ROM.CURVE_Gy)
G=ECP(gx,gy)
}
else
{G=ECP(gx)}
let r=BIG(ROM.CURVE_Order)
s=BIG.randomnum(r,rng)
var W=G.mul(r)
if !W.is_infinity() {
print("FAILURE - rG!=O")
fail=true;
}
var start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=G.mul(s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "EC mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
print("Generating \(ROM.FFLEN*ROM.BIGBITS) RSA public/private key pair")
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
RSA.KEY_PAIR(rng,65537,priv,pub)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "RSA gen - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
for i in 0..<RSA.RFS {M[i]=UInt8(i%128)}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
RSA.ENCRYPT(pub,M,&C)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "RSA enc - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
RSA.DECRYPT(priv,C,&P)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "RSA dec - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var cmp=true
for i in 0..<RSA.RFS {
if P[i] != M[i] {cmp=false}
}
if !cmp {
print("FAILURE - RSA decryption")
fail=true;
}
if !fail {
print("All tests pass")
}
}
//BenchtestEC()
|
afcaa2c62bacea1915813908618ccf94
| 27.10559 | 79 | 0.633812 | false | false | false | false |
pawel-sp/PSZCircularPicker
|
refs/heads/master
|
iOS-Example/DragAndDropViewController.swift
|
mit
|
1
|
//
// DragAndDropViewController.swift
// PSZCircularPickerFramework
//
// Created by Paweł Sporysz on 28.10.2014.
// Copyright (c) 2014 Paweł Sporysz. All rights reserved.
//
import UIKit
import PSZCircularPicker
class DragAndDropViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, CollectionViewDragAndDropControllerDelegate {
// MARK: - Outlets
@IBOutlet weak var pickerCollectionView: PickerCollectionView!
@IBOutlet weak var presenterCollectionView: PresenterCollectionView!
// MARK: - Data
var data:[UIColor] = [
UIColor.grayColor(),
UIColor.yellowColor(),
UIColor.orangeColor(),
UIColor.redColor(),
UIColor.greenColor(),
UIColor.magentaColor(),
UIColor.purpleColor(),
UIColor.blueColor(),
UIColor.brownColor(),
UIColor.blackColor()
]
lazy var pickerData:[UIColor] = { return self.data }()
var presenterData:[UIColor] = []
private var pickedColor:UIColor?
var dragAndDropManager:CollectionViewDragAndDropController?
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.dragAndDropManager = CollectionViewDragAndDropController(pickerCollectionView: self.pickerCollectionView, presenterCollectionView: self.presenterCollectionView, containerView: self.view)
self.dragAndDropManager?.delegate = self
self.presenterCollectionView.addGestureRecognizer(UITapGestureRecognizer(target:self, action:"test:"))
}
func test(gr:UITapGestureRecognizer) {
println("\(self.presenterCollectionView.indexPathForItemAtPoint(gr.locationInView(gr.view)))")
}
// MARK: - UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView is PickerCollectionView {
return pickerData.count
} else if collectionView is PresenterCollectionView {
return presenterData.count
} else {
return 0
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if collectionView is PickerCollectionView {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
cell.addGestureRecognizer(self.dragAndDropManager!.dragAndDropLongPressGestureRecognizer)
cell.backgroundColor = self.pickerData[indexPath.row]
return cell
} else if collectionView is PresenterCollectionView {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
cell.backgroundColor = self.presenterData[indexPath.row]
return cell
} else {
return UICollectionViewCell()
}
}
// MARK: - PSZCollectionViewDragAndDropControllerDelegate
func collectionViewDragAndDropController(collectionViewDragAndDropController: CollectionViewDragAndDropController, pickingUpView view: UIView, fromCollectionViewIndexPath indexPath: NSIndexPath) {
UIView.animateWithDuration(0.25, animations: { () -> Void in
view.transform = CGAffineTransformMakeScale(1.35, 1.35)
})
self.pickedColor = self.pickerData.removeAtIndex(indexPath.row)
self.pickerCollectionView.performBatchUpdates({ () -> Void in
self.pickerCollectionView.deleteItemsAtIndexPaths([indexPath])
}, completion: nil)
}
func collectionViewDragAndDropController(collectionViewDragAndDropController: CollectionViewDragAndDropController, dragginView view: UIView, pickedInLocation: CGPoint) {
//correct picked view origin after scale by 1.35
var origin = view.frame.origin
var size = view.frame.size
origin.x -= abs(pickedInLocation.x - size.width/2)*0.35
origin.y -= abs(pickedInLocation.y - size.height/2)*0.35
view.frame.origin = origin
}
func collectionViewDragAndDropController(collectionViewDragAndDropController: CollectionViewDragAndDropController, droppedView view: UIView, fromCollectionViewIndexPath fromIndexPath: NSIndexPath, toCollectionViewIndexPath toIndexPath: NSIndexPath, isCanceled canceled: Bool) {
if canceled {
self.pickerData.insert(self.pickedColor!, atIndex: fromIndexPath.row)
self.pickerCollectionView.performBatchUpdates({ () -> Void in
self.pickerCollectionView.insertItemsAtIndexPaths([fromIndexPath])
}, completion:nil)
let orginalCell = self.pickerCollectionView.cellForItemAtIndexPath(fromIndexPath)
let absoluteOrginalCellFrame = self.pickerCollectionView.convertRect(orginalCell!.frame, toView: self.view)
UIView.animateWithDuration(0.25, animations: { () -> Void in
view.frame = absoluteOrginalCellFrame
view.alpha = 0
}, completion: { (_) -> Void in
view.removeFromSuperview()
})
} else {
println("\(toIndexPath)")
var targetIndexPath = toIndexPath
if presenterData.count == 0 { targetIndexPath = NSIndexPathZero }
self.presenterData.insert(self.pickedColor!, atIndex: targetIndexPath.row)
self.presenterCollectionView.insertItemsAtIndexPaths([targetIndexPath])
var targetFrame = CGRectZero
if let insertedCell = self.presenterCollectionView.cellForItemAtIndexPath(targetIndexPath) {
targetFrame = self.view.convertRect(insertedCell.frame, fromView: self.presenterCollectionView)
}
UIView.animateWithDuration(0.25, animations: { () -> Void in
view.frame = targetFrame
view.alpha = 0
}, completion: { (_) -> Void in
view.removeFromSuperview()
})
}
}
}
|
7f317da3d201dd5cc8e29943008b995f
| 42.202797 | 281 | 0.679346 | false | false | false | false |
akrio714/Wbm
|
refs/heads/master
|
Wbm/Component/Calendar/CalendarView.swift
|
apache-2.0
|
1
|
//
// CalendarView.swift
// Wbm
//
// Created by akrio on 2017/7/21.
// Copyright © 2017年 akrio. All rights reserved.
//
import UIKit
import FSCalendar
import SwiftDate
import RxCocoa
import RxSwift
@IBDesignable
class CalendarView: UIView {
@IBOutlet weak var userHeaderButton: UserHeaderButton!
@IBOutlet var contView: UIView!
@IBOutlet weak var calendarView: FSCalendar!
@IBOutlet weak var calendarHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var arrowImage: BaseImageView!
@IBOutlet weak var dateTitleLabel: BaseLabel!
@IBOutlet weak var backButton: UIButton!
let selected:Variable<DateInRegion?> = Variable(nil)
var days:[CalendarDayModel] = [] {
didSet {
self.calendarView.reloadData()
if let date = days.first?.date.absoluteDate {
self.calendarView.select(date)
selected.value = date.inRegion()
self.dateTitleLabel.text = date.inRegion().monthName
}
}
}
lazy var doneImage:UIImage? = CalendarDayModel.DayType.success.image()
lazy var clearImage:UIImage? = CalendarDayModel.DayType.fail.image()
lazy var circleImage:UIImage? = CalendarDayModel.DayType.wait.image()
override init(frame: CGRect) {
super.init(frame: frame)
initFromXIB()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initFromXIB()
}
@IBAction func dateClick(_ sender: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.3){ [unowned self] in
self.arrowImage.transform = self.arrowImage.transform.rotated(by: .pi)
}
self.calendarView.setScope(self.calendarView.scope == .month ? .week : .month, animated: true)
}
func initFromXIB() {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CalendarView", bundle: bundle)
contView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
contView.frame = bounds
self.addSubview(contView)
calendarView.today = nil
calendarView.clipsToBounds = true
days = testData()
}
func testData() -> [CalendarDayModel] {
let day1 = CalendarDayModel(date: DateInRegion() + 1.days, type: .fail)
let day2 = CalendarDayModel(date: DateInRegion() + 2.days, type: .success)
let day3 = CalendarDayModel(date: DateInRegion() + 3.days, type: .wait)
let day4 = CalendarDayModel(date: DateInRegion() + 22.days, type: .success)
let day5 = CalendarDayModel(date: DateInRegion() + 13.days, type: .wait)
let day6 = CalendarDayModel(date: DateInRegion() - 2.days, type: .success)
let day7 = CalendarDayModel(date: DateInRegion() - 3.days, type: .wait)
return [day1,day2,day3,day4,day5,day6,day7].sorted{ $0.date < $1.date }
}
}
extension CalendarView: FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance {
/// 设置日历下方图片
///
/// - Parameters:
/// - calendar: 日历
/// - date: 日期
/// - Returns: 显示的图片
func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? {
return days.first{ $0.date.isInSameDayOf(date: date.inRegion()) }?.type.image()
}
/// 日历可滑动最小时间
///
/// - Parameter calendar: 日历
/// - Returns: 最小时间
func minimumDate(for calendar: FSCalendar) -> Date {
return days.first?.date.absoluteDate ?? (DateInRegion() - 6.months).absoluteDate
}
/// 日历可滑动最大时间
///
/// - Parameter calendar: 日历
/// - Returns: 最大时间
func maximumDate(for calendar: FSCalendar) -> Date {
return days.last?.date.absoluteDate ?? (DateInRegion() + 6.months).absoluteDate
}
/// 周月历切换时触发方法
///
/// - Parameters:
/// - calendar: 日历
/// - bounds: 大小变化
/// - animated: 是否有动画
func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
self.calendarHeightConstraint.constant = bounds.height
self.superview?.layoutIfNeeded()
print(bounds)
}
/// 日历是否可被选中
///
/// - Parameters:
/// - calendar: 日历
/// - date: 日期
/// - monthPosition: <#monthPosition description#>
/// - Returns: 是否可被选中
func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool {
return days.contains {$0.date.isInSameDayOf(date: date.inRegion()) }
}
/// 月份发生改变
///
/// - Parameter calendar: 日历
func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
self.dateTitleLabel.text = calendarView.currentPage.inRegion().monthName
UIView.animate(withDuration: 0.3){
self.layoutIfNeeded()
}
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? {
guard (days.contains {$0.date.isInSameDayOf(date: date.inRegion()) }) else {
return appearance.titlePlaceholderColor
}
return nil
}
/// 日历被选中时圆圈的颜色
///
/// - Parameters:
/// - calendar: 日历
/// - appearance: 日历一些配置
/// - date: 日期
/// - Returns: 选中后颜色
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillSelectionColorFor date: Date) -> UIColor? {
return days.first{ $0.date.isInSameDayOf(date: date.inRegion()) }?.type.color()
}
/// 日历选中事件
///
/// - Parameters:
/// - calendar: <#calendar description#>
/// - date: <#date description#>
/// - monthPosition: <#monthPosition description#>
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
self.selected.value = date.inRegion()
}
}
|
e3c52fedd2d4418860103ccae3cb3023
| 35.78481 | 123 | 0.630764 | false | false | false | false |
raphaelhanneken/iconizer
|
refs/heads/master
|
Iconizer/Models/ImageSet.swift
|
mit
|
1
|
//
// ImageSet.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//
import Cocoa
class ImageSet: Codable {
//scale of input image
static let inputScale: CGFloat = 3
let idiom: String
let scale: AssetScale
var filename: String {
return "image@\(scale.rawValue).png"
}
private enum ReadKeys: String, CodingKey {
case idiom
case scale
}
private enum WriteKeys: String, CodingKey {
case idiom
case scale
case filename
}
init(idiom: String, scale: AssetScale) {
self.idiom = idiom
self.scale = scale
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ReadKeys.self)
let idiom = try container.decode(String.self, forKey: .idiom)
guard let scale = AssetScale(rawValue: try container.decode(String.self, forKey: .scale)) else {
throw AssetCatalogError.invalidFormat(format: .scale)
}
self.idiom = idiom
self.scale = scale
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: WriteKeys.self)
try container.encode(idiom, forKey: .idiom)
try container.encode(scale.rawValue, forKey: .scale)
try container.encode(filename, forKey: .filename)
}
}
extension ImageSet: Asset {
static let resourcePrefix = "ImageSet"
static func directory(named: String) -> String {
return "\(Constants.Directory.imageSet)/\(named).\(Constants.AssetExtension.imageSet)"
}
func save(_ image: [ImageOrientation: NSImage], aspect: AspectMode?, to url: URL) throws {
guard let image = image[.all] else {
throw AssetCatalogError.missingImage
}
let url = url.appendingPathComponent(filename, isDirectory: false)
let coef = CGFloat(scale.value) / ImageSet.inputScale
let size = NSSize(width: ceil(image.size.width * coef), height: ceil(image.size.height * coef))
guard let resized = image.resize(toSize: size, aspectMode: aspect ?? .fit) else {
throw AssetCatalogError.rescalingImageFailed
}
try resized.savePng(url: url)
}
}
|
ca1589d1a23408e8f34bf5071e915d5e
| 27.615385 | 104 | 0.642025 | false | false | false | false |
avario/ChainKit
|
refs/heads/master
|
ChainKit/ChainKit/UIImageView+ChainKit.swift
|
mit
|
1
|
//
// UIImageView+ChainKit.swift
// ChainKit
//
// Created by Avario.
//
import UIKit
public extension UIImageView {
public func image(_ image: UIImage?) -> Self {
self.image = image
return self
}
public func highlightedImage(_ highlightedImage: UIImage?) -> Self {
self.highlightedImage = highlightedImage
return self
}
public func isHighlighted(_ isHighlighted: Bool) -> Self {
self.isHighlighted = isHighlighted
return self
}
public func animationImages(_ animationImages: [UIImage]?) -> Self {
self.animationImages = animationImages
return self
}
public func highlightedAnimationImages(_ highlightedAnimationImages: [UIImage]?) -> Self {
self.highlightedAnimationImages = highlightedAnimationImages
return self
}
public func animationDuration(_ animationDuration: TimeInterval) -> Self {
self.animationDuration = animationDuration
return self
}
public func animationRepeatCount(_ animationRepeatCount: Int) -> Self {
self.animationRepeatCount = animationRepeatCount
return self
}
}
|
95306a644edf5451d72d2982d845959b
| 24.425532 | 94 | 0.648536 | false | false | false | false |
codefellows/sea-b23-iOS
|
refs/heads/master
|
TwitterClone/HomeTimeLineViewController.swift
|
mit
|
1
|
//
// HomeTimeLineViewController.swift
// TwitterClone
//
// Created by Bradley Johnson on 10/6/14.
// Copyright (c) 2014 Code Fellows. All rights reserved.
//
import UIKit
import Accounts
import Social
class HomeTimeLineViewController: UIViewController, UITableViewDataSource, UIApplicationDelegate {
@IBOutlet weak var tableView: UITableView!
var tweets : [Tweet]?
var twitterAccount : ACAccount?
var networkController : NetworkController!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "TweetCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "TWEET_CELL")
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
self.networkController = appDelegate.networkController
self.networkController.fetchHomeTimeLine { (errorDescription : String?, tweets : [Tweet]?) -> (Void) in
if errorDescription != nil {
//alert the user that something went wrong
} else {
self.tweets = tweets
self.tableView.reloadData()
}
}
println("Hello")
if let path = NSBundle.mainBundle().pathForResource("tweet", ofType: "json") {
var error : NSError?
let jsonData = NSData(contentsOfFile: path)
self.tweets = Tweet.parseJSONDataIntoTweets(jsonData)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.tweets != nil {
return self.tweets!.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//step 1 dequeue the cell
let cell = tableView.dequeueReusableCellWithIdentifier("TWEET_CELL", forIndexPath: indexPath) as TweetCell
//step 2 figure out which model object youre going to use to configure the cell
//this is where we would grab a reference to the correct tweet and use it to configure the cell
let tweet = self.tweets?[indexPath.row]
cell.tweetLabel.text = tweet?.text
if tweet?.avatarImage != nil {
cell.avatarImageView.image = tweet?.avatarImage
} else {
self.networkController.downloadUserImageForTweet(tweet!, completionHandler: { (image) -> (Void) in
let cellForImage = self.tableView.cellForRowAtIndexPath(indexPath) as TweetCell?
cellForImage?.avatarImageView.image = image
})
}
//step 3 return the cell
return cell
}
}
|
33e36f61af703c7b38db1549cfe3e21e
| 36.040541 | 132 | 0.631521 | false | false | false | false |
psharanda/vmc2
|
refs/heads/master
|
4. MVVM/MVVM/MainViewModel.swift
|
mit
|
1
|
//
// Created by Pavel Sharanda on 17.11.16.
// Copyright © 2016 psharanda. All rights reserved.
//
import Foundation
class MainViewModel: MainViewModelProtocol {
weak var delegate: MainViewModelDelegate?
weak var routingDelegate: MainViewModelRoutingDelegate?
var loading: Bool = false {
didSet {
delegate?.loadingWasChanged(viewModel: self)
}
}
var text: String? {
didSet {
delegate?.textWasChanged(viewModel: self)
}
}
let textLoader: TextLoaderProtocol
init(textLoader: TextLoaderProtocol) {
self.textLoader = textLoader
}
func loadButtonClicked() {
loading = true
text = nil
self.textLoader.loadText {
self.loading = false
self.text = $0
}
}
func detailsClicked() {
routingDelegate?.showDetails(viewModel: self)
}
}
|
15893af2a094a36ef4c28bc45dc79f76
| 20.860465 | 59 | 0.592553 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothGAP/GAP3DInformation.swift
|
mit
|
1
|
//
// GAP3DInformation.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
The 3DD shall include a section in its EIR data providing 3D Synchronization Profile
- Note: Future versions of this EIR data may be extended to carry additional bytes in the Profile specific 3D Information data section. Therefore, 3DG compliant with this version of the Profile specification shall ignore any additional data beyond what is specified in Table 5.2, if present.
*/
@frozen
public struct GAP3DInformation: GAPData, Equatable {
public static var dataType: GAPDataType { return .informationData3D }
/**
GAP 3D Information Flags
• Association Notification: (Byte 2, bit 0)
0 – Not supported
1 – Supported
• Battery Level Reporting: (Byte 2, bit 1)
0 – Not supported
1 – Supported
• Send Battery Level Report on Start-up Synchronization: (Byte 2, bit 2)
0 – 3DD requests 3DG to not send a 3DG Connection Announcement Message with Battery Level Report on Start-up Synchronization.
1 – 3DD requests 3DG to send a 3DG Connection Announcement Message with Battery Level Report on Start-up Synchronization.
- Note: The value shall be set to 0 if the Battery Level Reporting is set to 0.
• Factory Test Mode: (Byte 2, bit 7)
0 – normal operating mode
1 – vendor-defined factory test mode
• Path Loss Threshold
In dB. Maximum allowable path attenuation from 3DD to 3DG.
Greater attenuation than this number will inform the 3DG that it is too far away and to look for another 3DD.
*/
public var flags: BitMaskOptionSet<Flag>
/**
Path Loss Threshold
In dB. Maximum allowable path attenuation from 3DD to 3DG.
Greater attenuation than this number will inform the 3DG that it is too far away and to look for another 3DD.
*/
public var pathLossThreshold: UInt8
public init(flags: BitMaskOptionSet<Flag> = 0,
pathLossThreshold: UInt8 = 0) {
self.flags = flags
self.pathLossThreshold = pathLossThreshold
}
}
public extension GAP3DInformation {
init?(data: Data) {
guard data.count == 2
else { return nil }
let flags = BitMaskOptionSet<Flag>(rawValue: data[data.startIndex])
let pathLossThreshold = data[1]
self.init(flags: flags, pathLossThreshold: pathLossThreshold)
}
func append(to data: inout Data) {
data += flags.rawValue
data += pathLossThreshold
}
var dataLength: Int {
return 2
}
}
// MARK: - Supporting Types
public extension GAP3DInformation {
/// GAP 3D Information Flag
enum Flag: UInt8, BitMaskOption {
/// Association Notification
case associationNotification = 0b01
/// Battery Level Reporting
case batteryLevelReporting = 0b10
/// Send Battery Level Report on Start-up Synchronization
case sendBatteryLevelOnStartUp = 0b100
/// Factory Test Mode
case factoryTestMode = 0b10000000
public static let allCases: [Flag] = [
.associationNotification,
.batteryLevelReporting,
.sendBatteryLevelOnStartUp,
.factoryTestMode
]
}
}
|
7d7cf9cd8bd68e5e7d82d90921cf07e6
| 29.356522 | 292 | 0.644801 | false | false | false | false |
AzenXu/Memo
|
refs/heads/master
|
Memo/Common/Views/SimpleCustomViews.swift
|
mit
|
1
|
//
// SimpleCustomViews.swift
// JFoundation
//
// Created by XuAzen on 16/7/4.
// Copyright © 2016年 st. All rights reserved.
//
import Foundation
import UIKit
//MARK:- Custom ContentSizeChange Element
public typealias UTravWebViewContentSizeChangeCallBack = (CGSize) -> ()
public class UTravWebView: UIWebView {
var lastContentSize = CGSizeZero
override public init(frame: CGRect) {
super.init(frame: frame)
scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var contentSizeChangeCallBack :UTravWebViewContentSizeChangeCallBack?
public func setContentSizeCallBack(contentSizeChange :UTravWebViewContentSizeChangeCallBack) {
contentSizeChangeCallBack = contentSizeChange
}
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "contentSize" {
let contentSize = change!["new"]!.CGSizeValue()
if contentSize != lastContentSize {
lastContentSize = contentSize
if let contentSizeChangeCallBack = contentSizeChangeCallBack {
contentSizeChangeCallBack(contentSize)
}
}
}
}
deinit {
scrollView.removeObserver(self, forKeyPath: "contentSize")
}
}
public class WebCollectionCell: BasicCollectionCell {
private var webView: UTravWebView = UTravWebView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 300))
private var request: NSURLRequest?
private var contentSizeCallBack: ((CGSize) -> ())?
public override init(frame: CGRect) {
super.init(frame: frame)
makeupViews()
}
public func setContentSizeCallBack(callBack: CGSize -> ()) {
self.contentSizeCallBack = callBack
webView.setContentSizeCallBack { (newSize) in
guard let contentSizeCallBack = self.contentSizeCallBack else {return}
contentSizeCallBack(newSize)
}
}
/**
防止每次reloadData都重新加载web
*/
public func setRequest(request: NSURLRequest) {
if self.request != request {
self.request = request
loadRequest(request)
}
}
private func loadRequest(request: NSURLRequest) {
webView.loadRequest(request)
}
private func makeupViews() {
webView.then { (web) in
addSubview(web)
web.snp_remakeConstraints(closure: { (make) in
make.left.equalTo(0)
make.right.equalTo(0)
make.bottom.equalTo(0)
make.top.equalTo(0)
})
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public class UICollectionViewWithContentSizeCallBack: UICollectionView {
private var lastContentSize = CGSizeZero
private var contentSizeChangeCallBack :UTravWebViewContentSizeChangeCallBack?
public func setContentSizeCallBack(contentSizeChange :UTravWebViewContentSizeChangeCallBack) {
contentSizeChangeCallBack = contentSizeChange
}
override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "contentSize" {
let contentSize = change!["new"]!.CGSizeValue()
if contentSize != lastContentSize {
lastContentSize = contentSize
if let contentSizeChangeCallBack = contentSizeChangeCallBack {
contentSizeChangeCallBack(contentSize)
}
}
}
}
deinit {
self.removeObserver(self, forKeyPath: "contentSize")
}
}
//MARK:- Basic UI Element
public class CustomColorButton: UIButton {
public var selectedBorderColor: UIColor?
public var unSelectedBorderColor: UIColor?
override public var selected: Bool {
didSet {
if self.selected {
if let selectedBorderColor = self.selectedBorderColor {
self.layer.borderColor = selectedBorderColor.CGColor
}
} else {
if let unSelectedBorderColor = self.unSelectedBorderColor {
self.layer.borderColor = unSelectedBorderColor.CGColor
}
}
}
}
public var hightlightedBackgroundColor: UIColor?
public var normalBackgroundColor: UIColor?
override public var highlighted: Bool {
didSet {
if highlighted {
if let hightlightedBackgroundColor = self.hightlightedBackgroundColor {
backgroundColor = hightlightedBackgroundColor
}
} else {
if let normalBackgroundColor = self.normalBackgroundColor {
backgroundColor = normalBackgroundColor
}
}
}
}
public var disableBackgroundColor: UIColor?
public var disableTextColor: UIColor?
public var enableBackgroundColor: UIColor?
public var enableTextColor: UIColor?
public var clickCallBack: ((button: UIButton)->())?
override public var enabled: Bool {
didSet {
if enabled {
if let enableBackgroundColor = self.enableBackgroundColor {
backgroundColor = enableBackgroundColor
}
if let enableTextColor = self.enableTextColor {
setTitleColor(enableTextColor, forState: UIControlState.Normal)
}
} else {
if let disableBackgroundColor = self.disableBackgroundColor {
backgroundColor = disableBackgroundColor
}
if let disableTextColor = self.disableTextColor {
setTitleColor(disableTextColor, forState: UIControlState.Normal)
}
}
}
}
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
clickCallBack?(button: self)
}
}
public class RightIconButton: CustomColorButton {
override public func layoutSubviews() {
super.layoutSubviews()
let titleL = titleLabel!
let imageV = imageView!
if titleL.x > imageV.x {
titleL.x = imageV.x
imageV.x = titleL.width + titleL.x + 7
}
}
}
|
183b058778e9ea706b92bc39cb4fe67c
| 32.892019 | 164 | 0.623026 | false | false | false | false |
rsyncOSX/RsyncOSX
|
refs/heads/master
|
RsyncOSX/Running.swift
|
mit
|
1
|
//
// Running.swift
// RsyncOSX
//
// Created by Thomas Evensen on 07.02.2018.
// Copyright © 2018 Thomas Evensen. All rights reserved.
//
import AppKit
import Foundation
final class Running {
let rsyncOSX = "no.blogspot.RsyncOSX"
let rsyncOSXsched = "no.blogspot.RsyncOSXsched"
var rsyncOSXisrunning: Bool = false
var rsyncOSXschedisrunning: Bool = false
var menuappnoconfig: Bool = true
func verifyrsyncosxsched() -> Bool {
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: (SharedReference.shared.pathrsyncosxsched ?? "/Applications/") +
SharedReference.shared.namersyncosssched) else { return false }
return true
}
@discardableResult
init() {
// Get all running applications
let workspace = NSWorkspace.shared
let applications = workspace.runningApplications
let rsyncosx = applications.filter { $0.bundleIdentifier == self.rsyncOSX }
let rsyncosxschde = applications.filter { $0.bundleIdentifier == self.rsyncOSXsched }
if rsyncosx.count > 0 {
rsyncOSXisrunning = true
} else {
rsyncOSXisrunning = false
}
if rsyncosxschde.count > 0 {
rsyncOSXschedisrunning = true
SharedReference.shared.menuappisrunning = true
} else {
rsyncOSXschedisrunning = false
SharedReference.shared.menuappisrunning = false
}
}
}
|
37698285e682879c15e83454223c95e9
| 31.173913 | 109 | 0.65473 | false | false | false | false |
segej87/ecomapper
|
refs/heads/master
|
iPhone/EcoMapper/EcoMapper/PhotoViewController.swift
|
gpl-3.0
|
2
|
//
// PhotoViewController.swift
// EcoMapper
//
// Created by Jon on 6/21/16.
// Copyright © 2016 Sege Industries. All rights reserved.
//
import UIKit
import CoreLocation
import Photos
class PhotoViewController: RecordViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
// IB Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var accessTextField: UITextField!
@IBOutlet weak var notesTextField: UITextView!
@IBOutlet weak var tagTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var gpsAccView: UILabel!
@IBOutlet weak var accessPickerButton: UIButton!
@IBOutlet weak var tagPickerButton: UIButton!
@IBOutlet weak var gpsStabView: UILabel!
@IBOutlet weak var gpsReportArea: UIView!
// The path to the photo on the device's drive
var photoURL: URL?
var media: Media?
var medOutName: String?
// MARK: Initialization
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: UI Methods
override func setUpFields() {
if mode == "old" {
if let record = record {
navigationItem.title = "Editing Photo"
nameTextField.text = record.props["name"] as? String
accessTextField.text = (record.props["access"] as? [String])?.joined(separator: ", ")
accessArray = record.props["access"] as! [String]
photoURL = URL(fileURLWithPath: record.props["filepath"] as! String)
selectedImage = record.photo
photoImageView.image = selectedImage
photoImageView.isUserInteractionEnabled = false
notesTextField.text = record.props["text"] as? String
tagTextField.text = (record.props["tags"] as? [String])?.joined(separator: ", ")
tagArray = record.props["tags"] as! [String]
dateTime = record.props["datetime"] as? String
userLoc = record.coords
gpsReportArea.isHidden = true
}
}
// Fill data into text fields
accessTextField.text = accessArray.joined(separator: ", ")
tagTextField.text = tagArray.joined(separator: ", ")
// Add border to text view
self.notesTextField.layer.borderWidth = 0.5
self.notesTextField.layer.cornerRadius = 10
self.notesTextField.layer.borderColor = UIColor.init(red: 200/255.0, green: 199/255.0, blue: 204/255.0, alpha: 1.0).cgColor
// Handle text fields' user input through delegate callbacks.
nameTextField.delegate = self
accessTextField.delegate = self
tagTextField.delegate = self
// Handle the notes field's user input through delegate callbacks.
notesTextField.delegate = self
}
// MARK: Camera alert
func noCamera() {
if #available(iOS 8.0, *) {
let alertVC = UIAlertController(title: "No Camera", message: "Sorry, this device doesn't have a camera", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertVC.addAction(okAction)
present(alertVC, animated: true, completion: nil)
} else {
let alertVC = UIAlertView(title: "No Camera", message: "Sorry, this device doesn't have a camera", delegate: self, cancelButtonTitle: "OK")
alertVC.show()
}
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let outImage = info[UIImagePickerControllerOriginalImage] as? UIImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
// Segue to the crop view
self.performSegue(withIdentifier: "CropSegue", sender: outImage)
}
// MARK: Location methods
override func updateGPS() {
if gpsAcc == -1 {
gpsAccView.text = "Locking"
gpsAccView.textColor = UIColor.red
} else {
gpsAccView.text = String(format: "%.1f m", abs(gpsAcc))
if gpsAcc <= minGPSAccuracy! {
gpsAccView.textColor = UIColor.green
} else {
gpsAccView.textColor = UIColor.red
}
}
if gpsStab == -1 {
gpsStabView.text = "Locking"
gpsStabView.textColor = UIColor.red
} else {
gpsStabView.text = String(format: "%.1f m", abs(gpsStab))
if gpsStab <= minGPSStability! {
gpsStabView.textColor = UIColor.green
} else {
gpsStabView.textColor = UIColor.red
}
}
}
// MARK: Navigation
@IBAction func cancel(_ sender: UIBarButtonItem) {
cancelView()
}
// This method lets you configure a view controller before it's presented.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
locationManager.stopUpdatingLocation()
if segue.identifier == "CropSegue" {
let secondVC = segue.destination as! CropImageViewController
if let imageOut = sender as? UIImage {
secondVC.inputImage = imageOut
}
}
// If the add access button was pressed, present the item picker with an access item type
if sender is UIButton && accessPickerButton === (sender as! UIButton) {
let secondVC = segue.destination as! ListPickerViewController
secondVC.itemType = "access"
// Send previous access levels to ListPicker
if accessTextField.text != "" {
for a in accessArray {
secondVC.selectedItems.append(a)
}
}
}
// If the add tags button was pressed, present the item picker with a tags item type
if sender is UIButton && tagPickerButton === (sender as! UIButton) {
let secondVC = segue.destination as! ListPickerViewController
secondVC.itemType = "tags"
// Send previous tags to ListPicker
if tagTextField.text != "" {
for t in tagArray {
secondVC.selectedItems.append(t)
}
}
}
}
// Handle returns from list pickers
@IBAction func unwindFromListPicker(_ segue: UIStoryboardSegue) {
// The view controller that initiated the segue
let secondVC : ListPickerViewController = segue.source as! ListPickerViewController
// The type of the view controller that initiated the segue
let secondType = secondVC.itemType
// The text field that should be modified by the results of the list picker
var targetField : UITextField?
// Set the target text field based on the second view controller's type
switch secondType! {
case "tags":
targetField = tagTextField
break
case "access":
targetField = accessTextField
break
default:
targetField = nil
}
// Handle changes to User Variables due to the list picker activity
handleListPickerResult(secondType: secondType!, secondVC: secondVC)
targetField!.text = secondVC.selectedItems.joined(separator: ", ")
}
@IBAction func unwindFromCropView(_ segue: UIStoryboardSegue) {
let secondVC = segue.source as! CropImageViewController
if let outImage = secondVC.outputImage {
selectedImage = outImage
// Set the aspect ratio of the image in the view
photoImageView.contentMode = .scaleAspectFit
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Set the name of the photo
medOutName = "Photo_\(dateTime!.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: ":", with: "").replacingOccurrences(of: " ", with: "_")).jpg"
// Set path of photo to be saved
photoURL = UserVars.PhotosURL.appendingPathComponent(medOutName!)
}
}
@IBAction func captureImage(_ sender: UITapGestureRecognizer) {
if PHPhotoLibrary.authorizationStatus() == .notDetermined {
PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
}
startImageCapture()
}
func requestAuthorizationHandler(status: PHAuthorizationStatus)
{
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized
{
self.startImageCapture()
}
else
{
self.dismiss(animated: true, completion: nil)
}
}
func startImageCapture() {
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
// Create a controller for handling the camera action
let imageTakerController = UIImagePickerController()
// Set camera options
imageTakerController.allowsEditing = false
imageTakerController.sourceType = .camera
imageTakerController.cameraCaptureMode = .photo
imageTakerController.modalPresentationStyle = .fullScreen
// Make sure ViewController is notified when the user takes an image.
imageTakerController.delegate = self
present(imageTakerController, animated: true, completion: nil)
} else {
noCamera()
}
}
// MARK: Actions
@IBAction func setDefaultNameText(_ sender: UIButton) {
nameTextField.text = "Photo" + " - " + dateTime!
}
@IBAction override func attemptSave(_ sender: AnyObject) {
print("Saving record?: \(saveRecord())")
if saveRecord() {
if mode == "new" {
// Set the media reference to be passed to NotebookViewController after the unwind segue.
media = Media(name: medOutName!, path: photoURL, marked: false)
//Save the photo
// Create an NSCoded photo object
let outPhoto = NewPhoto(photo: selectedImage)
// Save the photo to the photos directory
savePhoto(outPhoto!)
}
self.performSegue(withIdentifier: "exitSegue", sender: self)
}
}
// MARK: NSCoding
func savePhoto(_ photo: NewPhoto) {
if !FileManager.default.fileExists(atPath: UserVars.PhotosURL.path) {
do {
try FileManager.default.createDirectory(atPath: UserVars.PhotosURL.path, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
}
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(photo, toFile: photoURL!.path)
if !isSuccessfulSave {
NSLog("Failed to save photo...")
} else {
NSLog("Saving photo to \(photoURL!.path)")
}
}
// MARK: Helper methods
override func checkRequiredData() -> Bool {
var errorString : String?
let dateCheck = dateTime != nil && dateTime != ""
let locCheck = mode == "old" || (userOverrideStale || checkLocationOK())
if !(nameTextField.text != nil && nameTextField.text != "") {
errorString = "The Name field is required."
} else if !(accessArray.count > 0) {
errorString = "Select at least one Access Level."
} else if !(photoURL?.absoluteString != nil && photoURL?.absoluteString != "") {
errorString = "Take a photo."
} else if !(tagArray.count > 0) {
errorString = "Select at least one Tag."
}
if let error = errorString {
if #available(iOS 8.0, *) {
let alertVC = UIAlertController(title: "Missing required data.", message: error, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertVC.addAction(okAction)
present(alertVC, animated: true, completion: nil)
} else {
let alertVC = UIAlertView(title: "Missing required data.", message: error, delegate: self, cancelButtonTitle: "OK")
alertVC.show()
}
}
return errorString == nil && dateCheck && locCheck
}
override func setItemsOut() -> [String : AnyObject] {
let name = nameTextField.text ?? ""
let urlOut = photoURL!.absoluteString
return ["name": name as AnyObject, "tags": tagArray as AnyObject, "datatype": "photo" as AnyObject, "datetime": dateTime! as AnyObject, "access": accessArray as AnyObject, "accuracy": gpsAcc as AnyObject, "text": notesTextField.text as AnyObject, "filepath": urlOut as AnyObject] as [String:AnyObject]
}
}
|
cc96489eb0d65fefeff0f727c83e5a6d
| 36.284182 | 309 | 0.587186 | false | false | false | false |
manfengjun/KYMart
|
refs/heads/master
|
Section/Product/Detail/View/KYPropertyFootView.swift
|
mit
|
1
|
//
// KYPropertyFootView.swift
// KYMart
//
// Created by jun on 2017/6/8.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
import PPNumberButtonSwift
class KYPropertyFootView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var numberButton: PPNumberButton!
var CountResultClosure: ResultClosure? // 闭包
override init(frame: CGRect) {
super.init(frame: frame)
contentView = Bundle.main.loadNibNamed("KYPropertyFootView", owner: self, options: nil)?.first as! UIView
contentView.frame = self.bounds
addSubview(contentView)
awakeFromNib()
}
func reloadMaxValue(){
numberButton.maxValue = (SingleManager.instance.productBuyInfoModel?.good_buy_store_count)!
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
numberButton.shakeAnimation = true
numberButton.minValue = 1
numberButton.maxValue = (SingleManager.instance.productBuyInfoModel?.good_buy_store_count)!
numberButton.borderColor(UIColor.hexStringColor(hex: "#666666"))
numberButton.numberResult { (number) in
if let count = Int(number){
self.CountResultClosure?(count)
}
}
}
/**
加减按钮的响应闭包回调
*/
func countResult(_ finished: @escaping ResultClosure) {
CountResultClosure = finished
}
}
|
234289398882af99970474a4d288690c
| 30.229167 | 113 | 0.657105 | false | false | false | false |
BruceFight/JHB_HUDView
|
refs/heads/master
|
JHB_HUDView/JHB_HUDDiyManager.swift
|
mit
|
1
|
/****************** JHB_HUDDiyManager.swift *********************/
/******* (JHB) ************************************************/
/******* Created by Leon_pan on 16/8/15. ***********************/
/******* Copyright © 2016年 CoderBala. All rights reserved.*****/
/****************** JHB_HUDDiyManager.swift *********************/
import UIKit
class JHB_HUDDiyManager: JHB_HUDPublicManager {
// MARK: parameters
/*核心视图*//*Core View Part*/
var coreView = JHB_HUDDiyProgressView()
/*透明背景*//*Clear Background*/
var bgClearView = UIView()
// MARK: - Interface
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
self.setUp()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUp()
}
func setUp() {
self.setSubViews()
self.addSubview(self.bgClearView)
self.addSubview(self.coreView)
PreOrientation = UIDevice.current.orientation
InitOrientation = UIDevice.current.orientation
self.registerDeviceOrientationNotification()
if PreOrientation != .portrait {
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_HUDTopVcCannotRotated"), object: self.PreOrientation.hashValue, userInfo: nil)
}
}
func setSubViews() {
self.bgClearView = UIView.init()
self.bgClearView.backgroundColor = UIColor.clear
self.coreView = JHB_HUDDiyProgressView.init()
self.coreView.sizeToFit()
self.coreView.layer.cornerRadius = 10
self.coreView.layer.masksToBounds = true
self.coreView.backgroundColor = UIColor.black
self.coreView.alpha = 0
self.resetSubViews()
}
func resetSubViews() {
self.bgClearView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 70) / 2, y: (SCREEN_HEIGHT - 70) / 2, width: 70, height: 70)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 + 60)
}
// MARK: - 隐藏(Hidden❤️Type:dissolveToTop)
public func hideProgress() {// DEFAULT
self.perform(#selector(JHB_HUDDiyManager.hideWithAnimation), with: self, afterDelay: 0.6)
}
override func hideHud() {
self.hideProgress()
}
override func ifBeMoved(bool: Bool) {
let longTap = UILongPressGestureRecognizer.init(target: self, action: #selector(JHB_HUDDiyManager.hideHud))
self.isUserInteractionEnabled = bool
self.addGestureRecognizer(longTap)
}
}
extension JHB_HUDDiyManager{
// MARK: - 1⃣️单纯显示DIY进程中(Just Show In DIY-Progress)
public func showDIYProgressWithType(_ img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType,ifCustom:Bool,to:UIView) {
self.coreView.diyShowImage = img
self.coreView.diySpeed = diySpeed
self.coreView.diyHudType = diyHudType.hashValue
self.type = HudType.hashValue
self.showDIYProgressWithHUDType(HudType,ifCustom:ifCustom,to:to)
}
// MARK: - 2⃣️单纯显示DIY进程中(Just Show In DIY-Progress:❤️播放图片数组)
public func showDIYProgressAnimated(_ imgsName:NSString,imgsNumber:NSInteger,diySpeed:TimeInterval, HudType:HUDType,ifCustom:Bool,to:UIView){
self.coreView.diyShowImage = imgsName
self.coreView.diyImgsNumber = imgsNumber
self.coreView.diySpeed = diySpeed
self.type = HudType.hashValue
self.showDIYProgressWithHUDType(HudType,ifCustom:ifCustom,to:to)
}
fileprivate func showDIYProgressWithHUDType(_ HudType:HUDType,ifCustom:Bool,to:UIView) {
switch HudType {
case .kHUDTypeDefaultly:
self.EffectShowProgressAboutTopAndBottom(.kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to)
case .kHUDTypeShowImmediately:
self.EffectShowProgressAboutStablePositon(.kHUDTypeShowImmediately,ifCustom:ifCustom,to:to)
case .kHUDTypeShowSlightly:
self.EffectShowProgressAboutStablePositon(.kHUDTypeShowSlightly,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromBottomToTop:
self.EffectShowProgressAboutTopAndBottom(.kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromTopToBottom:
self.EffectShowProgressAboutTopAndBottom(.kHUDTypeShowFromTopToBottom,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromLeftToRight:
self.EffectShowProgressAboutLeftAndRight(.kHUDTypeShowFromLeftToRight,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromRightToLeft:
self.EffectShowProgressAboutLeftAndRight(.kHUDTypeShowFromRightToLeft,ifCustom:ifCustom,to:to)
case .kHUDTypeScaleFromInsideToOutside:
self.EffectShowProgressAboutInsideAndOutside(.kHUDTypeScaleFromInsideToOutside,ifCustom:ifCustom,to:to)
case .kHUDTypeScaleFromOutsideToInside:
self.EffectShowProgressAboutInsideAndOutside(.kHUDTypeScaleFromOutsideToInside,ifCustom:ifCustom,to:to)
}
}
// 1⃣️原位置不变化
fileprivate func EffectShowProgressAboutStablePositon(_ type:HUDType,ifCustom:Bool,to:UIView) {
var kIfNeedEffect : Bool = false
switch type {
case .kHUDTypeShowImmediately:
kIfNeedEffect = false
self.coreView.alpha = 1
break
case .kHUDTypeShowSlightly:
kIfNeedEffect = true
self.coreView.alpha = 0
break
default:
break
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsg"), object: nil)
/*重写位置*/
self.coreView.diyMsgLabel.isHidden = true
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 80) / 2, y: (SCREEN_HEIGHT - 80) / 2, width: 80, height: 80)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 )
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
if kIfNeedEffect == false {
}else if kIfNeedEffect == true {
/*实现动画*/
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2)
})
}
}
// 2⃣️上下相关
fileprivate func EffectShowProgressAboutTopAndBottom(_ type:HUDType,ifCustom:Bool,to:UIView) {
var value : CGFloat = 0
switch type {
case .kHUDTypeShowFromBottomToTop:
value = -60
break
case .kHUDTypeShowFromTopToBottom:
value = 60
break
default:
break
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsg"), object: nil)
/*重写位置*/
self.coreView.diyMsgLabel.isHidden = true
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 80) / 2, y: (SCREEN_HEIGHT - 80) / 2, width: 80, height: 80)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 - value)
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
/*实现动画*/
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2)
})
}
// 3⃣️左右相关
fileprivate func EffectShowProgressAboutLeftAndRight(_ type:HUDType,ifCustom:Bool,to:UIView){
var value : CGFloat = 0
switch type {
case .kHUDTypeShowFromLeftToRight:
value = -60
break
case .kHUDTypeShowFromRightToLeft:
value = 60
break
default:
break
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsg"), object: nil)
/*重写位置*/
self.coreView.diyMsgLabel.isHidden = true
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - 80) / 2, y: (SCREEN_HEIGHT - 80) / 2, width: 80, height: 80)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2 + value, y: SCREEN_HEIGHT / 2)
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
/*实现动画*/
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2)
})
}
// 4⃣️内外相关
fileprivate func EffectShowProgressAboutInsideAndOutside(_ type:HUDType,ifCustom:Bool,to:UIView){
var kInitValue : CGFloat = 0
var kScaleValue : CGFloat = 0
switch type {
case .kHUDTypeScaleFromInsideToOutside:
kInitValue = 85
kScaleValue = 1.28
break
case .kHUDTypeScaleFromOutsideToInside:
kInitValue = 130
kScaleValue = 0.85
break
default:
break
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveNoMsgWithScale"), object: kScaleValue)
/*重写位置*/
self.coreView.diyMsgLabel.isHidden = true
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - kInitValue) / 2, y: (SCREEN_HEIGHT - kInitValue) / 2, width: kInitValue, height: kInitValue)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2)
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
/*实现动画*/
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.transform = self.coreView.transform.scaledBy(x: kScaleValue,y: kScaleValue)
})
}
// MARK: - 3⃣️显示DIY进程及文字(Show DIY-InProgress-Status And The Words-Message)
public func showDIYProgressMsgsWithType(_ msgs:NSString,img:NSString,diySpeed:CFTimeInterval,diyHudType:DiyHUDType, HudType:HUDType,ifCustom:Bool,to:UIView) {// NEW
self.coreView.diySpeed = diySpeed
self.coreView.diyHudType = diyHudType.hashValue
self.coreView.diyShowImage = img
self.type = HudType.hashValue
self.showDIYProgressMsgsWithHUDType(msgs, HudType: HudType,ifCustom:ifCustom,to:to)
}
// MARK: - 4⃣️显示DIY进程及文字(Show DIY-InProgress-Status And The Words-Message❤️播放图片数组)
public func showDIYProgressMsgsAnimated(_ msgs:NSString,imgsName:NSString,imgsNumber:NSInteger,diySpeed:TimeInterval, HudType:HUDType,ifCustom:Bool,to:UIView) {// NEW
self.coreView.diyShowImage = imgsName
self.coreView.diyImgsNumber = imgsNumber
self.coreView.diySpeed = diySpeed
self.type = HudType.hashValue
self.showDIYProgressMsgsWithHUDType(msgs, HudType: HudType,ifCustom:ifCustom,to:to)
}
fileprivate func showDIYProgressMsgsWithHUDType(_ msgs:NSString,HudType:HUDType,ifCustom:Bool,to:UIView) {
switch HudType {
case .kHUDTypeDefaultly:
self.EffectShowProgressMsgsAboutTopAndBottom(msgs,type: .kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to)
case .kHUDTypeShowImmediately:
self.EffectShowProgressMsgsAboutStablePosition(msgs, type: .kHUDTypeShowImmediately,ifCustom:ifCustom,to:to)
case .kHUDTypeShowSlightly:
self.EffectShowProgressMsgsAboutStablePosition(msgs, type: .kHUDTypeShowSlightly,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromBottomToTop:
self.EffectShowProgressMsgsAboutTopAndBottom(msgs,type: .kHUDTypeShowFromBottomToTop,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromTopToBottom:
self.EffectShowProgressMsgsAboutTopAndBottom(msgs,type:.kHUDTypeShowFromTopToBottom,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromLeftToRight:
self.EffectShowProgressMsgsAboutLeftAndRight(msgs, type: .kHUDTypeShowFromLeftToRight,ifCustom:ifCustom,to:to)
case .kHUDTypeShowFromRightToLeft:
self.EffectShowProgressMsgsAboutLeftAndRight(msgs, type: .kHUDTypeShowFromRightToLeft,ifCustom:ifCustom,to:to)
case .kHUDTypeScaleFromInsideToOutside:
self.EffectShowProgressMsgsAboutInsideAndOutside(msgs, type: .kHUDTypeScaleFromInsideToOutside,ifCustom:ifCustom,to:to)
case .kHUDTypeScaleFromOutsideToInside:
self.EffectShowProgressMsgsAboutInsideAndOutside(msgs, type: .kHUDTypeScaleFromOutsideToInside,ifCustom:ifCustom,to:to)
}
}
// 1⃣️原位置不变
fileprivate func EffectShowProgressMsgsAboutStablePosition(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView) {
switch type {
case .kHUDTypeShowImmediately:
self.coreView.alpha = 1
break
case .kHUDTypeShowSlightly:
self.coreView.alpha = 0
break
default:
break
}
coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [
NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)
], context: nil)
var msgLabelWidth = coreViewRect.width
if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) {
msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin
}else if msgLabelWidth + 2*kMargin <= 80 {
msgLabelWidth = 80
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg"), object: nil)
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - 80) / 2,width: msgLabelWidth + 2*kMargin , height: 105)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2)
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2)
self.setNeedsDisplay()
})
self.coreView.diyMsgLabelWidth = msgLabelWidth
self.coreView.diyMsgLabel.text = msgs as String
}
// 2⃣️上下相关
fileprivate func EffectShowProgressMsgsAboutTopAndBottom(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView){
var value : CGFloat = 0
switch type {
case .kHUDTypeShowFromBottomToTop:
value = 60
break
case .kHUDTypeShowFromTopToBottom:
value = -60
break
default:
break
}
coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [
NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)
], context: nil)
var msgLabelWidth = coreViewRect.width
if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) {
msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin
}else if msgLabelWidth + 2*kMargin <= 80 {
msgLabelWidth = 80
}
self.coreView.diyMsgLabelWidth = msgLabelWidth + 20
self.coreView.diyMsgLabel.text = msgs as String
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg"), object: nil)
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - 80) / 2,width: msgLabelWidth + 2*kMargin , height: 105)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2 + value)
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2)
self.setNeedsDisplay()
})
}
// 3⃣️左右相关
fileprivate func EffectShowProgressMsgsAboutLeftAndRight(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView){
var value : CGFloat = 0
switch type {
case .kHUDTypeShowFromLeftToRight:
value = -60
break
case .kHUDTypeShowFromRightToLeft:
value = 60
break
default:
break
}
coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [
NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)
], context: nil)
var msgLabelWidth = coreViewRect.width
if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) {
msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin
}else if msgLabelWidth + 2*kMargin <= 80 {
msgLabelWidth = 80
}
self.coreView.diyMsgLabelWidth = msgLabelWidth + 20
self.coreView.diyMsgLabel.text = msgs as String
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg"), object: nil)
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - 80) / 2,width: msgLabelWidth + 2*kMargin , height: 105)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2 + value, y: SCREEN_HEIGHT / 2)
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2)
self.setNeedsDisplay()
})
}
// 4⃣️内外相关
fileprivate func EffectShowProgressMsgsAboutInsideAndOutside(_ msgs:NSString,type:HUDType,ifCustom:Bool,to:UIView){
coreViewRect = msgs.boundingRect(with: CGSize(width: self.coreView.diyMsgLabel.bounds.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [
NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)
], context: nil)
var msgLabelWidth = coreViewRect.width
if msgLabelWidth + 2*kMargin >= (SCREEN_WIDTH - 30) {
msgLabelWidth = SCREEN_WIDTH - 30 - 2*kMargin
}else if msgLabelWidth + 2*kMargin <= 80 {
msgLabelWidth = 80
}
let CoreWidth = msgLabelWidth + 2*kMargin
var iniWidthValue : CGFloat = 0
var iniHeightValue : CGFloat = 0
var kScaleValue : CGFloat = 0
switch type {
case .kHUDTypeScaleFromInsideToOutside:
kScaleValue = 1.05
iniWidthValue = (CoreWidth + 10)/kScaleValue
iniHeightValue = 105/kScaleValue
break
case .kHUDTypeScaleFromOutsideToInside:
kScaleValue = 0.90
iniWidthValue = CoreWidth/kScaleValue
iniHeightValue = 105/kScaleValue
break
default:
break
}
self.coreView.diyMsgLabelWidth = iniWidthValue
self.coreView.diyMsgLabel.text = msgs as String
NotificationCenter.default.post(name: Notification.Name(rawValue: "JHB_DIYHUD_haveMsg_WithScale"), object: kScaleValue)
self.coreView.frame = CGRect(x: (SCREEN_WIDTH - msgLabelWidth) / 2, y: (SCREEN_HEIGHT - iniHeightValue) / 2,width: iniWidthValue , height: iniHeightValue)
self.coreView.center = CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2)
ifCustom == true ? self.addTo(to: to):self.ResetWindowPosition()
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 1
self.coreView.transform = self.coreView.transform.scaledBy(x: kScaleValue,y: kScaleValue)
self.coreView.center = CGPoint(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height / 2)
self.setNeedsDisplay()
})
}
// MARK: - Self-Method Without Ask
@objc fileprivate func hideWithAnimation() {
switch self.type {
case HUDType.kHUDTypeDefaultly.hashValue:
// ❤️默认类型
self.EffectRemoveAboutBottomAndTop(.kHUDTypeShowFromBottomToTop)
break
case HUDType.kHUDTypeShowImmediately.hashValue:
self.EffectRemoveAboutStablePositon(.kHUDTypeShowImmediately)
break
case HUDType.kHUDTypeShowSlightly.hashValue:
self.EffectRemoveAboutStablePositon(.kHUDTypeShowSlightly)
break
case HUDType.kHUDTypeShowFromBottomToTop.hashValue:
self.EffectRemoveAboutBottomAndTop(.kHUDTypeShowFromBottomToTop)
break
case HUDType.kHUDTypeShowFromTopToBottom.hashValue:
self.EffectRemoveAboutBottomAndTop(.kHUDTypeShowFromTopToBottom)
break
case HUDType.kHUDTypeShowFromLeftToRight.hashValue:
self.EffectRemoveAboutLeftAndRight(.kHUDTypeShowFromLeftToRight)
break
case HUDType.kHUDTypeShowFromRightToLeft.hashValue:
self.EffectRemoveAboutLeftAndRight(.kHUDTypeShowFromRightToLeft)
break
case HUDType.kHUDTypeScaleFromInsideToOutside.hashValue:
self.EffectRemoveAboutInsideAndOutside(.kHUDTypeScaleFromInsideToOutside)
break
case HUDType.kHUDTypeScaleFromOutsideToInside.hashValue:
self.EffectRemoveAboutInsideAndOutside(.kHUDTypeScaleFromOutsideToInside)
break
default:
break
}
}
// 1⃣️原位置不变
func EffectRemoveAboutStablePositon(_ HudType:HUDType) {
var kIfNeedEffect : Bool = false
switch HudType {
case .kHUDTypeShowImmediately:
kIfNeedEffect = false
break
case .kHUDTypeShowSlightly:
kIfNeedEffect = true
break
default:
break
}
if kIfNeedEffect == false {
self.SuperInitStatus()
}else if kIfNeedEffect == true {
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 0
self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2, y: self.bgClearView.bounds.size.height / 2)
}, completion: { (true) in
self.SuperInitStatus()
})
}
}
// 2⃣️上下相关
func EffectRemoveAboutBottomAndTop(_ HudType:HUDType) {
var value : CGFloat = 0
switch HudType {
case .kHUDTypeShowFromBottomToTop:
value = -60
break
case .kHUDTypeShowFromTopToBottom:
value = 60
break
default:
break
}
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 0
self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2, y: self.bgClearView.bounds.size.height / 2 + value)
}, completion: { (true) in
self.SuperInitStatus()
})
}
// 3⃣️左右相关
func EffectRemoveAboutLeftAndRight(_ HudType:HUDType) {
var value : CGFloat = 0
switch HudType {
case .kHUDTypeShowFromLeftToRight:
value = 60
break
case .kHUDTypeShowFromRightToLeft:
value = -60
break
default:
break
}
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 0
self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2 + value, y: self.bgClearView.bounds.size.height / 2)
}, completion: { (true) in
self.SuperInitStatus()
})
}
// 4⃣️内外相关
func EffectRemoveAboutInsideAndOutside(_ HudType:HUDType) {
var kScaleValue : CGFloat = 0
switch HudType {
case .kHUDTypeScaleFromInsideToOutside:
kScaleValue = 1.78
break
case .kHUDTypeScaleFromOutsideToInside:
kScaleValue = 0.67
break
default:
break
}
UIView.animate(withDuration: 0.65, animations: {
self.coreView.alpha = 0
self.coreView.transform = self.coreView.transform.scaledBy(x: 1/kScaleValue,y: 1/kScaleValue)
self.coreView.center = CGPoint(x: self.bgClearView.bounds.size.width / 2, y: self.bgClearView.bounds.size.height / 2)
}, completion: { (true) in
self.SuperInitStatus()
})
}
///
public func addTo(to:UIView) {
self.frame = to.frame
self.center = to.center
to.addSubview(self)
}
}
|
137975a5c19f2bc2991b243da69268e8
| 40.968386 | 185 | 0.62784 | false | false | false | false |
apple/swift-corelibs-foundation
|
refs/heads/main
|
Sources/Foundation/NSDateComponents.swift
|
apache-2.0
|
1
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
// This is a just used as an extensible struct, basically;
// note that there are two uses: one for specifying a date
// via components (some components may be missing, making the
// specific date ambiguous), and the other for specifying a
// set of component quantities (like, 3 months and 5 hours).
// Undefined fields have (or fields can be set to) the value
// NSDateComponentUndefined.
// NSDateComponents is not responsible for answering questions
// about a date beyond the information it has been initialized
// with; for example, if you initialize one with May 6, 2004,
// and then ask for the weekday, you'll get Undefined, not Thurs.
// A NSDateComponents is meaningless in itself, because you need
// to know what calendar it is interpreted against, and you need
// to know whether the values are absolute values of the units,
// or quantities of the units.
// When you create a new one of these, all values begin Undefined.
public var NSDateComponentUndefined: Int = Int.max
open class NSDateComponents: NSObject, NSCopying, NSSecureCoding {
internal var _calendar: Calendar?
internal var _timeZone: TimeZone?
internal var _values = [Int](repeating: NSDateComponentUndefined, count: 19)
public override init() {
super.init()
}
open override var hash: Int {
var hasher = Hasher()
var mask = 0
// The list of fields fed to the hasher here must be exactly
// the same as the ones compared in isEqual(_:) (modulo
// ordering).
//
// Given that NSDateComponents instances usually only have a
// few fields present, it makes sense to only hash those, as
// an optimization. We keep track of the fields hashed in the
// mask value, which we also feed to the hasher to make sure
// any two unequal values produce different hash encodings.
//
// FIXME: Why not just feed _values, calendar & timeZone to
// the hasher?
if let calendar = calendar {
hasher.combine(calendar)
mask |= 1 << 0
}
if let timeZone = timeZone {
hasher.combine(timeZone)
mask |= 1 << 1
}
if era != NSDateComponentUndefined {
hasher.combine(era)
mask |= 1 << 2
}
if year != NSDateComponentUndefined {
hasher.combine(year)
mask |= 1 << 3
}
if quarter != NSDateComponentUndefined {
hasher.combine(quarter)
mask |= 1 << 4
}
if month != NSDateComponentUndefined {
hasher.combine(month)
mask |= 1 << 5
}
if day != NSDateComponentUndefined {
hasher.combine(day)
mask |= 1 << 6
}
if hour != NSDateComponentUndefined {
hasher.combine(hour)
mask |= 1 << 7
}
if minute != NSDateComponentUndefined {
hasher.combine(minute)
mask |= 1 << 8
}
if second != NSDateComponentUndefined {
hasher.combine(second)
mask |= 1 << 9
}
if nanosecond != NSDateComponentUndefined {
hasher.combine(nanosecond)
mask |= 1 << 10
}
if weekOfYear != NSDateComponentUndefined {
hasher.combine(weekOfYear)
mask |= 1 << 11
}
if weekOfMonth != NSDateComponentUndefined {
hasher.combine(weekOfMonth)
mask |= 1 << 12
}
if yearForWeekOfYear != NSDateComponentUndefined {
hasher.combine(yearForWeekOfYear)
mask |= 1 << 13
}
if weekday != NSDateComponentUndefined {
hasher.combine(weekday)
mask |= 1 << 14
}
if weekdayOrdinal != NSDateComponentUndefined {
hasher.combine(weekdayOrdinal)
mask |= 1 << 15
}
hasher.combine(isLeapMonth)
hasher.combine(mask)
return hasher.finalize()
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSDateComponents else { return false }
// FIXME: Why not just compare _values, calendar & timeZone?
return self === other
|| (era == other.era
&& year == other.year
&& quarter == other.quarter
&& month == other.month
&& day == other.day
&& hour == other.hour
&& minute == other.minute
&& second == other.second
&& nanosecond == other.nanosecond
&& weekOfYear == other.weekOfYear
&& weekOfMonth == other.weekOfMonth
&& yearForWeekOfYear == other.yearForWeekOfYear
&& weekday == other.weekday
&& weekdayOrdinal == other.weekdayOrdinal
&& isLeapMonth == other.isLeapMonth
&& calendar == other.calendar
&& timeZone == other.timeZone)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
self.init()
self.era = aDecoder.decodeInteger(forKey: "NS.era")
self.year = aDecoder.decodeInteger(forKey: "NS.year")
self.quarter = aDecoder.decodeInteger(forKey: "NS.quarter")
self.month = aDecoder.decodeInteger(forKey: "NS.month")
self.day = aDecoder.decodeInteger(forKey: "NS.day")
self.hour = aDecoder.decodeInteger(forKey: "NS.hour")
self.minute = aDecoder.decodeInteger(forKey: "NS.minute")
self.second = aDecoder.decodeInteger(forKey: "NS.second")
self.nanosecond = aDecoder.decodeInteger(forKey: "NS.nanosec")
self.weekOfYear = aDecoder.decodeInteger(forKey: "NS.weekOfYear")
self.weekOfMonth = aDecoder.decodeInteger(forKey: "NS.weekOfMonth")
self.yearForWeekOfYear = aDecoder.decodeInteger(forKey: "NS.yearForWOY")
self.weekday = aDecoder.decodeInteger(forKey: "NS.weekday")
self.weekdayOrdinal = aDecoder.decodeInteger(forKey: "NS.weekdayOrdinal")
self.isLeapMonth = aDecoder.decodeBool(forKey: "NS.isLeapMonth")
self.calendar = aDecoder.decodeObject(of: NSCalendar.self, forKey: "NS.calendar")?._swiftObject
self.timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone")?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.era, forKey: "NS.era")
aCoder.encode(self.year, forKey: "NS.year")
aCoder.encode(self.quarter, forKey: "NS.quarter")
aCoder.encode(self.month, forKey: "NS.month")
aCoder.encode(self.day, forKey: "NS.day")
aCoder.encode(self.hour, forKey: "NS.hour")
aCoder.encode(self.minute, forKey: "NS.minute")
aCoder.encode(self.second, forKey: "NS.second")
aCoder.encode(self.nanosecond, forKey: "NS.nanosec")
aCoder.encode(self.weekOfYear, forKey: "NS.weekOfYear")
aCoder.encode(self.weekOfMonth, forKey: "NS.weekOfMonth")
aCoder.encode(self.yearForWeekOfYear, forKey: "NS.yearForWOY")
aCoder.encode(self.weekday, forKey: "NS.weekday")
aCoder.encode(self.weekdayOrdinal, forKey: "NS.weekdayOrdinal")
aCoder.encode(self.isLeapMonth, forKey: "NS.isLeapMonth")
aCoder.encode(self.calendar?._nsObject, forKey: "NS.calendar")
aCoder.encode(self.timeZone?._nsObject, forKey: "NS.timezone")
}
static public var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
let newObj = NSDateComponents()
newObj.calendar = calendar
newObj.timeZone = timeZone
newObj.era = era
newObj.year = year
newObj.month = month
newObj.day = day
newObj.hour = hour
newObj.minute = minute
newObj.second = second
newObj.nanosecond = nanosecond
newObj.weekOfYear = weekOfYear
newObj.weekOfMonth = weekOfMonth
newObj.yearForWeekOfYear = yearForWeekOfYear
newObj.weekday = weekday
newObj.weekdayOrdinal = weekdayOrdinal
newObj.quarter = quarter
if leapMonthSet {
newObj.isLeapMonth = isLeapMonth
}
return newObj
}
/*@NSCopying*/ open var calendar: Calendar? {
get {
return _calendar
}
set {
if let val = newValue {
_calendar = val
} else {
_calendar = nil
}
}
}
/*@NSCopying*/ open var timeZone: TimeZone?
open var era: Int {
get {
return _values[0]
}
set {
_values[0] = newValue
}
}
open var year: Int {
get {
return _values[1]
}
set {
_values[1] = newValue
}
}
open var month: Int {
get {
return _values[2]
}
set {
_values[2] = newValue
}
}
open var day: Int {
get {
return _values[3]
}
set {
_values[3] = newValue
}
}
open var hour: Int {
get {
return _values[4]
}
set {
_values[4] = newValue
}
}
open var minute: Int {
get {
return _values[5]
}
set {
_values[5] = newValue
}
}
open var second: Int {
get {
return _values[6]
}
set {
_values[6] = newValue
}
}
open var weekday: Int {
get {
return _values[8]
}
set {
_values[8] = newValue
}
}
open var weekdayOrdinal: Int {
get {
return _values[9]
}
set {
_values[9] = newValue
}
}
open var quarter: Int {
get {
return _values[10]
}
set {
_values[10] = newValue
}
}
open var nanosecond: Int {
get {
return _values[11]
}
set {
_values[11] = newValue
}
}
open var weekOfYear: Int {
get {
return _values[12]
}
set {
_values[12] = newValue
}
}
open var weekOfMonth: Int {
get {
return _values[13]
}
set {
_values[13] = newValue
}
}
open var yearForWeekOfYear: Int {
get {
return _values[14]
}
set {
_values[14] = newValue
}
}
open var isLeapMonth: Bool {
get {
return _values[15] == 1
}
set {
_values[15] = newValue ? 1 : 0
}
}
internal var leapMonthSet: Bool {
return _values[15] != NSDateComponentUndefined
}
/*@NSCopying*/ open var date: Date? {
if let tz = timeZone {
calendar?.timeZone = tz
}
return calendar?.date(from: self._swiftObject)
}
/*
This API allows one to set a specific component of NSDateComponents, by enum constant value rather than property name.
The calendar and timeZone and isLeapMonth properties cannot be set by this method.
*/
open func setValue(_ value: Int, forComponent unit: NSCalendar.Unit) {
switch unit {
case .era:
era = value
case .year:
year = value
case .month:
month = value
case .day:
day = value
case .hour:
hour = value
case .minute:
minute = value
case .second:
second = value
case .nanosecond:
nanosecond = value
case .weekday:
weekday = value
case .weekdayOrdinal:
weekdayOrdinal = value
case .quarter:
quarter = value
case .weekOfMonth:
weekOfMonth = value
case .weekOfYear:
weekOfYear = value
case .yearForWeekOfYear:
yearForWeekOfYear = value
case .calendar:
print(".Calendar cannot be set via \(#function)")
case .timeZone:
print(".TimeZone cannot be set via \(#function)")
default:
break
}
}
/*
This API allows one to get the value of a specific component of NSDateComponents, by enum constant value rather than property name.
The calendar and timeZone and isLeapMonth property values cannot be gotten by this method.
*/
open func value(forComponent unit: NSCalendar.Unit) -> Int {
switch unit {
case .era:
return era
case .year:
return year
case .month:
return month
case .day:
return day
case .hour:
return hour
case .minute:
return minute
case .second:
return second
case .nanosecond:
return nanosecond
case .weekday:
return weekday
case .weekdayOrdinal:
return weekdayOrdinal
case .quarter:
return quarter
case .weekOfMonth:
return weekOfMonth
case .weekOfYear:
return weekOfYear
case .yearForWeekOfYear:
return yearForWeekOfYear
default:
break
}
return NSDateComponentUndefined
}
/*
Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar.
This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components.
Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
If the time zone property is set in the NSDateComponents object, it is used.
The calendar property must be set, or NO is returned.
*/
open var isValidDate: Bool {
if let cal = calendar {
return isValidDate(in: cal)
}
return false
}
/*
Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar.
This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components.
Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
If the time zone property is set in the NSDateComponents object, it is used.
*/
open func isValidDate(in calendar: Calendar) -> Bool {
var cal = calendar
if let tz = timeZone {
cal.timeZone = tz
}
let ns = nanosecond
if ns != NSDateComponentUndefined && 1000 * 1000 * 1000 <= ns {
return false
}
if ns != NSDateComponentUndefined && 0 < ns {
nanosecond = 0
}
let d = calendar.date(from: self._swiftObject)
if ns != NSDateComponentUndefined && 0 < ns {
nanosecond = ns
}
if let date = d {
let all: NSCalendar.Unit = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear]
let comps = cal._bridgeToObjectiveC().components(all, from: date)
var val = era
if val != NSDateComponentUndefined {
if comps.era != val {
return false
}
}
val = year
if val != NSDateComponentUndefined {
if comps.year != val {
return false
}
}
val = month
if val != NSDateComponentUndefined {
if comps.month != val {
return false
}
}
if leapMonthSet {
if comps.isLeapMonth != isLeapMonth {
return false
}
}
val = day
if val != NSDateComponentUndefined {
if comps.day != val {
return false
}
}
val = hour
if val != NSDateComponentUndefined {
if comps.hour != val {
return false
}
}
val = minute
if val != NSDateComponentUndefined {
if comps.minute != val {
return false
}
}
val = second
if val != NSDateComponentUndefined {
if comps.second != val {
return false
}
}
val = weekday
if val != NSDateComponentUndefined {
if comps.weekday != val {
return false
}
}
val = weekdayOrdinal
if val != NSDateComponentUndefined {
if comps.weekdayOrdinal != val {
return false
}
}
val = quarter
if val != NSDateComponentUndefined {
if comps.quarter != val {
return false
}
}
val = weekOfMonth
if val != NSDateComponentUndefined {
if comps.weekOfMonth != val {
return false
}
}
val = weekOfYear
if val != NSDateComponentUndefined {
if comps.weekOfYear != val {
return false
}
}
val = yearForWeekOfYear
if val != NSDateComponentUndefined {
if comps.yearForWeekOfYear != val {
return false
}
}
return true
}
return false
}
}
extension NSDateComponents: _SwiftBridgeable {
typealias SwiftType = DateComponents
var _swiftObject: SwiftType { return DateComponents(reference: self) }
}
extension NSDateComponents: _StructTypeBridgeable {
public typealias _StructType = DateComponents
public func _bridgeToSwift() -> DateComponents {
return DateComponents._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSDateComponents {
func _createCFDateComponents() -> CFDateComponents {
let components = CFDateComponentsCreate(kCFAllocatorSystemDefault)!
CFDateComponentsSetValue(components, kCFCalendarUnitEra, era)
CFDateComponentsSetValue(components, kCFCalendarUnitYear, year)
CFDateComponentsSetValue(components, kCFCalendarUnitMonth, month)
CFDateComponentsSetValue(components, kCFCalendarUnitDay, day)
CFDateComponentsSetValue(components, kCFCalendarUnitHour, hour)
CFDateComponentsSetValue(components, kCFCalendarUnitMinute, minute)
CFDateComponentsSetValue(components, kCFCalendarUnitSecond, second)
CFDateComponentsSetValue(components, kCFCalendarUnitWeekday, weekday)
CFDateComponentsSetValue(components, kCFCalendarUnitWeekdayOrdinal, weekdayOrdinal)
CFDateComponentsSetValue(components, kCFCalendarUnitQuarter, quarter)
CFDateComponentsSetValue(components, kCFCalendarUnitWeekOfMonth, weekOfMonth)
CFDateComponentsSetValue(components, kCFCalendarUnitWeekOfYear, weekOfYear)
CFDateComponentsSetValue(components, kCFCalendarUnitYearForWeekOfYear, yearForWeekOfYear)
CFDateComponentsSetValue(components, kCFCalendarUnitNanosecond, nanosecond)
return components
}
}
|
970a0ec8e34c1249969cdef18c074fc3
| 31.897314 | 175 | 0.553448 | false | false | false | false |
DAloG/BlueCap
|
refs/heads/master
|
BlueCapKit/Central/Service.swift
|
mit
|
1
|
//
// Service.swift
// BlueCap
//
// Created by Troy Stribling on 6/11/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import CoreBluetooth
///////////////////////////////////////////
// ServiceImpl
public protocol ServiceWrappable {
var uuid : CBUUID {get}
var name : String {get}
var state: CBPeripheralState {get}
func discoverCharacteristics(characteristics:[CBUUID]?)
func didDiscoverCharacteristics(error:NSError?)
func createCharacteristics()
func discoverAllCharacteristics() -> Future<Self>
}
public final class ServiceImpl<Wrapper:ServiceWrappable> {
private var characteristicsDiscoveredPromise = Promise<Wrapper>()
public func discoverAllCharacteristics(service:Wrapper) -> Future<Wrapper> {
Logger.debug("uuid=\(service.uuid.UUIDString), name=\(service.name)")
return self.discoverIfConnected(service, characteristics:nil)
}
public func discoverCharacteristics(service:Wrapper, characteristics:[CBUUID]?) -> Future<Wrapper> {
Logger.debug("uuid=\(service.uuid.UUIDString), name=\(service.name)")
return self.discoverIfConnected(service, characteristics:characteristics)
}
public func discoverIfConnected(service:Wrapper, characteristics:[CBUUID]?) -> Future<Wrapper> {
self.characteristicsDiscoveredPromise = Promise<Wrapper>()
if service.state == .Connected {
service.discoverCharacteristics(characteristics)
} else {
self.characteristicsDiscoveredPromise.failure(BCError.peripheralDisconnected)
}
return self.characteristicsDiscoveredPromise.future
}
public init() {
}
public func didDiscoverCharacteristics(service:Wrapper, error:NSError?) {
if let error = error {
Logger.debug("discover failed")
self.characteristicsDiscoveredPromise.failure(error)
} else {
service.createCharacteristics()
Logger.debug("discover success")
self.characteristicsDiscoveredPromise.success(service)
}
}
}
// ServiceImpl
///////////////////////////////////////////
public final class Service : ServiceWrappable {
internal var impl = ServiceImpl<Service>()
// ServiceWrappable
public var name : String {
if let profile = self.profile {
return profile.name
} else {
return "Unknown"
}
}
public var uuid : CBUUID {
return self.cbService.UUID
}
public var state : CBPeripheralState {
return self.peripheral.state
}
public func discoverCharacteristics(characteristics:[CBUUID]?) {
self.peripheral.cbPeripheral.discoverCharacteristics(characteristics, forService:self.cbService)
}
public func createCharacteristics() {
self.discoveredCharacteristics.removeAll()
if let cbChracteristics = self.cbService.characteristics {
for cbCharacteristic in cbChracteristics {
let bcCharacteristic = Characteristic(cbCharacteristic:cbCharacteristic, service:self)
self.discoveredCharacteristics[bcCharacteristic.uuid] = bcCharacteristic
bcCharacteristic.didDiscover()
Logger.debug("uuid=\(bcCharacteristic.uuid.UUIDString), name=\(bcCharacteristic.name)")
}
}
}
public func discoverAllCharacteristics() -> Future<Service> {
Logger.debug()
return self.impl.discoverIfConnected(self, characteristics:nil)
}
public func didDiscoverCharacteristics(error:NSError?) {
self.impl.didDiscoverCharacteristics(self, error:error)
}
// ServiceWrappable
private let profile : ServiceProfile?
internal let _peripheral : Peripheral
internal let cbService : CBService
internal var discoveredCharacteristics = [CBUUID:Characteristic]()
public var characteristics : [Characteristic] {
return Array(self.discoveredCharacteristics.values)
}
public var peripheral : Peripheral {
return self._peripheral
}
public func discoverCharacteristics(characteristics:[CBUUID]) -> Future<Service> {
Logger.debug()
return self.impl.discoverIfConnected(self, characteristics:characteristics)
}
internal init(cbService:CBService, peripheral:Peripheral) {
self.cbService = cbService
self._peripheral = peripheral
self.profile = ProfileManager.sharedInstance.serviceProfiles[cbService.UUID]
}
public func characteristic(uuid:CBUUID) -> Characteristic? {
return self.discoveredCharacteristics[uuid]
}
}
|
7081214298de4deb9b225d7355ed299e
| 31.993151 | 104 | 0.653862 | false | false | false | false |
broccolii/Demos
|
refs/heads/master
|
DEMO02-LoginAnimation/LoginAnimation/SwiftClass/SkyFloatingLabelTextField/SkyFloatingLabelTextField.swift
|
mit
|
1
|
// Copyright 2016 Skyscanner Ltd
//
// 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
/**
A beautiful and flexible textfield implementation with support for title label, error message and placeholder.
*/
@IBDesignable
public class SkyFloatingLabelTextField: UITextField {
/// A Boolean value that determines if the language displayed is LTR. Default value set automatically from the application language settings.
var isLTRLanguage = UIApplication.sharedApplication().userInterfaceLayoutDirection == .LeftToRight {
didSet {
self.updateTextAligment()
}
}
private func updateTextAligment() {
if(self.isLTRLanguage) {
self.textAlignment = .Left
} else {
self.textAlignment = .Right
}
}
// MARK: Animation timing
/// The value of the title appearing duration
public var titleFadeInDuration:NSTimeInterval = 0.2
/// The value of the title disappearing duration
public var titleFadeOutDuration:NSTimeInterval = 0.3
// MARK: Colors
private var cachedTextColor:UIColor?
/// A UIColor value that determines the text color of the editable text
@IBInspectable
override public var textColor:UIColor? {
set {
self.cachedTextColor = newValue
self.updateControl(false)
}
get {
return cachedTextColor
}
}
/// A UIColor value that determines text color of the placeholder label
@IBInspectable public var placeholderColor:UIColor = UIColor.lightGrayColor() {
didSet {
self.updatePlaceholder()
}
}
/// A UIColor value that determines text color of the placeholder label
@IBInspectable public var placeholderFont:UIFont? {
didSet {
self.updatePlaceholder()
}
}
private func updatePlaceholder() {
if let
placeholder = self.placeholder,
font = self.placeholderFont ?? self.font {
self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName:placeholderColor,
NSFontAttributeName: font])
}
}
/// A UIColor value that determines the text color of the title label when in the normal state
@IBInspectable public var titleColor:UIColor = UIColor.grayColor() {
didSet {
self.updateTitleColor()
}
}
/// A UIColor value that determines the color of the bottom line when in the normal state
@IBInspectable public var lineColor:UIColor = UIColor.lightGrayColor() {
didSet {
self.updateLineView()
}
}
/// A UIColor value that determines the color used for the title label and the line when the error message is not `nil`
@IBInspectable public var errorColor:UIColor = UIColor.redColor() {
didSet {
self.updateColors()
}
}
/// A UIColor value that determines the text color of the title label when editing
@IBInspectable public var selectedTitleColor:UIColor = UIColor.blueColor() {
didSet {
self.updateTitleColor()
}
}
/// A UIColor value that determines the color of the line in a selected state
@IBInspectable public var selectedLineColor:UIColor = UIColor.blackColor() {
didSet {
self.updateLineView()
}
}
// MARK: Line height
/// A CGFloat value that determines the height for the bottom line when the control is in the normal state
@IBInspectable public var lineHeight:CGFloat = 0.5 {
didSet {
self.updateLineView()
self.setNeedsDisplay()
}
}
/// A CGFloat value that determines the height for the bottom line when the control is in a selected state
@IBInspectable public var selectedLineHeight:CGFloat = 1.0 {
didSet {
self.updateLineView()
self.setNeedsDisplay()
}
}
// MARK: View components
/// The internal `UIView` to display the line below the text input.
public var lineView:UIView!
/// The internal `UILabel` that displays the selected, deselected title or the error message based on the current state.
public var titleLabel:UILabel!
// MARK: Properties
/**
The formatter to use before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`.
The default implementation converts the text to uppercase.
*/
public var titleFormatter:(String -> String) = { (text:String) -> String in
return text.uppercaseString
}
/**
Identifies whether the text object should hide the text being entered.
*/
override public var secureTextEntry:Bool {
set {
super.secureTextEntry = newValue
self.fixCaretPosition()
}
get {
return super.secureTextEntry
}
}
/// A String value for the error message to display.
public var errorMessage:String? {
didSet {
self.updateControl(true)
}
}
/// The backing property for the highlighted property
private var _highlighted = false
/// A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation
override public var highlighted:Bool {
get {
return _highlighted
}
set {
_highlighted = newValue
self.updateTitleColor()
self.updateLineView()
}
}
/// A Boolean value that determines whether the textfield is being edited or is selected.
public var editingOrSelected:Bool {
get {
return super.editing || self.selected;
}
}
/// A Boolean value that determines whether the receiver has an error message.
public var hasErrorMessage:Bool {
get {
return self.errorMessage != nil && self.errorMessage != ""
}
}
private var _renderingInInterfaceBuilder:Bool = false
/// The text content of the textfield
@IBInspectable
override public var text:String? {
didSet {
self.updateControl(false)
}
}
/**
The String to display when the input field is empty.
The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`.
*/
@IBInspectable
override public var placeholder:String? {
didSet {
self.setNeedsDisplay()
self.updatePlaceholder()
self.updateTitleLabel()
}
}
/// The String to display when the textfield is editing and the input is not empty.
@IBInspectable public var selectedTitle:String? {
didSet {
self.updateControl()
}
}
/// The String to display when the textfield is not editing and the input is not empty.
@IBInspectable public var title:String? {
didSet {
self.updateControl()
}
}
// Determines whether the field is selected. When selected, the title floats above the textbox.
public override var selected:Bool {
didSet {
self.updateControl(true)
}
}
// MARK: - Initializers
/**
Initializes the control
- parameter frame the frame of the control
*/
override public init(frame: CGRect) {
super.init(frame: frame)
self.init_SkyFloatingLabelTextField()
}
/**
Intialzies the control by deserializing it
- parameter coder the object to deserialize the control from
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.init_SkyFloatingLabelTextField()
}
private final func init_SkyFloatingLabelTextField() {
self.borderStyle = .None
self.createTitleLabel()
self.createLineView()
self.updateColors()
self.addEditingChangedObserver()
self.updateTextAligment()
}
private func addEditingChangedObserver() {
self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), forControlEvents: .EditingChanged)
}
/**
Invoked when the editing state of the textfield changes. Override to respond to this change.
*/
public func editingChanged() {
updateControl(true)
updateTitleLabel(true)
}
// MARK: create components
private func createTitleLabel() {
let titleLabel = UILabel()
titleLabel.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
titleLabel.font = UIFont.systemFontOfSize(13)
titleLabel.alpha = 0.0
titleLabel.textColor = self.titleColor
self.addSubview(titleLabel)
self.titleLabel = titleLabel
}
private func createLineView() {
if self.lineView == nil {
let lineView = UIView()
lineView.userInteractionEnabled = false
self.lineView = lineView
self.configureDefaultLineHeight()
}
lineView.autoresizingMask = [.FlexibleWidth, .FlexibleTopMargin]
self.addSubview(lineView)
}
private func configureDefaultLineHeight() {
let onePixel:CGFloat = 1.0 / UIScreen.mainScreen().scale
self.lineHeight = 2.0 * onePixel
self.selectedLineHeight = 2.0 * self.lineHeight
}
// MARK: Responder handling
/**
Attempt the control to become the first responder
- returns: True when successfull becoming the first responder
*/
override public func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
self.updateControl(true)
return result
}
/**
Attempt the control to resign being the first responder
- returns: True when successfull resigning being the first responder
*/
override public func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
self.updateControl(true)
return result
}
// MARK: - View updates
private func updateControl(animated:Bool = false) {
self.updateColors()
self.updateLineView()
self.updateTitleLabel(animated)
}
private func updateLineView() {
if let lineView = self.lineView {
lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected)
}
self.updateLineColor()
}
// MARK: - Color updates
/// Update the colors for the control. Override to customize colors.
public func updateColors() {
self.updateLineColor()
self.updateTitleColor()
self.updateTextColor()
}
private func updateLineColor() {
if self.hasErrorMessage {
self.lineView.backgroundColor = self.errorColor
} else {
self.lineView.backgroundColor = self.editingOrSelected ? self.selectedLineColor : self.lineColor
}
}
private func updateTitleColor() {
if self.hasErrorMessage {
self.titleLabel.textColor = self.errorColor
} else {
if self.editingOrSelected || self.highlighted {
self.titleLabel.textColor = self.selectedTitleColor
} else {
self.titleLabel.textColor = self.titleColor
}
}
}
private func updateTextColor() {
if self.hasErrorMessage {
super.textColor = self.errorColor
} else {
super.textColor = self.cachedTextColor
}
}
// MARK: - Title handling
private func updateTitleLabel(animated:Bool = false) {
var titleText:String? = nil
if self.hasErrorMessage {
titleText = self.titleFormatter(errorMessage!)
} else {
if self.editingOrSelected {
titleText = self.selectedTitleOrTitlePlaceholder()
if titleText == nil {
titleText = self.titleOrPlaceholder()
}
} else {
titleText = self.titleOrPlaceholder()
}
}
self.titleLabel.text = titleText
self.updateTitleVisibility(animated)
}
private var _titleVisible = false
/*
* Set this value to make the title visible
*/
public func setTitleVisible(titleVisible:Bool, animated:Bool = false, animationCompletion: (()->())? = nil) {
if(_titleVisible == titleVisible) {
return
}
_titleVisible = titleVisible
self.updateTitleColor()
self.updateTitleVisibility(animated, completion: animationCompletion)
}
/**
Returns whether the title is being displayed on the control.
- returns: True if the title is displayed on the control, false otherwise.
*/
public func isTitleVisible() -> Bool {
return self.hasText() || self.hasErrorMessage || _titleVisible
}
private func updateTitleVisibility(animated:Bool = false, completion: (()->())? = nil) {
let alpha:CGFloat = self.isTitleVisible() ? 1.0 : 0.0
let frame:CGRect = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible())
let updateBlock = { () -> Void in
self.titleLabel.alpha = alpha
self.titleLabel.frame = frame
}
if animated {
let animationOptions:UIViewAnimationOptions = .CurveEaseOut;
let duration = self.isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration
UIView.animateWithDuration(duration, delay: 0, options: animationOptions, animations: { () -> Void in
updateBlock()
}, completion: { _ in
completion?()
})
} else {
updateBlock()
completion?()
}
}
// MARK: - UITextField text/placeholder positioning overrides
/**
Calculate the rectangle for the textfield when it is not being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override public func textRectForBounds(bounds: CGRect) -> CGRect {
super.textRectForBounds(bounds)
let titleHeight = self.titleHeight()
let lineHeight = self.selectedLineHeight
let rect = CGRectMake(0, titleHeight, bounds.size.width, bounds.size.height - titleHeight - lineHeight)
return rect
}
/**
Calculate the rectangle for the textfield when it is being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let titleHeight = self.titleHeight()
let lineHeight = self.selectedLineHeight
let rect = CGRectMake(0, titleHeight, bounds.size.width, bounds.size.height - titleHeight - lineHeight)
return rect
}
/**
Calculate the rectangle for the placeholder
- parameter bounds: The current bounds of the placeholder
- returns: The rectangle that the placeholder should render in
*/
override public func placeholderRectForBounds(bounds: CGRect) -> CGRect {
let titleHeight = self.titleHeight()
let lineHeight = self.selectedLineHeight
let rect = CGRectMake(0, titleHeight, bounds.size.width, bounds.size.height - titleHeight - lineHeight)
return rect
}
// MARK: - Positioning Overrides
/**
Calculate the bounds for the title label. Override to create a custom size title field.
- parameter bounds: The current bounds of the title
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the title label should render in
*/
public func titleLabelRectForBounds(bounds:CGRect, editing:Bool) -> CGRect {
let titleHeight = self.titleHeight()
if editing {
return CGRectMake(0, 0, bounds.size.width, titleHeight)
}
return CGRectMake(0, titleHeight, bounds.size.width, titleHeight)
}
/**
Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox.
- parameter bounds: The current bounds of the line
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the line bar should render in
*/
public func lineViewRectForBounds(bounds:CGRect, editing:Bool) -> CGRect {
let lineHeight:CGFloat = editing ? CGFloat(self.selectedLineHeight) : CGFloat(self.lineHeight)
return CGRectMake(0, bounds.size.height - lineHeight, bounds.size.width, lineHeight);
}
/**
Calculate the height of the title label.
-returns: the calculated height of the title label. Override to size the title with a different height
*/
public func titleHeight() -> CGFloat {
if let titleLabel = self.titleLabel,
font = titleLabel.font {
return font.lineHeight
}
return 15.0
}
/**
Calcualte the height of the textfield.
-returns: the calculated height of the textfield. Override to size the textfield with a different height
*/
public func textHeight() -> CGFloat {
return self.font!.lineHeight + 7.0
}
// MARK: - Layout
/// Invoked when the interface builder renders the control
override public func prepareForInterfaceBuilder() {
if #available(iOS 8.0, *) {
super.prepareForInterfaceBuilder()
}
self.selected = true
_renderingInInterfaceBuilder = true
self.updateControl(false)
self.invalidateIntrinsicContentSize()
}
/// Invoked by layoutIfNeeded automatically
override public func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.frame = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible() || _renderingInInterfaceBuilder)
self.lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected || _renderingInInterfaceBuilder)
}
/**
Calculate the content size for auto layout
- returns: the content size to be used for auto layout
*/
override public func intrinsicContentSize() -> CGSize {
return CGSizeMake(self.bounds.size.width, self.titleHeight() + self.textHeight())
}
// MARK: - Helpers
private func titleOrPlaceholder() -> String? {
if let title = self.title ?? self.placeholder {
return self.titleFormatter(title)
}
return nil
}
private func selectedTitleOrTitlePlaceholder() -> String? {
if let title = self.selectedTitle ?? self.title ?? self.placeholder {
return self.titleFormatter(title)
}
return nil
}
}
|
54d781a0511266eda6613e8aec807e30
| 32.950257 | 309 | 0.63088 | false | false | false | false |
mas-cli/mas
|
refs/heads/main
|
Package.swift
|
mit
|
1
|
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "mas",
platforms: [
.macOS(.v10_11)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.executable(
name: "mas",
targets: ["mas"]
),
.library(
name: "MasKit",
targets: ["MasKit"]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/Carthage/Commandant.git", from: "0.18.0"),
.package(url: "https://github.com/Quick/Nimble.git", from: "10.0.0"),
.package(url: "https://github.com/Quick/Quick.git", from: "5.0.0"),
.package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.16.2"),
.package(url: "https://github.com/mxcl/Version.git", from: "2.0.1"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "mas",
dependencies: ["MasKit"],
swiftSettings: [
.unsafeFlags([
"-I", "Sources/PrivateFrameworks/CommerceKit",
"-I", "Sources/PrivateFrameworks/StoreFoundation",
])
]
),
.target(
name: "MasKit",
dependencies: ["Commandant", "PromiseKit", "Version"],
swiftSettings: [
.unsafeFlags([
"-I", "Sources/PrivateFrameworks/CommerceKit",
"-I", "Sources/PrivateFrameworks/StoreFoundation",
])
],
linkerSettings: [
.linkedFramework("CommerceKit"),
.linkedFramework("StoreFoundation"),
.unsafeFlags(["-F", "/System/Library/PrivateFrameworks"]),
]
),
.testTarget(
name: "MasKitTests",
dependencies: ["MasKit", "Nimble", "Quick"],
resources: [.copy("JSON")],
swiftSettings: [
.unsafeFlags([
"-I", "Sources/PrivateFrameworks/CommerceKit",
"-I", "Sources/PrivateFrameworks/StoreFoundation",
])
]
),
],
swiftLanguageVersions: [.v5]
)
// https://github.com/apple/swift-format#matching-swift-format-to-your-swift-version-swift-57-and-earlier
#if compiler(>=5.7)
package.dependencies += [
.package(url: "https://github.com/apple/swift-format", .branch("release/5.7"))
]
#elseif compiler(>=5.6)
package.dependencies += [
.package(url: "https://github.com/apple/swift-format", .branch("release/5.6"))
]
#elseif compiler(>=5.5)
package.dependencies += [
.package(url: "https://github.com/apple/swift-format", .branch("swift-5.5-branch"))
]
#elseif compiler(>=5.4)
package.dependencies += [
.package(url: "https://github.com/apple/swift-format", .branch("swift-5.4-branch"))
]
#elseif compiler(>=5.3)
package.dependencies += [
.package(url: "https://github.com/apple/swift-format", .branch("swift-5.3-branch"))
]
#endif
|
5ba3650cf33b05b8b4580269a897779a
| 36.138298 | 117 | 0.553423 | false | false | false | false |
DivineDominion/ErrorHandling
|
refs/heads/master
|
ErrorHandling/TextEmailer.swift
|
mit
|
1
|
// Copyright (c) 2015 Christian Tietze
//
// See the file LICENSE for copying permission.
import Foundation
import AppKit
public class TextEmailer {
static var appInfo: [String : Any]? {
return Bundle.main.infoDictionary
}
static var appName: String? {
return appInfo?["CFBundleName"] as? String
}
static var supportEmail: String? {
return appInfo?["SupportEmail"] as? String
}
static var build: String {
guard let build = appInfo?["CFBundleVersion"] as? String else { return "" }
return "b\(build)"
}
static var version: String {
guard let version = appInfo?["CFBundleShortVersionString"] as? String else { return "" }
return "v\(version)"
}
static var versionString: String? {
let combined = [version, build].filter { !$0.isEmpty }.joined(separator: " ")
guard !combined.isEmpty else { return nil }
return "(\(combined))"
}
static var emailSubject: String {
let base = "Report for \(appName!)"
guard let buildAndVersion = versionString else { return base }
return "\(base) \(buildAndVersion)"
}
static func guardInfoPresent() {
precondition(hasValue(appInfo), "Could not read app's Info dictionary.")
precondition(hasValue(appName), "Expected CFBundleName in Info.plist to use as appName in e-mail.")
precondition(hasValue(supportEmail), "Expected SupportEmail being set in Info.plist")
}
public init() {
TextEmailer.guardInfoPresent()
}
}
extension TextEmailer: ReportEmailer {
public func email(error: Error, instructions: String? = nil) {
email(text: (error as NSError).debugDescription, instructions: instructions)
}
public func email(report: Report, instructions: String? = nil) {
email(text: report.localizedDescription, instructions: instructions)
}
public func email(text: String, instructions: String?) {
guard let emailService = NSSharingService(named: .composeEmail) else {
legacyURLEmailer(text: text)
return
}
emailService.recipients = [TextEmailer.supportEmail!]
emailService.subject = TextEmailer.emailSubject
emailService.perform(withItems: [instructions, text].compactMap { $0 })
}
private func legacyURLEmailer(text: String) {
let recipient = TextEmailer.supportEmail!
let subject = TextEmailer.emailSubject
let query = "subject=\(subject)&body=\(text)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let mailtoAddress = "mailto:\(recipient)?\(query)"
let url = URL(string: mailtoAddress)!
NSWorkspace.shared.open(url)
}
}
|
c9cd45802daae2dcd90b297555076371
| 29.369565 | 117 | 0.642806 | false | false | false | false |
LawrenceHan/iOS-project-playground
|
refs/heads/master
|
Homepwner_swift/Homepwner/DetailViewController.swift
|
mit
|
1
|
//
// Copyright © 2015 Big Nerd Ranch
//
import UIKit
class DetailViewController: UIViewController, UITextFieldDelegate,
UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var nameField: UITextField!
@IBOutlet var serialNumberField: UITextField!
@IBOutlet var valueField: UITextField!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var imageView: UIImageView!
var item: Item! {
didSet {
navigationItem.title = item.name
}
}
var imageStore: ImageStore!
@IBAction func takePicture(sender: UIBarButtonItem) {
let imagePicker = UIImagePickerController()
// If the device has a camera, take a picture, otherwise,
// just pick from photo library
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
imagePicker.sourceType = .Camera
}
else {
imagePicker.sourceType = .PhotoLibrary
}
imagePicker.delegate = self
// Place image picker on the screen
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String: AnyObject]) {
// Get picked image from info dictionary
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// Store the image in the ImageStore for the item's key
imageStore.setImage(image, forKey:item.itemKey)
// Put that image onto the screen in our image view
imageView.image = image
// Take image picker off the screen -
// you must call this dismiss method
dismissViewControllerAnimated(true, completion: nil)
}
let numberFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
return formatter
}()
let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
return formatter
}()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nameField.text = item.name
serialNumberField.text = item.serialNumber
valueField.text = numberFormatter.stringFromNumber(item.valueInDollars)
dateLabel.text = dateFormatter.stringFromDate(item.dateCreated)
// Get the item key
let key = item.itemKey
// If there is an associated image with the item ...
if let imageToDisplay = imageStore.imageForKey(key) {
// ... display it on the image view
imageView.image = imageToDisplay
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Clear first responder
view.endEditing(true)
// "Save" changes to item
item.name = nameField.text ?? ""
item.serialNumber = serialNumberField.text
if let valueText = valueField.text,
let value = numberFormatter.numberFromString(valueText) {
item.valueInDollars = value.integerValue
}
else {
item.valueInDollars = 0
}
}
@IBAction func backgroundTapped(sender: UITapGestureRecognizer) {
view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
2ec825a1ddb366db663cd3117c8136be
| 30.694215 | 79 | 0.61721 | false | false | false | false |
Pluto-tv/RxSwift
|
refs/heads/master
|
RxTests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift
|
mit
|
1
|
//
// PrimitiveHotObservable.swift
// RxTests
//
// Created by Krunoslav Zaher on 6/4/15.
//
//
import Foundation
import RxSwift
let SubscribedToHotObservable = Subscription(0)
let UnsunscribedFromHotObservable = Subscription(0, 0)
class PrimitiveHotObservable<ElementType : Equatable> : ObservableType {
typealias E = ElementType
typealias Events = Recorded<E>
typealias Observer = AnyObserver<E>
var subscriptions: [Subscription]
var observers: Bag<AnyObserver<E>>
let lock = NSRecursiveLock()
init() {
self.subscriptions = []
self.observers = Bag()
}
func on(event: Event<E>) {
observers.forEach { $0.on(event) }
}
func subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable {
lock.lock()
defer { lock.unlock() }
let key = observers.insert(AnyObserver(observer))
subscriptions.append(SubscribedToHotObservable)
let i = self.subscriptions.count - 1
return AnonymousDisposable {
self.lock.lock()
defer { self.lock.unlock() }
let removed = self.observers.removeKey(key)
assert(removed != nil)
self.subscriptions[i] = UnsunscribedFromHotObservable
}
}
}
|
8f01f7a8b1f02a7bb086cc6691ccbee9
| 23.181818 | 80 | 0.609023 | false | false | false | false |
venticake/RetricaImglyKit-iOS
|
refs/heads/master
|
RetricaImglyKit/Classes/Frontend/Editor/PhotoEditViewController.swift
|
mit
|
1
|
// This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
import GLKit
import ImageIO
import MobileCoreServices
/// Posted immediately after the selected overlay view was changed.
/// The notification object is the view that was selected. The `userInfo` dictionary is `nil`.
public let PhotoEditViewControllerSelectedOverlayViewDidChangeNotification = "PhotoEditViewControllerSelectedOverlayViewDidChangeNotification"
/**
The `PhotoEditViewControllerDelegate` protocol defines methods that allow you respond to the events of an instance of `PhotoEditViewController`.
*/
@available(iOS 8, *)
@objc(IMGLYPhotoEditViewControllerDelegate) public protocol PhotoEditViewControllerDelegate {
/**
Called when a new tool was selected.
- parameter photoEditViewController: The photo edit view controller that was used to select the new tool.
- parameter toolController: The tool that was selected.
- parameter replaceTopToolController: Whether or not the tool controller should be placed above the previous tool or whether it should be replaced.
*/
func photoEditViewController(photoEditViewController: PhotoEditViewController, didSelectToolController toolController: PhotoEditToolController, wantsCurrentTopToolControllerReplaced replaceTopToolController: Bool)
/**
Called when a tool should be dismissed.
- parameter photoEditViewController: The photo edit view controller that was used to dismiss the tool.
*/
func photoEditViewControllerPopToolController(photoEditViewController: PhotoEditViewController)
/**
The currently active editing tool.
- parameter photoEditViewController: The photo edit view controller that is asking for the active editing tool.
- returns: An instance of `PhotoEditToolController` that is currently at the top.
*/
func photoEditViewControllerCurrentEditingTool(photoEditViewController: PhotoEditViewController) -> PhotoEditToolController?
/**
Called when the output image was generated.
- parameter photoEditViewController: The photo edit view controller that created the output image.
- parameter image: The output image that was generated.
*/
func photoEditViewController(photoEditViewController: PhotoEditViewController, didSaveImage image: UIImage)
/**
Called when the output image could not be generated.
- parameter photoEditViewController: The photo edit view controller that was unable to generate the output image.
*/
func photoEditViewControllerDidFailToGeneratePhoto(photoEditViewController: PhotoEditViewController)
/**
Called when the user wants to dismiss the editor.
- parameter photoEditviewController: The photo edit view controller that is asking to be cancelled.
*/
func photoEditViewControllerDidCancel(photoEditviewController: PhotoEditViewController)
}
/**
* A `PhotoEditViewController` is responsible for presenting and rendering an edited image.
*/
@available(iOS 8, *)
@objc(IMGLYPhotoEditViewController) public class PhotoEditViewController: UIViewController {
// MARK: - Statics
private static let IconCaptionCollectionViewCellReuseIdentifier = "IconCaptionCollectionViewCellReuseIdentifier"
private static let IconCaptionCollectionViewCellSize = CGSize(width: 64, height: 80)
private static let SeparatorCollectionViewCellReuseIdentifier = "SeparatorCollectionViewCellReuseIdentifier"
private static let SeparatorCollectionViewCellSize = CGSize(width: 15, height: 80)
// MARK: - View Properties
private var collectionView: UICollectionView?
private var previewViewScrollingContainer: UIScrollView?
private var mainPreviewView: GLKView?
private var overlayContainerView: UIView?
private var frameImageView: UIImageView?
private var placeholderImageView: UIImageView?
private var tapGestureRecognizer: UITapGestureRecognizer?
private var panGestureRecognizer: UIPanGestureRecognizer?
private var pinchGestureRecognizer: UIPinchGestureRecognizer?
private var rotationGestureRecognizer: UIRotationGestureRecognizer?
// MARK: - Constraint Properties
private var placeholderImageViewConstraints: [NSLayoutConstraint]?
private var previewViewScrollingContainerConstraints: [NSLayoutConstraint]?
// MARK: - Model Properties
/// The tool stack item for this controller.
/// - seealso: `ToolStackItem`.
public private(set) lazy var toolStackItem = ToolStackItem()
private var photo: UIImage? {
didSet {
updatePlaceholderImage()
}
}
private var photoImageOrientation: UIImageOrientation = .Up
private var photoFileURL: NSURL?
private let configuration: Configuration
private var photoEditModel: IMGLYPhotoEditMutableModel? {
didSet {
if oldValue != photoEditModel {
if let oldPhotoEditModel = oldValue {
NSNotificationCenter.defaultCenter().removeObserver(self, name: IMGLYPhotoEditModelDidChangeNotification, object: oldPhotoEditModel)
}
if let photoEditModel = photoEditModel {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PhotoEditViewController.photoEditModelDidChange(_:)), name: IMGLYPhotoEditModelDidChangeNotification, object: photoEditModel)
updateMainRenderer()
}
}
}
}
@NSCopying private var uneditedPhotoEditModel: IMGLYPhotoEditModel?
private var baseWorkUIImage: UIImage? {
didSet {
if oldValue != baseWorkUIImage {
let ciImage: CIImage?
if let baseWorkUIImage = baseWorkUIImage {
ciImage = orientedCIImageFromUIImage(baseWorkUIImage)
} else {
ciImage = nil
}
baseWorkCIImage = ciImage
updateMainRenderer()
loadFrameControllerIfNeeded()
if baseWorkUIImage != nil {
if let photo = photo {
// Save original photo image orientation
photoImageOrientation = photo.imageOrientation
// Write full resolution image to disc to free memory
let fileName = "\(NSProcessInfo.processInfo().globallyUniqueString)_photo.png"
let fileURL = NSURL(fileURLWithPath: (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(fileName))
UIImagePNGRepresentation(photo)?.writeToURL(fileURL, atomically: true)
photoFileURL = fileURL
self.photo = nil
}
}
}
}
}
private var baseWorkCIImage: CIImage?
private var mainRenderer: PhotoEditRenderer?
private var nextRenderCompletionBlock: (() -> Void)?
private var frameController: FrameController?
// MARK: - State Properties
private var previewViewScrollingContainerLayoutValid = false
private var lastKnownWorkImageSize = CGSize.zero
private var lastKnownPreviewViewSize = CGSize.zero
/// The identifier of the photo effect to apply to the photo immediately. This is useful if you
/// pass a photo that already has an effect applied by the `CameraViewController`. Note that you
/// must set this property before presenting the view controller.
public var initialPhotoEffectIdentifier: String?
/// The intensity of the photo effect that is applied to the photo immediately. See
/// `initialPhotoEffectIdentifier` for more information.
public var initialPhotoEffectIntensity: CGFloat?
private var toolForAction: [PhotoEditorAction: PhotoEditToolController]?
private var selectedOverlayView: UIView? {
didSet {
NSNotificationCenter.defaultCenter().postNotificationName(PhotoEditViewControllerSelectedOverlayViewDidChangeNotification, object: selectedOverlayView)
oldValue?.layer.borderWidth = 0
oldValue?.layer.shadowOffset = CGSize.zero
oldValue?.layer.shadowColor = UIColor.clearColor().CGColor
// Reset zoom
updateScrollViewZoomScaleAnimated(true)
if let selectedOverlayView = selectedOverlayView {
selectedOverlayView.layer.borderWidth = 2 / (0.5 * (selectedOverlayView.transform.xScale + selectedOverlayView.transform.yScale))
selectedOverlayView.layer.borderColor = UIColor.whiteColor().CGColor
selectedOverlayView.layer.shadowOffset = CGSize(width: 0, height: 2)
selectedOverlayView.layer.shadowRadius = 2
selectedOverlayView.layer.shadowOpacity = 0.12
selectedOverlayView.layer.shadowColor = UIColor.blackColor().CGColor
}
}
}
private var draggedOverlayView: UIView?
// MARK: - Other Properties
weak var delegate: PhotoEditViewControllerDelegate?
private lazy var stickerContextMenuController: ContextMenuController = {
let flipHorizontallyAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_orientation_flip_h", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in
guard let overlayView = self?.selectedOverlayView as? StickerImageView else {
return
}
self?.undoManager?.registerUndoForTarget(overlayView) { view in
view.flipHorizontally()
}
overlayView.flipHorizontally()
self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.FlipHorizontally)
}
flipHorizontallyAction.accessibilityLabel = Localize("Flip horizontally")
let flipVerticallyAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_orientation_flip_v", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in
guard let overlayView = self?.selectedOverlayView as? StickerImageView else {
return
}
self?.undoManager?.registerUndoForTarget(overlayView) { view in
view.flipVertically()
}
overlayView.flipVertically()
self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.FlipVertically)
}
flipVerticallyAction.accessibilityLabel = Localize("Flip vertically")
let bringToFrontAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_bringtofront", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in
guard let overlayView = self?.selectedOverlayView as? StickerImageView else {
return
}
if let overlayViewSuperview = overlayView.superview, currentOrder = overlayViewSuperview.subviews.indexOf(overlayView) {
self?.undoManager?.registerUndoForTarget(overlayViewSuperview) { superview in
superview.insertSubview(overlayView, atIndex: currentOrder)
}
}
overlayView.superview?.bringSubviewToFront(overlayView)
self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.BringToFront)
}
bringToFrontAction.accessibilityLabel = Localize("Bring to front")
let deleteAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_delete", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in
guard let overlayView = self?.selectedOverlayView as? StickerImageView, overlayContainerView = self?.overlayContainerView else {
return
}
self?.undoManager?.registerUndoForTarget(overlayContainerView) { view in
view.addSubview(overlayView)
}
self?.removeStickerOverlay(overlayView)
if self?.selectedOverlayView == overlayView {
self?.selectedOverlayView = nil
self?.hideOptionsForOverlayIfNeeded()
}
self?.configuration.stickerToolControllerOptions.stickerActionSelectedClosure?(.Delete)
}
deleteAction.accessibilityLabel = Localize("Delete")
let contextMenu = ContextMenuController()
contextMenu.menuColor = self.configuration.contextMenuBackgroundColor
let actions: [ContextMenuAction] = self.configuration.stickerToolControllerOptions.allowedStickerContextActions.map({
switch $0 {
case .FlipHorizontally:
self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(flipHorizontallyAction, .FlipHorizontally)
return flipHorizontallyAction
case .FlipVertically:
self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(flipVerticallyAction, .FlipVertically)
return flipVerticallyAction
case .BringToFront:
self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(bringToFrontAction, .BringToFront)
return bringToFrontAction
case .Delete:
self.configuration.stickerToolControllerOptions.contextActionConfigurationClosure?(deleteAction, .Delete)
return deleteAction
case .Separator:
return ContextMenuDividerAction()
}
})
actions.forEach { contextMenu.addAction($0) }
return contextMenu
}()
private lazy var textContextMenuController: ContextMenuController = {
let bringToFrontAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_bringtofront", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in
guard let overlayView = self?.selectedOverlayView as? TextLabel else {
return
}
if let overlayViewSuperview = overlayView.superview, currentOrder = overlayViewSuperview.subviews.indexOf(overlayView) {
self?.undoManager?.registerUndoForTarget(overlayViewSuperview) { superview in
superview.insertSubview(overlayView, atIndex: currentOrder)
}
}
overlayView.superview?.bringSubviewToFront(overlayView)
self?.configuration.textOptionsToolControllerOptions.textContextActionSelectedClosure?(.BringToFront)
}
bringToFrontAction.accessibilityLabel = Localize("Bring to front")
let deleteAction = ContextMenuAction(image: UIImage(named: "imgly_icon_option_delete", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)!) { [weak self] _ in
guard let overlayView = self?.selectedOverlayView as? TextLabel, overlayContainerView = self?.overlayContainerView else {
return
}
self?.undoManager?.registerUndoForTarget(overlayContainerView) { view in
view.addSubview(overlayView)
}
overlayView.removeFromSuperview()
if let elements = self?.previewViewScrollingContainer?.accessibilityElements as? [NSObject], index = elements.indexOf({$0 == overlayView}) {
self?.previewViewScrollingContainer?.accessibilityElements?.removeAtIndex(index)
}
self?.selectedOverlayView = nil
self?.hideOptionsForOverlayIfNeeded()
self?.configuration.textOptionsToolControllerOptions.textContextActionSelectedClosure?(.Delete)
}
deleteAction.accessibilityLabel = Localize("Delete")
let contextMenu = ContextMenuController()
contextMenu.menuColor = self.configuration.contextMenuBackgroundColor
let actions: [ContextMenuAction] = self.configuration.textOptionsToolControllerOptions.allowedTextContextActions.map({
switch $0 {
case .BringToFront:
self.configuration.textOptionsToolControllerOptions.contextActionConfigurationClosure?(bringToFrontAction, .BringToFront)
return bringToFrontAction
case .Delete:
self.configuration.textOptionsToolControllerOptions.contextActionConfigurationClosure?(deleteAction, .Delete)
return deleteAction
case .Separator:
return ContextMenuDividerAction()
}
})
actions.forEach { contextMenu.addAction($0) }
return contextMenu
}()
// MARK: - Initializers
/**
Returns a newly initialized photo edit view controller for the given photo with a default configuration.
- parameter photo: The photo to edit.
- returns: A newly initialized `PhotoEditViewController` object.
*/
convenience public init(photo: UIImage) {
self.init(photo: photo, configuration: Configuration())
}
/**
Returns a newly initialized photo edit view controller for the given photo with the given configuration options.
- parameter photo: The photo to edit.
- parameter configuration: The configuration options to apply.
- returns: A newly initialized and configured `PhotoEditViewController` object.
*/
required public init(photo: UIImage, configuration: Configuration) {
self.photo = photo
self.configuration = configuration
super.init(nibName: nil, bundle: nil)
updateLastKnownImageSize()
}
/**
:nodoc:
*/
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Configuration
private var options: PhotoEditViewControllerOptions {
return self.configuration.photoEditViewControllerOptions
}
// MARK: - UIViewController
/**
:nodoc:
*/
public override func viewDidLoad() {
super.viewDidLoad()
previewViewScrollingContainer = UIScrollView()
view.addSubview(previewViewScrollingContainer!)
previewViewScrollingContainer!.delegate = self
previewViewScrollingContainer!.alwaysBounceHorizontal = true
previewViewScrollingContainer!.alwaysBounceVertical = true
previewViewScrollingContainer!.showsHorizontalScrollIndicator = false
previewViewScrollingContainer!.showsVerticalScrollIndicator = false
previewViewScrollingContainer!.maximumZoomScale = 3
previewViewScrollingContainer!.minimumZoomScale = 1
previewViewScrollingContainer!.clipsToBounds = false
automaticallyAdjustsScrollViewInsets = false
let context = EAGLContext(API: .OpenGLES2)
mainPreviewView = GLKView(frame: CGRect.zero, context: context)
mainPreviewView!.delegate = self
mainPreviewView!.isAccessibilityElement = true
mainPreviewView!.accessibilityLabel = Localize("Photo")
mainPreviewView!.accessibilityTraits |= UIAccessibilityTraitImage
previewViewScrollingContainer!.addSubview(mainPreviewView!)
previewViewScrollingContainer!.accessibilityElements = [mainPreviewView!]
overlayContainerView = UIView()
overlayContainerView!.clipsToBounds = true
mainPreviewView!.addSubview(overlayContainerView!)
frameImageView = UIImageView()
frameImageView!.contentMode = options.frameScaleMode
overlayContainerView!.addSubview(frameImageView!)
view.setNeedsUpdateConstraints()
}
/**
:nodoc:
*/
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadPhotoEditModelIfNecessary()
loadToolsIfNeeded()
installGestureRecognizersIfNeeded()
updateToolStackItem()
updateBackgroundColor()
updatePlaceholderImage()
updateRenderedPreviewForceRender(false)
}
/**
:nodoc:
*/
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateScrollViewContentSize()
}
/**
:nodoc:
*/
public override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
/**
:nodoc:
*/
public override func prefersStatusBarHidden() -> Bool {
return true
}
/**
:nodoc:
*/
public override func updateViewConstraints() {
super.updateViewConstraints()
updatePreviewContainerLayout()
if let placeholderImageView = placeholderImageView, _ = previewViewScrollingContainer where placeholderImageViewConstraints == nil {
placeholderImageView.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .Width, relatedBy: .Equal, toItem: mainPreviewView, attribute: .Width, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .Height, relatedBy: .Equal, toItem: mainPreviewView, attribute: .Height, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .CenterX, relatedBy: .Equal, toItem: mainPreviewView, attribute: .CenterX, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: placeholderImageView, attribute: .CenterY, relatedBy: .Equal, toItem: mainPreviewView, attribute: .CenterY, multiplier: 1, constant: 0))
placeholderImageViewConstraints = constraints
NSLayoutConstraint.activateConstraints(constraints)
}
}
// MARK: - Notification Callbacks
@objc private func photoEditModelDidChange(notification: NSNotification) {
updateRenderedPreviewForceRender(false)
}
// MARK: - Setup
internal func updateLayoutForNewToolController() {
updateRenderedPreviewForceRender(false)
previewViewScrollingContainerLayoutValid = false
updateLastKnownImageSize()
updatePreviewContainerLayout()
updateScrollViewZoomScaleAnimated(false)
view.layoutIfNeeded()
updateScrollViewContentSize()
updateBackgroundColor()
if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) {
previewViewScrollingContainer?.panGestureRecognizer.enabled = currentEditingTool.wantsScrollingInDefaultPreviewViewEnabled
previewViewScrollingContainer?.pinchGestureRecognizer?.enabled = currentEditingTool.wantsScrollingInDefaultPreviewViewEnabled
} else {
previewViewScrollingContainer?.panGestureRecognizer.enabled = true
previewViewScrollingContainer?.pinchGestureRecognizer?.enabled = true
}
}
private func loadPhotoEditModelIfNecessary() {
if photoEditModel == nil {
let editModel = IMGLYPhotoEditMutableModel()
if let photoEffectIdentifier = initialPhotoEffectIdentifier where editModel.effectFilterIdentifier != photoEffectIdentifier {
editModel.effectFilterIdentifier = photoEffectIdentifier
}
if let photoEffectIntensity = initialPhotoEffectIntensity where editModel.effectFilterIntensity != CGFloat(photoEffectIntensity) {
editModel.effectFilterIntensity = CGFloat(photoEffectIntensity)
}
loadBaseImageIfNecessary()
photoEditModel = editModel
uneditedPhotoEditModel = editModel
}
}
private func installGestureRecognizersIfNeeded() {
if tapGestureRecognizer == nil {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handleTap(_:)))
view.addGestureRecognizer(tapGestureRecognizer)
self.tapGestureRecognizer = tapGestureRecognizer
}
if panGestureRecognizer == nil {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handlePan(_:)))
panGestureRecognizer.delegate = self
view.addGestureRecognizer(panGestureRecognizer)
self.panGestureRecognizer = panGestureRecognizer
}
if pinchGestureRecognizer == nil {
let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handlePinch(_:)))
pinchGestureRecognizer.delegate = self
view.addGestureRecognizer(pinchGestureRecognizer)
self.pinchGestureRecognizer = pinchGestureRecognizer
}
if rotationGestureRecognizer == nil {
let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(PhotoEditViewController.handleRotation(_:)))
rotationGestureRecognizer.delegate = self
view.addGestureRecognizer(rotationGestureRecognizer)
self.rotationGestureRecognizer = rotationGestureRecognizer
}
}
private func updateToolStackItem() {
if collectionView == nil {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .Horizontal
flowLayout.minimumLineSpacing = 8
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.clearColor()
collectionView.registerClass(IconCaptionCollectionViewCell.self, forCellWithReuseIdentifier: PhotoEditViewController.IconCaptionCollectionViewCellReuseIdentifier)
collectionView.registerClass(SeparatorCollectionViewCell.self, forCellWithReuseIdentifier: PhotoEditViewController.SeparatorCollectionViewCellReuseIdentifier)
self.collectionView = collectionView
toolStackItem.performChanges {
toolStackItem.mainToolbarView = collectionView
if let applyButton = toolStackItem.applyButton {
applyButton.addTarget(self, action: #selector(PhotoEditViewController.save(_:)), forControlEvents: .TouchUpInside)
applyButton.accessibilityLabel = Localize("Save photo")
options.applyButtonConfigurationClosure?(applyButton)
}
if let discardButton = toolStackItem.discardButton {
discardButton.addTarget(self, action: #selector(PhotoEditViewController.cancel(_:)), forControlEvents: .TouchUpInside)
discardButton.accessibilityLabel = Localize("Discard photo")
options.discardButtonConfigurationClosure?(discardButton)
}
toolStackItem.titleLabel?.text = options.title
}
}
}
private func updateBackgroundColor() {
view.backgroundColor = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredPreviewBackgroundColor ?? (options.backgroundColor ?? configuration.backgroundColor)
}
private func loadBaseImageIfNecessary() {
if let _ = baseWorkUIImage {
return
}
guard let photo = photo else {
return
}
let screen = UIScreen.mainScreen()
var targetSize = workImageSizeForScreen(screen)
if photo.size.width > photo.size.height {
let aspectRatio = photo.size.height / photo.size.width
targetSize = CGSize(width: targetSize.width, height: targetSize.height * aspectRatio)
} else if photo.size.width < photo.size.height {
let aspectRatio = photo.size.width / photo.size.height
targetSize = CGSize(width: targetSize.width * aspectRatio, height: targetSize.height)
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let resizedImage = photo.normalizedImageOfSize(targetSize)
dispatch_async(dispatch_get_main_queue()) {
self.baseWorkUIImage = resizedImage
self.updateRenderedPreviewForceRender(false)
}
}
}
private func updateMainRenderer() {
if mainRenderer == nil {
if let photoEditModel = photoEditModel, baseWorkCIImage = baseWorkCIImage {
mainRenderer = PhotoEditRenderer()
mainRenderer!.photoEditModel = photoEditModel
mainRenderer!.originalImage = baseWorkCIImage
updateLastKnownImageSize()
view.setNeedsLayout()
updateRenderedPreviewForceRender(false)
}
}
}
internal func updateLastKnownImageSize() {
let workImageSize: CGSize
if let renderer = mainRenderer {
workImageSize = renderer.outputImageSize
} else if let photo = photo {
workImageSize = photo.size * UIScreen.mainScreen().scale
} else {
workImageSize = CGSize.zero
}
if workImageSize != lastKnownWorkImageSize {
lastKnownWorkImageSize = workImageSize
updateScrollViewContentSize()
updateRenderedPreviewForceRender(false)
}
}
private func updatePlaceholderImage() {
if isViewLoaded() {
let showPlaceholderImageView: Bool
if let _ = baseWorkUIImage {
showPlaceholderImageView = false
} else {
showPlaceholderImageView = true
}
if let photo = photo where showPlaceholderImageView {
if placeholderImageView == nil {
placeholderImageView = UIImageView(image: photo)
placeholderImageView!.contentMode = .ScaleAspectFit
previewViewScrollingContainer?.addSubview(placeholderImageView!)
updateSubviewsOrdering()
view.setNeedsUpdateConstraints()
}
placeholderImageView?.hidden = false
} else {
if let placeholderImageView = placeholderImageView {
placeholderImageView.hidden = true
if photo == nil {
placeholderImageView.removeFromSuperview()
self.placeholderImageView = nil
placeholderImageViewConstraints = nil
}
}
}
}
}
private func updateSubviewsOrdering() {
guard let previewViewScrollingContainer = previewViewScrollingContainer else {
return
}
view.sendSubviewToBack(previewViewScrollingContainer)
if let mainPreviewView = mainPreviewView {
previewViewScrollingContainer.sendSubviewToBack(mainPreviewView)
}
if let placeholderImageView = placeholderImageView {
previewViewScrollingContainer.sendSubviewToBack(placeholderImageView)
}
}
private func updatePreviewContainerLayout() {
if previewViewScrollingContainerLayoutValid {
return
}
guard let previewViewScrollingContainer = previewViewScrollingContainer else {
return
}
if let previewViewScrollingContainerConstraints = previewViewScrollingContainerConstraints {
NSLayoutConstraint.deactivateConstraints(previewViewScrollingContainerConstraints)
self.previewViewScrollingContainerConstraints = nil
}
previewViewScrollingContainer.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
var previewViewInsets = UIEdgeInsets(top: 0, left: 0, bottom: 124, right: 0)
if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) {
previewViewInsets = previewViewInsets + currentEditingTool.preferredPreviewViewInsets
}
constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Left, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Left, multiplier: 1, constant: previewViewInsets.left))
constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Right, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Right, multiplier: 1, constant: -1 * previewViewInsets.right))
constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Top, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Top, multiplier: 1, constant: previewViewInsets.top))
constraints.append(NSLayoutConstraint(item: previewViewScrollingContainer, attribute: .Bottom, relatedBy: .Equal, toItem: previewViewScrollingContainer.superview, attribute: .Bottom, multiplier: 1, constant: -1 * previewViewInsets.bottom))
NSLayoutConstraint.activateConstraints(constraints)
previewViewScrollingContainerConstraints = constraints
previewViewScrollingContainerLayoutValid = true
}
internal func updateRenderedPreviewForceRender(forceRender: Bool) {
mainRenderer?.renderMode = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredRenderMode ?? [.AutoEnhancement, .Crop, .Orientation, .Focus, .PhotoEffect, .ColorAdjustments, .RetricaFilter]
let updatePreviewView: Bool
if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) where !currentEditingTool.wantsDefaultPreviewView {
updatePreviewView = false
} else {
updatePreviewView = baseWorkUIImage == nil ? false : true
}
mainPreviewView?.hidden = !updatePreviewView
if let _ = mainRenderer where updatePreviewView || forceRender {
mainPreviewView?.setNeedsDisplay()
}
frameController?.updatePositioning()
}
// MARK: - Helpers
private func workImageSizeForScreen(screen: UIScreen) -> CGSize {
let screenSize = screen.bounds.size
let screenScale = screen.scale
let scaledScreenSize = screenSize * screenScale
let maxLength = max(scaledScreenSize.width, scaledScreenSize.height)
return CGSize(width: maxLength, height: maxLength)
}
private func orientedCIImageFromUIImage(image: UIImage) -> CIImage {
guard let cgImage = image.CGImage else {
return CIImage.emptyImage()
}
var ciImage = CIImage(CGImage: cgImage)
ciImage = ciImage.imageByApplyingOrientation(Int32(image.imageOrientation.rawValue))
return ciImage
}
private func scaleSize(size: CGSize, toFitSize targetSize: CGSize) -> CGSize {
if size == CGSize.zero {
return CGSize.zero
}
let scale = min(targetSize.width / size.width, targetSize.height / size.height)
return size * scale
}
// MARK: - Tools
private func loadToolsIfNeeded() {
if toolForAction == nil {
var toolForAction = [PhotoEditorAction: PhotoEditToolController]()
for i in 0 ..< options.allowedPhotoEditorActions.count {
let action = options.allowedPhotoEditorActions[i]
if let photoEditModel = photoEditModel, toolController = InstanceFactory.toolControllerForEditorActionType(action, withPhotoEditModel: photoEditModel, configuration: configuration) {
toolController.delegate = self
toolForAction[action] = toolController
}
}
self.toolForAction = toolForAction
}
}
// MARK: - Overlays
@objc private func removeStickerOverlay(overlayView: StickerImageView?) {
guard let overlayView = overlayView else {
return
}
configuration.stickerToolControllerOptions.removedStickerClosure?(overlayView.sticker)
overlayView.removeFromSuperview()
if let elements = previewViewScrollingContainer?.accessibilityElements as? [NSObject], index = elements.indexOf({$0 == overlayView}) {
previewViewScrollingContainer?.accessibilityElements?.removeAtIndex(index)
}
}
private func loadFrameControllerIfNeeded() {
loadToolsIfNeeded()
if let _ = toolForAction?[.Frame] where frameController == nil {
frameController = FrameController()
frameController!.delegate = self
frameController!.imageView = frameImageView
frameController!.imageViewContainerView = mainPreviewView
if let baseWorkUIImage = baseWorkUIImage {
frameController!.imageRatio = Float(baseWorkUIImage.size.width / baseWorkUIImage.size.height)
}
}
}
// MARK: - Actions
/**
Applies all changes to the photo and passes the edited image to the `delegate`.
- parameter sender: The object that initiated the request.
*/
public func save(sender: AnyObject?) {
ProgressView.sharedView.showWithMessage(Localize("Exporting image..."))
// Load photo from disc
if let photoFileURL = photoFileURL, path = photoFileURL.path, photo = UIImage(contentsOfFile: path) {
if let mainPreviewView = mainPreviewView where photoEditModel == uneditedPhotoEditModel && mainPreviewView.subviews.count == 0 {
ProgressView.sharedView.hide()
delegate?.photoEditViewController(self, didSaveImage: photo)
} else if let cgImage = photo.CGImage {
var ciImage = CIImage(CGImage: cgImage)
ciImage = ciImage.imageByApplyingOrientation(Int32(IMGLYOrientation(imageOrientation: photoImageOrientation).rawValue))
let photoEditRenderer = PhotoEditRenderer()
photoEditRenderer.photoEditModel = photoEditModel?.mutableCopy() as? IMGLYPhotoEditMutableModel
photoEditRenderer.originalImage = ciImage
// Generate overlay if needed
if let overlayContainerView = self.overlayContainerView where overlayContainerView.subviews.count > 0 {
// Scale overlayContainerView to match the size of the high resolution photo
let scale = photoEditRenderer.outputImageSize.width / overlayContainerView.bounds.width
let scaledSize = overlayContainerView.bounds.size * scale
let rect = CGRect(origin: .zero, size: scaledSize)
// Create new image context
UIGraphicsBeginImageContextWithOptions(scaledSize, false, 1)
let cachedTransform = overlayContainerView.transform
overlayContainerView.transform = CGAffineTransformScale(overlayContainerView.transform, scale, scale)
// Draw the overlayContainerView on top of the image
overlayContainerView.drawViewHierarchyInRect(rect, afterScreenUpdates: false)
// Restore old transform
overlayContainerView.transform = cachedTransform
// Fetch image and end context
if let cgImage = UIGraphicsGetImageFromCurrentImageContext().CGImage {
(photoEditRenderer.photoEditModel as? IMGLYPhotoEditMutableModel)?.overlayImage = CIImage(CGImage: cgImage)
}
UIGraphicsEndImageContext()
}
let compressionQuality = CGFloat(0.9)
photoEditRenderer.generateOutputImageDataWithCompressionQuality(compressionQuality, metadataSourceImageURL: photoFileURL) { imageData, imageWidth, imageHeight in
dispatch_async(dispatch_get_main_queue()) {
ProgressView.sharedView.hide()
guard let imageData = imageData, image = UIImage(data: imageData) else {
dispatch_async(dispatch_get_main_queue()) {
ProgressView.sharedView.hide()
}
self.delegate?.photoEditViewControllerDidFailToGeneratePhoto(self)
return
}
self.delegate?.photoEditViewController(self, didSaveImage: image)
// Remove temporary file from disc
_ = try? NSFileManager.defaultManager().removeItemAtURL(photoFileURL)
}
}
}
}
}
/**
Discards all changes to the photo and call the `delegate`.
- parameter sender: The object that initiated the request.
*/
public func cancel(sender: AnyObject?) {
if let photoFileURL = photoFileURL {
// Remove temporary file from disc
_ = try? NSFileManager.defaultManager().removeItemAtURL(photoFileURL)
}
delegate?.photoEditViewControllerDidCancel(self)
}
// MARK: - Gesture Handling
private func hideOptionsForOverlayIfNeeded() {
if selectedOverlayView == nil {
if presentedViewController is ContextMenuController {
dismissViewControllerAnimated(true, completion: nil)
}
if let currentEditingTool = delegate?.photoEditViewControllerCurrentEditingTool(self) {
if currentEditingTool is TextOptionsToolController {
delegate?.photoEditViewControllerPopToolController(self)
} else if currentEditingTool is StickerToolController {
delegate?.photoEditViewControllerPopToolController(self)
}
}
}
}
private func showOptionsForOverlayIfNeeded(view: UIView?) {
if let view = view as? StickerImageView {
showOptionsForStickerIfNeeded(view)
} else if let view = view as? TextLabel {
showOptionsForTextIfNeeded(view)
}
}
private func showOptionsForStickerIfNeeded(stickerImageView: StickerImageView) {
guard let photoEditModel = photoEditModel else {
return
}
if !(delegate?.photoEditViewControllerCurrentEditingTool(self) is StickerToolController) {
// swiftlint:disable force_cast
let stickerOptionsToolController = (configuration.getClassForReplacedClass(StickerToolController.self) as! StickerToolController.Type).init(photoEditModel: photoEditModel, configuration: configuration)
// swiftlint:enable force_cast
stickerOptionsToolController.delegate = self
if delegate?.photoEditViewControllerCurrentEditingTool(self) is TextOptionsToolController {
delegate?.photoEditViewController(self, didSelectToolController: stickerOptionsToolController, wantsCurrentTopToolControllerReplaced: true)
} else {
delegate?.photoEditViewController(self, didSelectToolController: stickerOptionsToolController, wantsCurrentTopToolControllerReplaced: false)
}
}
let configurePresentationController = {
if let contextMenuPresentationController = self.stickerContextMenuController.presentationController as? ContextMenuPresentationController {
var viewController: UIViewController = self
while let parent = viewController.parentViewController {
viewController = parent
}
contextMenuPresentationController.passthroughViews = [viewController.view]
contextMenuPresentationController.contentFrame = self.previewViewScrollingContainer?.convertRect(self.previewViewScrollingContainer?.bounds ?? .zero, toView: nil)
if var contentFrame = contextMenuPresentationController.contentFrame where contentFrame.origin.y < self.topLayoutGuide.length {
contentFrame.size.height = contentFrame.size.height - self.topLayoutGuide.length - contentFrame.origin.y
contentFrame.origin.y = self.topLayoutGuide.length
contextMenuPresentationController.contentFrame = contentFrame
}
}
}
if presentedViewController == nil {
presentViewController(stickerContextMenuController, animated: true, completion: nil)
configurePresentationController()
} else if presentedViewController == textContextMenuController {
dismissViewControllerAnimated(false) {
self.presentViewController(self.stickerContextMenuController, animated: false, completion: nil)
configurePresentationController()
}
}
}
private func showOptionsForTextIfNeeded(label: TextLabel) {
guard let photoEditModel = photoEditModel else {
return
}
if !(delegate?.photoEditViewControllerCurrentEditingTool(self) is TextOptionsToolController) {
// swiftlint:disable force_cast
let textOptionsToolController = (configuration.getClassForReplacedClass(TextOptionsToolController.self) as! TextOptionsToolController.Type).init(photoEditModel: photoEditModel, configuration: configuration)
// swiftlint:enable force_cast
textOptionsToolController.delegate = self
if delegate?.photoEditViewControllerCurrentEditingTool(self) is TextToolController || delegate?.photoEditViewControllerCurrentEditingTool(self) is StickerToolController {
delegate?.photoEditViewController(self, didSelectToolController: textOptionsToolController, wantsCurrentTopToolControllerReplaced: true)
} else {
delegate?.photoEditViewController(self, didSelectToolController: textOptionsToolController, wantsCurrentTopToolControllerReplaced: false)
}
}
let configurePresentationController = {
if let contextMenuPresentationController = self.textContextMenuController.presentationController as? ContextMenuPresentationController {
var viewController: UIViewController = self
while let parent = viewController.parentViewController {
viewController = parent
}
contextMenuPresentationController.passthroughViews = [viewController.view]
contextMenuPresentationController.contentFrame = self.previewViewScrollingContainer?.convertRect(self.previewViewScrollingContainer?.bounds ?? .zero, toView: nil)
if var contentFrame = contextMenuPresentationController.contentFrame where contentFrame.origin.y < self.topLayoutGuide.length {
contentFrame.size.height = contentFrame.size.height - self.topLayoutGuide.length - contentFrame.origin.y
contentFrame.origin.y = self.topLayoutGuide.length
contextMenuPresentationController.contentFrame = contentFrame
}
}
}
if presentedViewController == nil {
presentViewController(textContextMenuController, animated: true, completion: nil)
configurePresentationController()
} else if presentedViewController == stickerContextMenuController {
dismissViewControllerAnimated(false) {
self.presentViewController(self.textContextMenuController, animated: false, completion: nil)
configurePresentationController()
}
}
}
@objc private func handleTap(gestureRecognizer: UITapGestureRecognizer) {
let view = gestureRecognizer.view
let location = gestureRecognizer.locationInView(view)
let target = view?.hitTest(location, withEvent: nil)
if let target = target as? StickerImageView {
selectedOverlayView = target
showOptionsForStickerIfNeeded(target)
} else if let target = target as? TextLabel {
selectedOverlayView = target
showOptionsForTextIfNeeded(target)
} else {
selectedOverlayView = nil
hideOptionsForOverlayIfNeeded()
undoManager?.removeAllActions()
}
}
@objc private func handlePan(gestureRecognizer: UIPanGestureRecognizer) {
guard let mainPreviewView = mainPreviewView, mainRenderer = mainRenderer else {
return
}
let location = gestureRecognizer.locationInView(mainPreviewView)
let translation = gestureRecognizer.translationInView(mainPreviewView)
let targetView = mainPreviewView.hitTest(location, withEvent: nil)
switch gestureRecognizer.state {
case .Began:
if targetView is StickerImageView || targetView is TextLabel {
draggedOverlayView = targetView
selectedOverlayView = targetView
showOptionsForOverlayIfNeeded(targetView)
}
case .Changed:
if let draggedOverlayView = draggedOverlayView {
let center = draggedOverlayView.center
undoManager?.registerUndoForTarget(draggedOverlayView) { view in
view.center = center
}
draggedOverlayView.center = center + translation
}
let renderMode = mainRenderer.renderMode
mainRenderer.renderMode = mainRenderer.renderMode.subtract(.Crop)
let outputImageSize = mainRenderer.outputImageSize
mainRenderer.renderMode = renderMode
if let stickerImageView = draggedOverlayView as? StickerImageView, photoEditModel = photoEditModel {
stickerImageView.normalizedCenterInImage = normalizePoint(stickerImageView.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect)
} else if let textLabel = draggedOverlayView as? TextLabel, photoEditModel = photoEditModel {
textLabel.normalizedCenterInImage = normalizePoint(textLabel.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect)
}
gestureRecognizer.setTranslation(CGPoint.zero, inView: mainPreviewView)
case .Cancelled, .Ended:
draggedOverlayView = nil
default:
break
}
}
@objc private func handlePinch(gestureRecognizer: UIPinchGestureRecognizer) {
guard let mainPreviewView = mainPreviewView else {
return
}
if gestureRecognizer.numberOfTouches() >= 2 {
let point1 = gestureRecognizer.locationOfTouch(0, inView: mainPreviewView)
let point2 = gestureRecognizer.locationOfTouch(1, inView: mainPreviewView)
let midPoint = point1 + CGVector(startPoint: point1, endPoint: point2) * 0.5
let scale = gestureRecognizer.scale
let targetView = mainPreviewView.hitTest(midPoint, withEvent: nil)
switch gestureRecognizer.state {
case .Began:
if targetView is StickerImageView || targetView is TextLabel {
draggedOverlayView = targetView
selectedOverlayView = targetView
showOptionsForOverlayIfNeeded(targetView)
}
case .Changed:
if let draggedOverlayView = draggedOverlayView as? StickerImageView {
let transform = draggedOverlayView.transform
undoManager?.registerUndoForTarget(draggedOverlayView) { view in
draggedOverlayView.transform = transform
}
draggedOverlayView.transform = CGAffineTransformScale(transform, scale, scale)
if let selectedOverlayView = selectedOverlayView {
selectedOverlayView.layer.borderWidth = 2 / (0.5 * (draggedOverlayView.transform.xScale + draggedOverlayView.transform.yScale))
}
} else if let draggedOverlayView = draggedOverlayView as? TextLabel {
let fontSize = draggedOverlayView.font.pointSize
undoManager?.registerUndoForTarget(draggedOverlayView) { view in
view.font = draggedOverlayView.font.fontWithSize(fontSize)
view.sizeToFit()
}
draggedOverlayView.font = draggedOverlayView.font.fontWithSize(fontSize * scale)
draggedOverlayView.sizeToFit()
}
gestureRecognizer.scale = 1
case .Cancelled, .Ended:
draggedOverlayView = nil
default:
break
}
}
}
@objc private func handleRotation(gestureRecognizer: UIRotationGestureRecognizer) {
guard let mainPreviewView = mainPreviewView else {
return
}
if gestureRecognizer.numberOfTouches() >= 2 {
let point1 = gestureRecognizer.locationOfTouch(0, inView: mainPreviewView)
let point2 = gestureRecognizer.locationOfTouch(1, inView: mainPreviewView)
let midPoint = point1 + CGVector(startPoint: point1, endPoint: point2) * 0.5
let rotation = gestureRecognizer.rotation
let targetView = mainPreviewView.hitTest(midPoint, withEvent: nil)
switch gestureRecognizer.state {
case .Began:
if targetView is StickerImageView || targetView is TextLabel {
draggedOverlayView = targetView
selectedOverlayView = targetView
showOptionsForOverlayIfNeeded(targetView)
}
case .Changed:
if let draggedOverlayView = draggedOverlayView {
let transform = draggedOverlayView.transform
undoManager?.registerUndoForTarget(draggedOverlayView) { view in
draggedOverlayView.transform = transform
}
draggedOverlayView.transform = CGAffineTransformRotate(transform, rotation)
}
gestureRecognizer.rotation = 0
case .Cancelled, .Ended:
draggedOverlayView = nil
default:
break
}
}
}
// MARK: - Orientation Handling
private func normalizePoint(point: CGPoint, inView view: UIView, baseImageSize: CGSize, normalizedCropRect: CGRect) -> CGPoint {
if normalizedCropRect == IMGLYPhotoEditModel.identityNormalizedCropRect() {
return CGPoint(x: point.x / view.bounds.width, y: point.y / view.bounds.height)
}
let convertedNormalizedCropRect = CGRect(x: normalizedCropRect.origin.x, y: 1 - normalizedCropRect.origin.y - normalizedCropRect.size.height, width: normalizedCropRect.size.width, height: normalizedCropRect.size.height)
let denormalizedCropRect = CGRect(
x: convertedNormalizedCropRect.origin.x * baseImageSize.width,
y: convertedNormalizedCropRect.origin.y * baseImageSize.height,
width: convertedNormalizedCropRect.size.width * baseImageSize.width,
height: convertedNormalizedCropRect.size.height * baseImageSize.height
)
let viewToCroppedImageScale = denormalizedCropRect.size.width / view.bounds.width
let pointInCropRect = CGPoint(x: point.x * viewToCroppedImageScale, y: point.y * viewToCroppedImageScale)
let pointInImage = CGPoint(x: pointInCropRect.x + denormalizedCropRect.origin.x, y: pointInCropRect.y + denormalizedCropRect.origin.y)
return CGPoint(x: pointInImage.x / baseImageSize.width, y: pointInImage.y / baseImageSize.height)
}
private func updateFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) {
if fromOrientation != toOrientation {
updateCropRectFromOrientation(fromOrientation, toOrientation: toOrientation)
updateOverlaysFromOrientation(fromOrientation, toOrientation: toOrientation)
updateFocusControlPointsFromOrientation(fromOrientation, toOrientation: toOrientation)
}
}
private func updateOverlaysFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) {
guard let overlayContainerView = overlayContainerView, mainPreviewView = mainPreviewView, mainRenderer = mainRenderer, containerBounds = previewViewScrollingContainer?.bounds else {
return
}
let outputImageSize = mainRenderer.outputImageSize
let newPreviewSize = scaleSize(outputImageSize, toFitSize: containerBounds.size)
let scale: CGFloat
if newPreviewSize == mainPreviewView.bounds.size {
scale = 1
} else {
scale = min(newPreviewSize.width / overlayContainerView.bounds.height, newPreviewSize.height / overlayContainerView.bounds.width)
}
let geometry = ImageGeometry(inputSize: overlayContainerView.bounds.size)
geometry.appliedOrientation = toOrientation
let transform = geometry.transformFromOrientation(fromOrientation)
for overlay in overlayContainerView.subviews {
if overlay is StickerImageView || overlay is TextLabel {
overlay.center = CGPointApplyAffineTransform(overlay.center, transform)
overlay.center = CGPoint(x: overlay.center.x * scale, y: overlay.center.y * scale)
overlay.transform = CGAffineTransformScale(overlay.transform, scale, scale)
var stickerTransform = transform
stickerTransform.tx = 0
stickerTransform.ty = 0
overlay.transform = CGAffineTransformConcat(overlay.transform, stickerTransform)
}
if let stickerImageView = overlay as? StickerImageView {
let normalizedGeometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1))
normalizedGeometry.appliedOrientation = geometry.appliedOrientation
stickerImageView.normalizedCenterInImage = CGPointApplyAffineTransform(stickerImageView.normalizedCenterInImage, normalizedGeometry.transformFromOrientation(fromOrientation))
} else if let textLabel = overlay as? TextLabel {
let normalizedGeometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1))
normalizedGeometry.appliedOrientation = geometry.appliedOrientation
textLabel.normalizedCenterInImage = CGPointApplyAffineTransform(textLabel.normalizedCenterInImage, normalizedGeometry.transformFromOrientation(fromOrientation))
}
}
}
private func updateCropRectFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) {
guard let photoEditModel = photoEditModel else {
return
}
let geometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1))
geometry.appliedOrientation = toOrientation
let transform = geometry.transformFromOrientation(fromOrientation)
var normalizedCropRect = photoEditModel.normalizedCropRect
// Change origin from bottom left to top left, otherwise the transform won't work
normalizedCropRect = CGRect(x: normalizedCropRect.origin.x, y: 1 - normalizedCropRect.origin.y - normalizedCropRect.height, width: normalizedCropRect.width, height: normalizedCropRect.height)
// Apply transform
normalizedCropRect = CGRectApplyAffineTransform(normalizedCropRect, transform)
// Change origin from top left to bottom left again
normalizedCropRect = CGRect(x: normalizedCropRect.origin.x, y: 1 - normalizedCropRect.origin.y - normalizedCropRect.height, width: normalizedCropRect.width, height: normalizedCropRect.height)
photoEditModel.normalizedCropRect = normalizedCropRect
}
private func updateFocusControlPointsFromOrientation(fromOrientation: IMGLYOrientation, toOrientation: IMGLYOrientation) {
guard let photoEditModel = photoEditModel else {
return
}
let geometry = ImageGeometry(inputSize: CGSize(width: 1, height: 1))
geometry.appliedOrientation = toOrientation
let transform = geometry.transformFromOrientation(fromOrientation)
var controlPoint1 = photoEditModel.focusNormalizedControlPoint1
var controlPoint2 = photoEditModel.focusNormalizedControlPoint2
// Change origin from bottom left to top left, otherwise the transform won't work
controlPoint1 = CGPoint(x: controlPoint1.x, y: 1 - controlPoint1.y)
controlPoint2 = CGPoint(x: controlPoint2.x, y: 1 - controlPoint2.y)
// Apply transform
controlPoint1 = CGPointApplyAffineTransform(controlPoint1, transform)
controlPoint2 = CGPointApplyAffineTransform(controlPoint2, transform)
// Change origin from top left to bottom left again
controlPoint1 = CGPoint(x: controlPoint1.x, y: 1 - controlPoint1.y)
controlPoint2 = CGPoint(x: controlPoint2.x, y: 1 - controlPoint2.y)
photoEditModel.focusNormalizedControlPoint1 = controlPoint1
photoEditModel.focusNormalizedControlPoint2 = controlPoint2
}
}
@available(iOS 8, *)
extension PhotoEditViewController: GLKViewDelegate {
/**
:nodoc:
*/
public func glkView(view: GLKView, drawInRect rect: CGRect) {
if let renderer = mainRenderer {
renderer.drawOutputImageInContext(view.context, inRect: CGRect(x: 0, y: 0, width: view.drawableWidth, height: view.drawableHeight), viewportWidth: view.drawableWidth, viewportHeight: view.drawableHeight)
nextRenderCompletionBlock?()
nextRenderCompletionBlock = nil
}
}
}
@available(iOS 8, *)
extension PhotoEditViewController: UIScrollViewDelegate {
private func updateScrollViewCentering() {
guard let previewViewScrollingContainer = previewViewScrollingContainer else {
return
}
let containerSize = previewViewScrollingContainer.bounds.size
let contentSize = previewViewScrollingContainer.contentSize
let horizontalCenterOffset: CGFloat
if contentSize.width < containerSize.width {
horizontalCenterOffset = (containerSize.width - contentSize.width) * 0.5
} else {
horizontalCenterOffset = 0
}
let verticalCenterOffset: CGFloat
if contentSize.height < containerSize.height {
verticalCenterOffset = (containerSize.height - contentSize.height) * 0.5
} else {
verticalCenterOffset = 0
}
mainPreviewView?.center = CGPoint(
x: contentSize.width * 0.5 + horizontalCenterOffset,
y: contentSize.height * 0.5 + verticalCenterOffset
)
}
private func updateScrollViewContentSize() {
guard let previewViewScrollingContainer = previewViewScrollingContainer else {
return
}
let zoomScale = previewViewScrollingContainer.zoomScale
let workImageSize = lastKnownWorkImageSize
let containerSize = previewViewScrollingContainer.bounds.size
let fittedSize = scaleSize(workImageSize, toFitSize: containerSize)
if lastKnownPreviewViewSize != fittedSize {
previewViewScrollingContainer.zoomScale = 1
lastKnownPreviewViewSize = fittedSize
mainPreviewView?.frame = CGRect(x: 0, y: 0, width: fittedSize.width, height: fittedSize.height)
overlayContainerView?.frame = CGRect(x: 0, y: 0, width: fittedSize.width, height: fittedSize.height)
previewViewScrollingContainer.contentSize = fittedSize
previewViewScrollingContainer.zoomScale = zoomScale
}
updateScrollViewCentering()
}
private func updateScrollViewZoomScaleAnimated(animated: Bool) {
if selectedOverlayView != nil {
previewViewScrollingContainer?.minimumZoomScale = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1
previewViewScrollingContainer?.maximumZoomScale = delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1
previewViewScrollingContainer?.setZoomScale(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, animated: animated)
previewViewScrollingContainer?.scrollEnabled = false
} else {
previewViewScrollingContainer?.minimumZoomScale = min(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, 1)
previewViewScrollingContainer?.maximumZoomScale = max(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, 3)
previewViewScrollingContainer?.setZoomScale(delegate?.photoEditViewControllerCurrentEditingTool(self)?.preferredDefaultPreviewViewScale ?? 1, animated: animated)
previewViewScrollingContainer?.scrollEnabled = true
}
}
/**
:nodoc:
*/
public func scrollViewDidZoom(scrollView: UIScrollView) {
if previewViewScrollingContainer == scrollView {
updateScrollViewCentering()
}
}
/**
:nodoc:
*/
public func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
if previewViewScrollingContainer == scrollView {
mainPreviewView?.contentScaleFactor = scale * UIScreen.mainScreen().scale
updateRenderedPreviewForceRender(false)
}
}
/**
:nodoc:
*/
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
if !options.allowsPreviewImageZoom {
return nil
}
if previewViewScrollingContainer == scrollView {
return mainPreviewView
}
return nil
}
}
@available(iOS 8, *)
extension PhotoEditViewController: UICollectionViewDataSource {
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return options.allowedPhotoEditorActions.count
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let actionType = options.allowedPhotoEditorActions[indexPath.item]
if actionType == .Separator {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoEditViewController.SeparatorCollectionViewCellReuseIdentifier, forIndexPath: indexPath)
if let separatorCell = cell as? SeparatorCollectionViewCell {
separatorCell.separator.backgroundColor = configuration.separatorColor
}
return cell
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoEditViewController.IconCaptionCollectionViewCellReuseIdentifier, forIndexPath: indexPath)
if let iconCaptionCell = cell as? IconCaptionCollectionViewCell {
switch actionType {
case .Separator:
fallthrough
case .Crop:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_crop", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Crop")
iconCaptionCell.accessibilityLabel = Localize("Crop")
case .Orientation:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_orientation", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Orientation")
iconCaptionCell.accessibilityLabel = Localize("Orientation")
case .Filter:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_filters", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Filter")
iconCaptionCell.accessibilityLabel = Localize("Filter")
case .RetricaFilter:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_filters", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Filter")
iconCaptionCell.accessibilityLabel = Localize("Filter")
case .Adjust:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_adjust", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Adjust")
iconCaptionCell.accessibilityLabel = Localize("Adjust")
case .Text:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_text", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Text")
iconCaptionCell.accessibilityLabel = Localize("Text")
case .Sticker:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_sticker", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Sticker")
iconCaptionCell.accessibilityLabel = Localize("Sticker")
case .Focus:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_focus", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Focus")
iconCaptionCell.accessibilityLabel = Localize("Focus")
case .Frame:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_frame", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Frame")
iconCaptionCell.accessibilityLabel = Localize("Frame")
case .Magic:
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_tool_magic", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Magic")
iconCaptionCell.accessibilityLabel = Localize("Magic")
}
options.actionButtonConfigurationClosure?(iconCaptionCell, actionType)
}
return cell
}
}
@available(iOS 8, *)
extension PhotoEditViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let actionType = options.allowedPhotoEditorActions[indexPath.item]
if actionType == .Separator {
return PhotoEditViewController.SeparatorCollectionViewCellSize
}
return PhotoEditViewController.IconCaptionCollectionViewCellSize
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
return UIEdgeInsetsZero
}
let cellSpacing = flowLayout.minimumInteritemSpacing
let cellCount = collectionView.numberOfItemsInSection(section)
let collectionViewWidth = collectionView.bounds.size.width
var totalCellWidth: CGFloat = 0
for i in 0..<cellCount {
let itemSize = self.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: NSIndexPath(forItem: i, inSection: section))
totalCellWidth = totalCellWidth + itemSize.width
}
let totalCellSpacing = cellSpacing * (CGFloat(cellCount) - 1)
let totalCellsWidth = totalCellWidth + totalCellSpacing
let edgeInsets = max((collectionViewWidth - totalCellsWidth) / 2.0, cellSpacing)
return UIEdgeInsets(top: 0, left: edgeInsets, bottom: 0, right: edgeInsets)
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let actionType = options.allowedPhotoEditorActions[indexPath.item]
if actionType == .Separator {
return
}
options.photoEditorActionSelectedClosure?(actionType)
if actionType == .Magic {
guard let photoEditModel = photoEditModel else {
return
}
photoEditModel.performChangesWithBlock {
photoEditModel.autoEnhancementEnabled = !photoEditModel.autoEnhancementEnabled
}
} else {
selectedOverlayView = nil
hideOptionsForOverlayIfNeeded()
if let toolController = toolForAction?[actionType] {
delegate?.photoEditViewController(self, didSelectToolController: toolController, wantsCurrentTopToolControllerReplaced: false)
}
}
collectionView.reloadItemsAtIndexPaths([indexPath])
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
let actionType = options.allowedPhotoEditorActions[indexPath.item]
if actionType == .Magic {
if let iconCaptionCell = cell as? IconCaptionCollectionViewCell {
if photoEditModel?.autoEnhancementEnabled ?? false {
iconCaptionCell.accessibilityTraits |= UIAccessibilityTraitSelected
iconCaptionCell.imageView.image = iconCaptionCell.imageView.image?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.imageView.tintAdjustmentMode = .Dimmed
} else {
iconCaptionCell.accessibilityTraits &= ~UIAccessibilityTraitSelected
iconCaptionCell.imageView.image = iconCaptionCell.imageView.image?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.imageView.tintAdjustmentMode = .Normal
}
}
}
}
}
@available(iOS 8, *)
extension PhotoEditViewController: PhotoEditToolControllerDelegate {
/**
:nodoc:
*/
public func photoEditToolControllerMainRenderer(photoEditToolController: PhotoEditToolController) -> PhotoEditRenderer? {
return mainRenderer
}
/**
:nodoc:
*/
public func photoEditToolControllerBaseImage(photoEditToolController: PhotoEditToolController) -> UIImage? {
return baseWorkUIImage
}
/**
:nodoc:
*/
public func photoEditToolControllerPreviewViewScrollingContainer(photoEditToolController: PhotoEditToolController) -> UIScrollView? {
return previewViewScrollingContainer
}
/**
:nodoc:
*/
public func photoEditToolControllerPreviewView(photoEditToolController: PhotoEditToolController) -> UIView? {
return mainPreviewView
}
/**
:nodoc:
*/
public func photoEditToolControllerOverlayContainerView(photoEditToolController: PhotoEditToolController) -> UIView? {
return overlayContainerView
}
/**
:nodoc:
*/
public func photoEditToolControllerOverlayViews(photoEditToolController: PhotoEditToolController) -> [UIView]? {
return overlayContainerView?.subviews
}
/**
:nodoc:
*/
public func photoEditToolControllerFrameController(photoEditToolController: PhotoEditToolController) -> FrameController? {
return frameController
}
/**
:nodoc:
*/
public func photoEditToolControllerDidFinish(photoEditToolController: PhotoEditToolController) {
if presentedViewController is ContextMenuController && !(photoEditToolController is TextFontToolController || photoEditToolController is TextColorToolController) {
selectedOverlayView = nil
dismissViewControllerAnimated(true, completion: nil)
}
delegate?.photoEditViewControllerPopToolController(self)
}
/**
:nodoc:
*/
public func photoEditToolController(photoEditToolController: PhotoEditToolController, didDiscardChangesInFavorOfPhotoEditModel photoEditModel: IMGLYPhotoEditModel) {
if presentedViewController is ContextMenuController && !(photoEditToolController is TextFontToolController || photoEditToolController is TextColorToolController) {
selectedOverlayView = nil
dismissViewControllerAnimated(true, completion: nil)
}
if let discardedPhotoEditModel = self.photoEditModel {
updateFromOrientation(discardedPhotoEditModel.appliedOrientation, toOrientation: photoEditModel.appliedOrientation)
}
self.photoEditModel?.copyValuesFromModel(photoEditModel)
delegate?.photoEditViewControllerPopToolController(self)
}
/**
:nodoc:
*/
public func photoEditToolController(photoEditToolController: PhotoEditToolController, didChangeToOrientation orientation: IMGLYOrientation, fromOrientation: IMGLYOrientation) {
updateFromOrientation(fromOrientation, toOrientation: orientation)
}
/**
:nodoc:
*/
public func photoEditToolControllerDidChangePreferredRenderMode(photoEditToolController: PhotoEditToolController) {
updateRenderedPreviewForceRender(false)
}
/**
:nodoc:
*/
public func photoEditToolControllerDidChangeWantsDefaultPreviewView(photoEditToolController: PhotoEditToolController) {
updateRenderedPreviewForceRender(false)
}
/**
:nodoc:
*/
public func photoEditToolController(photoEditToolController: PhotoEditToolController, didAddOverlayView view: UIView) {
guard let mainRenderer = mainRenderer else {
return
}
let renderMode = mainRenderer.renderMode
mainRenderer.renderMode = mainRenderer.renderMode.subtract(.Crop)
let outputImageSize = mainRenderer.outputImageSize
mainRenderer.renderMode = renderMode
if let stickerImageView = view as? StickerImageView, photoEditModel = photoEditModel, mainPreviewView = mainPreviewView {
undoManager?.registerUndoForTarget(self) { photoEditViewController in
photoEditViewController.removeStickerOverlay(stickerImageView)
}
stickerImageView.normalizedCenterInImage = normalizePoint(stickerImageView.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect)
} else if let textLabel = view as? TextLabel, photoEditModel = photoEditModel, mainPreviewView = mainPreviewView {
textLabel.activateHandler = { [weak self, unowned textLabel] in
self?.selectedOverlayView = textLabel
self?.showOptionsForTextIfNeeded(textLabel)
}
textLabel.normalizedCenterInImage = normalizePoint(textLabel.center, inView: mainPreviewView, baseImageSize: outputImageSize, normalizedCropRect: photoEditModel.normalizedCropRect)
}
selectedOverlayView = view
showOptionsForOverlayIfNeeded(view)
previewViewScrollingContainer?.accessibilityElements?.append(view)
}
/**
:nodoc:
*/
public func photoEditToolController(photoEditToolController: PhotoEditToolController, didSelectToolController toolController: PhotoEditToolController) {
delegate?.photoEditViewController(self, didSelectToolController: toolController, wantsCurrentTopToolControllerReplaced: false)
}
/**
:nodoc:
*/
public func photoEditToolControllerSelectedOverlayView(photoEditToolController: PhotoEditToolController) -> UIView? {
return selectedOverlayView
}
}
@available(iOS 8, *)
extension PhotoEditViewController: UIGestureRecognizerDelegate {
/**
:nodoc:
*/
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
/**
:nodoc:
*/
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panGestureRecognizer || gestureRecognizer == pinchGestureRecognizer || gestureRecognizer == rotationGestureRecognizer {
if presentedViewController == stickerContextMenuController {
return true
}
if presentedViewController == textContextMenuController {
return true
}
return false
}
return true
}
}
@available(iOS 8, *)
extension PhotoEditViewController: FrameControllerDelegate {
/**
:nodoc:
*/
public func frameControllerBaseImageSize(frameController: FrameController) -> CGSize {
guard let mainRenderer = mainRenderer else {
return .zero
}
let renderMode = mainRenderer.renderMode
mainRenderer.renderMode = mainRenderer.renderMode.subtract(.Crop)
let outputImageSize = mainRenderer.outputImageSize
mainRenderer.renderMode = renderMode
return outputImageSize
}
/**
:nodoc:
*/
public func frameControllerNormalizedCropRect(frameController: FrameController) -> CGRect {
return photoEditModel?.normalizedCropRect ?? .zero
}
}
|
86ba10c7529fb5d8d574a68fabb532d9
| 43.232855 | 247 | 0.684335 | false | false | false | false |
davecom/DKDropMenu
|
refs/heads/master
|
DKDropMenu.swift
|
mit
|
1
|
//The DKDropMenu License
//
//Copyright (c) 2015-2016 David Kopec
//
//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.
//
// DKDropMenu.swift
// DKDropMenu
//
// Created by David Kopec on 6/5/15.
// Copyright (c) 2015 Oak Snow Consulting. All rights reserved.
//
import UIKit
/// Delegate protocol for receiving change in list selection
@objc public protocol DKDropMenuDelegate {
func itemSelected(withIndex: Int, name:String)
@objc optional func collapsedChanged()
}
/// A simple drop down list like expandable menu for iOS
@IBDesignable
public class DKDropMenu: UIView {
@IBInspectable public var itemHeight: CGFloat = 44
@IBInspectable public var selectedFontName: String = "HelveticaNeue-Bold"
@IBInspectable public var listFontName: String = "HelveticaNeue-Thin"
@IBInspectable public var textColor: UIColor = UIColor.darkGray
@IBInspectable public var outlineColor: UIColor = UIColor.lightGray
@IBInspectable public var selectedColor: UIColor = UIColor.green
weak public var delegate: DKDropMenuDelegate? = nil //notified when a selection occurs
private var items: [String] = [String]()
public var selectedItem: String? = nil {
didSet {
setNeedsDisplay()
}
}
public var collapsed: Bool = true {
didSet {
delegate?.collapsedChanged?()
//animate collapsing or opening
UIView.animate(withDuration: 0.5, delay: 0, options: .transitionCrossDissolve, animations: {
var tempFrame = self.frame
if (self.collapsed) {
tempFrame.size.height = self.itemHeight
} else {
if (self.items.count > 1 && self.selectedItem != nil) {
tempFrame.size.height = self.itemHeight * CGFloat(self.items.count)
} else if (self.items.count > 0 && self.selectedItem == nil) {
tempFrame.size.height = self.itemHeight * CGFloat(self.items.count) + self.itemHeight
}
}
self.frame = tempFrame
self.invalidateIntrinsicContentSize()
}, completion: nil)
setNeedsDisplay()
}
}
// MARK: Overridden standard UIView methods
override public func sizeThatFits(_ size: CGSize) -> CGSize {
if (items.count < 2 || collapsed) {
return CGSize(width: size.width, height: itemHeight)
} else {
return CGSize(width: size.width, height: (itemHeight * CGFloat(items.count)))
}
}
override public var intrinsicContentSize: CGSize {
if (items.count < 2 || collapsed) {
return CGSize(width: bounds.size.width, height: itemHeight)
} else {
return CGSize(width: bounds.size.width, height: (itemHeight * CGFloat(items.count)))
}
}
override public func draw(_ rect: CGRect) {
// Drawing code
//draw first box regardless
let context = UIGraphicsGetCurrentContext()
outlineColor.setStroke()
context?.setLineWidth(1.0)
context?.move(to: CGPoint(x: 0, y: itemHeight))
context?.addLine(to: CGPoint(x: 0, y: 0.5))
context?.addLine(to: CGPoint(x: frame.size.width, y: 0.5))
context?.addLine(to: CGPoint(x: frame.size.width, y: itemHeight))
context?.strokePath()
if let sele = selectedItem {
//draw item text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedStringKey.font: UIFont(name: selectedFontName, size: 16)!, NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor: textColor]
if (collapsed) {
let tempS = "\(sele)" //put chevron down facing here if right unicode found
tempS.draw(in: CGRect(x: 20, y: itemHeight / 2 - 10, width: frame.size.width - 40, height: 20), withAttributes: attrs)
} else {
let tempS = "\(sele)" //put chevron up facing here if right unicode found
tempS.draw(in: CGRect(x: 20, y: itemHeight / 2 - 10, width: frame.size.width - 40, height: 20), withAttributes: attrs)
}
//draw selected line
selectedColor.setStroke()
context?.move(to: CGPoint(x: 0, y: itemHeight - 2))
context?.setLineWidth(4.0)
context?.addLine(to: CGPoint(x: frame.width, y: itemHeight - 2))
context?.strokePath()
} else {
context?.move(to: CGPoint(x: 0, y: itemHeight - 1))
context?.setLineWidth(1.0)
context?.addLine(to: CGPoint(x: frame.width, y: itemHeight - 1))
context?.strokePath()
}
//draw lower boxes
if (!collapsed && items.count > 1) {
var currentY = itemHeight
for item in items {
if item == selectedItem {
continue
}
//draw box
outlineColor.setStroke()
context?.setLineWidth(1.0)
context?.move(to: CGPoint(x: 0, y: currentY))
context?.addLine(to: CGPoint(x: 0, y: currentY + itemHeight))
context?.strokePath()
context?.setLineWidth(0.5)
context?.move(to: CGPoint(x: 0, y: currentY + itemHeight - 1))
context?.addLine(to: CGPoint(x: frame.size.width, y: currentY + itemHeight - 1))
context?.strokePath()
context?.setLineWidth(1.0)
context?.move(to: CGPoint(x: frame.size.width, y: currentY + itemHeight))
context?.addLine(to: CGPoint(x: frame.size.width, y: currentY))
context?.strokePath()
//draw item text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedStringKey.font: UIFont(name: listFontName, size: 16)!, NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor: textColor]
item.draw(in: CGRect(x: 20, y: currentY + (itemHeight / 2 - 10), width: frame.size.width - 40, height: 20), withAttributes: attrs)
currentY += itemHeight
}
}
}
// MARK: Add or remove items
/// Add an array of items to the menu
public func add(names: [String]) {
for name in names {
add(name: name)
}
}
/// Add a single item to the menu
public func add(name: String) {
//if we have no selected items, we'll take it
if items.isEmpty {
selectedItem = name
}
items.append(name)
//animate change
if (!collapsed && items.count > 1) {
UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: {
var tempFrame = self.frame
tempFrame.size.height = self.itemHeight * CGFloat(self.items.count)
self.frame = tempFrame
}, completion: nil)
}
//refresh display
setNeedsDisplay()
}
/// Remove a single item from the menu
public func remove(at index: Int) {
if (items[index] == selectedItem) {
selectedItem = nil
}
items.remove(at: index)
//animate change
if (!collapsed && items.count > 1) {
UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: {
var tempFrame = self.frame
tempFrame.size.height = self.itemHeight * CGFloat(self.items.count)
self.frame = tempFrame
}, completion: nil)
} else if (!collapsed) {
UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: {
var tempFrame = self.frame
tempFrame.size.height = self.itemHeight
self.frame = tempFrame
}, completion: nil)
}
setNeedsDisplay()
}
/// Remove the first occurence of item named *name*
public func remove(name: String) {
if let index = items.index(of: name) {
remove(at: index)
}
}
/// Remove all items
public func removeAll() {
selectedItem = nil
items.removeAll()
if (!collapsed) {
UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: {
var tempFrame = self.frame
tempFrame.size.height = self.itemHeight
self.frame = tempFrame
}, completion: nil)
}
setNeedsDisplay()
}
// MARK: Events
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch = touches.first!
let point: CGPoint = touch.location(in: self)
if point.y > itemHeight {
if let dele = delegate {
var thought = Int(point.y / itemHeight) - 1
if let sele = selectedItem {
if items.index(of: sele)! <= thought {
thought += 1
}
}
dele.itemSelected(withIndex: thought, name: items[thought])
selectedItem = items[thought]
}
}
collapsed = !collapsed
}
}
|
689be0c1042974abea9b078431a7e339
| 40.513725 | 199 | 0.586246 | false | false | false | false |
AngryLi/ResourceSummary
|
refs/heads/master
|
iOS/Demos/IBInspectorDemo/IBInspectorDemo/CustomView.swift
|
mit
|
3
|
//
// CustomView.swift
// IBInspectorDemo
//
// Created by 李亚洲 on 16/3/23.
// Copyright © 2016年 angryli. All rights reserved.
//
import UIKit
@IBDesignable
class CustomView: UIView {
// @IBInspectable
// var currentColor : UIColor? {
// didSet(newValue) {
// backgroundColor = newValue
// }
// }
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override var frame: CGRect {
set(newFrame) {
if newFrame.size.width < newFrame.size.height {
self.frame = CGRect(origin: frame.origin, size: CGSize(width: newFrame.size.height, height: newFrame.size.height))
} else {
super.frame = newFrame
}
layer.cornerRadius = frame.size.height * 0.5
}
get {
return super.frame
}
// didSet(newFrame) {
// if newFrame.size.width < newFrame.size.height {
// self.frame = CGRect(origin: frame.origin, size: CGSize(width: newFrame.size.height, height: newFrame.size.height))
// }
// layer.cornerRadius = frame.size.height * 0.5
// }
}
}
extension UIView {
@IBInspectable var boderWidth : CGFloat {
get {
return layer.borderWidth
}
set {
// self.boderWidth = newValue;
layer.borderWidth = newValue
}
}
// @IBInspectable var cornerRadius: CGFloat {
// get {
// return layer.cornerRadius
// }
// set {
// layer.cornerRadius = newValue
// layer.masksToBounds = newValue > 0
// }
// }
@IBInspectable var p_boderColor: UIColor? {
get {
return UIColor(CGColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.CGColor
}
}
}
|
0f0646d1d2761c7e1f02eef3c42e8ca7
| 25.192308 | 132 | 0.540871 | false | false | false | false |
DanielCech/Vapor-Catalogue
|
refs/heads/master
|
Sources/App/Controllers/ArtistController.swift
|
mit
|
1
|
import Vapor
import HTTP
final class ArtistController {
func addRoutes(drop: Droplet) {
let group = drop.grouped("artists")
group.get(handler: index)
group.post(handler: create)
group.get(Artist.self, handler: show)
group.patch(Artist.self, handler: update)
group.delete(Artist.self, handler: delete)
group.get(Artist.self, "albums", handler: albumsIndex)
let searchGroup = group.grouped("search")
searchGroup.get(handler: search)
}
func index(request: Request) throws -> ResponseRepresentable {
return try JSON(node: Artist.all().makeNode())
}
func create(request: Request) throws -> ResponseRepresentable {
var artist = try request.artist()
try artist.save()
return artist
}
func show(request: Request, artist: Artist) throws -> ResponseRepresentable {
return artist
}
func update(request: Request, artist: Artist) throws -> ResponseRepresentable {
let new = try request.artist()
var artist = artist
artist.name = new.name
try artist.save()
return artist
}
func delete(request: Request, artist: Artist) throws -> ResponseRepresentable {
try artist.delete()
return JSON([:])
}
// func makeResource() -> Resource<Artist> {
// return Resource(
// index: index,
// store: create,
// show: show,
// modify: update,
// destroy: delete
// )
// }
func albumsIndex(request: Request, artist: Artist) throws -> ResponseRepresentable {
let children = try artist.albums()
return try JSON(node: children.makeNode())
}
func search(request: Request) throws -> ResponseRepresentable {
let results: Node
if let searchQuery = request.query?["q"]?.string {
results = try Artist.query().filter("name", .contains, searchQuery).all().makeNode()
}
else {
results = []
}
if request.accept.prefers("html") {
let parameters = try Node(node: [
"searchResults": results,
])
return try drop.view.make("index", parameters)
} else {
return JSON(results)
}
}
}
extension Request {
func artist() throws -> Artist {
guard let json = json else { throw Abort.badRequest }
return try Artist(node: json)
}
}
|
6217045bc84d0c974ff7e2038b4f761c
| 27.307692 | 96 | 0.5625 | false | false | false | false |
Moriquendi/SwiftCrunch
|
refs/heads/master
|
MMSVideoFun/MMSVideoFun/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// MMSVideoFun
//
// Created by Michal Smialko on 7/5/14.
// Copyright (c) 2014 NSSpot. All rights reserved.
//
import UIKit
import AVFoundation
import CoreMedia
import MediaPlayer
@infix func + ( left:AVURLAsset,
right:(asset:AVURLAsset, range:Range<Int>)) -> AVURLAsset! {
var fullRange:Range<Int> = Range(start: 0, end: Int(CMTimeGetSeconds(left.duration)))
return (left, fullRange) + right
}
@infix func + ( left:(asset: AVURLAsset, range:Range<Int>),
right:(asset:AVURLAsset, range:Range<Int>)) -> AVURLAsset! {
// ------------------------------------------------- //
func merge() -> AVURLAsset! {
var composition = AVMutableComposition()
var trackId = CMPersistentTrackID(kCMPersistentTrackID_Invalid)
let compositionVideoTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo,
preferredTrackID:CMPersistentTrackID(kCMPersistentTrackID_Invalid))
var t = kCMTimeZero;
let clips = [left.asset.URL, right.asset.URL]
let ranges = [left.range, right.range]
for i in 0..2 {
let sourceAsset = AVURLAsset(URL: clips[i], options: [AVURLAssetPreferPreciseDurationAndTimingKey : true])
// Video
var sourceVideoTrack:AVAssetTrack
if sourceAsset.tracksWithMediaType(AVMediaTypeVideo).count > 0 {
sourceVideoTrack = (sourceAsset.tracksWithMediaType(AVMediaTypeVideo))[0] as AVAssetTrack
}
else {
break
}
var error:NSErrorPointer = nil
var ok = false;
let range = ranges[i]
var startSeconds:Float64 = Float64(range.startIndex)
var durationSeconds:Float64 = Float64(range.endIndex - range.startIndex)
let timeRange:CMTimeRange = CMTimeRange(start: CMTimeMakeWithSeconds(startSeconds, 600),
duration: CMTimeMakeWithSeconds(durationSeconds, 600))
ok = compositionVideoTrack.insertTimeRange(timeRange,
ofTrack: sourceVideoTrack,
atTime: composition.duration,
error: error)
if !ok {
NSLog("something went wrong");
}
// Audio
if sourceAsset.tracksWithMediaType(AVMediaTypeAudio).count > 0 {
let audioTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))
audioTrack.insertTimeRange(timeRange,
ofTrack: sourceAsset.tracksWithMediaType(AVMediaTypeAudio)[0] as AVAssetTrack,
atTime: t,
error: nil)
}
t = CMTimeAdd(t, timeRange.duration);
}
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainsMask, true);
var outputPath:NSString = ""
while true {
outputPath = paths[0] as NSString
let prefix:Int = random()
outputPath = outputPath.stringByAppendingPathComponent("out\(prefix).mov")
if !NSFileManager.defaultManager().fileExistsAtPath(outputPath) {
break
}
}
let outputURL = NSURL(fileURLWithPath: outputPath)
// First cleanup
var error:NSErrorPointer = nil
NSFileManager.defaultManager().removeItemAtURL(outputURL, error: error)
let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)
exporter.outputURL = outputURL
exporter.outputFileType = AVFileTypeQuickTimeMovie
exporter.shouldOptimizeForNetworkUse = true
var finished = false
exporter.exportAsynchronouslyWithCompletionHandler({
if exporter.status != AVAssetExportSessionStatus.Completed {
println("Merge error \(exporter.error)")
}
// Remove old assetes
NSFileManager.defaultManager().removeItemAtURL(left.asset.URL, error: nil)
NSFileManager.defaultManager().removeItemAtURL(right.asset.URL, error: nil)
println("FINISH")
finished = true
})
// Wait for exporter to finish
while !finished {}
// Bleh, fuj. Exporter is deallocated. How to keep it?
println("\(exporter)")
return AVURLAsset(URL: outputURL, options: nil)
}
return merge()
}
class ViewController: UIViewController {
let player = MPMoviePlayerViewController()
@IBAction func didTapButton(sender : UIButton) {
var bundle = NSBundle.mainBundle()
let movie1 = AVURLAsset(URL: bundle.URLForResource("1", withExtension: "mov"), options: nil);
let movie2 = AVURLAsset(URL: bundle.URLForResource("2", withExtension: "mov"), options: nil);
let movie3 = AVURLAsset(URL: bundle.URLForResource("3", withExtension: "mov"), options: nil);
////////////////////////////////////////////////////////////////////////////////////////
// let mergedAsset:AVURLAsset = movie1 + movie2 + movie3
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Hey, this is crazy, so vote for me maybe?
let mergedAsset:AVURLAsset = (movie1, 0..2) + (movie2, 0..2) + (movie3, 2..4)
////////////////////////////////////////////////////////////////////////////////////////
self.player.moviePlayer.contentURL = mergedAsset.URL
}
@IBAction func play(sender : UIButton) {
self.presentViewController(self.player, animated: true, completion: nil)
}
}
|
38393a2103769a04d1ef6008b17641ed
| 28.745455 | 160 | 0.525825 | false | false | false | false |
wangchong321/tucao
|
refs/heads/master
|
WCWeiBo/WCWeiBo/Classes/Model/Main/MainTabBar.swift
|
mit
|
1
|
//
// MainTabBar.swift
// WCWeiBo
//
// Created by 王充 on 15/5/10.
// Copyright (c) 2015年 wangchong. All rights reserved.
//
import UIKit
class MainTabBar: UITabBar {
override func layoutSubviews() {
super.layoutSubviews()
let tabBarNum = 5
let w = frame.width / CGFloat(tabBarNum)
let h = frame.height
let myFrame = CGRectMake(0, 0, w, h)
var index = 0
for v in subviews as! [UIView]{
if v is UIControl && !(v is UIButton) {
// 设置frame
let x = CGFloat(index) * w
v.frame = CGRectMake(x ,CGFloat(0), w, h)
// println(v)
index += (index == 1) ? 2 : 1
}
}
// 设置中间按钮的frame
centerButton.frame = CGRectMake(w * CGFloat(2), 0, w, h)
}
lazy var centerButton : UIButton = {
let btn = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
//btn.backgroundColor = UIColor.redColor()
self.addSubview(btn)
return btn
}()
}
|
102b3ae44906e52d0e833f74718b7415
| 32 | 121 | 0.590909 | false | false | false | false |
Scorocode/scorocode-SDK-swift
|
refs/heads/master
|
todolist/RegisterVC.swift
|
mit
|
1
|
//
// RegisterVC.swift
// todolist
//
// Created by Alexey Kuznetsov on 01.06.17.
// Copyright © 2017 ProfIT. All rights reserved.
//
import UIKit
class RegisterVC : UIViewController {
//Mark: outlets
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textFieldConfirmPassword: UITextField!
@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var buttonRegister: UIButton!
@IBOutlet weak var textFieldEmail: UITextField!
@IBOutlet weak var textFieldName: UITextField!
//Mark: vars
let user = User.sharedInstance
//Mark: override VC functions
override func viewDidLoad() {
super.viewDidLoad()
// keyboard show-hide, resize window.
setupViewResizerOnKeyboardShown()
hideKeyboardWhenTappedAround()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
//MARK: setupUI
func setupUI() {
//round login button
buttonRegister.layer.cornerRadius = 5.0;
buttonRegister.layer.masksToBounds = true;
}
func signup(email: String, password: String, name: String) {
let scUser = SCUser()
scUser.signup(name, email: email, password: password) { (success, error, result) in
if success {
self.user.saveCredentials(email: email, password: password)
self.user.saveTokenToServer()
self.user.parseUser(userDictionary: result?["user"] as? [String: Any])
self.showAlert(title: "Успешно", message: "Вы успешно зарегистрировались") {
let taskListVC = self.storyboard?.instantiateViewController(withIdentifier: "TaskListVC") as! TaskListVC
self.navigationController?.pushViewController(taskListVC, animated: true)
}
} else {
self.showAlert(title: "Регистрация не выполнена!", message: "Попробуйте еще раз.", completion: nil)
}
}
}
//MARK: button actions
@IBAction func buttonRegisterTapped(_ sender: AnyObject) {
guard textFieldPassword.text == textFieldConfirmPassword.text, textFieldConfirmPassword.text != "" else {
showAlert(title: "Пароли должны совпадать", message: "Пароль и подтверждение пароля не совпадают!", completion: nil)
return
}
guard let email = textFieldEmail.text, email != "", let password = textFieldPassword.text, password != "" else {
showAlert(title: "Регистрация не выполнена!", message: "Email и пароль доолжны быть заполнены.", completion: nil)
return
}
signup(email: textFieldEmail.text!, password: textFieldPassword.text!, name: textFieldName.text ?? "")
}
}
|
18ac6e370a944c5edd2d2aae92cbc319
| 36.358974 | 128 | 0.639327 | false | false | false | false |
oleander/bitbar
|
refs/heads/master
|
Sources/Plugin/StopWatch.swift
|
mit
|
1
|
import SwiftyTimer
class StopWatch: Base {
enum Event: String {
case stop, start
}
private let queue = DispatchQueue(label: "StopWatch", qos: .userInteractive, target: .main)
private var timer: Timer?
private let interval: Double
private var fired: Timer?
private weak var delegate: Timeable?
init(every time: Int, delegate: Timeable, start autostart: Bool = true) {
self.interval = Double(time)
super.init()
self.delegate = delegate
if autostart { start() }
}
internal var id: Int {
return ObjectIdentifier(timer ?? self).hashValue
}
public var isActive: Bool {
return timer?.isValid ?? false
}
private func newTimer() -> Timer {
return Timer.new(every: interval, onTick)
}
func fire(then event: Event) {
queue.async { [weak self] in
guard let this = self else { return }
this.onTick()
switch (event, this.isActive) {
case (.start, true):
this.log.info("Already started")
case (.start, false):
this.unsafeStart()
case (.stop, false):
this.log.info("Already stopped")
case (.stop, true):
this.unsafeStop()
}
}
}
func restart() {
log.verbose("Restart timer")
stop()
start()
}
func stop() {
queue.async { [weak self] in
self?.unsafeStop()
}
}
private func unsafeStop() {
queue.async { [weak self] in
self?.both()
}
}
private func invalidate(_ timer: Timer?) {
guard let aTimer = timer else { return }
guard aTimer.isValid else { return }
aTimer.invalidate()
}
func start() {
queue.async { [weak self] in
self?.unsafeStart()
}
}
private func unsafeStart() {
queue.async { [weak self] in
guard let this = self else { return }
if this.isActive { return this.log.info("Already active") }
this.log.verbose("Start timer")
this.both()
this.timer = this.newTimer()
this.timer?.start(modes: .defaultRunLoopMode, .eventTrackingRunLoopMode)
}
}
private func both() {
invalidate(timer)
invalidate(fired)
}
private func onTick() {
if let receiver = delegate {
return receiver.timer(didTick: self)
}
stop()
}
}
|
e2a055fb937d5bc663977e2baa3ae324
| 19.906542 | 93 | 0.608404 | false | false | false | false |
alex-alex/S2Geometry
|
refs/heads/master
|
Sources/S1Angle.swift
|
mit
|
1
|
//
// S1Angle.swift
// S2Geometry
//
// Created by Alex Studnicka on 7/1/16.
// Copyright © 2016 Alex Studnicka. MIT License.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
public struct S1Angle: Equatable, Comparable {
public let radians: Double
public var degrees: Double {
return radians * (180 / M_PI)
}
private func getInteger(multipliedBy m: Double) -> Int64 {
return Int64(round(degrees * m))
}
public var e5: Int64 { return getInteger(multipliedBy: 1e5) }
public var e6: Int64 { return getInteger(multipliedBy: 1e6) }
public var e7: Int64 { return getInteger(multipliedBy: 1e7) }
public init(radians: Double = 0) {
self.radians = radians
}
public init(degrees: Double) {
self.radians = degrees * (M_PI / 180)
}
public init(e5: Int64) {
self.init(degrees: Double(e5) * 1e-5)
}
public init(e6: Int64) {
self.init(degrees: Double(e6) * 1e-6)
}
public init(e7: Int64) {
self.init(degrees: Double(e7) * 1e-7)
}
}
public func ==(lhs: S1Angle, rhs: S1Angle) -> Bool {
return lhs.radians == rhs.radians
}
public func <(lhs: S1Angle, rhs: S1Angle) -> Bool {
return lhs.radians < rhs.radians
}
public func +(lhs: S1Angle, rhs: S1Angle) -> S1Angle {
return S1Angle(radians: lhs.radians + rhs.radians)
}
public func -(lhs: S1Angle, rhs: S1Angle) -> S1Angle {
return S1Angle(radians: lhs.radians - rhs.radians)
}
public func *(lhs: S1Angle, rhs: Double) -> S1Angle {
return S1Angle(radians: lhs.radians * rhs)
}
|
f2eac2950c0cbdf2104c88d83d6e7166
| 19.971831 | 62 | 0.671592 | false | false | false | false |
iOSTestApps/PhoneBattery
|
refs/heads/master
|
PhoneBattery WatchKit Extension/BatteryInformation.swift
|
mit
|
1
|
//
// BatteryInformation.swift
// PhoneBattery
//
// Created by Marcel Voß on 29.07.15.
// Copyright (c) 2015 Marcel Voss. All rights reserved.
//
import UIKit
class BatteryInformation: NSObject {
class func stringForBatteryState(batteryState: UIDeviceBatteryState) -> String {
if batteryState == UIDeviceBatteryState.Full {
return NSLocalizedString("FULL", comment: "")
} else if batteryState == UIDeviceBatteryState.Charging {
return NSLocalizedString("CHARGING", comment: "")
} else if batteryState == UIDeviceBatteryState.Unplugged {
return NSLocalizedString("REMAINING", comment: "")
} else {
return NSLocalizedString("UNKNOWN", comment: "")
}
}
}
|
7b06125d221eb18f1717709c9c7c7cd8
| 28.423077 | 84 | 0.647059 | false | false | false | false |
rolson/arcgis-runtime-samples-ios
|
refs/heads/master
|
arcgis-ios-sdk-samples/Search/Find address/FindAddressViewController.swift
|
apache-2.0
|
1
|
// Copyright 2016 Esri.
//
// 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
import ArcGIS
class FindAddressViewController: UIViewController, AGSGeoViewTouchDelegate, UISearchBarDelegate, UIAdaptivePresentationControllerDelegate, WorldAddressesVCDelegate {
@IBOutlet private var mapView:AGSMapView!
@IBOutlet private var button:UIButton!
@IBOutlet private var searchBar:UISearchBar!
private var locatorTask:AGSLocatorTask!
private var geocodeParameters:AGSGeocodeParameters!
private var graphicsOverlay:AGSGraphicsOverlay!
private let locatorURL = "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["FindAddressViewController", "WorldAddressesViewController"]
//instantiate a map with an imagery with labels basemap
let map = AGSMap(basemap: AGSBasemap.imageryWithLabelsBasemap())
self.mapView.map = map
self.mapView.touchDelegate = self
//initialize the graphics overlay and add to the map view
self.graphicsOverlay = AGSGraphicsOverlay()
self.mapView.graphicsOverlays.addObject(self.graphicsOverlay)
//initialize locator task
self.locatorTask = AGSLocatorTask(URL: NSURL(string: self.locatorURL)!)
//initialize geocode parameters
self.geocodeParameters = AGSGeocodeParameters()
self.geocodeParameters.resultAttributeNames.appendContentsOf(["*"])
self.geocodeParameters.minScore = 75
//register self for the keyboard show notification
//in order to un hide the cancel button for search
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FindAddressViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
}
//method that returns a graphic object for the specified point and attributes
//also sets the leader offset and offset
private func graphicForPoint(point: AGSPoint, attributes: [String: AnyObject]?) -> AGSGraphic {
let markerImage = UIImage(named: "RedMarker")!
let symbol = AGSPictureMarkerSymbol(image: markerImage)
symbol.leaderOffsetY = markerImage.size.height/2
symbol.offsetY = markerImage.size.height/2
let graphic = AGSGraphic(geometry: point, symbol: symbol, attributes: attributes)
return graphic
}
private func geocodeSearchText(text:String) {
//clear already existing graphics
self.graphicsOverlay.graphics.removeAllObjects()
//dismiss the callout if already visible
self.mapView.callout.dismiss()
//perform geocode with input text
self.locatorTask.geocodeWithSearchText(text, parameters: self.geocodeParameters, completion: { [weak self] (results:[AGSGeocodeResult]?, error:NSError?) -> Void in
if let error = error {
self?.showAlert(error.localizedDescription)
}
else {
if let results = results where results.count > 0 {
//create a graphic for the first result and add to the graphics overlay
let graphic = self?.graphicForPoint(results[0].displayLocation!, attributes: results[0].attributes)
self?.graphicsOverlay.graphics.addObject(graphic!)
//zoom to the extent of the result
if let extent = results[0].extent {
self?.mapView.setViewpointGeometry(extent, completion: nil)
}
}
else {
//provide feedback in case of failure
self?.showAlert("No results found")
}
}
})
}
//MARK: - Callout
//method shows the callout for the specified graphic,
//populates the title and detail of the callout with specific attributes
//hides the accessory button
private func showCalloutForGraphic(graphic:AGSGraphic, tapLocation:AGSPoint) {
let addressType = graphic.attributes["Addr_type"] as! String
self.mapView.callout.title = graphic.attributes["Match_addr"] as? String ?? ""
if addressType == "POI" {
self.mapView.callout.detail = graphic.attributes["Place_addr"] as? String ?? ""
}
else {
self.mapView.callout.detail = nil
}
self.mapView.callout.accessoryButtonHidden = true
self.mapView.callout.showCalloutForGraphic(graphic, tapLocation: tapLocation, animated: true)
}
private func showAlert(message:String) {
SVProgressHUD.showErrorWithStatus(message, maskType: .Gradient)
}
//MARK: - AGSGeoViewTouchDelegate
func geoView(geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
//dismiss the callout
self.mapView.callout.dismiss()
//identify graphics at the tapped location
self.mapView.identifyGraphicsOverlay(self.graphicsOverlay, screenPoint: screenPoint, tolerance: 5, returnPopupsOnly: false, maximumResults: 1) { (result: AGSIdentifyGraphicsOverlayResult) -> Void in
if let error = result.error {
self.showAlert(error.localizedDescription)
}
else if result.graphics.count > 0 {
//show callout for the graphic
self.showCalloutForGraphic(result.graphics[0], tapLocation: mapPoint)
}
}
}
//MARK: - UISearchBar delegates
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
self.geocodeSearchText(searchBar.text!)
self.hideKeyboard()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
self.graphicsOverlay.graphics.removeAllObjects()
self.mapView.callout.dismiss()
}
}
func searchBarResultsListButtonClicked(searchBar: UISearchBar) {
self.performSegueWithIdentifier("AddressesListSegue", sender: self)
}
//MARK: - Actions
func keyboardWillShow(sender:AnyObject) {
self.button.hidden = false
}
@IBAction func hideKeyboard() {
self.searchBar.resignFirstResponder()
self.button.hidden = true
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "AddressesListSegue" {
let controller = segue.destinationViewController as! WorldAddressesViewController
controller.presentationController?.delegate = self
controller.popoverPresentationController?.sourceView = self.view
controller.popoverPresentationController?.sourceRect = self.searchBar.frame
controller.preferredContentSize = CGSize(width: 300, height: 200)
controller.delegate = self
}
}
//MARK: - UIAdaptivePresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
//MARK: - AddressesListVCDelegate
func worldAddressesViewController(worldAddressesViewController: WorldAddressesViewController, didSelectAddress address: String) {
self.searchBar.text = address
self.geocodeSearchText(address)
self.dismissViewControllerAnimated(true, completion: nil)
self.hideKeyboard()
}
}
|
ce9ac6db51611bd6c059c82f7ea4c239
| 41.134328 | 206 | 0.671272 | false | false | false | false |
ozpopolam/DoctorBeaver
|
refs/heads/master
|
DoctorBeaver/DataPickerView.swift
|
mit
|
1
|
//
// DataPickerView.swift
// DoctorBeaver
//
// Created by Anastasia Stepanova-Kolupakhina on 03.03.16.
// Copyright © 2016 Anastasia Stepanova-Kolupakhina. All rights reserved.
//
import UIKit
protocol DataPickerViewDelegate: class {
func dataPicker(picker: DataPickerView, didPickValues values: [String])
func dataStillNeeded(fromPicker picker: DataPickerView) -> Bool
}
class DataPickerView: UIView {
weak var view: UIView!
@IBOutlet weak var pickerView: UIPickerView!
weak var delegate: DataPickerViewDelegate?
let minCircularRows = 300
let minCircularRowsMultiplier = 3
var font = UIFont.systemFontOfSize(17.0)
var textColor = UIColor.blackColor()
var isEmpty: Bool { // data sourse is empty
get {
return rowsInComponent.isEmpty
}
}
var needToResetInitialValues = false // need to be reloaded, when user selected some value, but later it wasn't used
var rowsInComponent: [Int] = []
var options: [[String]] = [] {
didSet {
rowsInComponent = []
for component in 0..<options.count {
rowsInComponent.append(circularNumberOfRowsFor(numberOfSourceRows: options[component].count))
}
}
}
var initialValues: [String] = []
var selectedValues: [String] = []
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
pickerView.dataSource = self
pickerView.delegate = self
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "DataPickerView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
func configure(withOptions options: [[String]], andInitialValues initialValues: [String], andDelegate delegate: DataPickerViewDelegate) {
self.options = options
self.initialValues = initialValues
self.delegate = delegate
pickerView.reloadAllComponents()
setPickerToValues(initialValues)
}
func configure(withInitialValues initialValues: [String]) {
self.initialValues = initialValues
setPickerToValues(initialValues)
}
func setPickerToValues(initialValues: [String]) {
for component in 0..<initialValues.count {
if let rowInd = options[component].indexOf(initialValues[component]) {
let row = ( rowsInComponent[component] / options[component].count / 2 ) * options[component].count + rowInd
pickerView.selectRow(row, inComponent: component, animated: true)
}
}
}
func cleanAllData() {
rowsInComponent = []
options = []
initialValues = []
selectedValues = []
}
}
extension DataPickerView: UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return rowsInComponent.count
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return rowsInComponent[component]
}
// number of rows to create effect of barrel
func circularNumberOfRowsFor(numberOfSourceRows rows: Int) -> Int {
var circularRows = 0
if rows >= minCircularRows {
circularRows = rows * minCircularRowsMultiplier
} else {
if minCircularRows % rows == 0 {
circularRows = minCircularRows
} else {
circularRows = rows * (minCircularRows / rows + 1)
}
}
return circularRows
}
}
extension DataPickerView: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView
{
var title: UILabel
if let ttl = view as? UILabel {
title = ttl
} else {
title = UILabel()
}
title.textAlignment = NSTextAlignment.Center
title.font = font
title.textColor = textColor
let sourceRow = row % options[component].count
title.text = options[component][sourceRow]
return title
}
// if all rows are empty -> combination is impossible
func impossibleCombination(selectedValues: [String]) -> Bool {
var selectedString = ""
for s in selectedValues {
selectedString += s
}
if selectedString.isVoid {
return true
} else {
return false
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedValues = []
var value: String
var selectedRow: Int
for ind in 0..<options.count {
selectedRow = pickerView.selectedRowInComponent(ind)
let sourceRow = selectedRow % options[ind].count
value = options[ind][sourceRow]
selectedValues.append(value)
}
selectedRow = pickerView.selectedRowInComponent(component)
if impossibleCombination(selectedValues) {
// select the next row
selectedRow += 1
let sourceRow = (selectedRow) % options[component].count
selectedValues[component] = options[component][sourceRow]
pickerView.selectRow(selectedRow, inComponent: component, animated: true)
}
if let delegate = delegate {
if delegate.dataStillNeeded(fromPicker: self) {
needToResetInitialValues = false
delegate.dataPicker(self, didPickValues: selectedValues)
} else {
needToResetInitialValues = true
}
}
}
}
|
72af1f2159387cbe09d3d308e1f4edf4
| 26.870647 | 139 | 0.681185 | false | false | false | false |
prot3ct/Ventio
|
refs/heads/master
|
Ventio/Ventio/Controllers/AccountViewController.swift
|
apache-2.0
|
1
|
import UIKit
import RxSwift
class AccountViewController: UIViewController
{
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
internal var userData: UserDataProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func onLoginClicked(_ sender: UIButton) {
self.startLoading()
let username = self.usernameTextField.text
let password = self.passwordTextField.text
guard username != nil, password != nil else
{
return
}
userData
.signIn(username: username!, password: password!)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default))
.observeOn(MainScheduler.instance)
.subscribe(onNext: { res in
self.changeInitialViewController(identifier: "myEventsViewController")
self.showSuccess(withStatus: "You have signed in successfully")
}, onError: { error in
print(error)
self.showError(withStatus: "Invalid username or password")
})
.disposed(by: disposeBag)
}
@IBAction func onRegisterClicked(_ sender: UIButton) {
self.startLoading()
let username = self.usernameTextField.text
let password = self.passwordTextField.text
guard username != nil, password != nil else
{
return
}
guard username!.count() >= 4 && username!.count() <= 10 else
{
self.showError(withStatus: "Username must be between 4 and 10 symbols long")
return
}
guard password!.count() >= 4 && password!.count() <= 20 else
{
self.showError(withStatus: "Password must be between 4 and 20 symbols long")
return
}
userData
.register(username: username!, password: password!)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default))
.observeOn(MainScheduler.instance)
.subscribe(onNext: { res in
self.showSuccess(withStatus: "You have registered successfully")
}, onError: { error in
print(error);
self.showError(withStatus: "Username already exists")
})
.disposed(by: disposeBag)
}
private func changeInitialViewController(identifier: String)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = storyboard
.instantiateViewController(withIdentifier: identifier)
UIApplication.shared.keyWindow?.rootViewController = initialViewController
}}
|
c25682ad8967069607cc4c25d3faddd2
| 31.516484 | 88 | 0.593782 | false | false | false | false |
xxxAIRINxxx/ARNPageContainer-Swift
|
refs/heads/master
|
Example/ARNPageContainer-Swift/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ARNPageContainer-Swift
//
// Created by xxxAIRINxxx on 2015/01/20.
// Copyright (c) 2015 xxxAIRINxxx. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var pageContainer : ARNPageContainer = ARNPageContainer()
override func viewDidLoad() {
super.viewDidLoad()
self.pageContainer.setPasentVC(self)
for index in 1...5 {
let controller = UIViewController()
controller.view.clipsToBounds = true
let imageView = UIImageView(image: UIImage(named: "image.JPG"))
imageView.contentMode = .ScaleAspectFill
controller.view.addSubview(imageView)
controller.view.arn_allPin(imageView)
controller.title = "controller \(index)"
self.pageContainer.addViewController(controller)
}
let tabView = ARNPageContainerTabView(frame: CGRectZero)
tabView.font = UIFont.boldSystemFontOfSize(20)
tabView.backgroundColor = UIColor.darkGrayColor()
tabView.titleColor = UIColor(red: 130.0/255.0, green: 130.0/255.0, blue: 255.0/255.0, alpha: 1.0)
tabView.itemTitles = self.pageContainer.headerTitles()
pageContainer.setTopBarView(tabView)
weak var weakTabView = tabView
self.pageContainer.changeOffsetHandler = {(collectionView: UICollectionView, selectedIndex: Int) in
if let _tabView = weakTabView {
_tabView.changeParentScrollView(collectionView, selectedIndex: selectedIndex, totalVCCount: collectionView.numberOfItemsInSection(0))
}
}
weak var weakSelf = self
tabView.selectTitleHandler = {(selectedIndex: Int) in
print("selectTitleBlock selectedIndex : \(selectedIndex)")
if let _self = weakSelf {
_self.pageContainer.setSelectedIndex(selectedIndex, animated: true)
}
}
self.pageContainer.changeIndexHandler = {(selectIndexController: UIViewController, selectedIndex: Int) in
print("changeIndexBlock selectedIndex : \(selectedIndex)")
if let _tabView = weakTabView {
_tabView.selectedIndex = selectedIndex
}
}
self.pageContainer.setSelectedIndex(2, animated: true)
self.pageContainer.topBarHeight = 60.0
}
}
|
036fb9ca56ecc1a8e7080c250af03b89
| 36.953125 | 149 | 0.638534 | false | false | false | false |
groue/GRDB.swift
|
refs/heads/master
|
Tests/CombineExpectations/PublisherExpectation.swift
|
mit
|
1
|
#if canImport(Combine)
import XCTest
/// A name space for publisher expectations
public enum PublisherExpectations { }
/// The base protocol for PublisherExpectation. It is an implementation detail
/// that you are not supposed to use, as shown by the underscore prefix.
public protocol _PublisherExpectationBase {
/// Sets up an XCTestExpectation. This method is an implementation detail
/// that you are not supposed to use, as shown by the underscore prefix.
func _setup(_ expectation: XCTestExpectation)
/// Returns an object that waits for the expectation. If nil, expectation
/// is waited by the XCTestCase.
func _makeWaiter() -> XCTWaiter?
}
extension _PublisherExpectationBase {
public func _makeWaiter() -> XCTWaiter? { nil }
}
/// The protocol for publisher expectations.
///
/// You can build publisher expectations from Recorder returned by the
/// `Publisher.record()` method.
///
/// For example:
///
/// // The expectation for all published elements until completion
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let expectation = recorder.elements
///
/// When a test grants some time for the expectation to fulfill, use the
/// XCTest `wait(for:timeout:description)` method:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherPublishesArrayElements() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let expectation = recorder.elements
/// let elements = try wait(for: expectation, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
/// }
///
/// On the other hand, when the expectation is supposed to be immediately
/// fulfilled, use the PublisherExpectation `get()` method in order to grab the
/// expected value:
///
/// // SUCCESS: no error
/// func testArrayPublisherSynchronouslyPublishesArrayElements() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let elements = try recorder.elements.get()
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
/// }
public protocol PublisherExpectation: _PublisherExpectationBase {
/// The type of the expected value.
associatedtype Output
/// Returns the expected value, or throws an error if the
/// expectation fails.
///
/// For example:
///
/// // SUCCESS: no error
/// func testArrayPublisherSynchronouslyPublishesArrayElements() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let elements = try recorder.elements.get()
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
/// }
func get() throws -> Output
}
extension XCTestCase {
/// Waits for the publisher expectation to fulfill, and returns the
/// expected value.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherPublishesArrayElements() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let elements = try wait(for: recorder.elements, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
/// }
///
/// - parameter publisherExpectation: The publisher expectation.
/// - parameter timeout: The number of seconds within which the expectation
/// must be fulfilled.
/// - parameter description: A string to display in the test log for the
/// expectation, to help diagnose failures.
/// - throws: An error if the expectation fails.
public func wait<R: PublisherExpectation>(
for publisherExpectation: R,
timeout: TimeInterval,
description: String = "")
throws -> R.Output
{
let expectation = self.expectation(description: description)
publisherExpectation._setup(expectation)
if let waiter = publisherExpectation._makeWaiter() {
waiter.wait(for: [expectation], timeout: timeout)
} else {
wait(for: [expectation], timeout: timeout)
}
return try publisherExpectation.get()
}
}
#endif
|
95a47e521c7a15a9e832c1b3add5e250
| 37.477876 | 81 | 0.635005 | false | true | false | false |
IvoPaunov/selfie-apocalypse
|
refs/heads/master
|
Selfie apocalypse/Frameworks/DCKit/UITextFields/DCMandatoryTextField.swift
|
mit
|
1
|
//
// BorderedTextField.swift
// DCKit
//
// Created by Andrey Gordeev on 16/02/15.
// Copyright (c) 2015 Andrey Gordeev ([email protected]). All rights reserved.
//
import UIKit
/// Highlights the text field if the entered value is false.
@IBDesignable
public class DCMandatoryTextField: DCBorderedTextField {
override public var selected: Bool {
didSet {
updateColor()
}
}
@IBInspectable
public var highlightedBorderColor: UIColor = UIColor.redColor() {
didSet {
updateColor()
}
}
@IBInspectable
public var isMandatory: Bool = true
// MARK: - Build control
override public func customInit() {
super.customInit()
updateColor()
isValid()
self.addTarget(self, action: Selector("isValid"), forControlEvents: UIControlEvents.EditingChanged)
}
// MARK: - Initializers
// IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out.
// http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Build control
override public func configurePlaceholder() {
}
// MARK: - Validation
/// Checks if the field's value is valid. Can be overriden by subclasses.
///
/// :return: True, if the field is mandatory and value is not empty.
public func isValid() -> Bool {
if isMandatory {
let valid = !(text ?? "").isEmpty
selected = !valid
return valid
}
else {
return true
}
}
// MARK: - Misc
func updateColor() {
layer.borderColor = selected ? highlightedBorderColor.CGColor : normalBorderColor.CGColor
}
}
|
70e3eed5452603e6a3e1fa32d321b853
| 23.804878 | 118 | 0.598328 | false | false | false | false |
zvonler/PasswordElephant
|
refs/heads/master
|
external/github.com/apple/swift-protobuf/Sources/protoc-gen-swift/EnumGenerator.swift
|
gpl-3.0
|
1
|
// Sources/protoc-gen-swift/EnumGenerator.swift - Enum logic
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This file handles the generation of a Swift enum for each .proto enum.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
import SwiftProtobuf
/// The name of the case used to represent unrecognized values in proto3.
/// This case has an associated value containing the raw integer value.
private let unrecognizedCaseName = "UNRECOGNIZED"
/// Generates a Swift enum from a protobuf enum descriptor.
class EnumGenerator {
private let enumDescriptor: EnumDescriptor
private let generatorOptions: GeneratorOptions
private let namer: SwiftProtobufNamer
/// The values that aren't aliases, sorted by number.
private let mainEnumValueDescriptorsSorted: [EnumValueDescriptor]
private let swiftRelativeName: String
private let swiftFullName: String
init(descriptor: EnumDescriptor,
generatorOptions: GeneratorOptions,
namer: SwiftProtobufNamer
) {
self.enumDescriptor = descriptor
self.generatorOptions = generatorOptions
self.namer = namer
mainEnumValueDescriptorsSorted = descriptor.values.filter({
return $0.aliasOf == nil
}).sorted(by: {
return $0.number < $1.number
})
swiftRelativeName = namer.relativeName(enum: descriptor)
swiftFullName = namer.fullName(enum: descriptor)
}
func generateMainEnum(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
p.print("\n")
p.print(enumDescriptor.protoSourceComments())
p.print("\(visibility)enum \(swiftRelativeName): SwiftProtobuf.Enum {\n")
p.indent()
p.print("\(visibility)typealias RawValue = Int\n")
// Cases/aliases
generateCasesOrAliases(printer: &p)
// Generate the default initializer.
p.print("\n")
p.print("\(visibility)init() {\n")
p.indent()
let dottedDefault = namer.dottedRelativeName(enumValue: enumDescriptor.defaultValue)
p.print("self = \(dottedDefault)\n")
p.outdent()
p.print("}\n")
p.print("\n")
generateInitRawValue(printer: &p)
p.print("\n")
generateRawValueProperty(printer: &p)
p.outdent()
p.print("\n")
p.print("}\n")
}
func generateRuntimeSupport(printer p: inout CodePrinter) {
p.print("\n")
p.print("extension \(swiftFullName): SwiftProtobuf._ProtoNameProviding {\n")
p.indent()
generateProtoNameProviding(printer: &p)
p.outdent()
p.print("}\n")
}
/// Generates the cases or statics (for alias) for the values.
///
/// - Parameter p: The code printer.
private func generateCasesOrAliases(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
for enumValueDescriptor in namer.uniquelyNamedValues(enum: enumDescriptor) {
let comments = enumValueDescriptor.protoSourceComments()
if !comments.isEmpty {
p.print("\n", comments)
}
let relativeName = namer.relativeName(enumValue: enumValueDescriptor)
if let aliasOf = enumValueDescriptor.aliasOf {
let aliasOfName = namer.relativeName(enumValue: aliasOf)
p.print("\(visibility)static let \(relativeName) = \(aliasOfName)\n")
} else {
p.print("case \(relativeName) // = \(enumValueDescriptor.number)\n")
}
}
if enumDescriptor.hasUnknownPreservingSemantics {
p.print("case \(unrecognizedCaseName)(Int)\n")
}
}
/// Generates the mapping from case numbers to their text/JSON names.
///
/// - Parameter p: The code printer.
private func generateProtoNameProviding(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
p.print("\(visibility)static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n")
p.indent()
for v in mainEnumValueDescriptorsSorted {
if v.aliases.isEmpty {
p.print("\(v.number): .same(proto: \"\(v.name)\"),\n")
} else {
let aliasNames = v.aliases.map({ "\"\($0.name)\"" }).joined(separator: ", ")
p.print("\(v.number): .aliased(proto: \"\(v.name)\", aliases: [\(aliasNames)]),\n")
}
}
p.outdent()
p.print("]\n")
}
/// Generates `init?(rawValue:)` for the enum.
///
/// - Parameter p: The code printer.
private func generateInitRawValue(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
p.print("\(visibility)init?(rawValue: Int) {\n")
p.indent()
p.print("switch rawValue {\n")
for v in mainEnumValueDescriptorsSorted {
let dottedName = namer.dottedRelativeName(enumValue: v)
p.print("case \(v.number): self = \(dottedName)\n")
}
if enumDescriptor.hasUnknownPreservingSemantics {
p.print("default: self = .\(unrecognizedCaseName)(rawValue)\n")
} else {
p.print("default: return nil\n")
}
p.print("}\n")
p.outdent()
p.print("}\n")
}
/// Generates the `rawValue` property of the enum.
///
/// - Parameter p: The code printer.
private func generateRawValueProperty(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
p.print("\(visibility)var rawValue: Int {\n")
p.indent()
p.print("switch self {\n")
for v in mainEnumValueDescriptorsSorted {
let dottedName = namer.dottedRelativeName(enumValue: v)
p.print("case \(dottedName): return \(v.number)\n")
}
if enumDescriptor.hasUnknownPreservingSemantics {
p.print("case .\(unrecognizedCaseName)(let i): return i\n")
}
p.print("}\n")
p.outdent()
p.print("}\n")
}
}
|
7286132a3c67a669f8c7d3cb6bc045c4
| 32.233333 | 91 | 0.661317 | false | false | false | false |
angmu/SwiftPlayCode
|
refs/heads/master
|
swift练习/playground Test.playground/Sources/Shape.swift
|
mit
|
1
|
import Foundation
import UIKit
//比较稳定的代码,放着里面
//: # Shape Type
public enum ShapeType {
case Triangle
case Square
case Round
}
//: # Shape View
public class Shape: UIView {
var type: ShapeType = .Triangle
public init(frame: CGRect, type: ShapeType = .Triangle) {
super.init(frame: frame)
self.backgroundColor = UIColor.whiteColor()
self.type = type
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not implement")
}
override public func drawRect(rect: CGRect) {
let bezier: UIBezierPath = UIBezierPath()
switch type {
case .Triangle:
bezier.moveToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.addLineToPoint(CGPoint(x: 100.0, y: 20.0))
bezier.addLineToPoint(CGPoint(x: 30.0, y: 60.0))
case .Square:
bezier.moveToPoint(CGPoint(x: 10.0, y: 20.0))
bezier.addLineToPoint(CGPoint(x: 90.0, y: 20.0))
bezier.addLineToPoint(CGPoint(x: 90.0, y: 80.0))
bezier.addLineToPoint(CGPoint(x: 10.0, y: 80.0))
case .Round:
bezier.addArcWithCenter(CGPoint(x: self.center.x, y: self.center.y), radius: 25.0, startAngle: 0, endAngle: CGFloat(M_PI) * 2.0, clockwise: true)
}
bezier.lineWidth = 2.0
let fillColor = UIColor.redColor()
fillColor.set()
bezier.closePath()
bezier.fill()
}
}
|
a7546b90e22fddf81ae56fd928fb52a2
| 26.142857 | 157 | 0.571053 | false | false | false | false |
spark/photon-tinker-ios
|
refs/heads/master
|
Photon-Tinker/Mesh/Gen3SetupControlPanelPrepareForPairingViewController.swift
|
apache-2.0
|
1
|
//
// Created by Raimundas Sakalauskas on 9/20/18.
// Copyright (c) 2018 Particle. All rights reserved.
//
import UIKit
import AVFoundation
import AVKit
class Gen3SetupControlPanelPrepareForPairingViewController: Gen3SetupViewController, Storyboardable {
internal var videoPlayer: AVPlayer?
internal var layer: AVPlayerLayer?
internal var defaultVideo : AVPlayerItem?
internal var defaultVideoURL: URL!
internal var isSOM:Bool!
@IBOutlet weak var textLabel: ParticleLabel!
@IBOutlet weak var videoView: UIControl!
@IBOutlet weak var signalSwitch: UISwitch!
@IBOutlet weak var signalLabel: ParticleLabel!
@IBOutlet weak var signalWarningLabel: ParticleLabel!
private var device: ParticleDevice!
override var customTitle: String {
return Gen3SetupStrings.ControlPanel.PrepareForPairing.Title
}
override func viewDidLoad() {
super.viewDidLoad()
setContent()
}
func setup(device: ParticleDevice!) {
self.device = device
self.deviceName = device.name!
self.deviceType = device.type
self.isSOM = (self.deviceType! == ParticleDeviceType.aSeries || self.deviceType! == ParticleDeviceType.bSeries || self.deviceType! == ParticleDeviceType.xSeries)
}
override func setStyle() {
videoView.backgroundColor = .clear
videoView.layer.cornerRadius = 5
videoView.clipsToBounds = true
textLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor)
signalLabel.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor)
signalWarningLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.SmallSize, color: ParticleStyle.PrimaryTextColor)
}
override func setContent() {
textLabel.text = Gen3SetupStrings.ControlPanel.PrepareForPairing.Text
signalLabel.text = Gen3SetupStrings.ControlPanel.PrepareForPairing.Signal
signalWarningLabel.text = Gen3SetupStrings.ControlPanel.PrepareForPairing.SignalWarning
initializeVideoPlayerWithVideo(videoFileName: "prepare_for_pairing")
videoView.addTarget(self, action: #selector(videoViewTapped), for: .touchUpInside)
view.setNeedsLayout()
view.layoutIfNeeded()
}
@objc public func videoViewTapped(sender: UIControl) {
// TODO: uncomment this, but figure out how to exit fullscreen video mode if device enters listening mode while it is visible (otherwise flow stops)
// let player = AVPlayer(url: defaultVideoURL)
//
// let playerController = AVPlayerViewController()
// playerController.player = player
// present(playerController, animated: true) {
// player.play()
// }
}
@IBAction func signalSwitchValueChanged(_ sender: Any) {
if signalSwitch.isOn {
self.device.signal(true)
} else {
self.device.signal(false)
}
}
func initializeVideoPlayerWithVideo(videoFileName: String) {
if (self.videoPlayer != nil) {
return
}
// Create a new AVPlayerItem with the asset and an
// array of asset keys to be automatically loaded
let defaultVideoString:String? = Bundle.main.path(forResource: videoFileName, ofType: "mov")
defaultVideoURL = URL(fileURLWithPath: defaultVideoString!)
defaultVideo = AVPlayerItem(url: defaultVideoURL)
self.videoPlayer = AVPlayer(playerItem: defaultVideo)
layer = AVPlayerLayer(player: videoPlayer)
layer!.frame = videoView.bounds
layer!.videoGravity = AVLayerVideoGravity.resizeAspect
NSLog("initializing layer?")
videoView.layer.addSublayer(layer!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setVideoLoopObserver()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layer?.frame = videoView.bounds
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.device.signal(false)
self.signalSwitch.setOn(false, animated: false)
desetVideoLoopObserver()
}
func desetVideoLoopObserver() {
self.videoPlayer?.pause()
NotificationCenter.default.removeObserver(self.videoPlayer?.currentItem)
}
func setVideoLoopObserver() {
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.videoPlayer?.currentItem, queue: .main) { _ in
self.videoPlayer?.seek(to: CMTime.zero)
self.videoPlayer?.play()
}
self.videoPlayer?.seek(to: CMTime.zero)
self.videoPlayer?.play()
}
}
|
9974597d82181a539021f1f70f16deb9
| 30.406452 | 169 | 0.690427 | false | false | false | false |
Henawey/TheArabianCenter
|
refs/heads/master
|
TheArabianCenter/ShareConfigurator.swift
|
mit
|
1
|
//
// ShareConfigurator.swift
// TheArabianCenter
//
// Created by Ahmed Henawey on 2/23/17.
// Copyright (c) 2017 Ahmed Henawey. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
// MARK: - Connect View, Interactor, and Presenter
extension ShareViewController: SharePresenterOutput
{
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
router.passDataToNextScene(segue: segue)
}
}
extension ShareInteractor: ShareViewControllerOutput
{
}
extension SharePresenter: ShareInteractorOutput
{
}
class ShareConfigurator
{
// MARK: - Object lifecycle
static let sharedInstance = ShareConfigurator()
private init() {}
// MARK: - Configuration
func configure(viewController: ShareViewController)
{
let router = ShareRouter()
router.viewController = viewController
let presenter = SharePresenter()
presenter.output = viewController
let interactor = ShareInteractor()
interactor.output = presenter
viewController.output = interactor
viewController.router = router
}
}
|
35f7babd68b84d3a3e41c2c879aaf72e
| 20.732143 | 79 | 0.723911 | false | true | false | false |
jiaxw32/ZRSwiftKit
|
refs/heads/master
|
ZRSwiftKit/Demo/MonkeyPintch/TickleGestureRecognizer.swift
|
mit
|
1
|
//
// TickleGestureRecognizer.swift
// ZRSwiftKit
//
// Created by jiaxw-mac on 2017/9/22.
// Copyright © 2017年 jiaxw32. All rights reserved.
//
import UIKit
class TickleGestureRecognizer: UIGestureRecognizer {
let requiredTickles = 2
let distanceForTickleGesture: CGFloat = 10.0
enum Direction: Int {
case DirectionUnknow = 0
case DirectionLeft
case DirectionRight
}
var tickleCount: Int = 0
var curTickleStart = CGPoint.zero
var lastDirection = Direction.DirectionUnknow
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
if let touch = touches.first {
curTickleStart = touch.location(in: self.view)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
if let touch = touches.first {
let ticklePoint = touch.location(in: self.view)
let moveAmt = ticklePoint.x - curTickleStart.x
print("moveAmt:\(moveAmt)")
var curDirection = Direction.DirectionUnknow
if moveAmt >= 0 {
curDirection = .DirectionRight
} else {
curDirection = .DirectionLeft
}
if abs(moveAmt) < distanceForTickleGesture {
return
}
if lastDirection == .DirectionUnknow || (lastDirection == .DirectionLeft && curDirection == .DirectionRight) || (lastDirection == .DirectionRight && curDirection == .DirectionLeft) {
self.tickleCount += 1
self.curTickleStart = ticklePoint
self.lastDirection = curDirection
print("current direction:\(curDirection),tickle count:\(tickleCount)")
if state == .possible && tickleCount > requiredTickles {
state = .ended
}
}
}
}
override func reset() {
self.tickleCount = 0
self.curTickleStart = CGPoint.zero
self.lastDirection = .DirectionUnknow
if state == .possible {
state = .failed
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
reset()
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
reset()
}
}
|
aabcea30487be5527d299ff72e79c8b2
| 29.769231 | 194 | 0.570417 | false | false | false | false |
salesawagner/wascar
|
refs/heads/master
|
wascarTests/ViewModels/PlaceDetailViewModelTests.swift
|
mit
|
1
|
//
// PlaceDetailViewModelTests.swift
// wascar
//
// Created by Wagner Sales on 25/11/16.
// Copyright © 2016 Wagner Sales. All rights reserved.
//
import XCTest
@testable import wascar
class PlaceDetailViewModelTests: WCARTest {
func testInitialization() {
let placeCellViewModel = PlaceDetailViewModel(place: self.place)
XCTAssertNotNil(placeCellViewModel, "The place detail view model should not be nil.")
}
func testUpdatePlace() {
let expectation = self.expectation(description: #function)
let placeDetailViewModel = PlaceDetailViewModel(place: self.place)
placeDetailViewModel.loadPlaceById { (success) in
expectation.fulfill()
XCTAssert(success, "The success should be true.")
}
self.waitForExpectations(timeout: 60, handler: nil)
}
func testUpdatePlaceFail() {
let expectation = self.expectation(description: #function)
let placeDetailViewModel = PlaceDetailViewModel(place: self.place)
placeDetailViewModel.placeId = ""
placeDetailViewModel.loadPlaceById { (success) in
expectation.fulfill()
XCTAssert(success == false, "The success should be false.")
}
self.waitForExpectations(timeout: 60, handler: nil)
}
}
|
a0d56011628d22001a41f69121e8607d
| 26.627907 | 87 | 0.746633 | false | true | false | false |
JadenGeller/Edgy
|
refs/heads/master
|
Edgy/Edgy/UniqueNode.swift
|
mit
|
1
|
//
// UniqueNode.swift
// Edgy
//
// Created by Jaden Geller on 12/29/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
public class UniqueNode<Element>: Hashable {
public let element: Element
public init(_ element: Element) {
self.element = element
}
public var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
}
public func ==<Element>(lhs: UniqueNode<Element>, rhs: UniqueNode<Element>) -> Bool {
return lhs === rhs
}
|
1d19a036081526ee25337470df201a84
| 20.521739 | 85 | 0.643725 | false | false | false | false |
yoichitgy/SwinjectPropertyLoader
|
refs/heads/master
|
Tests/Resolver+PropertiesSpec.swift
|
mit
|
1
|
//
// Resolver+PropertiesSpec.swift
// SwinjectPropertyLoader
//
// Created by Yoichi Tagaya on 5/8/16.
// Copyright © 2016 Swinject Contributors. All rights reserved.
//
import Foundation
import Quick
import Nimble
import Swinject
import SwinjectPropertyLoader
class Resolver_PropertiesSpec: QuickSpec {
override func spec() {
var container: Container!
beforeEach {
container = Container()
}
describe("JSON properties") {
it("can load properties from a single loader") {
let loader = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first")
try! container.applyPropertyLoader(loader)
container.register(Properties.self) { r in
let properties = Properties()
properties.stringValue = r.property("test.string")!
properties.optionalStringValue = r.property("test.string")
properties.implicitStringValue = r.property("test.string")
properties.intValue = r.property("test.int")!
properties.optionalIntValue = r.property("test.int")
properties.implicitIntValue = r.property("test.int")
properties.doubleValue = r.property("test.double")!
properties.optionalDoubleValue = r.property("test.double")
properties.implicitDoubleValue = r.property("test.double")
properties.arrayValue = r.property("test.array")!
properties.optionalArrayValue = r.property("test.array")
properties.implicitArrayValue = r.property("test.array")
properties.dictValue = r.property("test.dict")!
properties.optionalDictValue = r.property("test.dict")
properties.implicitDictValue = r.property("test.dict")
properties.boolValue = r.property("test.bool")!
properties.optionalBoolValue = r.property("test.bool")
properties.implicitBoolValue = r.property("test.bool")
return properties
}
let properties = container.resolve(Properties.self)!
expect(properties.stringValue) == "first"
expect(properties.optionalStringValue) == "first"
expect(properties.implicitStringValue) == "first"
expect(properties.intValue) == 100
expect(properties.optionalIntValue) == 100
expect(properties.implicitIntValue) == 100
expect(properties.doubleValue) == 30.50
expect(properties.optionalDoubleValue) == 30.50
expect(properties.implicitDoubleValue) == 30.50
expect(properties.arrayValue.count) == 2
expect(properties.arrayValue[0]) == "item1"
expect(properties.arrayValue[1]) == "item2"
expect(properties.optionalArrayValue!.count) == 2
expect(properties.optionalArrayValue![0]) == "item1"
expect(properties.optionalArrayValue![1]) == "item2"
expect(properties.implicitArrayValue.count) == 2
expect(properties.implicitArrayValue![0]) == "item1"
expect(properties.implicitArrayValue![1]) == "item2"
expect(properties.dictValue.count) == 2
expect(properties.dictValue["key1"]) == "item1"
expect(properties.dictValue["key2"]) == "item2"
expect(properties.optionalDictValue!.count) == 2
expect(properties.optionalDictValue!["key1"]) == "item1"
expect(properties.optionalDictValue!["key2"]) == "item2"
expect(properties.implicitDictValue.count) == 2
expect(properties.implicitDictValue!["key1"]) == "item1"
expect(properties.implicitDictValue!["key2"]) == "item2"
expect(properties.boolValue) == true
expect(properties.optionalBoolValue) == true
expect(properties.implicitBoolValue) == true
}
it("can load properties from multiple loader") {
let loader = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first")
let loader2 = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "second")
try! container.applyPropertyLoader(loader)
try! container.applyPropertyLoader(loader2)
container.register(Properties.self) { r in
let properties = Properties()
properties.stringValue = r.property("test.string")! // from loader2
properties.intValue = r.property("test.int")! // from loader
return properties
}
let properties = container.resolve(Properties.self)!
expect(properties.stringValue) == "second"
expect(properties.intValue) == 100
}
}
describe("Plist properties") {
it("can load properties from a single loader") {
let loader = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first")
try! container.applyPropertyLoader(loader)
container.register(Properties.self) { r in
let properties = Properties()
properties.stringValue = r.property("test.string")!
properties.optionalStringValue = r.property("test.string")
properties.implicitStringValue = r.property("test.string")
properties.intValue = r.property("test.int")!
properties.optionalIntValue = r.property("test.int")
properties.implicitIntValue = r.property("test.int")
properties.doubleValue = r.property("test.double")!
properties.optionalDoubleValue = r.property("test.double")
properties.implicitDoubleValue = r.property("test.double")
properties.arrayValue = r.property("test.array")!
properties.optionalArrayValue = r.property("test.array")
properties.implicitArrayValue = r.property("test.array")
properties.dictValue = r.property("test.dict")!
properties.optionalDictValue = r.property("test.dict")
properties.implicitDictValue = r.property("test.dict")
properties.boolValue = r.property("test.bool")!
properties.optionalBoolValue = r.property("test.bool")
properties.implicitBoolValue = r.property("test.bool")
return properties
}
let properties = container.resolve(Properties.self)!
expect(properties.stringValue) == "first"
expect(properties.optionalStringValue) == "first"
expect(properties.implicitStringValue) == "first"
expect(properties.intValue) == 100
expect(properties.optionalIntValue) == 100
expect(properties.implicitIntValue) == 100
expect(properties.doubleValue) == 30.50
expect(properties.optionalDoubleValue) == 30.50
expect(properties.implicitDoubleValue) == 30.50
expect(properties.arrayValue.count) == 2
expect(properties.arrayValue[0]) == "item1"
expect(properties.arrayValue[1]) == "item2"
expect(properties.optionalArrayValue!.count) == 2
expect(properties.optionalArrayValue![0]) == "item1"
expect(properties.optionalArrayValue![1]) == "item2"
expect(properties.implicitArrayValue.count) == 2
expect(properties.implicitArrayValue![0]) == "item1"
expect(properties.implicitArrayValue![1]) == "item2"
expect(properties.dictValue.count) == 2
expect(properties.dictValue["key1"]) == "item1"
expect(properties.dictValue["key2"]) == "item2"
expect(properties.optionalDictValue!.count) == 2
expect(properties.optionalDictValue!["key1"]) == "item1"
expect(properties.optionalDictValue!["key2"]) == "item2"
expect(properties.implicitDictValue.count) == 2
expect(properties.implicitDictValue!["key1"]) == "item1"
expect(properties.implicitDictValue!["key2"]) == "item2"
expect(properties.boolValue) == true
expect(properties.optionalBoolValue) == true
expect(properties.implicitBoolValue) == true
}
it("can load properties from multiple loader") {
let loader = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first")
let loader2 = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "second")
try! container.applyPropertyLoader(loader)
try! container.applyPropertyLoader(loader2)
container.register(Properties.self) { r in
let properties = Properties()
properties.stringValue = r.property("test.string")! // from loader2
properties.intValue = r.property("test.int")! // from loader
return properties
}
let properties = container.resolve(Properties.self)!
expect(properties.stringValue) == "second"
expect(properties.intValue) == 100
}
}
}
}
|
45f22aa315bbb669829c73bee7e44cde
| 48.924171 | 107 | 0.53484 | false | true | false | false |
fishcafe/SunnyHiddenBar
|
refs/heads/master
|
SunnyHiddenBar/Classes/UIViewController+SunnyHiddenBar.swift
|
mit
|
1
|
//
// UIViewController+SunnyHiddenBar.swift
// SunnyHiddenBar
//
// Created by amaker on 16/4/19.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
/** SunnyHiddenBar Extends UIViewController
*/
//定义关联的Key
let key = "keyScrollView"
let navBarBackgroundImageKey = "navBarBackgroundImage"
let isLeftAlphaKey = "isLeftAlpha"
let isRightAlphaKey = "isRightAlpha"
let isTitleAlphaKey = "isTitleAlpha"
var alpha:CGFloat = 0;
public extension UIViewController {
var keyScrollView:UIScrollView?{
set{
objc_setAssociatedObject(self, key, keyScrollView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get{
return objc_getAssociatedObject(self, key) as? UIScrollView
}
}
var navBarBackgroundImage:UIImage?{
set{
objc_setAssociatedObject(self, navBarBackgroundImageKey, navBarBackgroundImage, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get{
return objc_getAssociatedObject(self, navBarBackgroundImageKey) as? UIImage
}
}
var isLeftAlpha:Bool?{
set{
return objc_setAssociatedObject(self, isLeftAlphaKey, (isLeftAlpha), .OBJC_ASSOCIATION_ASSIGN)
}
get{
return objc_getAssociatedObject(self, isLeftAlphaKey) as? Bool
}
}
var isRightAlpha:Bool?{
set{
return objc_setAssociatedObject(self, isRightAlphaKey, (isRightAlpha), .OBJC_ASSOCIATION_ASSIGN)
}
get{
return objc_getAssociatedObject(self, isRightAlphaKey) as? Bool
}
}
var isTitleAlpha:Bool?{
set{
return objc_setAssociatedObject(self, isTitleAlphaKey, (isTitleAlpha), .OBJC_ASSOCIATION_ASSIGN)
}
get{
return objc_getAssociatedObject(self, isTitleAlphaKey) as? Bool
}
}
func scrollControlByOffsetY(offsetY:CGFloat){
if self.getScrollerView() != Optional.None{
let scrollerView = self.getScrollerView()
alpha = scrollerView.contentOffset.y/offsetY
}else {
return
}
alpha = (alpha <= 0) ? 0 : alpha
alpha = (alpha >= 1) ? 1 : alpha
//TODO: titleView alpha no fix
self.navigationItem.leftBarButtonItem?.customView?.alpha = (self.isLeftAlpha != nil) ? alpha : 1
self.navigationItem.titleView?.alpha = (self.isTitleAlpha != nil) ? alpha : 1
self.navigationItem.rightBarButtonItem?.customView?.alpha = (self.isRightAlpha != nil) ? alpha : 1
self.navigationController?.navigationBar.subviews.first?.alpha = alpha
}
func setInViewWillAppear() {
struct Static {
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
self.navBarBackgroundImage = self.navigationController?.navigationBar.backgroundImageForBarMetrics(.Default)
}
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.subviews.first?.alpha = 0
if self.keyScrollView != nil {
self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y - 1)
self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y + 1)
}
}
func setInViewWillDisappear() {
self.navigationController?.navigationBar.subviews.first?.alpha = 1
self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = nil
}
func getScrollerView() -> UIScrollView{
if self.isKindOfClass(UITableViewController) || self.isKindOfClass(UICollectionViewController) {
return self.view as! UIScrollView
} else {
for myView in self.view.subviews {
if myView.isEqual(self.keyScrollView) && myView.isKindOfClass(UIScrollView) || myView.isEqual(self.keyScrollView) && view.isKindOfClass(UIScrollView){
return myView as! UIScrollView
}
}
}
return Optional.None!
}
}
|
deda142fb73e25ddc8b872e9cb866850
| 29.588652 | 166 | 0.632506 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Library/String+Attributed.swift
|
apache-2.0
|
1
|
import Foundation
import UIKit
public func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString {
let combined = NSMutableAttributedString()
combined.append(left)
combined.append(right)
return NSMutableAttributedString(attributedString: combined)
}
public extension String {
func attributed(
with font: UIFont,
foregroundColor: UIColor,
attributes: [NSAttributedString.Key: Any],
bolding strings: [String]
) -> NSAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self)
let fullRange = (self as NSString).localizedStandardRange(of: self)
let regularFontAttributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: foregroundColor
]
.withAllValuesFrom(attributes)
attributedString.addAttributes(regularFontAttributes, range: fullRange)
let boldFontAttribute = [NSAttributedString.Key.font: font.bolded]
for string in strings {
attributedString.addAttributes(
boldFontAttribute,
range: (self as NSString).localizedStandardRange(of: string)
)
}
return attributedString
}
}
|
770e8fe10be1d0f3d27729c006f652aa
| 28.825 | 93 | 0.74518 | false | false | false | false |
wuzzapcom/Fluffy-Book
|
refs/heads/master
|
FluffyBook/ContentsTableViewController.swift
|
mit
|
1
|
//
// ContentsTableViewController.swift
// FluffyBook
//
// Created by Владимир Лапатин on 20.05.17.
// Copyright © 2017 FluffyBook. All rights reserved.
//
import UIKit
class ContentsTableViewController: UITableViewController {
public var currentBookModel : BookModel? //set in segue
fileprivate var contentsTableViewModel : ContentsTableViewModel?
public var delegate:TransferDataProtocol?
fileprivate var settedValue : Int?
override func viewDidLoad() {
super.viewDidLoad()
guard currentBookModel != nil else {
print("No book model")
return
}
let pair = currentBookModel!.getTitles()
contentsTableViewModel = ContentsTableViewModel(withContent: pair.0)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contentsTableViewModel!.getNumberOfElements()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CONTENT_CELL_IDENTIFIER, for: indexPath)
cell.textLabel?.text = contentsTableViewModel!.getChapterTitle(withIndexPath: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
settedValue = indexPath.row
navigationController?.popViewController(animated: true)
}
override func viewDidDisappear(_ animated: Bool) {
delegate?.setSelectedRow(number: settedValue)
}
}
|
35a916b7505d2217a851faf9c172b948
| 25.895522 | 116 | 0.663152 | false | false | false | false |
NickAger/elm-slider
|
refs/heads/master
|
Modules/HTTP/Sources/HTTP/Serializer/RequestSerializer.swift
|
mit
|
5
|
public class RequestSerializer {
let stream: Stream
let bufferSize: Int
public init(stream: Stream, bufferSize: Int = 2048) {
self.stream = stream
self.bufferSize = bufferSize
}
public func serialize(_ request: Request, deadline: Double) throws {
let newLine: [UInt8] = [13, 10]
try stream.write("\(request.method) \(request.url.absoluteString) HTTP/\(request.version.major).\(request.version.minor)", deadline: deadline)
try stream.write(newLine, deadline: deadline)
for (name, value) in request.headers.headers {
try stream.write("\(name): \(value)", deadline: deadline)
try stream.write(newLine, deadline: deadline)
}
try stream.write(newLine, deadline: deadline)
switch request.body {
case .buffer(let buffer):
try stream.write(buffer, deadline: deadline)
case .reader(let reader):
while !reader.closed {
let buffer = try reader.read(upTo: bufferSize, deadline: deadline)
guard !buffer.isEmpty else {
break
}
try stream.write(String(buffer.count, radix: 16), deadline: deadline)
try stream.write(newLine, deadline: deadline)
try stream.write(buffer, deadline: deadline)
try stream.write(newLine, deadline: deadline)
}
try stream.write("0", deadline: deadline)
try stream.write(newLine, deadline: deadline)
try stream.write(newLine, deadline: deadline)
case .writer(let writer):
let body = BodyStream(stream)
try writer(body)
try stream.write("0", deadline: deadline)
try stream.write(newLine, deadline: deadline)
try stream.write(newLine, deadline: deadline)
}
try stream.flush(deadline: deadline)
}
}
|
b32873b46e260a81a2cf858aa64bb691
| 35.603774 | 150 | 0.592784 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
refs/heads/master
|
piwigo/Album/Cells/ImageCollectionViewCell.swift
|
mit
|
1
|
//
// ImageCollectionViewCell.swift
// piwigo
//
// Created by Spencer Baker on 1/27/15.
// Copyright (c) 2015 bakercrew. All rights reserved.
//
// Converted to Swift 5.4 by Eddy Lelièvre-Berna on 31/01/2022
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
var imageData: PiwigoImageData?
@IBOutlet weak var cellImage: UIImageView!
@IBOutlet weak var darkenView: UIView!
@IBOutlet weak var darkImgWidth: NSLayoutConstraint!
@IBOutlet weak var darkImgHeight: NSLayoutConstraint!
// Image title
@IBOutlet weak var bottomLayer: UIView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var noDataLabel: UILabel!
// Icon showing that it is a movie
@IBOutlet weak var playImg: UIImageView!
@IBOutlet weak var playBckg: UIImageView!
@IBOutlet weak var playLeft: NSLayoutConstraint!
@IBOutlet weak var playTop: NSLayoutConstraint!
// Icon showing that it is a favorite
@IBOutlet weak var favImg: UIImageView!
@IBOutlet weak var favBckg: UIImageView!
@IBOutlet weak var favLeft: NSLayoutConstraint!
@IBOutlet weak var favBottom: NSLayoutConstraint!
// Selected images are darkened
@IBOutlet weak var selectedImg: UIImageView!
@IBOutlet weak var selImgRight: NSLayoutConstraint!
@IBOutlet weak var selImgTop: NSLayoutConstraint!
// On iPad, thumbnails are presented with native aspect ratio
private var deltaX: CGFloat = 1.0 // Must be initialised with margin value
private var deltaY: CGFloat = 1.0 // Must be initialised with margin value
// Constants used to place and resize objects
private let margin: CGFloat = 1.0
private let offset: CGFloat = 1.0
private let bannerHeight: CGFloat = 16.0
private let favScale: CGFloat = 0.12
private let favRatio: CGFloat = 1.0
private let selectScale: CGFloat = 0.2
private let playScale: CGFloat = 0.17
private let playRatio: CGFloat = 0.9 // was 58/75 = 0.7733;
private var _isSelection = false
@objc var isSelection: Bool {
get {
_isSelection
}
set(isSelection) {
_isSelection = isSelection
selectedImg?.isHidden = !isSelection
darkenView?.isHidden = !isSelection
}
}
private var _isFavorite = false
@objc var isFavorite: Bool {
get {
_isFavorite
}
set(isFavorite) {
_isFavorite = isFavorite
// Update the vertical constraint
if bottomLayer?.isHidden ?? false {
// Place icon at the bottom
favBottom?.constant = deltaY
} else {
// Place icon at the bottom but above the title
let height = CGFloat(fmax(bannerHeight + margin, deltaY))
favBottom?.constant = height
}
// Display/hide the favorite icon
favBckg?.isHidden = !isFavorite
favImg?.isHidden = !isFavorite
}
}
@objc func applyColorPalette() {
bottomLayer?.backgroundColor = UIColor.piwigoColorBackground()
nameLabel?.textColor = UIColor.piwigoColorLeftLabel()
favBckg?.tintColor = UIColor(white: 0, alpha: 0.3)
favImg?.tintColor = UIColor.white
}
func config(with imageData: PiwigoImageData?, inCategoryId categoryId: Int) {
// Do we have any info on that image ?
noDataLabel?.text = NSLocalizedString("loadingHUD_label", comment: "Loading…")
guard let imageData = imageData else { return }
if imageData.imageId == 0 { return }
// Store image data
self.imageData = imageData
noDataLabel.isHidden = true
isAccessibilityElement = true
// Play button
playImg?.isHidden = !(imageData.isVideo)
playBckg?.isHidden = !(imageData.isVideo)
// Title
if AlbumVars.shared.displayImageTitles ||
(categoryId == kPiwigoVisitsCategoryId) ||
(categoryId == kPiwigoBestCategoryId) ||
(categoryId == kPiwigoRecentCategoryId) {
bottomLayer?.isHidden = false
nameLabel?.isHidden = false
if categoryId == kPiwigoVisitsCategoryId {
nameLabel?.text = String(format: "%ld %@", Int(imageData.visits), NSLocalizedString("categoryDiscoverVisits_legend", comment: "hits"))
} else if categoryId == kPiwigoBestCategoryId {
// self.nameLabel.text = [NSString stringWithFormat:@"(%.2f) %@", imageData.ratingScore, imageData.name];
if let imageTitle = imageData.imageTitle, imageTitle.isEmpty == false {
nameLabel?.text = imageTitle
} else {
nameLabel?.text = imageData.fileName
}
} else if categoryId == kPiwigoRecentCategoryId,
let dateCreated = imageData.dateCreated {
nameLabel?.text = DateFormatter.localizedString(from: dateCreated, dateStyle: .medium, timeStyle: .none)
} else {
if let imageTitle = imageData.imageTitle, imageTitle.isEmpty == false {
nameLabel?.text = imageTitle
} else {
nameLabel?.text = imageData.fileName
}
}
} else {
bottomLayer?.isHidden = true
nameLabel?.isHidden = true
}
// Thumbnails are not squared on iPad
if UIDevice.current.userInterfaceIdiom == .pad {
cellImage?.contentMode = .scaleAspectFit
}
// Download the image of the requested resolution (or get it from the cache)
switch kPiwigoImageSize(rawValue: AlbumVars.shared.defaultThumbnailSize) {
case kPiwigoImageSizeSquare:
if AlbumVars.shared.hasSquareSizeImages, let squarePath = imageData.squarePath, squarePath.isEmpty == false {
setImageFromPath(squarePath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeXXSmall:
if AlbumVars.shared.hasXXSmallSizeImages, let xxSmallPath = imageData.xxSmallPath, xxSmallPath.isEmpty == false {
setImageFromPath(xxSmallPath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeXSmall:
if AlbumVars.shared.hasXSmallSizeImages, let xSmallPath = imageData.xSmallPath, xSmallPath.isEmpty == false {
setImageFromPath(xSmallPath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeSmall:
if AlbumVars.shared.hasSmallSizeImages, let smallPath = imageData.smallPath, smallPath.isEmpty == false {
setImageFromPath(smallPath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeMedium:
if AlbumVars.shared.hasMediumSizeImages, let mediumPath = imageData.mediumPath, mediumPath.isEmpty == false {
setImageFromPath(mediumPath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeLarge:
if AlbumVars.shared.hasLargeSizeImages, let largePath = imageData.largePath, largePath.isEmpty == false {
setImageFromPath(largePath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeXLarge:
if AlbumVars.shared.hasXLargeSizeImages, let xLargePath = imageData.xLargePath, xLargePath.isEmpty == false {
setImageFromPath(xLargePath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeXXLarge:
if AlbumVars.shared.hasXXLargeSizeImages, let xxLargePath = imageData.xxLargePath, xxLargePath.isEmpty == false {
setImageFromPath(xxLargePath)
} else if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
case kPiwigoImageSizeThumb, kPiwigoImageSizeFullRes:
fallthrough
default:
if AlbumVars.shared.hasThumbSizeImages, let thumbPath = imageData.thumbPath, thumbPath.isEmpty == false {
setImageFromPath(thumbPath)
} else {
noDataLabel?.isHidden = false
return
}
}
applyColorPalette()
}
private func setImageFromPath(_ imagePath: String) {
// Do we have a correct URL?
let placeHolderImage = UIImage(named: "placeholderImage")
if imagePath.isEmpty {
// No image thumbnail
cellImage?.image = placeHolderImage
return
}
// Retrieve the image file
let scale = CGFloat(fmax(1.0, Float(traitCollection.displayScale)))
guard let anURL = URL(string: imagePath) else { return }
var request = URLRequest(url: anURL)
request.addValue("image/*", forHTTPHeaderField: "Accept")
cellImage?.setImageWith(request, placeholderImage: placeHolderImage,
success: { [self] _, _, image in
// Downsample image is necessary
var displayedImage = image
let maxDimensionInPixels = CGFloat(max(self.bounds.size.width, self.bounds.size.height)) * scale
if CGFloat(max(image.size.width, image.size.height)) > maxDimensionInPixels {
displayedImage = ImageUtilities.downsample(image: image, to: self.bounds.size, scale: scale)
}
self.cellImage?.image = displayedImage
// Favorite image position depends on device
self.deltaX = margin
self.deltaY = margin
let imageScale = CGFloat(min(self.bounds.size.width / displayedImage.size.width,
self.bounds.size.height / displayedImage.size.height))
if UIDevice.current.userInterfaceIdiom == .pad {
// Case of an iPad: respect aspect ratio
// Image width smaller than collection view cell?
let imageWidth = displayedImage.size.width * imageScale
if imageWidth < self.bounds.size.width {
// The image does not fill the cell horizontally
self.darkImgWidth?.constant = imageWidth
self.deltaX += (self.bounds.size.width - imageWidth) / 2.0
}
// Image height smaller than collection view cell?
let imageHeight = displayedImage.size.height * imageScale
if imageHeight < self.bounds.size.height {
// The image does not fill the cell vertically
self.darkImgHeight?.constant = imageHeight
self.deltaY += (self.bounds.size.height - imageHeight) / 2.0
}
}
// Update horizontal constraints
self.selImgRight?.constant = self.deltaX
self.favLeft?.constant = self.deltaX
self.playLeft?.constant = self.deltaX
// Update vertical constraints
self.selImgTop?.constant = self.deltaY + 2 * margin
self.playTop?.constant = self.deltaY
if self.bottomLayer?.isHidden ?? false {
// The title is not displayed
self.favBottom?.constant = self.deltaY
} else {
// The title is displayed
let deltaY = CGFloat(fmax(bannerHeight + margin, self.deltaY))
self.favBottom?.constant = deltaY
}
},
failure: { request, response, error in
debugPrint("••> cell image: \(error.localizedDescription)")
})
}
override func prepareForReuse() {
super.prepareForReuse()
imageData = nil
cellImage?.image = nil
deltaX = margin
deltaY = margin
isSelection = false
isFavorite = false
playImg?.isHidden = true
noDataLabel?.isHidden = true
}
func highlight(onCompletion completion: @escaping () -> Void) {
// Select cell of image of interest and apply effect
backgroundColor = UIColor.piwigoColorBackground()
contentMode = .scaleAspectFit
UIView.animate(withDuration: 0.4, delay: 0.3, options: .allowUserInteraction, animations: { [self] in
cellImage?.alpha = 0.2
}) { [self] finished in
UIView.animate(withDuration: 0.4, delay: 0.7, options: .allowUserInteraction, animations: { [self] in
cellImage?.alpha = 1.0
}) { finished in
completion()
}
}
}
}
|
26d2d41850850ec01adac07034ae4b50
| 42.023739 | 150 | 0.594386 | false | false | false | false |
Adorkable/StoryboardKit
|
refs/heads/master
|
StoryboardKit/SegueInstanceInfo.swift
|
mit
|
1
|
//
// SegueInstanceInfo.swift
// StoryboardKit
//
// Created by Ian on 5/3/15.
// Copyright (c) 2015 Adorkable. All rights reserved.
//
import Foundation
// TODO: should we keep it weak? should we be using the weak attribute?
public typealias SegueConnection = StoryboardKit_WeakWrapper<ViewControllerInstanceInfo>
/// Represents a Segue Instance used in your application and its storyboards
public class SegueInstanceInfo: NSObject, Idable {
/// Class
public let classInfo : SegueClassInfo
/// Storyboard Id
public let id : String
/// Source
public let source : SegueConnection
/// Destination
public let destination : SegueConnection
/// Kind of Segue
public let kind : String?
/// Identifier
public let identifier : String?
/**
Default init
- parameter classInfo: Class
- parameter id: Storyboard Id
- parameter source: Source
- parameter destination: Destination
- parameter kind: Kind of Segue
- parameter identifier: Identifier
- returns: A new instance.
*/
public init(classInfo : SegueClassInfo, id : String, source : SegueConnection, destination : SegueConnection, kind : String?, identifier : String?) {
self.classInfo = classInfo
self.id = id
self.source = source
self.destination = destination
self.kind = kind
self.identifier = identifier
super.init()
self.classInfo.add(instanceInfo: self)
}
/**
Convenience init: Destination as a View Controller Instance
- parameter classInfo: Class
- parameter id: Storyboard Id
- parameter source: Source as SegueConnection
- parameter destination: Destination as View Controller Instance
- parameter kind: Kind of Segue
- parameter identifier: Identifier
- returns: A new instance.
*/
public convenience init(classInfo : SegueClassInfo, id : String, source : SegueConnection, destination : ViewControllerInstanceInfo, kind : String?, identifier : String?) {
self.init(classInfo: classInfo, id: id, source: source, destination: StoryboardKit_WeakWrapper(destination), kind: kind, identifier: identifier)
}
}
extension SegueInstanceInfo /*: CustomDebugStringConvertible*/ {
/// Debug Description
override public var debugDescription : String {
get {
var result = super.debugDescription
result += "\n\(self.classInfo)"
result += "\nId: \(self.id)"
result += "\nSource: \(self.source.value)"
result += "\nDestination: \(self.destination.value)"
result += "\nKind: \(self.kind)"
result += "\nIdentifier: \(self.identifier)"
return result
}
}
}
|
d1de87e9a26fcfa1bc4c6b3e82223485
| 30 | 176 | 0.625472 | false | false | false | false |
zmian/xcore.swift
|
refs/heads/main
|
Sources/Xcore/Cocoa/Components/UIImage/ImageTransform/ResizeImageTransform.swift
|
mit
|
1
|
//
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
public struct ResizeImageTransform: ImageTransform {
private let size: CGSize
private let scalingMode: ScalingMode
public var id: String {
"\(transformName)-size:(\(size.width)x\(size.height))-scalingMode:(\(scalingMode))"
}
public init(to size: CGSize, scalingMode: ScalingMode = .aspectFill) {
self.size = size
self.scalingMode = scalingMode
}
public func transform(_ image: UIImage, source: ImageRepresentable) -> UIImage {
let rect = scalingMode.rect(newSize: size, and: image.size)
return UIGraphicsImageRenderer(bounds: rect).image { _ in
image.draw(in: rect)
}
}
}
extension ResizeImageTransform {
/// Represents a scaling mode
public enum ScalingMode {
case fill
case aspectFill
case aspectFit
/// Calculates the aspect ratio between two sizes.
///
/// - Parameters:
/// - size: The first size used to calculate the ratio.
/// - otherSize: The second size used to calculate the ratio.
/// - Returns: the aspect ratio between the two sizes.
private func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat {
let aspectWidth = size.width / otherSize.width
let aspectHeight = size.height / otherSize.height
switch self {
case .fill:
return 1
case .aspectFill:
return max(aspectWidth, aspectHeight)
case .aspectFit:
return min(aspectWidth, aspectHeight)
}
}
fileprivate func rect(newSize: CGSize, and otherSize: CGSize) -> CGRect {
guard self != .fill else {
return CGRect(origin: .zero, size: newSize)
}
let aspectRatio = self.aspectRatio(between: newSize, and: otherSize)
// Build the rectangle representing the area to be drawn
let scaledImageRect = CGRect(
x: (newSize.width - otherSize.width * aspectRatio) / 2.0,
y: (newSize.height - otherSize.height * aspectRatio) / 2.0,
width: otherSize.width * aspectRatio,
height: otherSize.height * aspectRatio
)
return scaledImageRect
}
}
}
|
d5a7cda47df21630807b5352b348e5e5
| 31.666667 | 91 | 0.584898 | false | false | false | false |
LeaderQiu/SwiftWeibo
|
refs/heads/master
|
103 - swiftWeibo/103 - swiftWeibo/Classes/Tools/String+Hash.swift
|
mit
|
6
|
//
// StringHash.swift
// 黑马微博
//
// Created by 刘凡 on 15/2/21.
// Copyright (c) 2015年 joyios. All rights reserved.
//
/// 注意:要使用本分类,需要在 bridge.h 中添加以下头文件导入
/// #import <CommonCrypto/CommonCrypto.h>
/// 如果使用了单元测试,项目 和 测试项目的 bridge.h 中都需要导入
import Foundation
extension String {
/// 返回字符串的 MD5 散列结果
var md5: String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.dealloc(digestLen)
return hash.copy() as! String
}
}
|
7d79089d3fc5f9e51890c6a521535c79
| 25.848485 | 83 | 0.621896 | false | false | false | false |
danthorpe/TaylorSource
|
refs/heads/development
|
Tests/Models.swift
|
mit
|
2
|
//
// Models.swift
// TaylorSource
//
// Created by Daniel Thorpe on 08/03/2016.
//
//
import Foundation
import ValueCoding
import YapDatabaseExtensions
import YapDatabase
@testable import TaylorSource
struct EventSection: SectionType {
typealias ItemType = Event
let title: String
let items: [Event]
}
extension EventSection: CustomStringConvertible {
var description: String {
return "\(title) (\(items.count) items)"
}
}
extension EventSection: Equatable { }
func == (lhs: EventSection, rhs: EventSection) -> Bool {
return lhs.title == rhs.title && lhs.items == rhs.items
}
struct Event {
enum Color {
case Red, Blue, Green
}
let uuid: String
let color: Color
let date: NSDate
init(uuid: String = NSUUID().UUIDString, color: Color, date: NSDate = NSDate()) {
self.uuid = uuid
self.color = color
self.date = date
}
static func create(color color: Color = .Red) -> Event {
return Event(color: color)
}
}
extension Event.Color: CustomStringConvertible {
var description: String {
switch self {
case .Red: return "Red"
case .Blue: return "Blue"
case .Green: return "Green"
}
}
}
extension Event.Color: Equatable { }
func == (lhs: Event.Color, rhs: Event.Color) -> Bool {
switch (lhs,rhs) {
case (.Red, .Red), (.Blue, .Blue), (.Green, .Green):
return true
default:
return false
}
}
extension Event: Equatable { }
func == (lhs: Event, rhs: Event) -> Bool {
return (lhs.color == rhs.color) && (lhs.uuid == rhs.uuid) && (lhs.date == rhs.date)
}
extension Event.Color: ValueCoding {
typealias Coder = EventColorCoder
enum Kind: Int {
case Red = 1, Blue, Green
}
var kind: Kind {
switch self {
case .Red: return Kind.Red
case .Blue: return Kind.Blue
case .Green: return Kind.Green
}
}
}
class EventColorCoder: NSObject, NSCoding, CodingType {
let value: Event.Color
required init(_ v: Event.Color) {
value = v
}
required init?(coder aDecoder: NSCoder) {
if let kind = Event.Color.Kind(rawValue: aDecoder.decodeIntegerForKey("kind")) {
switch kind {
case .Red:
value = Event.Color.Red
case .Blue:
value = Event.Color.Blue
case .Green:
value = Event.Color.Green
}
}
else { fatalError("Event.Color.Kind not correctly encoded.") }
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(value.kind.rawValue, forKey: "kind")
}
}
extension Event: Identifiable {
var identifier: String {
return uuid
}
}
extension Event: Persistable {
static var collection: String {
return "Events"
}
}
extension Event: ValueCoding {
typealias Coder = EventCoder
}
class EventCoder: NSObject, NSCoding, CodingType {
let value: Event
required init(_ v: Event) {
value = v
}
required init?(coder aDecoder: NSCoder) {
let color = Event.Color.decode(aDecoder.decodeObjectForKey("color"))
let uuid = aDecoder.decodeObjectForKey("uuid") as? String
let date = aDecoder.decodeObjectForKey("date") as? NSDate
value = Event(uuid: uuid!, color: color!, date: date!)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(value.color.encoded, forKey: "color")
aCoder.encodeObject(value.uuid, forKey: "uuid")
aCoder.encodeObject(value.date, forKey: "date")
}
}
func createSomeEvents(numberOfDays: Int = 10) -> [Event] {
let today = NSDate()
let interval: NSTimeInterval = 86_400
return (0..<numberOfDays).map { index in
let date = today.dateByAddingTimeInterval(-1.0 * Double(index) * interval)
return Event(color: .Red, date: date)
}
}
func events(byColor: Bool = false) -> YapDB.Fetch {
let grouping: YapDB.View.Grouping = .ByObject({ (_, collection, key, object) -> String! in
if collection == Event.collection {
if !byColor {
return collection
}
if let event = Event.decode(object) {
return event.color.description
}
}
return .None
})
let sorting: YapDB.View.Sorting = .ByObject({ (_, group, collection1, key1, object1, collection2, key2, object2) -> NSComparisonResult in
if let event1 = Event.decode(object1),
let event2 = Event.decode(object2) {
return event1.date.compare(event2.date)
}
return .OrderedSame
})
let view = YapDB.View(name: Event.collection, grouping: grouping, sorting: sorting, collections: [Event.collection])
return .View(view)
}
func events(byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> YapDB.FetchConfiguration {
return YapDB.FetchConfiguration(fetch: events(byColor), block: mappingBlock)
}
func events(byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> Configuration<Event> {
return Configuration(fetch: events(byColor), itemMapper: Event.decode)
}
func eventsWithColor(color: Event.Color, byColor: Bool = false) -> YapDB.Fetch {
let filtering: YapDB.Filter.Filtering = .ByObject({ (_, group, collection, key, object) -> Bool in
if let event = Event.decode(object) {
return event.color == color
}
return false
})
let filter = YapDB.Filter(name: "\(color) Events", parent: events(byColor), filtering: filtering, collections: [Event.collection])
return .Filter(filter)
}
func eventsWithColor(color: Event.Color, byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> YapDB.FetchConfiguration {
return YapDB.FetchConfiguration(fetch: eventsWithColor(color, byColor: byColor), block: mappingBlock)
}
func eventsWithColor(color: Event.Color, byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> Configuration<Event> {
return Configuration(fetch: eventsWithColor(color, byColor: byColor), itemMapper: Event.decode)
}
|
4696621db5e0dbc18f719c9d7b809010
| 25.662447 | 169 | 0.634911 | false | true | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Extensions/NoResultsViewController+Model.swift
|
gpl-2.0
|
2
|
import Foundation
extension NoResultsViewController {
struct Model {
let titleText: String
let subtitleText: String?
let buttonText: String?
var imageName: String?
let accessoryView: UIView?
init(title: String, subtitle: String? = nil, buttonText: String? = nil, imageName: String? = nil, accessoryView: UIView? = nil) {
self.titleText = title
self.subtitleText = subtitle
self.buttonText = buttonText
self.imageName = imageName
self.accessoryView = accessoryView
}
}
func bindViewModel(_ viewModel: Model) {
configure(title: viewModel.titleText, buttonTitle: viewModel.buttonText, subtitle: viewModel.subtitleText, image: viewModel.imageName, accessoryView: viewModel.accessoryView)
}
}
|
2adedf9488dfb90540b66b5e662cd2a5
| 35.130435 | 182 | 0.65704 | false | false | false | false |
CodaFi/swift
|
refs/heads/master
|
test/Interop/Cxx/class/synthesized-initializers-silgen.swift
|
apache-2.0
|
5
|
// RUN: %target-swift-frontend -I %S/Inputs -enable-cxx-interop -emit-silgen %s | %FileCheck %s
import SynthesizedInitializers
// CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo11EmptyStructVABycfC : $@convention(method) (@thin EmptyStruct.Type) -> EmptyStruct
// CHECK: bb0(%{{[0-9]+}} : $@thin EmptyStruct.Type):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var EmptyStruct }
// CHECK-NEXT: [[UNINIT:%.*]] = mark_uninitialized [rootself] [[BOX]] : ${ var EmptyStruct }
// CHECK-NEXT: [[PTR:%.*]] = project_box [[UNINIT]] : ${ var EmptyStruct }, 0
// CHECK-NEXT: [[OBJ:%.*]] = builtin "zeroInitializer"<EmptyStruct>() : $EmptyStruct
// CHECK-NEXT: [[PA:%.*]] = begin_access [modify] [unknown] [[PTR]] : $*EmptyStruct
// CHECK-NEXT: assign [[OBJ]] to [[PA]]
// CHECK-NEXT: end_access [[PA]]
// CHECK-NEXT: [[OUT:%.*]] = load [trivial] [[PTR]]
// CHECK-NEXT: destroy_value [[UNINIT]]
// CHECK-NEXT: return [[OUT]]
// CHECK-LABEL: end sil function '$sSo11EmptyStructVABycfC'
public func emptyTypeNoArgInit() {
let e = EmptyStruct()
}
// CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo6IntBoxVABycfC : $@convention(method) (@thin IntBox.Type) -> IntBox
// CHECK: bb0(%{{[0-9]+}} : $@thin IntBox.Type):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var IntBox }
// CHECK-NEXT: [[UNINIT:%.*]] = mark_uninitialized [rootself] [[BOX]] : ${ var IntBox }
// CHECK-NEXT: [[PTR:%.*]] = project_box [[UNINIT]] : ${ var IntBox }, 0
// CHECK-NEXT: [[OBJ:%.*]] = builtin "zeroInitializer"<IntBox>() : $IntBox
// CHECK-NEXT: [[PA:%.*]] = begin_access [modify] [unknown] [[PTR]] : $*IntBox
// CHECK-NEXT: assign [[OBJ]] to [[PA]]
// CHECK-NEXT: end_access [[PA]]
// CHECK-NEXT: [[OUT:%.*]] = load [trivial] [[PTR]]
// CHECK-NEXT: destroy_value [[UNINIT]]
// CHECK-NEXT: return [[OUT]]
// CHECK-LABEL: end sil function '$sSo6IntBoxVABycfC'
public func singleMemberTypeNoArgInit() {
let i = IntBox()
}
// CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo6IntBoxV1xABs5Int32V_tcfC : $@convention(method) (Int32, @thin IntBox.Type) -> IntBox
// CHECK: bb0([[I:%[0-9]+]] : $Int32, %{{[0-9]+}} : $@thin IntBox.Type):
// CHECK-NEXT: [[S:%.*]] = struct $IntBox ([[I]] : $Int32)
// CHECK-NEXT: return [[S]]
// CHECK-LABEL: end sil function '$sSo6IntBoxV1xABs5Int32V_tcfC'
public func singleMemberTypeValueInit() {
let i = IntBox(x: 42)
}
|
e7737826b35524a842d9748fbe1d0002
| 50.456522 | 153 | 0.634559 | false | false | false | false |
finder39/resumod
|
refs/heads/master
|
Resumod/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// Resumod
//
// Created by Joseph Neuman on 7/23/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import Foundation
import UIKit
struct CONSTANTS {
/*enum Palette {
case VeryLightPastelRedBlueYellow
case DarkRedBlueYellow
}
let paletteToUse = Palette.VeryLightPastelRedBlueYellow
switch (paletteToUse) {
case .VeryLightPastelRedBlueYellow:
let color1 = "a"
}*/
// http://www.paletton.com/#uid=33K0I0kiCFn8GVde7NVmtwSqXtg
let color1 = UIColor(red: 1, green: 0.945, blue: 0.42, alpha: 1)
let color2 = UIColor(red: 0.369, green: 0.498, blue: 0.776, alpha: 1)
let color3 = UIColor(red: 1, green: 0.576, blue: 0.42, alpha: 1)
}
/*class Constants {
/*class var sharedInstance:Constants {
struct Static {
static let instance = Constants()
}
return Static.instance
}*/
let constants = constantsStruct()
}*/
extension String {
func md5() -> String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash)
}
}
|
f2e4279d3f4ec2707db305740b6ff9a8
| 23.016667 | 84 | 0.675 | false | false | false | false |
Lollipop95/WeiBo
|
refs/heads/master
|
WeiBo/WeiBo/Classes/View/Compose/WBComposeViewController.swift
|
mit
|
1
|
//
// WBComposeViewController.swift
// WeiBo
//
// Created by Ning Li on 2017/5/6.
// Copyright © 2017年 Ning Li. All rights reserved.
//
import UIKit
import SVProgressHUD
class WBComposeViewController: UIViewController {
@IBOutlet weak var textView: WBComposeTextView!
@IBOutlet weak var toolbar: UIToolbar!
/// 工具栏底部约束
@IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
/// 发布按钮
@IBOutlet var sendButton: UIButton!
/// 懒加载表情键盘视图
lazy var emoticonKeyboardView: WBEmoticonInputView = WBEmoticonInputView.inputView { [weak self] (emoticon) in
self?.textView.insertEmoticon(emoticon: emoticon)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// 注册键盘通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 激活键盘
textView.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// 退出键盘
textView.resignFirstResponder()
}
deinit {
// 注销通知
NotificationCenter.default.removeObserver(self)
}
// MARK: - 监听方法
/// 关闭按钮监听方法
@objc fileprivate func close() {
dismiss(animated: true, completion: nil)
}
/// 发布微博
@IBAction func postStatus() {
textView.resignFirstResponder()
let text = textView.emoticonText
SVProgressHUD.show()
let image: UIImage? = nil //#imageLiteral(resourceName: "notification.png")
WBNetworkManager.shared.postStatus(text: text, image: image) { (result, isSuccess) in
let message = isSuccess ? "发布成功" : "网络不给了,请稍后重试"
SVProgressHUD.showInfo(withStatus: message)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
self.close()
// 如果发布成功, 刷新数据
if isSuccess {
let mainVC = UIApplication.shared.keyWindow?.rootViewController as? WBMainViewController
let nav = mainVC?.childViewControllers[0] as? WBNavigationViewController
let homeVC = nav?.childViewControllers[0] as? WBHomeViewController
homeVC?.loadData()
}
})
}
}
/// 键盘frame监听方法
@objc private func keyboardChanged(n: Notification) {
guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
let yOffset: CGFloat = view.bounds.height - rect.origin.y
toolbarBottomCons.constant = yOffset
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
}
/// 切换表情键盘 - 如果使用系统默认键盘, inputView 为 nil
@objc private func emoticonKeyboard() {
textView.inputView = (textView.inputView == nil) ? emoticonKeyboardView : nil
textView.reloadInputViews()
}
}
// MARK: - 设置界面
extension WBComposeViewController {
fileprivate func setupUI() {
view.backgroundColor = UIColor.white
setupNavigationBar()
setupToolbar()
}
/// 设置导航栏
private func setupNavigationBar() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
navigationItem.title = "发微博"
sendButton.isEnabled = false
}
/// 设置工具栏
private func setupToolbar() {
/// 图片信息数组
let itemsInfo: [[String: String]] = [["imageName": "compose_toolbar_picture"],
["imageName": "compose_mentionbutton_background"],
["imageName": "compose_trendbutton_background"],
["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
["imageName": "compose_add_background"]]
var items = [UIBarButtonItem]()
for dict in itemsInfo {
guard let imageName = dict["imageName"] else {
return
}
let image = UIImage(named: imageName)
let imageHL = UIImage(named: imageName + "_highlighted")
let btn: UIButton = UIButton()
btn.setBackgroundImage(image, for: [])
btn.setBackgroundImage(imageHL, for: .highlighted)
btn.sizeToFit()
if let actionName = dict["actionName"] {
btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
}
items.append(UIBarButtonItem(customView: btn))
// 添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
}
// 删除末尾的弹簧
items.removeLast()
toolbar.items = items
}
}
// MARK: - UITextViewDelegate
extension WBComposeViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
// 修改 '发布' 按钮状态
sendButton.isEnabled = textView.hasText
}
}
|
e59165d7081a0dfd4416734194279fc4
| 28.591837 | 158 | 0.556897 | false | false | false | false |
onmyway133/Github.swift
|
refs/heads/master
|
Carthage/Checkouts/Sugar/Source/iOS/Extensions/UITableView+Indexes.swift
|
mit
|
1
|
import UIKit
public extension UITableView {
func insert(indexes: [Int], section: Int = 0, animation: UITableViewRowAnimation = .Automatic) {
let indexPaths = indexes.map { NSIndexPath(forRow: $0, inSection: section) }
if animation == .None { UIView.setAnimationsEnabled(false) }
performUpdates { insertRowsAtIndexPaths(indexPaths, withRowAnimation: animation) }
if animation == .None { UIView.setAnimationsEnabled(true) }
}
func reload(indexes: [Int], section: Int = 0, animation: UITableViewRowAnimation = .Automatic) {
let indexPaths = indexes.map { NSIndexPath(forRow: $0, inSection: section) }
if animation == .None { UIView.setAnimationsEnabled(false) }
performUpdates { reloadRowsAtIndexPaths(indexPaths, withRowAnimation: animation) }
if animation == .None { UIView.setAnimationsEnabled(true) }
}
func delete(indexes: [Int], section: Int = 0, animation: UITableViewRowAnimation = .Automatic) {
let indexPaths = indexes.map { NSIndexPath(forRow: $0, inSection: section) }
if animation == .None { UIView.setAnimationsEnabled(false) }
performUpdates { deleteRowsAtIndexPaths(indexPaths, withRowAnimation: animation) }
if animation == .None { UIView.setAnimationsEnabled(true) }
}
func reloadSection(section: Int = 0, animation: UITableViewRowAnimation = .Automatic) {
if animation == .None { UIView.setAnimationsEnabled(false) }
performUpdates {
reloadSections(NSIndexSet(index: section), withRowAnimation: animation)
}
if animation == .None { UIView.setAnimationsEnabled(true) }
}
private func performUpdates(@noescape closure: () -> Void) {
beginUpdates()
closure()
endUpdates()
}
}
|
7d2673abc6610a45b2f0ac4f1471a704
| 41.45 | 98 | 0.717314 | false | false | false | false |
jeffreybergier/udacity-animation
|
refs/heads/master
|
animation-playground.playground/Pages/Gesture Recognizers.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import UIKit
import XCPlayground
// MARK: Custom View Controller Subclass
class SpringViewController: UIViewController {
// MARK: Custom Properties
let redView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.redColor()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var xConstraint: NSLayoutConstraint = { self.redView.centerXAnchor.constraintEqualToAnchor(vc.view.centerXAnchor, constant: 0) }()
lazy var yConstraint: NSLayoutConstraint = { self.redView.centerYAnchor.constraintEqualToAnchor(vc.view.centerYAnchor, constant: 0) }()
// MARK: Configure the View Controller
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.configureRedView()
}
// MARK: Add View to Animate
// and configure constraints
func configureRedView() {
vc.view.addSubview(self.redView)
NSLayoutConstraint.activateConstraints(
[
self.xConstraint,
self.yConstraint,
self.redView.heightAnchor.constraintEqualToConstant(60),
self.redView.widthAnchor.constraintEqualToConstant(60)
]
)
}
// MARK: Handle Animations from Gesture Recognizer
func animateBackToCenter() {
UIView.animateWithDuration(
0.6,
delay: 0.0,
usingSpringWithDamping: 0.35,
initialSpringVelocity: 1.5,
options: [],
animations: {
self.xConstraint.constant = 0
self.yConstraint.constant = 0
vc.view.setNeedsLayout()
},
completion: { finished in
print("Snapped Back")
}
)
}
func gestureFired(sender: UIPanGestureRecognizer) {
switch sender.state {
case .Began, .Possible:
// don't need to do anything to start
break
case .Changed:
// get the amount of change cause by the finger moving
let translation = sender.translationInView(vc.view)
// add that change to our autolayout constraints
xConstraint.constant += translation.x
yConstraint.constant += translation.y
// tell the view to update
vc.view.setNeedsLayout()
// reset the translation in the gesture recognizer to 0
// try removing this line of code and see what happens when dragging
sender.setTranslation(CGPoint.zero, inView: vc.view)
case .Cancelled, .Ended, .Failed:
// animate back to the center when done
animateBackToCenter()
}
}
}
// MARK: Instantiate Spring View Controller
let vc = SpringViewController()
vc.view.frame = CGRect(x: 0, y: 0, width: 400, height: 600)
XCPlaygroundPage.currentPage.liveView = vc.view
// MARK: Configure Gesture Recognizer
let panGestureRecognizer = UIPanGestureRecognizer(target: vc, action: #selector(vc.gestureFired(_:)))
vc.redView.addGestureRecognizer(panGestureRecognizer)
|
15cfea5ef80f3050a8364fada71290d7
| 30.970588 | 139 | 0.611469 | false | false | false | false |
titi-us/StarlingDemoKit
|
refs/heads/master
|
StarlingKit/MovieScene.swift
|
mit
|
1
|
//
// MovieScene.swift
// StarlingKit
//
// Created by Thibaut Crenn on 11/13/14.
// Copyright (c) 2014 Thibaut Crenn. All rights reserved.
//
import Foundation
import SpriteKit
class MovieScene:BaseScene {
override init()
{
var textures:[SKTexture] = [];
var i = 0;
for (i; i < 14; i++)
{
let dec = Int(i/10)
let rem = i - dec*10
textures.append(SKTexture(imageNamed: "flight_"+String(dec)+String(rem)))
}
let movieClip = SKSpriteNode(texture: textures[0])
let action = SKAction.repeatActionForever(SKAction.animateWithTextures(textures, timePerFrame: 0.05))
movieClip.runAction(action)
super.init()
self.addChild(movieClip)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
b27545287b90e15ed46bab04a5e4461d
| 22.74359 | 109 | 0.573434 | false | false | false | false |
laszlokorte/reform-swift
|
refs/heads/master
|
ReformCore/ReformCore/RotateInstruction.swift
|
mit
|
1
|
//
// RotateInstruction.swift
// ReformCore
//
// Created by Laszlo Korte on 14.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import ReformMath
public struct RotateInstruction : Instruction {
public typealias PointType = LabeledPoint
public typealias AngleType = RuntimeRotationAngle & Labeled
public var target : FormIdentifier? {
return formId
}
public let formId : FormIdentifier
public let angle : AngleType
public let fixPoint : PointType
public init(formId: FormIdentifier, angle: AngleType, fixPoint: PointType) {
self.formId = formId
self.angle = angle
self.fixPoint = fixPoint
}
public func evaluate<T:Runtime>(_ runtime: T) {
guard let form = runtime.get(formId) as? Rotatable else {
runtime.reportError(.unknownForm)
return
}
guard let fix : Vec2d = fixPoint.getPositionFor(runtime) else {
runtime.reportError(.invalidFixPoint)
return
}
guard let a : Angle = angle.getAngleFor(runtime) else {
runtime.reportError(.invalidAngle)
return
}
form.rotator.rotate(runtime, angle: a, fix: fix)
}
public func getDescription(_ stringifier: Stringifier) -> String { let formName = stringifier.labelFor(formId) ?? "???"
return "Rotate \(formName) around \(fixPoint.getDescription(stringifier)) by \(angle.getDescription(stringifier))"
}
public func analyze<T:Analyzer>(_ analyzer: T) {
}
public var isDegenerated : Bool {
return angle.isDegenerated
}
}
extension RotateInstruction : Mergeable {
public func mergeWith(_ other: RotateInstruction, force: Bool) -> RotateInstruction? {
guard formId == other.formId else {
return nil
}
if force {
return other
}
guard fixPoint.isEqualTo(other.fixPoint) else {
return nil
}
guard let angleA = angle as? ConstantAngle, let angleB = other.angle as? ConstantAngle else {
return nil
}
return RotateInstruction(formId: formId, angle: combine(angle: angleA, angle: angleB), fixPoint: fixPoint)
}
}
|
0e9b64bda9d8b867287976aefc504c22
| 26.819277 | 130 | 0.614985 | false | false | false | false |
TinyCrayon/TinyCrayon-iOS-SDK
|
refs/heads/master
|
TCMask/ImageScrollView.swift
|
mit
|
1
|
//
// ImageScrollView.swift
// TinyCrayon
//
// Created by Xin Zeng on 1/4/16.
//
//
import UIKit
enum FitMode {
case inner, outer
}
class ImageScrollView: UIScrollView, UIScrollViewDelegate {
var baseView: UIView
var zoomFactor: CGFloat = 1
var minScale: CGFloat = 1
var fitMode = FitMode.inner
var draggingDisabled = false
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let gesture = gestureRecognizer as? UIPanGestureRecognizer {
if draggingDisabled && gesture.numberOfTouches == 1 {
return false
}
}
return true
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if (draggingDisabled) {
targetContentOffset.pointee = scrollView.contentOffset
}
}
weak var _zoomView: UIView?
var zoomView: UIView? {
willSet {
_zoomView?.removeFromSuperview()
if let view = newValue {
baseView.addSubview(view)
}
_zoomView = newValue
}
}
required init?(coder aDecoder: NSCoder) {
baseView = UIView()
super.init(coder: aDecoder)
self.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
self.clipsToBounds = true
self.bounces = true
self.bouncesZoom = true
self.delegate = self
self.delaysContentTouches = true
self.addSubview(baseView)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return baseView
}
func refresh() {
self.resetImageViewFrame()
self.resetZoomScale(false, resetScale: true)
}
func resetImageViewFrame() -> (){
if let view = _zoomView {
view.frame.origin = CGPoint(x: 0, y: 0)
baseView.bounds = view.bounds
}
}
func resetZoomScale(_ animated: Bool, resetScale: Bool = false) -> (){
if let view = _zoomView {
let rw = self.width / view.width
let rh = self.height / view.height
if (self.fitMode == FitMode.inner) {
self.minimumZoomScale = min(rw, rh)
self.maximumZoomScale = max(max(rw, rh) * zoomFactor, self.minimumZoomScale)
}
else {
self.minimumZoomScale = max(rw, rh)
self.maximumZoomScale = self.minimumZoomScale * zoomFactor
}
if (resetScale) {
self.contentSize = view.frame.size
self.setZoomScale(minimumZoomScale, animated: animated)
}
else {
self.setZoomScale(zoomScale, animated: animated)
}
scrollViewDidZoom(self)
}
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let ws = scrollView.width - scrollView.contentInset.left - scrollView.contentInset.right
let hs = scrollView.height - scrollView.contentInset.top - scrollView.contentInset.bottom
let w = baseView.width
let h = baseView.height
var rct = baseView.frame
rct.origin.x = max((ws-w)/2, 0)
rct.origin.y = max((hs-h)/2, 0)
baseView.frame = rct
}
}
|
6ed7a5a156d570b5b5ed7759077153d8
| 29.469027 | 148 | 0.585536 | false | false | false | false |
duzexu/ARuler
|
refs/heads/master
|
ARuler/ViewController/SupportViewController.swift
|
gpl-2.0
|
1
|
//
// SupportViewController.swift
// ARuler
//
// Created by duzexu on 2017/9/21.
// Copyright © 2017年 duzexu. All rights reserved.
//
import UIKit
import StoreKit
import SafariServices
class SupportViewController: UIViewController {
var values: Array<String>!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
SKStoreReviewController.requestReview()
values = ["去 APP Store 评价","分享给你的朋友","给此开源项目 Star","打赏作者"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension SupportViewController : UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UILabel()
header.font = UIFont.systemFont(ofSize: 14)
header.textColor = UIColor.headerTextColor
header.text = " 可以通过以下方式表达对ARuler的支持"
return header
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.supportCell.identifier, for: indexPath)
cell.accessoryType = .none
cell.textLabel?.font = UIFont.systemFont(ofSize: 16)
cell.textLabel?.textColor = UIColor.textColor
cell.textLabel?.text = values[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
let url = "itms-apps://itunes.apple.com/app/id1255077231?action=write-review"
UIApplication.shared.open(URL(string: url)!, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
break
case 1:
let share = UIActivityViewController(activityItems: [R.image.logo()!,URL(string: "https://itunes.apple.com/us/app/aruler/id1255077231?l=zh&mt=8")!,"我正在使用ARuler测距离,快来试试吧!"], applicationActivities: nil)
self.navigationController?.present(share, animated: true, completion: nil)
break
case 2:
let vc = WebViewController(url: "https://github.com/duzexu/ARuler")
self.navigationController?.pushViewController(vc, animated: true)
break
case 3:
self.navigationController?.pushViewController(R.storyboard.main.donateViewController()!, animated: true)
break
default:
break
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
|
5d81a69738c4c643ce9f3d7c403e7394
| 36.686047 | 212 | 0.682197 | false | false | false | false |
anhnc55/fantastic-swift-library
|
refs/heads/master
|
Example/Pods/paper-onboarding/Source/PageView/PageContainerView/PageContainer.swift
|
mit
|
1
|
//
// PageContaineView.swift
// AnimatedPageView
//
// Created by Alex K. on 13/04/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class PageContrainer: UIView {
var items: [PageViewItem]?
let space: CGFloat // space between items
var currentIndex = 0
private let itemRadius: CGFloat
private let selectedItemRadius: CGFloat
private let itemsCount: Int
private let animationKey = "animationKey"
init(radius: CGFloat, selectedRadius: CGFloat, space: CGFloat, itemsCount: Int) {
self.itemsCount = itemsCount
self.space = space
self.itemRadius = radius
self.selectedItemRadius = selectedRadius
super.init(frame: CGRect.zero)
items = createItems(itemsCount, radius: radius, selectedRadius: selectedRadius)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: public
extension PageContrainer {
func currenteIndex(index: Int, duration: Double, animated: Bool) {
guard let items = self.items where
index != currentIndex else {return}
animationItem(items[index], selected: true, duration: duration)
let fillColor = index > currentIndex ? true : false
animationItem(items[currentIndex], selected: false, duration: duration, fillColor: fillColor)
currentIndex = index
}
}
// MARK: animations
extension PageContrainer {
private func animationItem(item: PageViewItem, selected: Bool, duration: Double, fillColor: Bool = false) {
let toValue = selected == true ? selectedItemRadius * 2 : itemRadius * 2
item.constraints
.filter{ $0.identifier == "animationKey" }
.forEach {
$0.constant = toValue
}
UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
item.animationSelected(selected, duration: duration, fillColor: fillColor)
}
}
// MARK: create
extension PageContrainer {
private func createItems(count: Int, radius: CGFloat, selectedRadius: CGFloat) -> [PageViewItem] {
var items = [PageViewItem]()
// create first item
var item = createItem(radius, selectedRadius: selectedRadius, isSelect: true)
addConstraintsToView(item, radius: selectedRadius)
items.append(item)
for _ in 1..<count {
let nextItem = createItem(radius, selectedRadius: selectedRadius)
addConstraintsToView(nextItem, leftItem: item, radius: radius)
items.append(nextItem)
item = nextItem
}
return items
}
private func createItem(radius: CGFloat, selectedRadius: CGFloat, isSelect: Bool = false) -> PageViewItem {
let item = Init(PageViewItem(radius: radius, selectedRadius: selectedRadius, isSelect: isSelect)) {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = .clearColor()
}
self.addSubview(item)
return item
}
private func addConstraintsToView(item: UIView, radius: CGFloat) {
[NSLayoutAttribute.Left, NSLayoutAttribute.CenterY].forEach { attribute in
(self, item) >>>- { $0.attribute = attribute }
}
[NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in
item >>>- {
$0.attribute = attribute
$0.constant = radius * 2.0
$0.identifier = animationKey
}
}
}
private func addConstraintsToView(item: UIView, leftItem: UIView, radius: CGFloat) {
(self, item) >>>- { $0.attribute = .CenterY }
(self, item, leftItem) >>>- {
$0.attribute = .Leading
$0.secondAttribute = .Trailing
$0.constant = space
}
[NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in
item >>>- {
$0.attribute = attribute
$0.constant = radius * 2.0
$0.identifier = animationKey
}
}
}
}
|
4633c9d48180d2ef06f264fd81acc427
| 28.857143 | 109 | 0.657179 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
KsApi/models/graphql/adapters/Reward+RewardFragmentTests.swift
|
apache-2.0
|
1
|
@testable import KsApi
import Prelude
import XCTest
final class Reward_RewardFragmentTests: XCTestCase {
func test() {
do {
let variables = ["includeShippingRules": true, "includeLocalPickup": true]
let fragment = try GraphAPI.RewardFragment(jsonObject: rewardDictionary(), variables: variables)
XCTAssertNotNil(fragment)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let v1Reward = Reward.reward(
from: fragment,
dateFormatter: dateFormatter
) else {
XCTFail("reward should be created from fragment")
return
}
XCTAssertEqual(v1Reward.backersCount, 13)
XCTAssertEqual(v1Reward.convertedMinimum, 31.0)
XCTAssertEqual(v1Reward.description, "Description")
XCTAssertEqual(v1Reward.endsAt, nil)
XCTAssertEqual(v1Reward.estimatedDeliveryOn, 1_638_316_800.0)
XCTAssertEqual(v1Reward.id, 8_173_901)
XCTAssertEqual(v1Reward.limit, nil)
XCTAssertEqual(v1Reward.limitPerBacker, 1)
XCTAssertEqual(v1Reward.minimum, 25.0)
XCTAssertEqual(v1Reward.localPickup?.country, "US")
XCTAssertEqual(v1Reward.localPickup?.localizedName, "San Jose")
XCTAssertEqual(v1Reward.localPickup?.displayableName, "San Jose, CA")
XCTAssertEqual(v1Reward.localPickup?.id, decompose(id: "TG9jYXRpb24tMjQ4ODA0Mg=="))
XCTAssertEqual(v1Reward.localPickup?.name, "San Jose")
XCTAssertTrue(v1Reward.hasAddOns)
XCTAssertEqual(v1Reward.remaining, nil)
XCTAssertEqual(v1Reward.rewardsItems[0].item.id, 1_170_799)
XCTAssertEqual(v1Reward.rewardsItems[0].item.name, "Soft-Cover Book (Signed)")
XCTAssertEqual(v1Reward.rewardsItems[0].quantity, 2)
XCTAssertEqual(v1Reward.rewardsItems[1].item.id, 1_170_813)
XCTAssertEqual(v1Reward.rewardsItems[1].item.name, "Custom Bookmark")
XCTAssertEqual(v1Reward.rewardsItems[1].quantity, 1)
XCTAssertEqual(v1Reward.shipping.enabled, true)
XCTAssertEqual(v1Reward.shipping.preference, .unrestricted)
XCTAssertEqual(v1Reward.shipping.summary, "Ships worldwide")
XCTAssertEqual(v1Reward.shippingRules?.count, 2)
XCTAssertEqual(v1Reward.startsAt, nil)
XCTAssertEqual(v1Reward.title, "Soft Cover Book (Signed)")
XCTAssertEqual(v1Reward.isLimitedQuantity, false)
XCTAssertEqual(v1Reward.isLimitedTime, false)
} catch {
XCTFail(error.localizedDescription)
}
}
}
private func rewardDictionary() -> [String: Any] {
let json = """
{
"__typename": "Reward",
"allowedAddons": {
"__typename": "RewardConnection",
"pageInfo": {
"__typename": "PageInfo",
"startCursor": "WzIsODMzNzczN10="
}
},
"localReceiptLocation": {
"__typename": "Location",
"country": "US",
"countryName": "United States",
"displayableName": "San Jose, CA",
"id": "TG9jYXRpb24tMjQ4ODA0Mg==",
"name": "San Jose"
},
"amount": {
"__typename": "Money",
"amount": "25.0",
"currency": "USD",
"symbol": "$"
},
"backersCount": 13,
"convertedAmount": {
"__typename": "Money",
"amount": "31.0",
"currency": "CAD",
"symbol": "$"
},
"description": "Description",
"displayName": "Soft Cover Book (Signed) ($25)",
"endsAt": null,
"estimatedDeliveryOn": "2021-12-01",
"id": "UmV3YXJkLTgxNzM5MDE=",
"isMaxPledge": false,
"items": {
"__typename": "RewardItemsConnection",
"edges": [
{
"__typename": "RewardItemEdge",
"quantity": 2,
"node": {
"__typename": "RewardItem",
"id": "UmV3YXJkSXRlbS0xMTcwNzk5",
"name": "Soft-Cover Book (Signed)"
}
},
{
"__typename": "RewardItemEdge",
"quantity": 1,
"node": {
"__typename": "RewardItem",
"id": "UmV3YXJkSXRlbS0xMTcwODEz",
"name": "Custom Bookmark"
}
}
]
},
"limit": null,
"limitPerBacker": 1,
"name": "Soft Cover Book (Signed)",
"project": {
"__typename": "Project",
"id": "UHJvamVjdC0xNTk2NTk0NDYz"
},
"remainingQuantity": null,
"shippingSummary": "Ships worldwide",
"shippingPreference": "unrestricted",
"shippingRules": [{
"__typename": "ShippingRule",
"cost": {
"__typename": "Money",
"amount": "0.0",
"currency": "USD",
"symbol": "$"
},
"id": "U2hpcHBpbmdSdWxlLTExNDEzMzc5",
"location": {
"__typename": "Location",
"country": "ZZ",
"countryName": null,
"displayableName": "Earth",
"id": "TG9jYXRpb24tMQ==",
"name": "Rest of World"
}
},
{
"__typename": "ShippingRule",
"cost": {
"__typename": "Money",
"amount": "0.0",
"currency": "USD",
"symbol": "$"
},
"id": "U2hpcHBpbmdSdWxlLTExMjc4NzUy",
"location": {
"__typename": "Location",
"country": "US",
"countryName": "United States",
"displayableName": "United States",
"id": "TG9jYXRpb24tMjM0MjQ5Nzc=",
"name": "United States"
}
}
],
"startsAt": null
}
"""
let data = Data(json.utf8)
return (try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]) ?? [:]
}
|
27c526870ff185f8f0d79b427364dec6
| 30.451977 | 102 | 0.587031 | false | false | false | false |
arvedviehweger/swift
|
refs/heads/master
|
test/Parse/matching_patterns.swift
|
apache-2.0
|
1
|
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-source-import
import imported_enums
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int,Int,Int), y: (Int,Int,Int)) -> Bool {
return true
}
var x:Int
func square(_ x: Int) -> Int { return x*x }
struct A<B> {
struct C<D> { }
}
switch x {
// Expressions as patterns.
case 0:
()
case 1 + 2:
()
case square(9):
()
// 'var' and 'let' patterns.
case var a:
a = 1
case let a:
a = 1 // expected-error {{cannot assign}}
case var var a: // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
a += 1
case var let a: // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
print(a, terminator: "")
case var (var b): // expected-error {{'var' cannot appear nested inside another 'var'}}
b += 1
// 'Any' pattern.
case _:
()
// patterns are resolved in expression-only positions are errors.
case 1 + (_): // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}}
()
}
switch (x,x) {
case (var a, var a): // expected-error {{definition conflicts with previous value}} expected-note {{previous definition of 'a' is here}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
fallthrough
case _:
()
}
var e : Any = 0
switch e { // expected-error {{switch must be exhaustive, consider adding a default clause:}}
// 'is' pattern.
case is Int,
is A<Int>,
is A<Int>.C<Int>,
is (Int, Int),
is (a: Int, b: Int):
()
}
// Enum patterns.
enum Foo { case A, B, C }
func == <T>(_: Voluntary<T>, _: Voluntary<T>) -> Bool { return true }
enum Voluntary<T> : Equatable {
case Naught
case Mere(T)
case Twain(T, T)
func enumMethod(_ other: Voluntary<T>, foo: Foo) {
switch self {
case other:
()
case .Naught,
.Naught(),
.Naught(_, _): // expected-error{{tuple pattern has the wrong length for tuple type '()'}}
()
case .Mere,
.Mere(), // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}}
.Mere(_),
.Mere(_, _): // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}}
()
case .Twain(), // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}}
.Twain(_),
.Twain(_, _),
.Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}}
()
}
switch foo {
case .Naught: // expected-error{{pattern cannot match values of type 'Foo'}}
()
case .A, .B, .C:
()
}
}
}
var n : Voluntary<Int> = .Naught
switch n {
case Foo.A: // expected-error{{enum case 'A' is not a member of type 'Voluntary<Int>'}}
()
case Voluntary<Int>.Naught,
Voluntary<Int>.Naught(),
Voluntary<Int>.Naught(_, _), // expected-error{{tuple pattern has the wrong length for tuple type '()'}}
Voluntary.Naught,
.Naught:
()
case Voluntary<Int>.Mere,
Voluntary<Int>.Mere(_),
Voluntary<Int>.Mere(_, _), // expected-error{{tuple pattern cannot match values of the non-tuple type 'Int'}}
Voluntary.Mere,
Voluntary.Mere(_),
.Mere,
.Mere(_):
()
case .Twain,
.Twain(_),
.Twain(_, _),
.Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(Int, Int)'}}
()
}
var notAnEnum = 0
switch notAnEnum {
case .Foo: // expected-error{{pattern cannot match values of type 'Int'}}
()
}
struct ContainsEnum {
enum Possible<T> {
case Naught
case Mere(T)
case Twain(T, T)
}
func member(_ n: Possible<Int>) {
switch n { // expected-error {{switch must be exhaustive, consider adding missing cases:}}
// expected-note@-1 {{missing case: '.Mere(_)'}}
// expected-note@-2 {{missing case: '.Twain(_, _)'}}
case ContainsEnum.Possible<Int>.Naught,
ContainsEnum.Possible.Naught,
Possible<Int>.Naught,
Possible.Naught,
.Naught:
()
}
}
}
func nonmemberAccessesMemberType(_ n: ContainsEnum.Possible<Int>) {
switch n { // expected-error {{switch must be exhaustive, consider adding missing cases:}}
// expected-note@-1 {{missing case: '.Mere(_)'}}
// expected-note@-2 {{missing case: '.Twain(_, _)'}}
case ContainsEnum.Possible<Int>.Naught,
.Naught:
()
}
}
var m : ImportedEnum = .Simple
switch m {
case imported_enums.ImportedEnum.Simple,
ImportedEnum.Simple,
.Simple:
()
case imported_enums.ImportedEnum.Compound,
imported_enums.ImportedEnum.Compound(_),
ImportedEnum.Compound,
ImportedEnum.Compound(_),
.Compound,
.Compound(_):
()
}
// Check that single-element tuple payloads work sensibly in patterns.
enum LabeledScalarPayload {
case Payload(name: Int)
}
var lsp: LabeledScalarPayload = .Payload(name: 0)
func acceptInt(_: Int) {}
func acceptString(_: String) {}
switch lsp {
case .Payload(0):
()
case .Payload(name: 0):
()
case let .Payload(x):
acceptInt(x)
acceptString("\(x)")
case let .Payload(name: x):
acceptInt(x)
acceptString("\(x)")
case let .Payload((name: x)):
acceptInt(x)
acceptString("\(x)")
case .Payload(let (name: x)):
acceptInt(x)
acceptString("\(x)")
case .Payload(let (name: x)):
acceptInt(x)
acceptString("\(x)")
case .Payload(let x):
acceptInt(x)
acceptString("\(x)")
case .Payload((let x)):
acceptInt(x)
acceptString("\(x)")
}
// Property patterns.
struct S {
static var stat: Int = 0
var x, y : Int
var comp : Int {
return x + y
}
func nonProperty() {}
}
// Tuple patterns.
var t = (1, 2, 3)
prefix operator +++
infix operator +++
prefix func +++(x: (Int,Int,Int)) -> (Int,Int,Int) { return x }
func +++(x: (Int,Int,Int), y: (Int,Int,Int)) -> (Int,Int,Int) {
return (x.0+y.0, x.1+y.1, x.2+y.2)
}
switch t {
case (_, var a, 3):
a += 1
case var (_, b, 3):
b += 1
case var (_, var c, 3): // expected-error{{'var' cannot appear nested inside another 'var'}}
c += 1
case (1, 2, 3):
()
// patterns in expression-only positions are errors.
case +++(_, var d, 3):
// expected-error@-1{{'+++' is not a prefix unary operator}}
()
case (_, var e, 3) +++ (1, 2, 3):
// expected-error@-1{{'_' can only appear in a pattern}}
// expected-error@-2{{'var' binding pattern cannot appear in an expression}}
()
}
// FIXME: We don't currently allow subpatterns for "isa" patterns that
// require interesting conditional downcasts.
class Base { }
class Derived : Base { }
switch [Derived(), Derived(), Base()] {
case let ds as [Derived]: // expected-error{{downcast pattern value of type '[Derived]' cannot be used}}
()
default:
()
}
// Optional patterns.
let op1 : Int?
let op2 : Int??
switch op1 {
case nil: break
case 1?: break
case _?: break
}
switch op2 {
case nil: break
case _?: break
case (1?)?: break
case (_?)?: break
}
// <rdar://problem/20365753> Bogus diagnostic "refutable pattern match can fail"
let (responseObject: Int?) = op1
// expected-error @-1 {{expected ',' separator}} {{25-25=,}}
// expected-error @-2 {{expected pattern}}
|
1917725646bc03f44c452386ac3aa3f9
| 22.120635 | 322 | 0.612385 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.