repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
brettg/Signal-iOS
Signal/src/Models/SyncPushTokensJob.swift
1
3363
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit @objc(OWSSyncPushTokensJob) class SyncPushTokensJob: NSObject { let TAG = "[SyncPushTokensJob]" let pushManager: PushManager let accountManager: AccountManager let preferences: PropertyListPreferences var uploadOnlyIfStale = true // useful to ensure promise runs to completion var retainCycle: SyncPushTokensJob? required init(pushManager: PushManager, accountManager: AccountManager, preferences: PropertyListPreferences) { self.pushManager = pushManager self.accountManager = accountManager self.preferences = preferences } @objc class func run(pushManager: PushManager, accountManager: AccountManager, preferences: PropertyListPreferences) -> AnyPromise { let job = self.init(pushManager: pushManager, accountManager: accountManager, preferences: preferences) return AnyPromise(job.run()) } @objc func run() -> AnyPromise { return AnyPromise(run()) } func run() -> Promise<Void> { Logger.debug("\(TAG) Starting.") // Make sure we don't GC until completion. self.retainCycle = self // Required to potentially prompt user for notifications settings // before `requestPushTokens` will return. self.pushManager.validateUserNotificationSettings() return self.requestPushTokens().then { (pushToken: String, voipToken: String) in var shouldUploadTokens = !self.uploadOnlyIfStale if self.preferences.getPushToken() != pushToken || self.preferences.getVoipToken() != voipToken { Logger.debug("\(self.TAG) push tokens changed.") shouldUploadTokens = true } guard shouldUploadTokens else { Logger.info("\(self.TAG) skipping push token upload") return Promise(value: ()) } Logger.info("\(self.TAG) Sending new tokens to account servers.") return self.accountManager.updatePushTokens(pushToken:pushToken, voipToken:voipToken).then { Logger.info("\(self.TAG) Recording tokens locally.") return self.recordNewPushTokens(pushToken:pushToken, voipToken:voipToken) } }.always { self.retainCycle = nil } } private func requestPushTokens() -> Promise<(pushToken: String, voipToken: String)> { return Promise { fulfill, reject in self.pushManager.requestPushToken( success: { (pushToken: String, voipToken: String) in fulfill((pushToken:pushToken, voipToken:voipToken)) }, failure: reject ) } } private func recordNewPushTokens(pushToken: String, voipToken: String) -> Promise<Void> { Logger.info("\(TAG) Recording new push tokens.") if (pushToken != self.preferences.getPushToken()) { Logger.info("\(TAG) Recording new plain push token") self.preferences.setPushToken(pushToken) } if (voipToken != self.preferences.getVoipToken()) { Logger.info("\(TAG) Recording new voip token") self.preferences.setVoipToken(voipToken) } return Promise(value: ()) } }
gpl-3.0
9b68b40286153a8ed3e122fef420f20f
36.366667
136
0.638715
4.895197
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01835-getselftypeforcontainer.swift
1
729
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -typecheck func i<Y> { t..Iterator.f = Swift.init([0.E == { class a { } print() -> { class A { } } } class func ^() { } protocol b = { protocol a { } } enum B : A { return { c) -> T } protocol b { extension NSSet { } typealias f : b<Y> { func f: Sequence where h>, self.c: A, AnyObject, ")) func b: a { } } protocol A { func b: A> Int = j> {
apache-2.0
61021efb54aa30a58c940873f273e8bd
19.25
79
0.658436
3.050209
false
false
false
false
codefellows/sea-b19-ios
Projects/Week5 CoreDataMusic_refactor/CoreDataMusic/AddArtistViewController.swift
2
1686
// // AddArtistViewController.swift // CoreDataMusic // // Created by Bradley Johnson on 8/19/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit import CoreData class AddArtistViewController: UIViewController { var myContext : NSManagedObjectContext! var selectedLabel : Label? @IBOutlet weak var lastNameField: UITextField! @IBOutlet weak var firstNameFIeld: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func saveButtonPressed(sender: AnyObject) { var labelContext = self.selectedLabel?.managedObjectContext var newArtist = NSEntityDescription.insertNewObjectForEntityForName("Artist", inManagedObjectContext: labelContext) as Artist newArtist.firstName = self.firstNameFIeld.text newArtist.lastName = self.lastNameField.text newArtist.label = self.selectedLabel! var error : NSError? labelContext?.save(&error) if error != nil { println(error?.localizedDescription) } } /* // 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. } */ }
gpl-2.0
4465262ed09e488b10cca28f62b7b749
29.654545
133
0.682088
5.203704
false
false
false
false
marcdown/SayWhat
SayWhat/Views/ArtistsViewController.swift
1
6020
// // ArtistsViewController.swift // SayWhat // // Created by Marc Brown on 8/28/16. // Copyright © 2016 creative mess. All rights reserved. // import Speech import UIKit class ArtistsViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, SpeechRecognitionDelegate { enum ErrorMessage: String { case Denied = "To enable Speech Recognition go to Settings -> Privacy." case NotDetermined = "Authorization not determined - please try again." case Restricted = "Speech Recognition is restricted on this device." case NoResults = "No results found - please try a different search." } @IBOutlet var tableView: UITableView! @IBOutlet var searchBar: UISearchBar! @IBOutlet var microphoneButton: UIBarButtonItem! private var searchResults: [ArtistModel] = [] override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView(frame: CGRect.zero) } func requestSpeechAuthorization() { SFSpeechRecognizer.requestAuthorization { authStatus in switch authStatus { case .authorized: self.startListening() case .denied: self.displayErrorAlert(message: .Denied) case .notDetermined: self.displayErrorAlert(message: .NotDetermined) case .restricted: self.displayErrorAlert(message: .Restricted) } } } func startListening() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "SpeechRecognitionViewController") as! SpeechRecognitionViewController vc.delegate = self OperationQueue.main.addOperation { self.present(vc, animated: true, completion: nil) } } func displayErrorAlert(message: ErrorMessage) { let alertController = UIAlertController(title: nil, message: message.rawValue, preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertAction) OperationQueue.main.addOperation { self.present(alertController, animated: true, completion: nil) } } func search(artist: String?) { guard let artist = artist else { return } reset() let urlEncodedArtist = artist.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! let url: URL = URL(string: "https://api.spotify.com/v1/search?q=\(urlEncodedArtist)&type=artist")! let session = URLSession.shared let task = session.dataTask(with: url) { (data, response, error) in guard let data = data else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] if let artists = json?["artists"]?["items"] as? [AnyObject] { if artists.isEmpty { self.displayErrorAlert(message: .NoResults) } else { for artist in artists { let artistModel = ArtistModel(artist: artist as! [String : AnyObject]) self.searchResults.append(artistModel) } OperationQueue.main.addOperation { self.tableView.reloadData() } } } } catch { return } } task.resume() } func reset() { searchResults = [] tableView.reloadData() } @IBAction func microphoneButtonTapped() { switch SFSpeechRecognizer.authorizationStatus() { case .authorized: startListening() break case .denied: displayErrorAlert(message: .Denied) break case .notDetermined: requestSpeechAuthorization() break case .restricted: displayErrorAlert(message: .Restricted) break } } // MARK: UISearchBarDelegate func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false searchBar.resignFirstResponder() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false searchBar.resignFirstResponder() search(artist: searchBar.text) } // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ArtistCell", for: indexPath) let artistModel: ArtistModel = searchResults[indexPath.row] cell.textLabel?.text = artistModel.name return cell } // MARK: SpeechRecognitionDelegate func speechRecognitionComplete(query: String?) { if let query = query { search(artist: query) searchBar.text = "" } dismiss(animated: true, completion: nil) } func speechRecognitionCancelled() { dismiss(animated: true, completion: nil) } }
mit
915c5e53e6bb0d7c371df3126725f612
31.535135
140
0.568035
5.959406
false
false
false
false
CesarValiente/CursoSwiftUniMonterrey2-UI
week2/imccalculator/imccalculator/ViewController.swift
1
2017
// // ViewController.swift // imccalculator // // Created by Cesar Valiente on 03/01/16. // Copyright © 2016 Cesar Valiente. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var weight: UITextField! @IBOutlet weak var height: UITextField! @IBOutlet weak var scroll: UIScrollView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. weight.delegate = self height.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func textFieldDidBeginEditing(textField: UITextField) { var point : CGPoint point = CGPointMake(0, textField.frame.origin.y-50) self.scroll.setContentOffset(point, animated: true) } @IBAction func textFieldDidEndEditing(textField: UITextField) { self.scroll.setContentOffset(CGPointZero, animated: true) } @IBAction func textFieldDoneEditing(sender : UITextField) { sender.resignFirstResponder() //The keyboard will hide after editing } @IBAction func backgroundTap (sender : UIControl) { weight.resignFirstResponder() height.resignFirstResponder() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let result = imc() let nextView = segue.destinationViewController as! ViewResult nextView.imcIndex = result } @IBAction func calculateImc(sender: AnyObject) { imc() } func imc () -> Double { var imc : Double let localWeight : Double? localWeight = Double(self.weight.text!)! let localHeight : Double = Double(self.height.text!)! imc = localWeight!/(localHeight*localHeight) print("Result: \(imc)") return imc } }
mit
a0bc020e112e47c86b99f2ecf9f4687d
28.647059
81
0.65625
4.905109
false
false
false
false
trident10/TDMediaPicker
TDMediaPicker/Classes/View/CustomView/TDMediaPreviewMainView.swift
1
13171
// // TDMediaPreviewMainView.swift // ImagePicker // // Created by Abhimanu Jindal on 28/06/17. // Copyright © 2017 Abhimanu Jindal. All rights reserved. // import UIKit protocol TDMediaPreviewMainViewDataSource: class { func previewMainViewHideCaptionView(_ view: TDMediaPreviewMainView)-> Bool? } protocol TDMediaPreviewMainViewDelegate: class { func previewMainView(_ view: TDMediaPreviewMainView, didDisplayViewAtIndex index: Int) func previewMainView(_ view: TDMediaPreviewMainView, didRequestUpdateMedia media: TDPreviewViewModel) } class TDMediaPreviewMainView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ // MARK: - Variable(s) weak var delegate: TDMediaPreviewMainViewDelegate? weak var dataSource: TDMediaPreviewMainViewDataSource? var bottomSpace:CGFloat = 65 var captionCount:Int = 1000 fileprivate var mediaItems: [TDPreviewViewModel] = [] fileprivate var selectedIndex: Int = 0 private let rows: CGFloat = 1 private let cellSpacing: CGFloat = 2 // This logic is used to avoid multiple reload of thumpreview private var isScrolledByUser: Bool = true private var timer: Timer? private var currentVisibleIndex = -1 private var currentPlayerSetupIndex = -1 fileprivate var videoPlayerView: TDMediaVideoView? @IBOutlet var collectionView: UICollectionView! @IBOutlet var captionTextViewBottomConstraint:NSLayoutConstraint! @IBOutlet var captionTextViewHeightConstraint:NSLayoutConstraint! @IBOutlet var captionTextView:UITextView! // MARK: - LifeCycle override func awakeFromNib() { captionTextView.delegate = self } override func layoutSubviews() { collectionView.reloadData() videoPlayerView?.frame = self.bounds } // MARK: - Public Method(s) func getMedia()->[TDPreviewViewModel]{ return self.mediaItems } func viewWillTransition(){ isScrolledByUser = false } func viewDidTransition(){ collectionView.reloadData() collectionView.scrollToItem(at: IndexPath(row: selectedIndex, section: 0), at: .centeredHorizontally, animated: false) isScrolledByUser = true self.updateTextViewFrame() } func setupView(){ TDMediaCell.registerCellWithType(.Image, collectionView: collectionView) TDMediaCell.registerCellWithType(.Video, collectionView: collectionView) videoPlayerView = TDMediaVideoView(frame: self.bounds) videoPlayerView?.delegate = self } func purgeData(){ mediaItems.removeAll() videoPlayerView?.removeFromSuperview() videoPlayerView = nil } func reload(media: TDMediaPreviewViewModel){ if media.previewMedia.count == 0 { return } mediaItems.removeAll() mediaItems = media.previewMedia collectionView.reloadData() currentVisibleIndex = 0 selectedIndex = 0 captionTextView.text = mediaItems[selectedIndex].caption self.updateTextViewFrame() DispatchQueue.main.async { self.setupVideoPlayerView() } } func reload(toIndex: Int){ if mediaItems.count <= toIndex{ return } var shouldScrollAnimated = true if abs(selectedIndex - toIndex) > 3{ shouldScrollAnimated = false } selectedIndex = toIndex let indexPath = IndexPath(row: selectedIndex, section: 0) isScrolledByUser = false collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.right, animated: shouldScrollAnimated) if !shouldScrollAnimated{ DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute: { self.setupVideoPlayerView() }) } //TEMP HACK TO AVOID MULTIPLE RELOAD OF THUMB PREVIEW VIEW. if timer != nil{ timer?.invalidate() timer = nil } timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { (timer) in self.isScrolledByUser = true }) captionTextView.text = mediaItems[selectedIndex].caption self.updateTextViewFrame() } // MARK: - Private Method(s) private func notifyScrolling(){ if !isScrolledByUser{ return } self.delegate?.previewMainView(self, didDisplayViewAtIndex: currentVisibleIndex) selectedIndex = currentVisibleIndex captionTextView.text = mediaItems[selectedIndex].caption self.updateTextViewFrame() } fileprivate func purgeVideoPlayer(_ completion: @escaping () -> Void){ videoPlayerView?.removeFromSuperview() videoPlayerView?.purgeVideoPlayer { completion() } } fileprivate func updateTextViewFrame(){ let contentSize = self.captionTextView.sizeThatFits(self.captionTextView.bounds.size) if contentSize.height > 60{ captionTextViewHeightConstraint.constant = 60 captionTextView.isScrollEnabled = true }else{ captionTextViewHeightConstraint.constant = contentSize.height captionTextView.isScrollEnabled = false } captionTextView.contentInset = .zero } private func setupVideoPlayerView(){ if currentVisibleIndex == -1 || (currentPlayerSetupIndex != -1 && currentPlayerSetupIndex == currentVisibleIndex){ // Stop Setup of player videoPlayerView?.stopVideo() return } if mediaItems.count <= currentVisibleIndex{ return } let media = mediaItems[currentVisibleIndex] if media.asset?.mediaType == .video{ let cell = collectionView.cellForItem(at: IndexPath(item: currentVisibleIndex, section: 0)) if cell != nil{ currentPlayerSetupIndex = currentVisibleIndex purgeVideoPlayer { cell?.addSubview(self.videoPlayerView!) self.videoPlayerView?.setupVideoPlayer(media.asset!, completion: {}) } return } } currentPlayerSetupIndex = -1 videoPlayerView?.removeFromSuperview() videoPlayerView?.purgeVideoPlayer {} } private func updateCurrentVisibleIndex(){ var visibleRect = CGRect() visibleRect.origin = collectionView.contentOffset visibleRect.size = collectionView.bounds.size let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY) if let visibleIndexPath: IndexPath = collectionView.indexPathForItem(at: visiblePoint){ currentVisibleIndex = visibleIndexPath.item } } private func handleMediaCellActions(cell:TDMediaCell, indexPath: IndexPath){ cell.onButtonTap { (buttonType) in if buttonType == .videoPlay{ self.videoPlayerView?.isHidden = false self.videoPlayerView?.playVideo() } } } private func setUpMediaCell(mediaItem: TDPreviewViewModel, indexPath: IndexPath) -> TDMediaCell?{ if mediaItem.asset?.mediaType == .image{ return TDMediaCell.mediaCellWithType(.Image, collectionView: collectionView, for: indexPath) } if mediaItem.asset?.mediaType == .video{ let cell = TDMediaCell.mediaCellWithType(.Video, collectionView: collectionView, for: indexPath) handleMediaCellActions(cell: cell, indexPath: indexPath) return cell } return nil } private func configureMediaCell(item: TDPreviewViewModel, indexPath: IndexPath)-> UICollectionViewCell{ let cell: TDMediaCell? cell = setUpMediaCell(mediaItem: item, indexPath: indexPath) if cell == nil{ print("ERROR IN GENERATING CORRECT CELL") return UICollectionViewCell() } if item.mainImage != nil{ cell?.configure(item.mainImage!) } else{ cell?.configure(item.asset!, completionHandler: { (image) in item.mainImage = image }) } return cell! } // MARK: - Collection View Datasource Method(s) func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return mediaItems.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = mediaItems[(indexPath as NSIndexPath).item] if item.itemType == .Media{ return configureMediaCell(item: item, indexPath: indexPath) } print("THIS SHOULD NOT BE CALLED. CHECK FOR ERROR") return UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height) } // MARK: - Collection View Delegate Method(s) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { isScrolledByUser = true } // MARK: - ScrollView Delegate Method(s) func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.collectionView{ updateCurrentVisibleIndex() notifyScrolling() setupVideoPlayerView() } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { setupVideoPlayerView() } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { setupVideoPlayerView() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { setupVideoPlayerView() } } //MARK: - VideoPlayer Delegate Method(s) extension TDMediaPreviewMainView: TDMediaVideoViewDelegate{ func videoViewDidStopPlay(_ view: TDMediaVideoView) { } } extension TDMediaPreviewMainView{ func viewWillAppear(){ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) if let isHidden = self.dataSource?.previewMainViewHideCaptionView(self){ captionTextView.isHidden = isHidden } } func viewDidDisappear(){ NotificationCenter.default.removeObserver(self) } @objc private func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { let height = keyboardSize.height var duration = 0.3 if let userInfo = notification.userInfo { duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0.3 } UIView.animate(withDuration: duration) { var captionBottomspace:CGFloat = self.bottomSpace - 5 if UIApplication.shared.statusBarOrientation.isLandscape{ if captionBottomspace > 0{ captionBottomspace -= 40 } } self.captionTextViewBottomConstraint.constant = height-captionBottomspace self.layoutIfNeeded() } } } @objc private func keyboardWillHide(notification: NSNotification) { var duration = 0.3 if let userInfo = notification.userInfo { duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0.3 } UIView.animate(withDuration: duration) { self.captionTextViewBottomConstraint.constant = 5 self.layoutIfNeeded() } } } extension TDMediaPreviewMainView:UITextViewDelegate{ func textViewDidChange(_ textView: UITextView) { self.updateTextViewFrame() mediaItems[selectedIndex].caption = textView.text self.delegate?.previewMainView(self, didRequestUpdateMedia : mediaItems[selectedIndex]) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n"{ textView.resignFirstResponder() return false } guard let preText = textView.text else { return true } let newLength = preText.count + text.count - range.length return newLength <= captionCount } }
mit
b9773b866c4f3a6d35df91d83691764d
34.12
165
0.644267
5.545263
false
false
false
false
johndpope/Palettes
Palettes/PaletteTableCellView.swift
1
3349
// // PaletteTableCellView.swift // Palettes // // Created by Amit Burstein on 11/26/14. // Copyright (c) 2014 Amit Burstein. All rights reserved. // import Cocoa class PaletteTableCellView: NSTableCellView { // MARK: Properties let FadeAnimationDuration = 0.2 let CopyViewAnimationDuration = Int64(2 * Double(NSEC_PER_SEC)) var fadeAnimation: POPBasicAnimation! var fadeReverseAnimation: POPBasicAnimation! var colors: [String]! var url: String! @IBOutlet weak var paletteView: NSView! @IBOutlet weak var openButton: NSButton! // MARK: Initialization required init?(coder: NSCoder) { super.init(coder: coder) colors = [] url = nil // Set up fade animation fadeAnimation = POPBasicAnimation() fadeAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerOpacity) as! POPAnimatableProperty fadeAnimation.fromValue = 0 fadeAnimation.toValue = 1 fadeAnimation.duration = FadeAnimationDuration // Set up fade reverse animation fadeReverseAnimation = POPBasicAnimation() fadeReverseAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerOpacity) as! POPAnimatableProperty fadeReverseAnimation.fromValue = 1 fadeReverseAnimation.toValue = 0 fadeReverseAnimation.duration = FadeAnimationDuration } // MARK: NSResponder override func mouseDown(event: NSEvent) { // Get index of selected color let colorWidth = ceil(paletteView.bounds.width / CGFloat(paletteView.subviews.count)) let colorStartX = paletteView.frame.origin.x let colorIndex = Int(floor((event.locationInWindow.x - colorStartX) / colorWidth)) // Copy color to clipboard let viewController = nextResponder?.nextResponder?.nextResponder?.nextResponder?.nextResponder?.nextResponder! as! ViewController let pasteboard = NSPasteboard.generalPasteboard() pasteboard.clearContents() pasteboard.writeObjects([ColorConverter.getColorString(index: viewController.copyType, rawHex: colors[colorIndex])]) // Show copy view viewController.copiedView.layer?.pop_addAnimation(viewController.copiedViewAnimation, forKey: nil) // Hide copy view after 2 seconds dispatch_after(dispatch_time(DISPATCH_TIME_NOW, CopyViewAnimationDuration), dispatch_get_main_queue(), { viewController.copiedView.layer!.pop_addAnimation(viewController.copiedViewReverseAnimation, forKey: nil) }) } override func mouseEntered(theEvent: NSEvent) { openButton.layer?.pop_addAnimation(fadeAnimation, forKey: nil) } override func mouseExited(theEvent: NSEvent) { openButton.layer?.pop_addAnimation(fadeReverseAnimation, forKey: nil) } override func cursorUpdate(event: NSEvent) { if paletteView.convertPoint(event.locationInWindow, fromView: nil).y > 0 { NSCursor.pointingHandCursor().set() } } // MARK: IBActions @IBAction func clickedOpenButton(sender: NSButton) { NSWorkspace.sharedWorkspace().openURL(NSURL(string: url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!) } }
mit
ece66c6d3db7e855856eb6689e0ffc96
35.402174
137
0.687369
5.152308
false
false
false
false
smogun/KVLAnimatedLoader
KVLAnimatedLoader/KVLLoaderViewController.swift
1
4574
// // KVLLoaderViewController.swift // KVLAnimatedLoader // // Created by Misha Koval on 12/6/15. // Copyright © 2015 Misha Koval. All rights reserved. // import Foundation import UIKit typealias Selectors_KVLLoaderViewController = KVLLoaderViewController public class KVLLoaderViewController : UIViewController { var loader : UIView? = nil; var width : CGFloat = 0.0; var loaderStarted : Bool = false; var loaderSize: Double = 0.0 var gap : Double = 6 var elementSize : Double = 0 var startStopButton: UIButton? = nil; var addRemoveButton: UIButton? = nil; convenience init<T: UIView where T:protocol<KVLLoaderProtocol>> (loader: T!, width: CGFloat) { self.init(); self.loader = loader; self.width = width; } override public func viewDidLoad() { super.viewDidLoad(); self.view.backgroundColor = UIColor.lightGrayColor() self.view.frame = CGRectMake(0, 0, self.width, self.width); self.elementSize = Double(self.width) / 3.0 self.loaderSize = elementSize * 2.0 - gap / 2.0 self.loader!.frame = CGRectMake(0, self.width / 2 - CGFloat(loaderSize) / 2, CGFloat(loaderSize), CGFloat(loaderSize)) self.view.addSubview(self.loader!) addButtonsPane() startStopLoader() } private func addButtonsPane() { let buttonsPane = UIView(); self.startStopButton = UIButton(type: UIButtonType.RoundedRect) self.startStopButton!.setTitle("Start", forState: .Normal) self.startStopButton!.titleLabel?.adjustsFontSizeToFitWidth = true self.startStopButton!.setTitleColor(UIColor.blackColor(), forState: .Normal) self.startStopButton!.addTarget(self, action: "startStopLoader", forControlEvents: .TouchUpInside); self.startStopButton!.frame = CGRectMake(0, 0, CGFloat(self.elementSize - self.gap * 1.5), 40) self.startStopButton!.backgroundColor = UIColor.grayColor() buttonsPane.addSubview(self.startStopButton!) // addRemoveButton = UIButton(type: UIButtonType.RoundedRect) // addRemoveButton!.setTitle("Remove", forState: .Normal) // addRemoveButton!.titleLabel?.adjustsFontSizeToFitWidth = true // addRemoveButton!.setTitleColor(UIColor.blackColor(), forState: .Normal) // addRemoveButton!.addTarget(self, action: "addRemoveLoader", forControlEvents: .TouchUpInside); // addRemoveButton!.frame = CGRectMake(0, startStopButton!.endY + CGFloat(self.gap), CGFloat(self.elementSize - self.gap * 1.5), 40) // addRemoveButton!.backgroundColor = UIColor.grayColor() // buttonsPane.addSubview(addRemoveButton!) // // // let buttonsPaneHeight = addRemoveButton!.endY; let buttonsPaneHeight = self.startStopButton!.endY; buttonsPane.frame = CGRectMake(self.loader!.endX + CGFloat(self.gap), self.width / 2 - buttonsPaneHeight / 2, self.startStopButton!.size.width, buttonsPaneHeight) self.view.addSubview(buttonsPane); } } extension Selectors_KVLLoaderViewController { func startStopLoader() { let localLoader = self.loader as? KVLLoaderProtocol; if ((localLoader) != nil) { self.loaderStarted = !self.loaderStarted; if (self.loaderStarted) { localLoader!.startAnimating() startStopButton!.setTitle("Stop", forState: .Normal) } else { localLoader!.stopAnimating() startStopButton!.setTitle("Start", forState: .Normal) } } } func addRemoveLoader() { let localLoader = self.loader as? KVLLoaderProtocol; if ((localLoader) != nil) { if (self.loader!.superview == nil) { startStopButton!.enabled = true; self.view.addSubview(self.loader!) addRemoveButton!.setTitle("Remove", forState: .Normal) } else { startStopButton!.enabled = false; self.loaderStarted = true startStopLoader() self.loader!.removeFromSuperview() addRemoveButton!.setTitle("Re-Add", forState: .Normal) } } } }
mit
378ec9d457e87092ad99bae75dd93043
31.211268
170
0.596764
4.798531
false
false
false
false
trill-lang/LLVMSwift
Tests/LLVMTests/BFC.swift
1
12709
import LLVM import XCTest import FileCheck import Foundation class BFCSpec : XCTestCase { func testCompile() { // So, this looks weird for a reason. It has to be edge-aligned because // I'm lazy and didn't want to implement column resets correctly. And it has // to be indented on every operation because LLVM de-duplicates source // locations by file and line. So even if you emit two distinct locations // for two distinct operations on the same line, you'll step over both of // them if they don't have discriminators set. We need hooks for this. XCTAssert(fileCheckOutput(of: .stderr, withPrefixes: ["BFC"]) { // BFC: ; ModuleID = 'brainfuck' compile( """ + + + + + + + + [ > + + + + [ > + + > + + + > + + + > + < < < < - ] > + > + > - > > + [ < ] < - ] > > . > - - - . + + + + + + + . . + + + . > > . < - . < . + + + . - - - - - - . - - - - - - - - . > > + . > + + . """) }) } #if !os(macOS) static var allTests = testCase([ ("testCompile", testCompile) ]) #endif } private let cellType = IntType.int8 private let cellTapeType = ArrayType(elementType: cellType, count: 30000) struct Loop { let entry: BasicBlock let body: BasicBlock let exit: BasicBlock let headerDestination: PhiNode let exitDestination: PhiNode } private enum Externs { case putchar case getchar case flush func resolve(_ builder: IRBuilder) -> Function { let lastEntry = builder.insertBlock defer { if let pos = lastEntry { builder.positionAtEnd(of: pos) } } switch self { case .getchar: let f = builder.addFunction("readchar", type: FunctionType([], cellType)) let getCharExtern = builder.addFunction("getchar", type: FunctionType([], cellType)) let entry = f.appendBasicBlock(named: "entry") builder.positionAtEnd(of: entry) let charValue = builder.buildCall(getCharExtern, args: []) let cond = builder.buildICmp(charValue, cellType.constant(0), .signedGreaterThanOrEqual) let retVal = builder.buildSelect(cond, then: charValue, else: cellType.constant(0)) builder.buildRet(retVal) return f case .putchar: return builder.addFunction("putchar", type: FunctionType([ cellType ], VoidType())) case .flush: let f = builder.addFunction("flush", type: FunctionType([], VoidType())) let entry = f.appendBasicBlock(named: "entry") builder.positionAtEnd(of: entry) let ptrTy = PointerType(pointee: IntType.int8) let fflushExtern = builder.addFunction("fflush", type: FunctionType([ ptrTy ], IntType.int32)) _ = builder.buildCall(fflushExtern, args: [ ptrTy.constPointerNull() ]) builder.buildRetVoid() return f } } } private func compile(at column: Int = #column, line: Int = #line, _ program: String) { let module = Module(name: "brainfuck") let builder = IRBuilder(module: module) let dibuilder = DIBuilder(module: module) let cellTape = module.addGlobal("tape", initializer: cellTapeType.null()) let main = builder.addFunction("main", type: FunctionType([], IntType.int32)) let sourceFile = #file.components(separatedBy: "/").last! let sourceDir = #file.components(separatedBy: "/").dropLast().joined(separator: "/") let mainFile = dibuilder.buildFile(named: sourceFile, in: sourceDir) let compileUnit = dibuilder.buildCompileUnit(for: .c, in: mainFile, kind: .full) let mainModule = dibuilder.buildModule( named: "bf", scope: compileUnit, macros: [], includePath: sourceDir, includeSystemRoot: "") _ = dibuilder.buildImportedModule( in: mainFile, module: mainModule, file: mainFile, line: 0) let diFnTy = dibuilder.buildSubroutineType(in: mainFile, parameterTypes: []) main.metadata = dibuilder.buildFunction( named: "main", linkageName: "_main", scope: mainFile, file: mainFile, line: line, scopeLine: line, type: diFnTy, flags: [], isLocal: true) let entryBlock = main.appendBasicBlock(named: "entry") builder.positionAtEnd(of: entryBlock) let mainScope = dibuilder.buildLexicalBlock( scope: main.metadata, file: mainFile, line: line, column: column) compileProgramBody(program, (line, column), builder, dibuilder, main, mainScope, mainFile, cellTape) dibuilder.finalize() module.dump() /* Uncomment to output an object file. let targetMachine = try! TargetMachine(optLevel: .none) try! targetMachine.emitToFile(module: module, type: .object, path: sourceDir + "/bf.o") */ } private func compileProgramBody( _ program: String, _ startPoint: (Int, Int), _ builder: IRBuilder, _ dibuilder: DIBuilder, _ function: Function, _ entryScope: DIScope, _ file: FileMetadata, _ cellTape: Global ) { let putCharExtern = Externs.putchar.resolve(builder) let getCharExtern = Externs.getchar.resolve(builder) let flushExtern = Externs.flush.resolve(builder) var addressPointer: IRValue = cellTape.constGEP(indices: [ IntType.int32.zero(), // (*self) IntType.int32.zero() // [0] ]) /// Create an artificial typedef and variable for the current /// pointer into the tape. /// /// typedef long value_t; /// /// value_t this = 0; let diDataTy = dibuilder.buildBasicType(named: "value_t", encoding: .signed, flags: [], size: builder.module.dataLayout.abiSize(of: cellType)) let diPtrTy = dibuilder.buildPointerType(pointee: diDataTy, size: builder.module.dataLayout.pointerSize()) let diVariable = dibuilder.buildLocalVariable(named: "this", scope: entryScope, file: file, line: startPoint.0, type: diPtrTy, flags: .artificial) var sourceLine = startPoint.0 + 1 var sourceColumn = startPoint.1 + 1 // Declare the variable at the start of the function and give it a value of 0. let loc = dibuilder.buildDebugLocation(at: (sourceLine, sourceColumn), in: entryScope) dibuilder.buildDeclare(of: addressPointer, atEndOf: builder.insertBlock!, metadata: diVariable, expr: dibuilder.buildExpression([]), location: loc) dibuilder.buildDbgValue(of: cellType.zero(), to: diVariable, atEndOf: builder.insertBlock!, expr: dibuilder.buildExpression([]), location: loc) var loopNest = [Loop]() var scopeStack = [DIScope]() scopeStack.append(entryScope) for c in program { sourceColumn += 1 let scope = scopeStack.last! switch c { case ">": // Move right addressPointer = builder.buildGEP(addressPointer, type: cellTapeType, indices: [ IntType.int32.constant(1) ]) builder.currentDebugLocation = dibuilder.buildDebugLocation(at: (sourceLine, sourceColumn), in: scope) dibuilder.buildDbgValue(of: addressPointer, to: diVariable, atEndOf: builder.insertBlock!, expr: dibuilder.buildExpression([.deref]), location: builder.currentDebugLocation!) case "<": // Move left addressPointer = builder.buildGEP(addressPointer, type: cellTapeType, indices: [ IntType.int32.constant(-1) ]) builder.currentDebugLocation = dibuilder.buildDebugLocation(at: (sourceLine, sourceColumn), in: scope) dibuilder.buildDbgValue(of: addressPointer, to: diVariable, atEndOf: builder.insertBlock!, expr: dibuilder.buildExpression([.deref]), location: builder.currentDebugLocation!) case "+": // Increment let value = builder.buildLoad(addressPointer, type: cellType) let ptrUp = builder.buildAdd(value, cellType.constant(1)) builder.buildStore(ptrUp, to: addressPointer) builder.currentDebugLocation = dibuilder.buildDebugLocation(at: (sourceLine, sourceColumn), in: scope) dibuilder.buildDbgValue(of: value, to: diVariable, atEndOf: builder.insertBlock!, expr: dibuilder.buildExpression([.plus_uconst(1)]), location: builder.currentDebugLocation!) case "-": // Decrement let value = builder.buildLoad(addressPointer, type: cellType) let ptrDown = builder.buildSub(value, cellType.constant(1)) builder.buildStore(ptrDown, to: addressPointer) builder.currentDebugLocation = dibuilder.buildDebugLocation(at: (sourceLine, sourceColumn), in: scope) dibuilder.buildDbgValue(of: value, to: diVariable, atEndOf: builder.insertBlock!, expr: dibuilder.buildExpression([.constu(1), .minus]), location: builder.currentDebugLocation!) case ".": // Write let dataValue = builder.buildLoad(addressPointer, type: cellType) _ = builder.buildCall(putCharExtern, args: [dataValue]) builder.currentDebugLocation = dibuilder.buildDebugLocation(at: (sourceLine, sourceColumn), in: scope) case ",": // Read let readValue = builder.buildCall(getCharExtern, args: []) builder.buildStore(readValue, to: addressPointer) builder.currentDebugLocation = dibuilder.buildDebugLocation(at: (sourceLine, sourceColumn), in: scope) case "[": // Jump If Zero let loopEntry = builder.insertBlock! let loopBody = function.appendBasicBlock(named: "loop") let loopExit = function.appendBasicBlock(named: "exit") // If zero let cond = builder.buildIsNotNull(builder.buildLoad(addressPointer, type: cellType)) builder.buildCondBr(condition: cond, then: loopBody, else: loopExit) // Build a PHI for any address pointer changes in the exit block. builder.positionAtEnd(of: loopExit) let exitDestPHI = builder.buildPhi(addressPointer.type) exitDestPHI.addIncoming([ (addressPointer, loopEntry) ]) // Build a PHI for any address pointer changes in the loop body. builder.positionAtEnd(of: loopBody) let headerDestPHI = builder.buildPhi(addressPointer.type) headerDestPHI.addIncoming([ (addressPointer, loopEntry) ]) // Build a lexical scope and enter it. let loopScope = dibuilder.buildLexicalBlock( scope: scope, file: file, line: sourceLine, column: sourceColumn) scopeStack.append(loopScope) // Move to the loop header. addressPointer = headerDestPHI // Push the loop onto the nest. loopNest.append(Loop(entry: loopEntry, body: loopBody, exit: loopExit, headerDestination: headerDestPHI, exitDestination: exitDestPHI)) case "]": // Jump If Not Zero // Pop the innermost loop off the nest. guard let loop = loopNest.popLast() else { fatalError("] requires matching [") } // Exit the loop's scope _ = scopeStack.popLast() // Finish off the phi nodes. loop.headerDestination.addIncoming([ (addressPointer, builder.insertBlock!) ]) loop.exitDestination.addIncoming([ (addressPointer, builder.insertBlock!) ]) // If not zero. let cond = builder.buildIsNotNull(builder.buildLoad(addressPointer, type: cellType)) builder.buildCondBr(condition: cond, then: loop.body, else: loop.exit) // Move the exit block after the loop body. loop.exit.moveAfter(builder.insertBlock!) // Move to the exit. addressPointer = loop.exitDestination builder.positionAtEnd(of: loop.exit) case "\n": sourceLine += 1 sourceColumn = 1 default: continue } } // Ensure all loops have been closed. guard loopNest.isEmpty && scopeStack.count == 1 else { fatalError("[ requires matching ]") } // Flush everything _ = builder.buildCall(flushExtern, args: []) builder.buildRet(IntType.int32.zero()) }
mit
a9d01228b77e2a5cc71b01ab4118ade9
29.477218
116
0.609489
4.118276
false
false
false
false
rickerbh/Moya
Moya/ReactiveCocoa/Moya+ReactiveCocoa.swift
1
3396
import Foundation import ReactiveCocoa import Alamofire /// Subclass of MoyaProvider that returns RACSignal instances when requests are made. Much better than using completion closures. public class ReactiveCocoaMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> { /// Current requests that have not completed or errored yet. /// Note: Do not access this directly. It is public only for unit-testing purposes (sigh). public var inflightRequests = Dictionary<Endpoint<T>, RACSignal>() /// Initializes a reactive provider. override public init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEndpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, manager: Manager = Alamofire.Manager.sharedInstance) { super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure, manager: manager) } /// Designated request-making method. public func request(token: T) -> RACSignal { let endpoint = self.endpoint(token) // weak self just for best practices – RACSignal will take care of any retain cycles anyway, // and we're connecting immediately (below), so self in the block will always be non-nil return RACSignal.`defer` { [weak self] () -> RACSignal! in if let weakSelf = self { objc_sync_enter(weakSelf) let inFlight = weakSelf.inflightRequests[endpoint] objc_sync_exit(weakSelf) if let existingSignal = inFlight { return existingSignal } } let signal = RACSignal.createSignal { (subscriber) -> RACDisposable! in let cancellableToken = self?.request(token) { data, statusCode, response, error in if let error = error { if let statusCode = statusCode { subscriber.sendError(NSError(domain: MoyaErrorDomain, code: statusCode, userInfo: [NSUnderlyingErrorKey: error as NSError])) } else { subscriber.sendError(error as NSError) } } else { if let data = data { subscriber.sendNext(MoyaResponse(statusCode: statusCode!, data: data, response: response)) } subscriber.sendCompleted() } } return RACDisposable { () -> Void in if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = nil cancellableToken?.cancel() objc_sync_exit(weakSelf) } } }.publish().autoconnect() if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = signal objc_sync_exit(weakSelf) } return signal } } }
mit
3ac4c25e7ca3e34c933cd68051167af5
48.188406
368
0.584266
6.082437
false
false
false
false
Keanyuan/SwiftContact
SwiftContent/SwiftContent/Classes/Common/ALMacro.swift
1
1688
// // ALMacro.swift // ExpressSystem // // Created by Kean on 2017/5/31. // Copyright © 2017年 Kean. All rights reserved. // import UIKit /// 第一次启动 let YMFirstLaunch = "firstLaunch" let LOGIN_STATUS_KEY = "Login_Status_Key" /// 屏幕的宽 let SCREENW = UIScreen.main.bounds.size.width /// 屏幕的高 let SCREENH = UIScreen.main.bounds.size.height /// iPhone 5 let isIPhone5 = SCREENH == 568 ? true : false /// iPhone 6 let isIPhone6 = SCREENH == 667 ? true : false /// iPhone 6P let isIPhone6P = SCREENH == 736 ? true : false let UIRate = (UIScreen.main.bounds.size.width/375) /// prin输出 /// /// - Parameters: /// - message: 输出内容 /// - logError: 是否错误 default is false /// - file: 输出文件位置 /// - method: 对应方法 /// - line: 所在行 /* #file String 所在的文件名 #line Int 所在的行数 #column Int 所在的列数 #function String 所在的声明的名字 */ func printLog<T>(_ message: T, _ logError: Bool = false, file: String = #file, method: String = #function, line: Int = #line) { if logError { print("\((file as NSString).lastPathComponent)\(method) [Line \(line)]: \(message)") } else { #if DEBUG print("\((file as NSString).lastPathComponent)\(method) [Line \(line)]: \(message)") #endif } } /// 利用泛型获取随机数组中的一个元素 /// /// - Parameter array: 传入的数组 /// - Returns: 返回数组中一个随机元素 func randomElementFromArray<T>(_ array:Array<T>) -> T { let index: Int = Int(arc4random_uniform(UInt32(array.count))) return array[index] }
mit
0f2f8d67f77fb165581c31fdab609b22
20.442857
96
0.61026
3.234914
false
false
false
false
PiXeL16/PasswordTextField
PasswordTextField/PasswordTextField.swift
1
6601
// // PasswordTextField.swift // PasswordTextField // // Created by Chris Jimenez on 2/9/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import UIKit // A custom TextField with a switchable icon which shows or hides the password open class PasswordTextField: UITextField { //KVO Context fileprivate var kvoContext: UInt8 = 0 /// Enums with the values of when to show the secure or insecure text button public enum ShowButtonWhile: String { case Editing = "editing" case Always = "always" case Never = "never" var textViewMode: UITextField.ViewMode { switch self{ case .Editing: return .whileEditing case .Always: return .always case .Never: return .never } } } /** Default initializer for the textfield - parameter frame: fra me of the view - returns: */ public override init(frame: CGRect) { super.init(frame: frame) setup() } /** Default initializer for the textfield done from storyboard - parameter coder: coder - returns: */ public required init?(coder: NSCoder) { super.init(coder: coder) setup() } /// When to show the button defaults to only when editing open var showButtonWhile = ShowButtonWhile.Editing{ didSet{ self.rightViewMode = self.showButtonWhile.textViewMode } } /// The rule to apply to the validation password rule open var validationRule:RegexRule = PasswordRule() /** * Shows the toggle button while editing, never, or always. The possible values to set are "editing", "never", "always */ @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'showButtonWhile' instead.") @IBInspectable var showToggleButtonWhile: String? { willSet { if let newShow = ShowButtonWhile(rawValue: newValue?.lowercased() ?? "") { self.showButtonWhile = newShow } } } /// Convenience var to change teh border width @IBInspectable dynamic open var borderWidth: CGFloat = 0 { didSet { self.layer.borderWidth = borderWidth } } /// Convenience var to change the corner radius @IBInspectable dynamic open var cornerRadius: CGFloat = 0 { didSet { self.layer.cornerRadius = cornerRadius } } /** The color of the image. This property applies a color to the image. The default value for this property is gray. */ @IBInspectable open var imageTintColor: UIColor = UIColor.gray { didSet { self.secureTextButton.tintColor = imageTintColor } } /** The image to show the secure text */ @IBInspectable open var customShowSecureTextImage: UIImage? { didSet{ if let image = customShowSecureTextImage { self.secureTextButton.showSecureTextImage = image } } } /** The image to hide the secure text */ @IBInspectable open var customHideSecureTextImage: UIImage? { didSet{ if let image = customHideSecureTextImage { self.secureTextButton.hideSecureTextImage = image } } } /** Initialize properties and values */ func setup() { self.isSecureTextEntry = true self.autocapitalizationType = .none self.autocorrectionType = .no // Note from Camilo -> Removing so it can be set from XIB //self.keyboardType = .asciiCapable self.rightViewMode = self.showButtonWhile.textViewMode self.rightView = self.secureTextButton self.secureTextButton.addObserver(self, forKeyPath: "isSecure", options: NSKeyValueObservingOptions.new, context: &kvoContext) } /// retuns if the textfield is secure or not open var isSecure: Bool{ get{ return isSecureTextEntry } } open lazy var secureTextButton: SecureTextToggleButton = { return SecureTextToggleButton(imageTint: self.imageTintColor) }() /** Toggle the secure text view or not */ open func setSecureMode(_ secure:Bool) { // Note by Camilo: it cause weird animation. //self.resignFirstResponder() self.isSecureTextEntry = secure /// Kind of ugly hack to make the text refresh after the toggle. The size of the secure fonts are different than the normal ones and it shows trailing white space let tempText = self.text; self.text = " "; self.text = tempText; // Note by Camilo: it cause weird animation. //self.becomeFirstResponder() } /** Checks if the password typed is valid - returns: valid password of not */ open func isValid() -> Bool{ var returnValue = false if let text = self.text{ returnValue = validationRule.validate(text) } return returnValue } /** Convenience function to check if the validation is invalid - returns: true if the validation is invalid */ open func isInvalid() ->Bool { return !isValid() } /** Returns the error message of the validation rule setted - returns: error message */ open func errorMessage() -> String{ return validationRule.errorMessage() } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &kvoContext { if context == &kvoContext { self.setSecureMode(self.secureTextButton.isSecure) } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } } deinit { self.secureTextButton.removeObserver(self, forKeyPath: "isSecure") } }
mit
618b826964fa30fac48e40b004400bf8
25.4
170
0.565152
5.436573
false
false
false
false
UIKit0/VPNOn
TodayWidget/TodayViewController.swift
18
10930
// // TodayViewController.swift // TodayWidget // // Created by Lex Tang on 12/10/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // import UIKit import NotificationCenter import NetworkExtension import VPNOnKit import CoreData let kVPNOnSelectedIDInToday = "kVPNOnSelectedIDInToday" let kVPNOnExpanedInToday = "kVPNOnExpanedInToday" let kVPNOnWidgetNormalHeight: CGFloat = 148 class TodayViewController: UIViewController, NCWidgetProviding, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var leftMarginView: ModeButton! @IBOutlet weak var collectionView: UICollectionView! var hasSignaled = false private var _complitionHandler: (NCUpdateResult -> Void)? = nil var vpns: [VPN] { get { return VPNDataManager.sharedManager.allVPN() } } var selectedID: String? { get { return NSUserDefaults.standardUserDefaults().objectForKey(kVPNOnSelectedIDInToday) as! String? } set { if let newID = newValue { NSUserDefaults.standardUserDefaults().setObject(newID, forKey: kVPNOnSelectedIDInToday) } else { NSUserDefaults.standardUserDefaults().removeObjectForKey(kVPNOnSelectedIDInToday) } } } var expanded: Bool { get { return NSUserDefaults.standardUserDefaults().boolForKey(kVPNOnExpanedInToday) as Bool } set { NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: kVPNOnExpanedInToday) if newValue { self.preferredContentSize = self.collectionView.contentSize } else { self.preferredContentSize = CGSizeMake(self.view.bounds.size.width, kVPNOnWidgetNormalHeight) } } } override func viewDidLoad() { super.viewDidLoad() preferredContentSize = CGSizeMake(0, 82) let tapGasture = UITapGestureRecognizer(target: self, action: Selector("didTapLeftMargin:")) tapGasture.numberOfTapsRequired = 1 tapGasture.numberOfTouchesRequired = 1 leftMarginView.userInteractionEnabled = true leftMarginView.addGestureRecognizer(tapGasture) leftMarginView.backgroundColor = UIColor(white: 1.0, alpha: 0.005) leftMarginView.displayMode = VPNManager.sharedManager.displayFlags ? .FlagMode : .SwitchMode NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("coreDataDidSave:"), name: NSManagedObjectContextDidSaveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("VPNStatusDidChange:"), name: NEVPNStatusDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("pingDidUpdate:"), name: kPingDidUpdate, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver( self, name: NSManagedObjectContextDidSaveNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver( self, name: NEVPNStatusDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver( self, name: kPingDidUpdate, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) LTPingQueue.sharedQueue.restartPing() collectionView.dataSource = nil updateContent() collectionView.dataSource = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if collectionView.visibleCells().count > vpns.count { leftMarginView.expandIconView.hidden = true self.expanded = false } else { leftMarginView.expandIconView.hidden = false } if self.expanded { preferredContentSize = collectionView.contentSize } else { preferredContentSize = CGSizeMake(collectionView.contentSize.width, min(kVPNOnWidgetNormalHeight, collectionView.contentSize.height)) } } // Note: A workaround to ensure the widget is interactable. // @see: http://stackoverflow.com/questions/25961513/ios-8-today-widget-stops-working-after-a-while func singalComplete(updateResult: NCUpdateResult) { hasSignaled = true if let handler = _complitionHandler { handler(updateResult) } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if !hasSignaled { singalComplete(NCUpdateResult.Failed) } } func updateContent() { // Note: In order to get the latest data. // @see: http://stackoverflow.com/questions/25924223/core-data-ios-8-today-widget-issue VPNDataManager.sharedManager.managedObjectContext?.reset() } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData _complitionHandler = completionHandler completionHandler(NCUpdateResult.NewData) } // MARK: - Layout func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsetsZero } // MARK: - Collection View Data source func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return vpns.count + 1 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if indexPath.row == vpns.count { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("addCell", forIndexPath: indexPath) as! AddCell return cell } else { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("vpnCell", forIndexPath: indexPath) as! VPNCell let vpn = vpns[indexPath.row] let selected = Bool(selectedID == vpn.ID) cell.configureWithVPN(vpns[indexPath.row], selected: selected) if selected { cell.status = VPNManager.sharedManager.status } else { cell.status = .Disconnected } cell.latency = LTPingQueue.sharedQueue.latencyForHostname(vpn.server) return cell } } // MARK: - Collection View Delegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if indexPath.row == vpns.count { didTapAdd() return } let vpn = vpns[indexPath.row] if VPNManager.sharedManager.status == .Connected { if selectedID == vpn.ID { // Do not connect it again if tap the same one return } } selectedID = vpn.ID let cell = collectionView.cellForItemAtIndexPath(indexPath)! as! VPNCell let passwordRef = VPNKeychainWrapper.passwordForVPNID(vpn.ID) let secretRef = VPNKeychainWrapper.secretForVPNID(vpn.ID) let certificate = VPNKeychainWrapper.certificateForVPNID(vpn.ID) let titleWithSubfix = "Widget - \(vpn.title)" if vpn.ikev2 { VPNManager.sharedManager.connectIKEv2(titleWithSubfix, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate) } else { VPNManager.sharedManager.connectIPSec(titleWithSubfix, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate) } } func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { if indexPath.row == vpns.count { return true } let cell = collectionView.cellForItemAtIndexPath(indexPath) as! VPNCell switch VPNManager.sharedManager.status { case .Connected, .Connecting: VPNManager.sharedManager.disconnect() default: () } return true } // MARK: - Left margin func didTapLeftMargin(gesture: UITapGestureRecognizer) { var tappedBottom = Bool(gesture.locationInView(leftMarginView).y > leftMarginView.frame.size.height / 3 * 2) if !self.expanded && collectionView.contentSize.height == preferredContentSize.height { tappedBottom = false } if tappedBottom { self.expanded = !self.expanded } else { LTPingQueue.sharedQueue.restartPing() VPNManager.sharedManager.displayFlags = !VPNManager.sharedManager.displayFlags collectionView.reloadData() leftMarginView.displayMode = VPNManager.sharedManager.displayFlags ? .FlagMode : .SwitchMode } } // MARK: - Open App func didTapAdd() { let appURL = NSURL(string: "vpnon://") extensionContext!.openURL(appURL!, completionHandler: { (complete: Bool) -> Void in }) } // MARK: - Notification func pingDidUpdate(notification: NSNotification) { collectionView.reloadData() } func coreDataDidSave(notification: NSNotification) { VPNDataManager.sharedManager.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification) updateContent() } func VPNStatusDidChange(notification: NSNotification?) { collectionView.reloadData() if VPNManager.sharedManager.status == .Disconnected { LTPingQueue.sharedQueue.restartPing() } } }
mit
83d34b186952a87c785cb91b6b15ca0a
33.698413
145
0.624245
5.495224
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift
11
2488
// // ScatterChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class ScatterChartDataSet: LineScatterCandleRadarChartDataSet, IScatterChartDataSet { @objc(ScatterShape) public enum Shape: Int { case square case circle case triangle case cross case x case chevronUp case chevronDown } /// The size the scatter shape will have open var scatterShapeSize = CGFloat(10.0) /// The radius of the hole in the shape (applies to Square, Circle and Triangle) /// **default**: 0.0 open var scatterShapeHoleRadius: CGFloat = 0.0 /// Color for the hole in the shape. Setting to `nil` will behave as transparent. /// **default**: nil open var scatterShapeHoleColor: NSUIColor? = nil /// Sets the ScatterShape this DataSet should be drawn with. /// This will search for an available IShapeRenderer and set this renderer for the DataSet @objc open func setScatterShape(_ shape: Shape) { self.shapeRenderer = ScatterChartDataSet.renderer(forShape: shape) } /// The IShapeRenderer responsible for rendering this DataSet. /// This can also be used to set a custom IShapeRenderer aside from the default ones. /// **default**: `SquareShapeRenderer` open var shapeRenderer: IShapeRenderer? = SquareShapeRenderer() @objc open class func renderer(forShape shape: Shape) -> IShapeRenderer { switch shape { case .square: return SquareShapeRenderer() case .circle: return CircleShapeRenderer() case .triangle: return TriangleShapeRenderer() case .cross: return CrossShapeRenderer() case .x: return XShapeRenderer() case .chevronUp: return ChevronUpShapeRenderer() case .chevronDown: return ChevronDownShapeRenderer() } } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! ScatterChartDataSet copy.scatterShapeSize = scatterShapeSize copy.scatterShapeHoleRadius = scatterShapeHoleRadius copy.scatterShapeHoleColor = scatterShapeHoleColor copy.shapeRenderer = shapeRenderer return copy } }
apache-2.0
0f7a39aa941c167eea7a933a9010a7cd
30.897436
94
0.672026
5.140496
false
false
false
false
hgani/ganiweb-ios
ganiweb/Classes/Browser/GWebScreen.swift
1
689
import GaniLib open class GWebScreen: GScreen { private let webView = GWebView() private let url: URL private let autoLoad: Bool public init(url: String, autoLoad: Bool = false) { self.url = URL(string: url)! self.autoLoad = autoLoad super.init(container: GScreenContainer(webView: webView)) } public required init?(coder aDecoder: NSCoder) { fatalError("Unsupported operation") } open override func viewDidLoad() { super.viewDidLoad() if autoLoad { onRefresh() } } open override func onRefresh() { _ = webView.load(url: url) } }
mit
993c0aa58da5541d2650b0f563325923
21.966667
65
0.576197
4.474026
false
false
false
false
ichu501/DGRunkeeperSwitch
DGRunkeeperSwitchExample/ViewController.swift
1
4068
// // ViewController.swift // DGRunkeeperSwitchExample // // Created by Danil Gontovnik on 9/3/15. // Copyright © 2015 Danil Gontovnik. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - // MARK: Vars @IBOutlet weak var runkeeperSwitch4: DGRunkeeperSwitch? // MARK: - // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().statusBarStyle = .LightContent navigationController!.navigationBar.translucent = false navigationController!.navigationBar.barTintColor = UIColor(red: 252.0/255.0, green: 182.0/255.0, blue: 54.0/255.0, alpha: 1.0) let runkeeperSwitch = DGRunkeeperSwitch(leftTitle: "Feed", rightTitle: "Leaderboard") runkeeperSwitch.backgroundColor = UIColor(red: 229.0/255.0, green: 163.0/255.0, blue: 48.0/255.0, alpha: 1.0) runkeeperSwitch.selectedBackgroundColor = .whiteColor() runkeeperSwitch.titleColor = .whiteColor() runkeeperSwitch.selectedTitleColor = UIColor(red: 255.0/255.0, green: 196.0/255.0, blue: 92.0/255.0, alpha: 1.0) runkeeperSwitch.titleFont = UIFont(name: "HelveticaNeue-Medium", size: 13.0) runkeeperSwitch.frame = CGRect(x: 30.0, y: 40.0, width: 200.0, height: 30.0) runkeeperSwitch.addTarget(self, action: Selector("switchValueDidChange:"), forControlEvents: .ValueChanged) navigationItem.titleView = runkeeperSwitch let runkeeperSwitch2 = DGRunkeeperSwitch() runkeeperSwitch2.leftTitle = "Weekly" runkeeperSwitch2.rightTitle = "Monthly" runkeeperSwitch2.backgroundColor = UIColor(red: 239.0/255.0, green: 95.0/255.0, blue: 49.0/255.0, alpha: 1.0) runkeeperSwitch2.selectedBackgroundColor = .whiteColor() runkeeperSwitch2.titleColor = .whiteColor() runkeeperSwitch2.selectedTitleColor = UIColor(red: 239.0/255.0, green: 95.0/255.0, blue: 49.0/255.0, alpha: 1.0) runkeeperSwitch2.titleFont = UIFont(name: "HelveticaNeue-Medium", size: 13.0) runkeeperSwitch2.frame = CGRect(x: 50.0, y: 20.0, width: view.bounds.width - 100.0, height: 30.0) runkeeperSwitch2.autoresizingMask = [.FlexibleWidth] view.addSubview(runkeeperSwitch2) let runkeeperSwitch3 = DGRunkeeperSwitch() runkeeperSwitch3.leftTitle = "Super long left title" runkeeperSwitch3.rightTitle = "Super long right title" runkeeperSwitch3.backgroundColor = UIColor(red: 239.0/255.0, green: 95.0/255.0, blue: 49.0/255.0, alpha: 1.0) runkeeperSwitch3.selectedBackgroundColor = .whiteColor() runkeeperSwitch3.titleColor = .whiteColor() runkeeperSwitch3.selectedTitleColor = UIColor(red: 239.0/255.0, green: 95.0/255.0, blue: 49.0/255.0, alpha: 1.0) runkeeperSwitch3.titleFont = UIFont(name: "HelveticaNeue-Medium", size: 13.0) runkeeperSwitch3.frame = CGRect(x: 50.0, y: 70.0, width: view.bounds.width - 100.0, height: 30.0) runkeeperSwitch3.autoresizingMask = [.FlexibleWidth] view.addSubview(runkeeperSwitch3) if let runkeeperSwitch4 = runkeeperSwitch4 { runkeeperSwitch4.leftTitle = "Apple" runkeeperSwitch4.rightTitle = "Google" runkeeperSwitch4.backgroundColor = UIColor(red: 122/255.0, green: 203/255.0, blue: 108/255.0, alpha: 1.0) runkeeperSwitch4.selectedBackgroundColor = .whiteColor() runkeeperSwitch4.titleColor = .whiteColor() runkeeperSwitch4.selectedTitleColor = UIColor(red: 135/255.0, green: 227/255.0, blue: 120/255.0, alpha: 1.0) runkeeperSwitch4.titleFont = UIFont(name: "HelveticaNeue-Light", size: 17.0) } } // MARK: - func switchValueDidChange(sender:DGRunkeeperSwitch) { print("valueChanged: \(sender.selectedIndex)") } @IBAction func switchValueDidChange(sender: DGRunkeeperSwitch!) { print("valueChanged: \(sender.selectedIndex)") } }
mit
045df0139a1710fba0b420f307eb05a0
46.847059
134
0.672486
3.755309
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Account/Views/GroupButtonView.swift
1
1691
// // GroupButtonView.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/11/3. // Copyright © 2017年 伯驹 黄. All rights reserved. // class GroupButtonView: UIView { typealias GroupButtonViewItem = (title: String, action: Selector) private var leftButton: UIButton! private var rightButton: UIButton! convenience init(target: Any, items: (GroupButtonViewItem, GroupButtonViewItem)) { self.init(frame: .zero) leftButton = generatButton(with: items.0.title, target: target, action: items.0.action) addSubview(leftButton) leftButton.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.trailing.equalTo(snp.centerX).offset(-9) } let vLine = UIView() vLine.backgroundColor = .lightGray addSubview(vLine) vLine.snp.makeConstraints { (make) in make.height.equalTo(17) make.width.equalTo(1) make.center.equalToSuperview() } rightButton = generatButton(with: items.1.title, target: target, action: items.1.action) addSubview(rightButton) rightButton.snp.makeConstraints { (make) in make.centerY.equalTo(leftButton.snp.centerY) make.leading.equalTo(snp.centerX).offset(9) } } private func generatButton(with title: String?, target: Any, action: Selector) -> UIButton { let button = HZUIHelper.generateNormalButton(title: title, target: target, action: action) button.setTitleColor(UIColor(hex: 0x7E3886), for: .normal) button.titleLabel?.font = UIFontMake(13) return button } }
mit
281688dba9cb4b608027b1d44faacb9c
33.204082
98
0.643198
4.200501
false
false
false
false
tsc000/SCCycleScrollView
SCCycleScrollView/Pods/Kingfisher/Sources/AnimatedImageView.swift
9
17482
// // AnimatableImageView.swift // Kingfisher // // Created by bl4ckra1sond3tre on 4/22/16. // // The AnimatableImageView, AnimatedFrame and Animator is a modified version of // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) // // The MIT License (MIT) // // Copyright (c) 2018 Reda Lemeden. // // 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. // // The name and characters used in the demo of this software are property of their // respective owners. import UIKit import ImageIO /// Protocol of `AnimatedImageView`. public protocol AnimatedImageViewDelegate: AnyObject { /** Called after the animatedImageView has finished each animation loop. - parameter imageView: The animatedImageView that is being animated. - parameter count: The looped count. */ func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) /** Called after the animatedImageView has reached the max repeat count. - parameter imageView: The animatedImageView that is being animated. */ func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) } extension AnimatedImageViewDelegate { public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {} public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {} } /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image. open class AnimatedImageView: UIImageView { /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView. class TargetProxy { private weak var target: AnimatedImageView? init(target: AnimatedImageView) { self.target = target } @objc func onScreenUpdate() { target?.updateFrame() } } /// Enumeration that specifies repeat count of GIF public enum RepeatCount: Equatable { case once case finite(count: UInt) case infinite public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool { switch (lhs, rhs) { case let (.finite(l), .finite(r)): return l == r case (.once, .once), (.infinite, .infinite): return true case (.once, .finite(let count)), (.finite(let count), .once): return count == 1 case (.once, _), (.infinite, _), (.finite, _): return false } } } // MARK: - Public property /// Whether automatically play the animation when the view become visible. Default is true. public var autoPlayAnimatedImage = true /// The size of the frame cache. public var framePreloadCount = 10 /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true. public var needsPrescaling = true /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. #if swift(>=4.2) public var runLoopMode = RunLoop.Mode.common { willSet { if runLoopMode == newValue { return } else { stopAnimating() displayLink.remove(from: .main, forMode: runLoopMode) displayLink.add(to: .main, forMode: newValue) startAnimating() } } } #else public var runLoopMode = RunLoopMode.commonModes { willSet { if runLoopMode == newValue { return } else { stopAnimating() displayLink.remove(from: .main, forMode: runLoopMode) displayLink.add(to: .main, forMode: newValue) startAnimating() } } } #endif /// The repeat count. public var repeatCount = RepeatCount.infinite { didSet { if oldValue != repeatCount { reset() setNeedsDisplay() layer.setNeedsDisplay() } } } /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more. public weak var delegate: AnimatedImageViewDelegate? // MARK: - Private property /// `Animator` instance that holds the frames of a specific image in memory. private var animator: Animator? /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D private var isDisplayLinkInitialized: Bool = false /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.isDisplayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.add(to: .main, forMode: self.runLoopMode) displayLink.isPaused = true return displayLink }() // MARK: - Override override open var image: Image? { didSet { if image != oldValue { reset() } setNeedsDisplay() layer.setNeedsDisplay() } } deinit { if isDisplayLinkInitialized { displayLink.invalidate() } } override open var isAnimating: Bool { if isDisplayLinkInitialized { return !displayLink.isPaused } else { return super.isAnimating } } /// Starts the animation. override open func startAnimating() { if self.isAnimating { return } else { if animator?.isReachMaxRepeatCount ?? false { return } displayLink.isPaused = false } } /// Stops the animation. override open func stopAnimating() { super.stopAnimating() if isDisplayLinkInitialized { displayLink.isPaused = true } } override open func display(_ layer: CALayer) { if let currentFrame = animator?.currentFrame { layer.contents = currentFrame.cgImage } else { layer.contents = image?.cgImage } } override open func didMoveToWindow() { super.didMoveToWindow() didMove() } override open func didMoveToSuperview() { super.didMoveToSuperview() didMove() } // This is for back compatibility that using regular UIImageView to show animated image. override func shouldPreloadAllAnimation() -> Bool { return false } // MARK: - Private method /// Reset the animator. private func reset() { animator = nil if let imageSource = image?.kf.imageSource?.imageRef { animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount, repeatCount: repeatCount) animator?.delegate = self animator?.needsPrescaling = needsPrescaling animator?.prepareFramesAsynchronously() } didMove() } private func didMove() { if autoPlayAnimatedImage && animator != nil { if let _ = superview, let _ = window { startAnimating() } else { stopAnimating() } } } /// Update the current frame with the displayLink duration. private func updateFrame() { let duration: CFTimeInterval // CA based display link is opt-out from ProMotion by default. // So the duration and its FPS might not match. // See [#718](https://github.com/onevcat/Kingfisher/issues/718) if #available(iOS 10.0, tvOS 10.0, *) { // By setting CADisableMinimumFrameDuration to YES in Info.plist may // cause the preferredFramesPerSecond being 0 if displayLink.preferredFramesPerSecond == 0 { duration = displayLink.duration } else { // Some devices (like iPad Pro 10.5) will have a different FPS. duration = 1.0 / Double(displayLink.preferredFramesPerSecond) } } else { duration = displayLink.duration } if animator?.updateCurrentFrame(duration: duration) ?? false { layer.setNeedsDisplay() if animator?.isReachMaxRepeatCount ?? false { stopAnimating() delegate?.animatedImageViewDidFinishAnimating(self) } } } } extension AnimatedImageView: AnimatorDelegate { func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) { delegate?.animatedImageView(self, didPlayAnimationLoops: count) } } /// Keeps a reference to an `Image` instance and its duration as a GIF frame. struct AnimatedFrame { var image: Image? let duration: TimeInterval static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0) } protocol AnimatorDelegate: AnyObject { func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) } // MARK: - Animator class Animator { // MARK: Private property fileprivate let size: CGSize fileprivate let maxFrameCount: Int fileprivate let imageSource: CGImageSource fileprivate let maxRepeatCount: AnimatedImageView.RepeatCount fileprivate var animatedFrames = [AnimatedFrame]() fileprivate let maxTimeStep: TimeInterval = 1.0 fileprivate var frameCount = 0 fileprivate var currentFrameIndex = 0 fileprivate var currentFrameIndexInBuffer = 0 fileprivate var currentPreloadIndex = 0 fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0 fileprivate var needsPrescaling = true fileprivate var currentRepeatCount: UInt = 0 fileprivate weak var delegate: AnimatorDelegate? /// Loop count of animated image. private var loopCount = 0 var currentFrame: UIImage? { return frame(at: currentFrameIndexInBuffer) } var isReachMaxRepeatCount: Bool { switch maxRepeatCount { case .once: return currentRepeatCount >= 1 case .finite(let maxCount): return currentRepeatCount >= maxCount case .infinite: return false } } var contentMode = UIView.ContentMode.scaleToFill private lazy var preloadQueue: DispatchQueue = { return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") }() /** Init an animator with image source reference. - parameter imageSource: The reference of animated image. - parameter contentMode: Content mode of AnimatedImageView. - parameter size: Size of AnimatedImageView. - parameter framePreloadCount: Frame cache size. - returns: The animator object. */ init(imageSource source: CGImageSource, contentMode mode: UIView.ContentMode, size: CGSize, framePreloadCount count: Int, repeatCount: AnimatedImageView.RepeatCount) { self.imageSource = source self.contentMode = mode self.size = size self.maxFrameCount = count self.maxRepeatCount = repeatCount } func frame(at index: Int) -> Image? { return animatedFrames[safe: index]?.image } func prepareFramesAsynchronously() { preloadQueue.async { [weak self] in self?.prepareFrames() } } private func prepareFrames() { frameCount = CGImageSourceGetCount(imageSource) if let properties = CGImageSourceCopyProperties(imageSource, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int { self.loopCount = loopCount } let frameToProcess = min(frameCount, maxFrameCount) animatedFrames.reserveCapacity(frameToProcess) animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))} currentPreloadIndex = (frameToProcess + 1) % frameCount - 1 } private func prepareFrame(at index: Int) -> AnimatedFrame { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return AnimatedFrame.null } let defaultGIFFrameDuration = 0.100 let frameDuration = imageSource.kf.gifProperties(at: index).map { gifInfo -> Double in let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double? let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double? let duration = unclampedDelayTime ?? delayTime ?? 0.0 /** http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. */ return duration > 0.011 ? duration : defaultGIFFrameDuration } ?? defaultGIFFrameDuration let image = Image(cgImage: imageRef) let scaledImage: Image? if needsPrescaling { scaledImage = image.kf.resize(to: size, for: contentMode) } else { scaledImage = image } return AnimatedFrame(image: scaledImage, duration: frameDuration) } /** Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`. */ func updateCurrentFrame(duration: CFTimeInterval) -> Bool { timeSinceLastFrameChange += min(maxTimeStep, duration) guard let frameDuration = animatedFrames[safe: currentFrameIndexInBuffer]?.duration, frameDuration <= timeSinceLastFrameChange else { return false } timeSinceLastFrameChange -= frameDuration let lastFrameIndex = currentFrameIndexInBuffer currentFrameIndexInBuffer += 1 currentFrameIndexInBuffer = currentFrameIndexInBuffer % animatedFrames.count if animatedFrames.count < frameCount { preloadFrameAsynchronously(at: lastFrameIndex) } currentFrameIndex += 1 if currentFrameIndex == frameCount { currentFrameIndex = 0 currentRepeatCount += 1 delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount) } return true } private func preloadFrameAsynchronously(at index: Int) { preloadQueue.async { [weak self] in self?.preloadFrame(at: index) } } private func preloadFrame(at index: Int) { animatedFrames[index] = prepareFrame(at: currentPreloadIndex) currentPreloadIndex += 1 currentPreloadIndex = currentPreloadIndex % frameCount } } extension CGImageSource: KingfisherCompatible { } extension Kingfisher where Base: CGImageSource { func gifProperties(at index: Int) -> [String: Double]? { let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary? return properties?[kCGImagePropertyGIFDictionary] as? [String: Double] } } extension Array { fileprivate subscript(safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } } private func pure<T>(_ value: T) -> [T] { return [value] }
mit
954ac67d829a8f3f4f19815fc94a7c28
33.755467
184
0.627503
5.544561
false
false
false
false
jin/NUSWhispers-iOS
NUSWhispers/Comment.swift
1
712
// // Comment.swift // NUSWhispers // // Created by jin on 10/5/15. // Copyright (c) 2015 crypt. All rights reserved. // import Foundation import SwiftyJSON class Comment { var createdAt: NSDate! var authorID: String! var authorName: String! var commentID: String! var message: String! init(json: JSON) { authorID = json["from"]["id"].string authorName = json["from"]["name"].string commentID = json["id"].string message = json["message"].string let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxx" self.createdAt = dateFormatter.dateFromString(json["created_time"].string!) } }
mit
cff2bb40e3764582bfddb1041158aeed
22
83
0.636236
3.933702
false
false
false
false
ResearchSuite/ResearchSuiteAppFramework-iOS
Source/Core/Classes/RSAFTaskBuilderManager.swift
1
3699
// // RSAFTaskBuilderManager.swift // Pods // // Created by James Kizer on 3/25/17. // // import UIKit import ResearchSuiteTaskBuilder open class RSAFTaskBuilderManager: NSObject { open class var stepGeneratorServices: [RSTBStepGenerator] { return [ RSTBInstructionStepGenerator(), RSTBTextFieldStepGenerator(), RSTBIntegerStepGenerator(), RSTBTimePickerStepGenerator(), RSTBFormStepGenerator(), RSTBDatePickerStepGenerator(), RSTBSingleChoiceStepGenerator(), RSTBMultipleChoiceStepGenerator(), RSTBBooleanStepGenerator(), RSTBPasscodeStepGenerator() ] } open class var answerFormatGeneratorServices: [RSTBAnswerFormatGenerator] { return [ RSTBTextFieldStepGenerator(), RSTBIntegerStepGenerator(), RSTBTimePickerStepGenerator(), RSTBDatePickerStepGenerator() ] } open class var elementGeneratorServices: [RSTBElementGenerator] { return [ RSTBElementListGenerator(), RSTBElementFileGenerator(), RSTBElementSelectorGenerator() ] } public let rstb: RSTBTaskBuilder // public init( // stateHelper: RSTBStateHelper // ) { // // // Do any additional setup after loading the view, typically from a nib. // self.rstb = RSTBTaskBuilder( // stateHelper: stateHelper, // elementGeneratorServices: RSAFTaskBuilderManager.elementGeneratorServices(), // stepGeneratorServices: RSAFTaskBuilderManager.stepGeneratorServices(), // answerFormatGeneratorServices: RSAFTaskBuilderManager.answerFormatGeneratorServices()) // // super.init() // // // } public init( stateHelper: RSTBStateHelper, elementGeneratorServices: [RSTBElementGenerator], stepGeneratorServices: [RSTBStepGenerator], answerFormatGeneratorServices: [RSTBAnswerFormatGenerator] ) { // Do any additional setup after loading the view, typically from a nib. self.rstb = RSTBTaskBuilder( stateHelper: stateHelper, elementGeneratorServices: elementGeneratorServices, stepGeneratorServices: stepGeneratorServices, answerFormatGeneratorServices: answerFormatGeneratorServices) super.init() } convenience public init(stateHelper: RSTBStateHelper) { self.init( stateHelper: stateHelper, elementGeneratorServices: RSAFTaskBuilderManager.elementGeneratorServices, stepGeneratorServices: RSAFTaskBuilderManager.stepGeneratorServices, answerFormatGeneratorServices: RSAFTaskBuilderManager.answerFormatGeneratorServices ) } static func getJson(forFilename filename: String, inBundle bundle: Bundle = Bundle.main) -> JsonElement? { guard let filePath = bundle.path(forResource: filename, ofType: "json") else { assertionFailure("unable to locate file \(filename)") return nil } guard let fileContent = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else { assertionFailure("Unable to create NSData with content of file \(filePath)") return nil } let json = try! JSONSerialization.jsonObject(with: fileContent, options: JSONSerialization.ReadingOptions.mutableContainers) return json as JsonElement? } }
apache-2.0
b7e3304b4e9f7bd3b8bb0c53bee50691
31.734513
132
0.631792
5.504464
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/Controller/CreateTripController.swift
1
7984
// // CreateTrip.swift // TravelApp // // Created by Pankaj Rawat on 24/01/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class CreateTripController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { var trip = Trip() var tripView: UIView! var tripEditForm: TripEdit! var selectedPlaceEditCell: PlaceEditCell? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.appMainBGColor() view.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(dismissKeyboard))) // Do any additional setup after loading the view. loadSubViews() } func dismissKeyboard() { view.endEditing(true) } lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.backgroundColor = UIColor.white cv.translatesAutoresizingMaskIntoConstraints = false cv.dataSource = self cv.delegate = self return cv }() lazy var datePickerView: UIView = { let dpv = UIView() dpv.backgroundColor = UIColor.appMainBGColor() dpv.translatesAutoresizingMaskIntoConstraints = false return dpv }() lazy var datePicker: UIDatePicker = { let dp = UIDatePicker() dp.backgroundColor = UIColor.appMainBGColor() dp.translatesAutoresizingMaskIntoConstraints = false return dp }() lazy var datePickerDoneButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor.appMainBGColor() button.setTitle("Done", for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.setTitleColor(UIColor.appLightBlue(), for: .normal) button.addTarget(self, action: #selector(handleDoneAddingDate), for: .touchUpInside) button.isUserInteractionEnabled = true return button }() func handleDoneAddingDate() { handleDateSelection(sender: self.datePicker) UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.datePickerView.frame = CGRect(x: 0, y: (self.view.frame.height), width: (self.view.frame.width), height: 200) }) } func handleDateSelection(sender:UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateStyle = DateFormatter.Style.medium dateFormatter.timeStyle = DateFormatter.Style.short selectedPlaceEditCell?.placeViewBadgeDateLabel.text = dateFormatter.string(from: sender.date) collectionView.reloadData() } let cellId = "cellId" func loadSubViews() { trip.user = SharedData.sharedInstance.currentUser trip.places = [Place(), Place()] addTripEditForm() setupCollectionViews() addDatePickerView() } func addTripEditForm() { let tripHeaderFrame = CGRect(x: 0, y: 0, width: view.frame.width, height: 150) tripEditForm = TripEdit(frame: tripHeaderFrame) tripEditForm.createTripCtrl = self tripEditForm.layer.shadowOpacity = 0.5 tripEditForm.layer.shadowRadius = 3 tripEditForm.layer.shadowOffset = CGSize(width: 0, height: 2) tripEditForm.layer.shadowColor = UIColor.black.cgColor view.addSubview(tripEditForm) } func setupCollectionViews() { view.addSubview(collectionView) collectionView.topAnchor.constraint(equalTo: tripEditForm.bottomAnchor).isActive = true collectionView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true collectionView.showsVerticalScrollIndicator = false collectionView.register(PlaceEditCell.self, forCellWithReuseIdentifier: cellId) } func addDatePickerView() { view.addSubview(datePickerView) datePickerView.addSubview(datePickerDoneButton) datePickerView.addSubview(datePicker) datePickerView.topAnchor.constraint(equalTo: view.bottomAnchor).isActive = true datePickerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true datePickerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true datePickerView.heightAnchor.constraint(equalToConstant: 200).isActive = true datePickerDoneButton.topAnchor.constraint(equalTo: datePickerView.topAnchor, constant: 2).isActive = true datePickerDoneButton.rightAnchor.constraint(equalTo: datePickerView.rightAnchor, constant: -2).isActive = true datePickerDoneButton.widthAnchor.constraint(equalToConstant: 50).isActive = true datePickerDoneButton.heightAnchor.constraint(equalToConstant: 20).isActive = true datePicker.topAnchor.constraint(equalTo: datePickerDoneButton.bottomAnchor).isActive = true datePicker.widthAnchor.constraint(equalTo: datePickerView.widthAnchor).isActive = true datePicker.bottomAnchor.constraint(equalTo: datePickerView.bottomAnchor).isActive = true datePicker.leftAnchor.constraint(equalTo: datePickerView.leftAnchor).isActive = true } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return trip.places.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PlaceEditCell cell.place = trip.places[indexPath.item] cell.createTripCtrl = self return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let text = trip.places[indexPath.item].review let approxWidth = view.frame.width - 60 let size = CGSize(width: approxWidth, height: 1000) let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 12)] let estimatedFrame = NSString(string: text).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) return CGSize(width: view.frame.width, height: estimatedFrame.height + 300) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func scrollViewDidScroll(_ scrollView: UIScrollView) { UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { switch true { case scrollView.contentOffset.y >= 100: self.tripEditForm.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 60) self.collectionView.frame = CGRect(x: 0, y: 60, width: self.view.frame.width, height: self.view.frame.height - 60) self.tripEditForm.hideAll() break case scrollView.contentOffset.y <= 1: self.tripEditForm.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 150) self.collectionView.frame = CGRect(x: 0, y: 150, width: self.view.frame.width, height: self.view.frame.height - 150) self.tripEditForm.showAll() break default: break } }, completion: nil) } }
mit
2b8fcf9df542c1e6f810d865ee461141
41.68984
170
0.679193
5.22106
false
false
false
false
tribalworldwidelondon/CassowarySwift
Sources/Cassowary/ConstraintOperatorsCGFloat.swift
1
10124
/* Copyright (c) 2017, Tribal Worldwide London Copyright (c) 2015, Alex Birkett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of kiwi-java nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation extension Term { convenience init(variable: Variable, coefficient: CGFloat) { self.init(variable: variable, coefficient: Double(coefficient)) } } extension Expression { convenience init(constant: CGFloat) { self.init(constant: Double(constant)) } } // MARK: - Variable *, /, and unary invert public func * (_ variable: Variable, _ coefficient: CGFloat) -> Term { return Term(variable: variable, coefficient: coefficient) .addingDebugDescription("\(variable.name) * \(coefficient)") } public func / (_ variable: Variable, _ denominator: CGFloat) -> Term { return (variable * (1.0 / denominator)) .addingDebugDescription("\(variable.name) / \(denominator)") } // Term *, /, and unary invert public func * (_ term: Term, _ coefficient: CGFloat) -> Term { return Term(variable: term.variable, coefficient: term.coefficient * Double(coefficient)) .addingDebugDescription("(\(term.debugDescription)) * \(coefficient)") } public func / (_ term: Term, _ denominator: CGFloat) -> Term { return (term * (1.0 / denominator)) .addingDebugDescription("(\(term.debugDescription)) / \(denominator)") } // MARK: - Expression *, /, and unary invert public func * (_ expression: Expression, _ coefficient: CGFloat) -> Expression { var terms = [Term]() for term in expression.terms { terms.append(term * coefficient) } // TODO: Do we need to make a copy of the term objects in the array? return Expression(terms: terms, constant: expression.constant * Double(coefficient)) .addingDebugDescription("(\(expression.debugDescription)) * \(coefficient)") } public func / (_ expression: Expression, _ denominator: CGFloat) -> Expression { return (expression * (1.0 / denominator)) .addingDebugDescription("(\(expression.debugDescription)) / \(denominator)") } // MARK: - CGFloat * public func * (_ coefficient: CGFloat, _ expression: Expression) -> Expression { return (expression * coefficient) .addingDebugDescription("(\(expression.debugDescription)) * \(coefficient)") } public func * (_ coefficient: CGFloat, _ term: Term) -> Term { return (term * coefficient) .addingDebugDescription("\(coefficient) * (\(term.debugDescription))") } public func * (_ coefficient: CGFloat, _ variable: Variable) -> Term { return (variable * coefficient) .addingDebugDescription("\(coefficient) * \(variable.name)") } public func + (_ expression: Expression, _ constant: CGFloat) -> Expression { return Expression(terms: expression.terms, constant: expression.constant + Double(constant)) .addingDebugDescription("(\(expression.debugDescription))¨ + \(constant)") } public func - (_ expression: Expression, _ constant: CGFloat) -> Expression{ return (expression + -constant) .addingDebugDescription("(\(expression.debugDescription)) - \(constant)") } public func + (_ term: Term, _ constant: CGFloat) -> Expression { return Expression(term: term, constant: Double(constant)) .addingDebugDescription("(\(term.debugDescription)) + \(constant)") } public func - (_ term: Term, _ constant: CGFloat) -> Expression { return (term + -constant) .addingDebugDescription("(\(term.debugDescription)) - \(constant)") } public func + (_ variable: Variable, _ constant: CGFloat) -> Expression { return (Term(variable: variable) + constant) .addingDebugDescription("\(variable.name) + \(constant)") } public func - (_ variable: Variable, _ constant: CGFloat) -> Expression { return (variable + -constant) .addingDebugDescription("\(variable.name) - \(constant)") } // MARK: - CGFloat + and - public func + (_ constant: CGFloat, _ expression: Expression) -> Expression { return (expression + constant) .addingDebugDescription("\(constant) + (\(expression.debugDescription))") } public func + (_ constant: CGFloat, _ term: Term) -> Expression { return (term + constant) .addingDebugDescription("\(constant) + (\(term.debugDescription))") } public func + (_ constant: CGFloat, _ variable: Variable) -> Expression { return (variable + constant) .addingDebugDescription("\(constant) + \(variable.name)") } public func - (_ constant: CGFloat, _ expression: Expression) -> Expression { return (-expression + constant) .addingDebugDescription("\(constant) - (\(expression.debugDescription))") } public func - (_ constant: CGFloat, _ term: Term) -> Expression { return (-term + constant) .addingDebugDescription("\(constant) - (\(term.debugDescription))") } public func - (_ constant: CGFloat, _ variable: Variable) -> Expression { return (-variable + constant) .addingDebugDescription("\(constant) - \(variable.name)") } public func == (_ expression: Expression, _ constant: CGFloat) -> Constraint { return (expression == Expression(constant: constant)) .addingDebugDescription("\(expression.debugDescription) == \(constant)") } public func <= (_ expression: Expression, _ constant: CGFloat) -> Constraint { return (expression <= Expression(constant: constant)) .addingDebugDescription("\(expression.debugDescription) <= \(constant)") } public func >= (_ expression: Expression, _ constant: CGFloat) -> Constraint { return (expression >= Expression(constant: constant)) .addingDebugDescription("\(expression.debugDescription) >= \(constant)") } public func == (_ term: Term, _ constant: CGFloat) -> Constraint { return (Expression(term: term) == constant) .addingDebugDescription("\(term.debugDescription) == \(constant)") } public func <= (_ term: Term, _ constant: CGFloat) -> Constraint { return (Expression(term: term) <= constant) .addingDebugDescription("\(term.debugDescription) <= \(constant))") } public func >= (_ term: Term, _ constant: CGFloat) -> Constraint { return (Expression(term: term) >= constant) .addingDebugDescription("\(term.debugDescription) >= \(constant)") } public func == (_ variable: Variable, _ constant: CGFloat) -> Constraint{ return (Term(variable: variable) == constant) .addingDebugDescription("\(variable.name) == \(constant)") } public func <= (_ variable: Variable, _ constant: CGFloat) -> Constraint { return (Term(variable: variable) <= constant) .addingDebugDescription("\(variable.name) <= \(constant)") } public func >= (_ variable: Variable, _ constant: CGFloat) -> Constraint { return (Term(variable: variable) >= constant) .addingDebugDescription("\(variable.name) >= \(constant)") } // MARK: - CGFloat relations public func == (_ constant: CGFloat, _ expression: Expression) -> Constraint { return (expression == constant) .addingDebugDescription("\(constant) == \(expression.debugDescription)") } public func == (_ constant: CGFloat, _ term: Term) -> Constraint { return (term == constant) .addingDebugDescription("\(constant) == \(term.debugDescription)") } public func == (_ constant: CGFloat, _ variable: Variable) -> Constraint { return (variable == constant) .addingDebugDescription("\(constant) == \(variable.name)") } public func <= (_ constant: CGFloat, _ expression: Expression) -> Constraint { return (Expression(constant: constant) <= expression) .addingDebugDescription("\(constant) <= \(expression.debugDescription)") } public func <= (_ constant: CGFloat, _ term: Term) -> Constraint { return (constant <= Expression(term: term)) .addingDebugDescription("\(constant) <= \(term.debugDescription)") } public func <= (_ constant: CGFloat, _ variable: Variable) -> Constraint { return (constant <= Term(variable: variable)) .addingDebugDescription("\(constant) <= \(variable.name)") } public func >= (_ constant: CGFloat, _ term: Term) -> Constraint { return (Expression(constant: constant) >= term) .addingDebugDescription("\(constant) >= \(term.debugDescription)") } public func >= (_ constant: CGFloat, _ variable: Variable) -> Constraint { return (constant >= Term(variable: variable)) .addingDebugDescription("\(constant) >= \(variable.name)") } // MARK: - Constraint strength modifier public func modifyStrength(_ constraint: Constraint, _ strength: CGFloat) -> Constraint { return Constraint(other: constraint, strength: Double(strength)) } public func modifyStrength(_ strength: CGFloat, _ constraint: Constraint) -> Constraint { return modifyStrength(constraint, strength) }
bsd-3-clause
81e2fef7e74b050c4ccd978c662b2e42
37.934615
96
0.686951
4.582617
false
false
false
false
edx/edx-app-ios
Source/KeyboardInsetsSource.swift
2
2519
// // KeyboardInsetsSource.swift // edX // // Created by Akiva Leffert on 6/10/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit extension UIView.AnimationCurve { var asAnimationOptions : UIView.AnimationOptions { switch(self) { case .easeIn: return .curveEaseIn case .easeOut: return .curveEaseOut case .easeInOut: return .curveEaseInOut case .linear: return .curveLinear default: return .curveEaseIn } } } public class KeyboardInsetsSource : NSObject, ContentInsetsSource { public weak var insetsDelegate : ContentInsetsSourceDelegate? public let affectsScrollIndicators = true private let scrollView : UIScrollView private var keyboardHeight : CGFloat = 0 public init(scrollView : UIScrollView) { self.scrollView = scrollView super.init() NotificationCenter.default.oex_addObserver(observer: self, name: UIResponder.keyboardDidChangeFrameNotification.rawValue) { (notification, observer, _) -> Void in let globalFrame : CGRect = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue // Don't want to convert to the scroll view's coordinates since they're always moving so use the superview if let container = scrollView.superview { let localFrame = container.convert(globalFrame, from: nil) let intersection = localFrame.intersection(container.bounds); let keyboardHeight = intersection.size.height; observer.keyboardHeight = keyboardHeight let duration = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let curveValue = (notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).intValue let curve = UIView.AnimationCurve(rawValue: curveValue) let curveOptions = curve?.asAnimationOptions ?? UIView.AnimationOptions() UIView.animate(withDuration: duration, delay: 0, options: curveOptions, animations: { observer.insetsDelegate?.contentInsetsSourceChanged(source: observer) }, completion: nil) } } } public var currentInsets : UIEdgeInsets { return UIEdgeInsets.init(top: 0, left: 0, bottom: keyboardHeight, right: 0) } }
apache-2.0
eb679999edfc7d3aecf217a6a88eaa50
39.629032
170
0.657801
5.585366
false
false
false
false
PekanMmd/Pokemon-XD-Code
Objects/scripts/Colosseum/CMSMacroTypes.swift
1
15579
// // CMSMacroTypes.swift // GoD Tool // // Created by Stars Momodu on 03/06/2021. // import Foundation indirect enum CMSMacroTypes { case invalid case null case bool case msgID case scriptFunction case integer case float case pokemon case item case model case move case room case ability case battleResult case shadowStatus case battleID case shadowID case treasureID case battlefield case integerMoney case integerCoupons case integerQuantity case integerIndex case groupID case resourceID case giftPokemon case flag case region case language case transitionID case yesNoIndex case buttonInput case fileIdentifier case array(CMSMacroTypes) var needsMacro: Bool { switch self { case .integer, .float, .invalid: return false case .array(let subType): return subType.needsMacro default: return true } } var needsDefine: Bool { switch self { case .bool: return false case .msgID: return false case .scriptFunction: return false case .invalid, .integer, .float, .null: return false case .array(let subType): return subType.needsDefine default: return true } } var typeName: String { switch self { case .invalid: return "Invalid" case .null: return "Void" case .bool: return "Bool" case .msgID: return "MsgID" case .scriptFunction: return "ScriptFunction" case .integer: return "Int" case .float: return "Float" case .pokemon: return "Pokemon" case .item: return "Item" case .model: return "Model" case .move: return "Move" case .room: return "Room" case .ability: return "Ability" case .battleResult: return "BattleResult" case .shadowStatus: return "ShadowStatus" case .battleID: return "Battle" case .shadowID: return "ShadowPokemon" case .treasureID: return "Treasure" case .battlefield: return "BattleField" case .integerMoney: return "Pokedollars" case .integerCoupons: return "Pokecoupons" case .integerQuantity: return "IntegerQuantity" case .integerIndex: return "Index" case .groupID: return "GroupID" case .resourceID: return "ResourceID" case .giftPokemon: return "GiftPokemon" case .flag: return "Flag" case .region: return "Region" case .language: return "Language" case .transitionID: return "Transition" case .yesNoIndex: return "YesNoIndex" case .buttonInput: return "ButtonInput" case .fileIdentifier: return "FileIdentifier" case .array(let subType): return "[\(subType.typeName)]" } } static var autocompletableTypes: [CMSMacroTypes] { return [ .pokemon, .item, .model, .move, .room, .flag, .ability, .battleResult, .shadowStatus, .shadowID, .battlefield, .giftPokemon, .region, .language, .transitionID, .scriptFunction, .buttonInput ] } var autocompleteValues: [Int] { switch self { case .pokemon: return allPokemonArray().map{ $0.index } case .item: return allItemsArray().map{ $0.index } case .model: return XGFsys(file: .fsys("people_archive")).identifiers case .move: return allPokemonArray().map{ $0.index } case .room: return XGRoom.allValues.map{ $0.roomID }.sorted() case .flag: return XDSFlags.allCases.map{ $0.rawValue } case .ability: return Array(0 ..< kNumberOfAbilities) case .battleResult: return Array(0 ... 3) case .shadowStatus: return Array(0 ... 4) case .shadowID: return Array(0 ..< CommonIndexes.NumberOfShadowPokemon.value) case .battlefield: return Array(0 ..< CommonIndexes.NumberOfBattleFields.value) case .giftPokemon: return Array(0 ..< kNumberOfGiftPokemon) case .region: return Array(0 ... 2) case .language: return XGLanguages.allCases.map{ $0.rawValue } case .transitionID: return Array(2 ... 5) case .scriptFunction: return (0 ..< XGFiles.common_rel.scriptData.ftbl.count).map { 0x596_0000 + $0 } case .buttonInput: return (0 ..< 12).map{ Int(pow(2.0, Double($0))) }.filter{ $0 != 0x80 } default: return [] } } func macroWithName(_ name: String) -> String { return "#" + name } func textForValue(_ value: CMSConstant, script: XGScript?) -> String { switch self { case .bool: return value.integerValue != 0 ? "YES" : "NO" case .msgID: return getStringSafelyWithID(id: value.integerValue).unformattedString case .scriptFunction: switch value.integerValue >> 16 { case 0: return "Null" case 0x596: return "Common.\(value.integerValue & 0xFFFF)" case 0x100: return "This.\(value.integerValue & 0xFFFF)" default: return "Error(Invalid macro value)" } case .integer, .float: assertionFailure("Shouldn't have literals as macros") return "\(value)" case .null: return "Null" case .flag: if let flag = XDSFlags(rawValue: value.integerValue) { return macroWithName("FLAG_" + flag.name.underscoreSimplified.uppercased() + "_\(value.integerValue)") } for shadow in CMShadowData.allValues { if shadow.captureFlag == value.integerValue { return macroWithName("FLAG_SHADOW_" + shadow.species.name.unformattedString.underscoreSimplified.uppercased() + "_CAUGHT_\(value.integerValue)") } } return macroWithName("FLAG_" + value.integerValue.string) case .pokemon: if value.integerValue == 0 { return macroWithName("pokemon_none".uppercased()) } if value.integerValue < 0 { return macroWithName("POKEMON_CANCEL") } let mon = XGPokemon.index(value.integerValue) if fileDecodingMode || mon.nameID == 0 { return macroWithName("POKEMON_" + value.integerValue.string) } return macroWithName("POKEMON_" + mon.name.string.underscoreSimplified.uppercased()) case .item: if value.integerValue == 0 { return macroWithName("item_none".uppercased()) } if value.integerValue < 0 { return macroWithName("ITEM_CANCEL") } let item = XGItems.index(value.integerValue) if fileDecodingMode || item.nameID == 0 { return macroWithName("ITEM_" + value.integerValue.string) } return macroWithName("ITEM_" + item.name.string.underscoreSimplified.uppercased()) case .model: if value.integerValue == 0 { return macroWithName("model_none".uppercased()) } if fileDecodingMode { return macroWithName("MODEL_" + "\(value.integerValue)") } if let scriptFile = script?.file { let fsysFile = XGFiles.fsys(scriptFile.folder.name) if fsysFile.exists { let fsys = XGFsys(file: fsysFile) if fsys.identifiers.contains(value.integerValue) { return macroWithName("MODEL_" + fsys.fileNameForFileWithIdentifier(value.integerValue)!.removeFileExtensions().underscoreSimplified.uppercased() + "\(value.integerValue)") } } } let peopleArchive = XGFiles.fsys("people_archive").fsysData if peopleArchive.identifiers.contains(value.integerValue) { return macroWithName("MODEL_" + XGCharacterModel.modelWithIdentifier(id: value.integerValue).name.removeFileExtensions().underscoreSimplified.uppercased() + "\(value.integerValue)") } return macroWithName("MODEL_" + value.integerValue.hex()) case .move: if value.integerValue == 0 { return macroWithName("move_none".uppercased()) } if value.integerValue < 0 { return macroWithName("MOVE_CANCEL") } let move = XGMoves.index(value.integerValue) if fileDecodingMode || move.nameID == 0 { return macroWithName("MOVE_" + value.integerValue.string) } return macroWithName("MOVE_" + move.name.string.underscoreSimplified.uppercased()) case .room: if value.integerValue == 0 { return macroWithName("room_none".uppercased()) } if fileDecodingMode { return macroWithName("ROOM_" + value.integerValue.string) } if let room = XGRoom.roomWithID(value.integerValue) { return macroWithName("ROOM_" + room.name.underscoreSimplified.uppercased()) } return macroWithName("ROOM_" + (XGRoom.roomWithID(value.integerValue) ?? XGRoom(index: 0)).name.simplified.uppercased()) case .battlefield: if value.integerValue == 0 { return macroWithName("battlefield_none".uppercased()) } if !fileDecodingMode, let room = XGBattleField(index: value.integerValue).room { return macroWithName("BATTLEFIELD_" + room.name.underscoreSimplified.uppercased()) } return macroWithName("BATTLEFIELD_" + value.integerValue.string) case .ability: if value.integerValue == 0 { return macroWithName("ability_none".uppercased()) } let ability = XGAbilities.index(value.integerValue) if fileDecodingMode || ability.nameID == 0 { return macroWithName("ABILITY_" + value.integerValue.string) } return macroWithName("ABILITY_" + ability.name.string.underscoreSimplified.uppercased()) case .battleResult: switch value.integerValue { case 0: return macroWithName("result_none".uppercased()) case 1: return macroWithName("result_lose".uppercased()) case 2: return macroWithName("result_win".uppercased()) case 3: return macroWithName("result_tie".uppercased()) default: return macroWithName("result_unknown".uppercased() + value.integerValue.string) } case .shadowStatus: switch value.integerValue { case 0: return macroWithName("shadow_status_not_seen".uppercased()) case 1: return macroWithName("shadow_status_seen_as_spectator".uppercased()) case 2: return macroWithName("shadow_status_seen_in_battle".uppercased()) case 3: return macroWithName("shadow_status_caught".uppercased()) case 4: return macroWithName("shadow_status_purified".uppercased()) default: printg("error unknown shadow pokemon status");return "error unknown shadow pokemon status" } case .battleID: if value.integerValue == 0 { return macroWithName("battle_none".uppercased()) } let mid: String if let battle = XGBattle(index: value.integerValue) { mid = (battle.p3Trainer == nil ? "VS_\(battle.p2Trainer?.trainerClass.name.unformattedString ?? "unknown_class")_\(battle.p2Trainer?.name.unformattedString ?? "unknown_trainer")" : "VS_\(battle.p3Trainer?.name.unformattedString ?? "unknown_class")_AND_\(battle.p4Trainer?.name.unformattedString ?? "unknown_trainer")").underscoreSimplified.uppercased() } else { mid = "unknown_class_unknown_trainer".uppercased() } return macroWithName("BATTLE_\(mid)_" + String(format: "%03d", value.integerValue)) case .shadowID: if value.integerValue == 0 { return macroWithName("shadow_pokemon_none".uppercased()) } let mid = (fileDecodingMode || value.integerValue < 0 || CMShadowData(index: value.integerValue).species.nameID == 0) ? "POKEMON" : CMShadowData(index: value.integerValue).species.name.string.underscoreSimplified.uppercased() return macroWithName("SHADOW_" + mid + String(format: "_%02d", value.integerValue)) case .treasureID: if value.integerValue == 0 { return macroWithName("treasure_none".uppercased()) } let mid = fileDecodingMode ? "ITEM" : XGTreasure(index: value.integerValue).item.name.string.underscoreSimplified.uppercased() return macroWithName("TREASURE_" + mid + String(format: "_%03d", value.integerValue)) case .buttonInput: switch value.integerValue { case 0x1: return macroWithName("BUTTON_INPUT_D_PAD_LEFT") case 0x2: return macroWithName("BUTTON_INPUT_D_PAD_RIGHT") case 0x4: return macroWithName("BUTTON_INPUT_D_PAD_DOWN") case 0x8: return macroWithName("BUTTON_INPUT_D_PAD_UP") case 0x10: return macroWithName("BUTTON_INPUT_TRIGGER_Z") case 0x20: return macroWithName("BUTTON_INPUT_TRIGGER_R") case 0x40: return macroWithName("BUTTON_INPUT_TRIGGER_L") case 0x100: return macroWithName("BUTTON_INPUT_A") case 0x200: return macroWithName("BUTTON_INPUT_B") case 0x400: return macroWithName("BUTTON_INPUT_X") case 0x800: return macroWithName("BUTTON_INPUT_Y") case 0x1000: return macroWithName("BUTTON_INPUT_START") default: return macroWithName("BUTTON_INPUT_UNKNOWN_\(value.integerValue)") } case .integerMoney: return macroWithName("P$\(value.integerValue.string.replacingOccurrences(of: "-", with: "_"))") case .integerCoupons: return macroWithName("C$\(value.integerValue.string.replacingOccurrences(of: "-", with: "_"))") case .integerQuantity: return macroWithName("X\(value.integerValue.string.replacingOccurrences(of: "-", with: "_"))") case .integerIndex: if value.integerValue < 0 { return macroWithName("INDEX_CANCEL") } return macroWithName("INDEX_\(value.integerValue)") case .yesNoIndex: return macroWithName(value.integerValue == 0 ? "INDEX_YES" : "INDEX_NO") case .giftPokemon: if !fileDecodingMode && value.integerValue <= kNumberOfGiftPokemon && value.integerValue > 0 { let gift = XGGiftPokemonManager.allGiftPokemon()[value.integerValue] let type = gift.giftType.underscoreSimplified.uppercased() let species = gift.species.name.string.underscoreSimplified.uppercased() return macroWithName(type + "_" + species) } if value.integerValue == 0 { return macroWithName("GIFT_POKEMON_NONE") } return macroWithName("GIFT_POKEMON_" + String(format: "%03d", value.integerValue)) case .groupID: return macroWithName(value.integerValue == 0 ? "GROUP_ID_PROTAGONISTS" : "GROUP_ID_CURRENT_MAP") case .resourceID: let rid = value.integerValue switch rid { case 100: return macroWithName("CHARACTER_RID_WES") case 101: return macroWithName("CHARACTER_RID_RUI") default: if let characters = script?.mapRel?.characters, rid < characters.count, characters[rid].name.count > 1 { return macroWithName("CHARACTER_RID_\(rid)_\(characters[rid].name)") } return macroWithName("CHARACTER_RID_\(rid)") } case .region: switch value.integerValue { case 0: return macroWithName("REGION_JP") case 1: return macroWithName("REGION_US") case 2: return macroWithName("REGION_PAL") default: printg("error invalid region"); return macroWithName("INVALID_REGION") } case .language: switch value.integerValue { case 0: return macroWithName("LANGUAGE_JAPANESE") case 1: return macroWithName("LANGUAGE_ENGLISH_UK") case 2: return macroWithName("LANGUAGE_ENGLISH_US") case 3: return macroWithName("LANGUAGE_GERMAN") case 4: return macroWithName("LANGUAGE_FRENCH") case 5: return macroWithName("LANGUAGE_ITALIAN") case 6: return macroWithName("LANGUAGE_SPANISH") default: printg("error invalid language"); return macroWithName("INVALID_LANGUAGE") } case .transitionID: var name = "" switch value.integerValue { case 0: name = "NONE" case 2: name = "FADE_IN_BLACK" case 3: name = "FADE_OUT_BLACK" case 4: name = "FADE_IN_WHITE" case 5: name = "FADE_OUT_WHITE" default: name = value.integerValue.string } return macroWithName("TRANSITION_" + name.uppercased()) case .fileIdentifier: if value.integerValue == 0 { return macroWithName("file_none".uppercased()) } if fileDecodingMode { return macroWithName("FILE_" + value.integerValue.hex()) } if let scriptFile = script?.file { let fsysFile = XGFiles.fsys(scriptFile.folder.name) if fsysFile.exists { let fsys = XGFsys(file: fsysFile) if fsys.identifiers.contains(value.integerValue) { return macroWithName("FILE_" + fsys.fileNameForFileWithIdentifier(value.integerValue)!.removeFileExtensions().underscoreSimplified.uppercased() + "_\(value.integerValue.hex())") } } } return macroWithName("FILE_" + value.integerValue.hex()) case .array(let subType): return subType.textForValue(value, script: script) case .invalid: return "INVALID_\(value.integerValue)" } } }
gpl-2.0
ff2659d126035f8cc79ea5fce0721832
33.390728
356
0.706913
3.480563
false
false
false
false
xuech/OMS-WH
OMS-WH/Utilities/TreeTableView/OMSTreeTableViewNode.swift
1
1792
// // OMSTreeTableViewNode.swift // OMS-WH // // Created by xuech on 2017/12/20. // Copyright © 2017年 medlog. All rights reserved. // import UIKit class OMSTreeTableViewNode: NSObject { var parentNode:OMSTreeTableViewNode?{ didSet{ if let parentN = parentNode, !parentN.subNodes.contains(self) { parentN.subNodes.append(self) } } } var subNodes:[OMSTreeTableViewNode] = [OMSTreeTableViewNode](){ didSet{ for childNode in subNodes{ childNode.parentNode = self } } } /// 本节点ID var nodeID:UInt = 0 /// 本节点名称 var nodeName:String = "" /// 左侧图标 var leftImageName:String = "" /// 右侧图标 var rightImageName:String = "" /// 本节点是否处于展开状态 var isExpand:Bool = false /// 深度:根节点为0 var depth:Int{ if let parentN = parentNode{ return parentN.depth + 1 } return 0 } /// 私有化构造函数 private override init(){ super.init() } convenience init?(nodeID:UInt,nodeName:String,leftImageName:String,rightImageName:String,isExpand:Bool){ self.init() if nodeName == ""{ return nil } else{ self.nodeID = nodeID self.nodeName = nodeName self.leftImageName = leftImageName self.rightImageName = rightImageName self.isExpand = isExpand } } /// 添加子节点 /// /// - Parameter childNode: 子节点 func addChildNode(childNode:OMSTreeTableViewNode){ childNode.parentNode = self } }
mit
9cc42a0891fcf581e9861b19438180f7
20.405063
108
0.537552
4.238095
false
false
false
false
loudnate/Loop
Loop/Models/PredictionInputEffect.swift
1
2489
// // PredictionInputEffect.swift // Loop // // Created by Nate Racklyeft on 9/4/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit struct PredictionInputEffect: OptionSet { let rawValue: Int static let carbs = PredictionInputEffect(rawValue: 1 << 0) static let insulin = PredictionInputEffect(rawValue: 1 << 1) static let momentum = PredictionInputEffect(rawValue: 1 << 2) static let retrospection = PredictionInputEffect(rawValue: 1 << 3) static let all: PredictionInputEffect = [.carbs, .insulin, .momentum, .retrospection] var localizedTitle: String? { switch self { case [.carbs]: return NSLocalizedString("Carbohydrates", comment: "Title of the prediction input effect for carbohydrates") case [.insulin]: return NSLocalizedString("Insulin", comment: "Title of the prediction input effect for insulin") case [.momentum]: return NSLocalizedString("Glucose Momentum", comment: "Title of the prediction input effect for glucose momentum") case [.retrospection]: return NSLocalizedString("Retrospective Correction", comment: "Title of the prediction input effect for retrospective correction") default: return nil } } func localizedDescription(forGlucoseUnit unit: HKUnit) -> String? { switch self { case [.carbs]: return String(format: NSLocalizedString("Carbs Absorbed (g) ÷ Carb Ratio (g/U) × Insulin Sensitivity (%1$@/U)", comment: "Description of the prediction input effect for carbohydrates. (1: The glucose unit string)"), unit.localizedShortUnitString) case [.insulin]: return String(format: NSLocalizedString("Insulin Absorbed (U) × Insulin Sensitivity (%1$@/U)", comment: "Description of the prediction input effect for insulin"), unit.localizedShortUnitString) case [.momentum]: return NSLocalizedString("15 min glucose regression coefficient (b₁), continued with decay over 30 min", comment: "Description of the prediction input effect for glucose momentum") case [.retrospection]: return NSLocalizedString("30 min comparison of glucose prediction vs actual, continued with decay over 60 min", comment: "Description of the prediction input effect for retrospective correction") default: return nil } } }
apache-2.0
5f9ce458d461782fcef39dd510f01e3b
46.75
258
0.681836
4.812016
false
false
false
false
PairOfNewbie/BeautifulDay
BeautifulDay/AppDelegate.swift
1
10369
// // AppDelegate.swift // BeautifulDay // // Created by DaiFengyi on 16/4/4. // Copyright © 2016年 PairOfNewbie. All rights reserved. // import UIKit import CoreData import RESideMenu @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = reSideMenuAfterSetup() window?.makeKeyAndVisible() setupShareSDK() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } //MARK: - Configuration private func reSideMenuAfterSetup() -> RESideMenu { let sb = UIStoryboard(name: "Main", bundle: nil) let contentVC = sb.instantiateViewControllerWithIdentifier("mainNav") let leftVC = sb.instantiateViewControllerWithIdentifier("leftVC") let rm = RESideMenu(contentViewController: contentVC, leftMenuViewController: leftVC, rightMenuViewController: nil) rm.panFromEdge = true rm.contentViewScaleValue = 1 rm.contentViewInPortraitOffsetCenterX = UIScreen.mainScreen().bounds.width * (0.75-0.5) return rm } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "PairOfNewbie.BeautifulDay" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("BeautifulDay", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } //MARK: - private func setupShareSDK() { /** * 设置ShareSDK的appKey,如果尚未在ShareSDK官网注册过App,请移步到http://mob.com/login 登录后台进行应用注册, * 在将生成的AppKey传入到此方法中。 * 方法中的第二个参数用于指定要使用哪些社交平台,以数组形式传入。第三个参数为需要连接社交平台SDK时触发, * 在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发,根据返回的平台类型来配置平台信息。 * 如果您使用的时服务端托管平台信息时,第二、四项参数可以传入nil,第三项参数则根据服务端托管平台来决定要连接的社交SDK。 */ // todo 所有的appkey等信息 ShareSDK.registerApp("iosv1101", activePlatforms: [SSDKPlatformType.TypeSinaWeibo.rawValue, SSDKPlatformType.TypeQQ.rawValue, SSDKPlatformType.TypeWechat.rawValue,], onImport: {(platform : SSDKPlatformType) -> Void in switch platform{ case SSDKPlatformType.TypeSinaWeibo: ShareSDKConnector.connectWeibo(WeiboSDK.classForCoder()) case SSDKPlatformType.TypeQQ: ShareSDKConnector.connectQQ(QQApiInterface.classForCoder(), tencentOAuthClass: TencentOAuth.classForCoder()) case SSDKPlatformType.TypeWechat: ShareSDKConnector.connectWeChat(WXApi.classForCoder()) default: break } }, onConfiguration: {(platform : SSDKPlatformType,appInfo : NSMutableDictionary!) -> Void in switch platform { case SSDKPlatformType.TypeSinaWeibo: //设置新浪微博应用信息,其中authType设置为使用SSO+Web形式授权 appInfo.SSDKSetupSinaWeiboByAppKey("568898243", appSecret : "38a4f8204cc784f81f9f0daaf31e02e3", redirectUri : "http://www.sharesdk.cn", authType : SSDKAuthTypeBoth) case SSDKPlatformType.TypeQQ: appInfo.SSDKSetupQQByAppId("", appKey: "", authType: SSDKAuthTypeBoth) case SSDKPlatformType.TypeWechat: //设置微信应用信息 appInfo.SSDKSetupWeChatByAppId("wx4868b35061f87885", appSecret: "64020361b8ec4c99936c0e3999a9f249") default: break } }) } }
mit
83cd1c5c5df863f9fd181cea987ddbd2
53.417582
291
0.629746
5.829311
false
false
false
false
Erez-Panda/LiveBankSDK
Pod/Classes/Socket.swift
1
3279
// // Socket.swift // Pods // // Created by Erez Haim on 1/5/16. // // import Foundation class Socket: NSObject { private let name: String private let sender: String private var socket: Int? private var timer: NSTimer? private let DEFAULT_INTERVAL = 3 private var callbacks : Array<((message: Dictionary<String, AnyObject>) -> Void)> = [] init(fromString name: NSString) { self.name = name as String self.sender = NSUUID().UUIDString super.init() } convenience override init() { self.init(fromString:"") // calls above mentioned controller with default name } func convertStringToDictionary(text: String) -> [String:AnyObject]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { var json: [String:AnyObject]? do { json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as? [String : AnyObject] } catch let error as NSError { print (error) json = nil } catch { fatalError() } return json } return nil } func requestForMessages(){ RemoteAPI.sharedInstance.getMessagesFromSocket(["socket": socket!, "sender": sender]) { (result) -> Void in for message in result{ for callback in self.callbacks{ if let dataStr = message["data"] as? String{ if let data = self.convertStringToDictionary(dataStr){ callback(message: data) } } else { if let data = message["data"] as? Dictionary<String, AnyObject>{ callback(message: data) } //print(message["data"]) } } } } } func registerForMessages(){ timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(DEFAULT_INTERVAL), target: self, selector: Selector("requestForMessages"), userInfo: AnyObject?(), repeats: true) } func connect(completion: (result: Bool) -> Void) -> Void{ RemoteAPI.sharedInstance.connectToSocket(["name": self.name]) { (result) -> Void in if let socket = result["id"] as? Int{ self.socket = socket self.registerForMessages() self.sendMessage(["_type": "connected" ,"connected":true]) completion(result: true) } else { completion(result: false) } } } func disconnect(){ timer?.invalidate() socket = nil callbacks = [] } func sendMessage(message: Dictionary<String, AnyObject>){ if nil != socket { RemoteAPI.sharedInstance.sendMessageToSocket(["sender": sender, "socket": socket!, "data": message]) { (result) -> Void in // } } } func onMessage(completion: (message: Dictionary<String, AnyObject>) -> Void) -> Void{ callbacks.append(completion) } }
mit
74f4a04d449e8e55a628d0c3b2cc9b0c
30.528846
183
0.524245
5.171924
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/SimpleBuy/CashIdentityVerificationViewController.swift
1
3207
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit final class CashIdentityVerificationViewController: UIViewController { private let tableView = SelfSizingTableView() private let presenter: CashIdentityVerificationPresenter init(presenter: CashIdentityVerificationPresenter) { self.presenter = presenter super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Lifecycle override func loadView() { view = UIView() view.backgroundColor = .white } override func viewDidLoad() { super.viewDidLoad() setupTableView() tableView.reloadData() } private func setupTableView() { view.addSubview(tableView) tableView.layoutToSuperview(axis: .horizontal, usesSafeAreaLayoutGuide: true) tableView.layoutToSuperview(axis: .vertical, usesSafeAreaLayoutGuide: true) tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableView.automaticDimension tableView.register(AnnouncementTableViewCell.self) tableView.register(BadgeNumberedTableViewCell.self) tableView.registerNibCell(ButtonsTableViewCell.self, in: .platformUIKit) tableView.separatorColor = .clear tableView.delegate = self tableView.dataSource = self } } // MARK: - UITableViewDelegate, UITableViewDataSource extension CashIdentityVerificationViewController: UITableViewDelegate, UITableViewDataSource { func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int ) -> Int { presenter.cellCount } func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let cell: UITableViewCell let type = presenter.cellArrangement[indexPath.row] switch type { case .announcement(let viewModel): cell = announcement(for: indexPath, viewModel: viewModel) case .numberedItem(let viewModel): cell = numberedCell(for: indexPath, viewModel: viewModel) case .buttons(let buttons): cell = buttonsCell(for: indexPath, buttons: buttons) } return cell } // MARK: - Accessors private func announcement(for indexPath: IndexPath, viewModel: AnnouncementCardViewModel) -> UITableViewCell { let cell = tableView.dequeue(AnnouncementTableViewCell.self, for: indexPath) cell.viewModel = viewModel return cell } private func numberedCell(for indexPath: IndexPath, viewModel: BadgeNumberedItemViewModel) -> UITableViewCell { let cell = tableView.dequeue(BadgeNumberedTableViewCell.self, for: indexPath) cell.viewModel = viewModel return cell } private func buttonsCell(for indexPath: IndexPath, buttons: [ButtonViewModel]) -> UITableViewCell { let cell = tableView.dequeue(ButtonsTableViewCell.self, for: indexPath) cell.models = buttons return cell } }
lgpl-3.0
ab65fc5d60aa04ea5dbc1bb5806f92b2
32.747368
115
0.687149
5.415541
false
false
false
false
wess/overlook
Sources/overlook/overlook.swift
1
2605
// // overlook.swift // overlook // // Created by Wesley Cope on 9/30/16. // // import Foundation import SwiftCLI import PathKit import Rainbow import config import env public class Overlook { static let name = "overlook" static let version = "0.1.4" static let desc = "File monitoring tool that excutes on change. Used anywhere." static let dotTemplate:[String:Any] = [ "env" : ["example" : "variable"], "verbose" : true, "ignore" : [".git", ".gitignore", ".overlook",], "directories" : ["build", "tests",], "execute" : "ls -la", ] private lazy var helpCommand:HelpCommand = HelpCommand() private lazy var versionCommand:VersionCommand = VersionCommand() private lazy var defaultCommand:DefaultCommand = DefaultCommand() private lazy var initCommand:InitCommand = InitCommand() private lazy var adhocCommand:AdhocCommand = AdhocCommand() private lazy var router:OverlookRouter = OverlookRouter(self.defaultCommand) private var runOnce:[Command] { return [ helpCommand, versionCommand, initCommand, ] } public init() { CLI.setup(name: Overlook.name, version: Overlook.version, description: Overlook.desc) setupRouter() setupCommands() setupAliases() } private func setupRouter() { CLI.router = self.router } private func setupCommands() { CLI.versionCommand = versionCommand CLI.helpCommand = helpCommand CLI.register(command: initCommand) CLI.register(command: adhocCommand) } private func setupAliases() { CLI.alias(from: "-h", to: "help") CLI.alias(from: "--help", to: "help") CLI.alias(from: "-v", to: "version") CLI.alias(from: "--version", to: "version") CLI.alias(from: "-i", to: "init") CLI.alias(from: "--init", to: "init") CLI.alias(from: "-w", to: "watch") CLI.alias(from: "--watch", to: "watch") } public func run() { let result = CLI.go() guard result == CLIResult.success else { exit(result) } guard self.router.exitImmediately == false else { exit(result) } guard runOnce.contains(where: { $0 == self.router.current } ) else { dispatchMain() } exit(result) } } public func startup(_ run:String, watching:[String]) { let executing = "executing: " let target = run.bold print("\nStarting Overlook...".green.bold) print(executing + target.bold) print("watching:") for directory in watching { print(" ", directory.bold) } }
mit
98c3260deb74b11a09ea0fd81fcb2f9a
21.850877
91
0.619578
3.726753
false
false
false
false
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Main/Controller/BTMainTabBarVC.swift
1
2271
// // BTMainTabBarVC.swift // BanTang // // Created by 张灿 on 16/5/23. // Copyright © 2016年 张灿. All rights reserved. // import UIKit class BTMainTabBarVC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() //加载子控制器 setupAllChildVC() //自定义tabbar setupTabBarButton() view.backgroundColor = UIColor.whiteColor() } } //MARK:- 加载所有子控制器(photo除外) extension BTMainTabBarVC { func setupAllChildVC() { //首页 let homeVC = BTHomeViewController() setupOneChildVC(homeVC, imageName: "tab_首页_24x24_", selectImageName: "tab_首页_pressed_24x24_", title: "首页") //发现 let discoverVC = BTDiscoverViewController() setupOneChildVC(discoverVC, imageName: "tab_社区_26x26_", selectImageName: "tab_社区_pressed_26x26_", title: "发现") //消息 let messageVC = BTMessageViewController() setupOneChildVC(messageVC, imageName: "tab_分类_27x21_", selectImageName: "tab_分类_pressed_27x21_", title: "消息") //账号 let accountVC = BTAccountViewController() setupOneChildVC(accountVC, imageName: "tab_我的_22x23_", selectImageName: "tab_我的_pressed_22x23_", title: "账号") } } //MARK:- 设置子控制器 extension BTMainTabBarVC { func setupOneChildVC(viewController: UIViewController, imageName: String, selectImageName: String, title: String?) { let baseNav = BTBaseNaviController(rootViewController: viewController) // viewController.navigationItem.title = title // viewController.tabBarItem.title = nil viewController.tabBarItem.image = UIImage(named: imageName) viewController.tabBarItem.selectedImage = UIImage(named: selectImageName) viewController.tabBarItem.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0) self.addChildViewController(baseNav) } } //MARK:- 自定义tabBar按钮 extension BTMainTabBarVC { func setupTabBarButton() { //创建自定义tabbar let tabbar = BTTabBar() self.setValue(tabbar, forKey: "tabBar") } }
apache-2.0
cbedd0e72ae99abf2c438ad28352108c
28.541667
120
0.645343
4.049524
false
false
false
false
pyanfield/ataturk_olympic
swift_programming_closures.playground/section-1.swift
1
5701
// Playground - noun: a place where people can play // when import UIKit, there is error when using sorted. // http://stackoverflow.com/questions/26249784/implicit-returns-from-single-expression-closures-in-swift-playground //import UIKit // 2.7 // 闭包是自包含的函数代码块,可以在代码中被传递和使用。 Swift 中的闭包与 C 和 Objective-C 中的代码块(blocks)以及其他一些编程语言中的 lambdas 函数比较相似。 // 闭包可以捕获和存储其所在上下文中任意常量和变量的引用。 // Swift 标准库提供了sorted函数,会根据您提供的基于输出类型排序的闭包函数将已知类型数组中的值进行排序。 // sorted 传入两个参数,其一是一个数组,其二是一个闭包函数,该函数有两个参数,参数类型与数组相同,且返回一个布尔值,即 (type, type) -> Bool 的函数类型。 let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] func backwards(s1: String, s2: String) -> Bool { return s1 > s2 } var reversed = sorted(names, backwards) // [String], (String,String) -> Bool // 如果闭包函数作为另一个函数的最后一个参数传递的时候,可以使用闭包表达式语法来表示: // { (parameters) -> returnType in // statements // } // 所以上面的写法可以改进为: reversed = sorted(names,{ (s1: String, s2:String) -> Bool in return s1 > s2 }) // 闭包表达式语法可以使用常量、变量和inout类型作为参数,不提供默认值。 也可以在参数列表的最后使用可变参数。 元组也可以作为参数和返回值。 // 实际上任何情况下,通过内联闭包表达式构造的闭包作为参数传递给函数时,都可以推断出闭包的参数和返回值类型,这意味着您几乎不需要利用完整格式构造任何内联闭包。 // 所以对上面的写法进一步改进为: reversed = sorted(names,{ s1, s2 in return s1 > s2 }) // 单行表达式闭包可以通过隐藏return关键字来隐式返回单行表达式的结果 var reversed1 = sorted(names, { s1, s2 in s1 > s2 // 闭包函数体只包含了一个表达式 }) // Swift 自动为内联函数提供了参数名称缩写功能,您可以直接通过$0,$1,$2来顺序调用闭包的参数。 // 如果您在闭包表达式中使用参数名称缩写,您可以在闭包参数列表中省略对其的定义,并且对应参数名称缩写的类型会通过函数类型进行推断。 // in关键字也同样可以被省略,因为此时闭包表达式完全由闭包函数体构成: var reversed2 = sorted(names, { $0 > $1 }) // 而对于 sorted 还可以使用运算符函数 reversed2 = sorted(names, >) // 其实只要是因为 String 类型定义了关于 > 的字符串实现,而 > 作为一个函数,起类型正好是 (String, String) -> Bool 类型,所以 Swift 自动推断出具体的实现过程。 // 需要将一个很长的闭包表达式作为最后一个参数传递给函数,可以使用尾随闭包来增强函数的可读性。 // 尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个参数调用。 func someFunctionThatTakesAClosure(closure: () -> ()) { // 函数体部分 } // 以下是不使用尾随闭包进行函数调用 someFunctionThatTakesAClosure({ // 闭包主体部分 }) // 以下是使用尾随闭包进行函数调用 someFunctionThatTakesAClosure() { // 闭包主体部分 } // 所以上面的 sorted 可以写成: var reversed3 = sorted(names,{ $0 > $1 }) var reversed4 = sorted(names){ $0 > $1 } // 如果函数只有闭包表达式一个参数,那么可以省略掉 (), 直接写成: someFunctionThatTakesAClosure{ // 闭包主体部分 } // 捕获值(Capturing Values) // 闭包可以在其定义的上下文中捕获常量或变量。 即使定义这些常量和变量的原域已经不存在,闭包仍然可以在闭包函数体内引用和修改这些值。 func makeIncrementor(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementor() -> Int { runningTotal += amount return runningTotal } return incrementor } let incrementByTen = makeIncrementor(forIncrement: 10) incrementByTen() incrementByTen() incrementByTen() // incrementor函数并没有获取任何参数,但是在函数体内访问了runningTotal和amount变量。这是因为其通过捕获在包含它的函数体内已经存在的runningTotal和amount变量而实现。 // 由于没有修改amount变量,incrementor实际上捕获并存储了该变量的一个副本,而该副本随着incrementor一同被存储。 // 每次调用该函数的时候都会修改runningTotal的值,incrementor捕获了当前runningTotal变量的引用,而不是仅仅复制该变量的初始值。 // 捕获一个引用保证了当makeIncrementor结束时候并不会消失,也保证了当下一次执行incrementor函数时,runningTotal可以继续增加。 // 如果您将闭包赋值给一个类实例的属性,并且该闭包通过指向该实例或其成员来捕获了该实例,您将创建一个在闭包和实例间的强引用环。 Swift 使用捕获列表来打破这种强引用环。 // 无论您将函数/闭包赋值给一个常量还是变量,您实际上都是将常量/变量的值设置为对应函数/闭包的引用。 // incrementByTen指向闭包的引用是一个常量,而并非闭包内容本身。 // 这也意味着如果您将闭包赋值给了两个不同的常量/变量,两个值都会指向同一个闭包: let alsoIncrementByTen = incrementByTen alsoIncrementByTen()
mit
7c03f478b5477e54d63e3fbd2381d707
32.427083
115
0.759427
2.512921
false
false
false
false
wilfreddekok/Antidote
Antidote/StaticTableBaseCell.swift
1
1973
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit private struct Constants { static let HorizontalOffset = 20.0 static let MinHeight = 50.0 } class StaticTableBaseCell: BaseCell { /** View to add all content to. */ var customContentView: UIView! private var bottomSeparatorView: UIView! func setBottomSeparatorHidden(hidden: Bool) { bottomSeparatorView.hidden = hidden } /** Override this method in subclass. */ override func setupWithTheme(theme: Theme, model: BaseCellModel) { super.setupWithTheme(theme, model: model) bottomSeparatorView.backgroundColor = theme.colorForType(.SeparatorsAndBorders) } /** Override this method in subclass. */ override func createViews() { super.createViews() customContentView = UIView() customContentView.backgroundColor = UIColor.clearColor() contentView.addSubview(customContentView) bottomSeparatorView = UIView() contentView.addSubview(bottomSeparatorView) } /** Override this method in subclass. */ override func installConstraints() { super.installConstraints() customContentView.snp_makeConstraints { $0.leading.equalTo(contentView).offset(Constants.HorizontalOffset) $0.trailing.equalTo(contentView).offset(-Constants.HorizontalOffset) $0.top.equalTo(contentView) $0.height.greaterThanOrEqualTo(Constants.MinHeight) } bottomSeparatorView.snp_makeConstraints { $0.leading.equalTo(customContentView) $0.top.equalTo(customContentView.snp_bottom) $0.trailing.bottom.equalTo(contentView) $0.height.equalTo(0.5) } } }
mpl-2.0
c009098b2d68cd90c171205c9e003a21
28.014706
87
0.661429
4.788835
false
false
false
false
EmilYo/FoldingTabBar.iOS
Example-Swift/Example-Swift/ViewControllers/ChatViewController.swift
1
2201
// // ChatViewController.swift // Example-Swift // // Created by Serhii Butenko on 29/8/16. // Copyright © 2016 Yalantis. All rights reserved. // import UIKit private let ChatDemoImageName = "imageName" private let DemoUserName = "userName" private let ChatDemoMessageText = "messageText" private let ChatDemeDateText = "dateText" private let reuseIdentifier = "ChatCollectionViewCell" class ChatViewController: UIViewController { typealias Message = [String: String] fileprivate var messages: [Message] = [] @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() messages = NSArray(contentsOfFile: Bundle.main.path(forResource: "YALChatDemoList", ofType: "plist")!) as! [Message] } } extension ChatViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ChatCollectionViewCell let message = messages[(indexPath as NSIndexPath).row] cell.configure( withImage: UIImage(named: message[ChatDemoImageName]!)!, userName: message[DemoUserName]!, messageText: message[ChatDemoMessageText]!, dateText: message[ChatDemeDateText]! ) return cell } } extension ChatViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let layout = collectionViewLayout as! UICollectionViewFlowLayout return CGSize(width: view.bounds.width, height: layout.itemSize.height) } } extension ChatViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { segue.destination.hidesBottomBarWhenPushed = true } }
mit
193cd3f94799c9a648714c869d82c847
31.835821
160
0.714545
5.378973
false
false
false
false
AnRanScheme/MagiRefresh
MagiRefresh/Classes/UI/Footer/MagiArrowFooter.swift
2
3886
// // MagiArrowFooter.swift // MagiRefresh // // Created by anran on 2018/9/5. // Copyright © 2018年 anran. All rights reserved. // import Foundation import UIKit public class MagiArrowFooter: MagiRefreshFooterConrol { public var pullingText: String = MagiRefreshDefaults.shared.footPullingText public var readyText: String = MagiRefreshDefaults.shared.readyText public var refreshingText: String = MagiRefreshDefaults.shared.refreshingText fileprivate lazy var arrowImgV: UIImageView = { let arrowImgV = UIImageView() let curBundle = Bundle(for: MagiArrowFooter.classForCoder()) var curBundleDirectory = "" if let curBundleName = curBundle.infoDictionary?["CFBundleName"] as? String { curBundleDirectory = curBundleName+".bundle" } let path = curBundle.path(forResource: "Image", ofType: "bundle", inDirectory: curBundleDirectory) ?? "" let urlString = (path as NSString).appendingPathComponent("arrow.png") let image = UIImage(contentsOfFile: urlString) arrowImgV.image = image arrowImgV.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) return arrowImgV }() fileprivate lazy var promptlabel: UILabel = { let promptlabel = UILabel() promptlabel.textAlignment = .center promptlabel.textColor = UIColor.gray promptlabel.sizeToFit() if #available(iOS 8.2, *) { promptlabel.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.thin) } else { promptlabel.font = UIFont.systemFont(ofSize: 11) } return promptlabel }() lazy var indicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView( style: .gray) indicator.hidesWhenStopped = true return indicator }() override public func setupProperties() { super.setupProperties() addSubview(arrowImgV) addSubview(promptlabel) addSubview(indicator) } override public func layoutSubviews() { super.layoutSubviews() promptlabel.sizeToFit() promptlabel.center = CGPoint(x: magi_width/2, y: magi_height/2) arrowImgV.frame = CGRect(x: 0, y: 0, width: 12, height: 12) arrowImgV.magi_right = promptlabel.magi_left-20.0 arrowImgV.magi_centerY = promptlabel.magi_centerY indicator.center = arrowImgV.center } override public func magiDidScrollWithProgress(progress: CGFloat, max: CGFloat) { super.magiDidScrollWithProgress(progress: progress, max: max) } override public func magiRefreshStateDidChange(_ status: MagiRefreshStatus) { super.magiRefreshStateDidChange(status) switch status { case .none: arrowImgV.isHidden = false indicator.stopAnimating() UIView.animate(withDuration: 0.3) { self.arrowImgV.transform = CGAffineTransform(rotationAngle: CGFloat.pi) } case .scrolling: promptlabel.text = pullingText promptlabel.sizeToFit() UIView.animate(withDuration: 0.3) { self.arrowImgV.transform = CGAffineTransform(rotationAngle: CGFloat.pi) } case .ready: indicator.stopAnimating() promptlabel.text = readyText UIView.animate(withDuration: 0.3) { self.arrowImgV.transform = CGAffineTransform(rotationAngle: 2*CGFloat.pi) } case .refreshing: promptlabel.text = refreshingText arrowImgV.isHidden = true indicator.startAnimating() case .willEndRefresh: indicator.stopAnimating() } } }
mit
5e3da68d03b50872e29358dda8b3329f
33.061404
112
0.619109
4.835616
false
false
false
false
wgywgy/SimpleActionSheet
CustomSheet/Source/ActionSheetItem.swift
1
2126
// // ActionSheetItem.swift // CustomSheet // // Created by wuguanyu on 16/9/23. // Copyright © 2016年 wuguanyu. All rights reserved. // import UIKit public protocol ActionSheetItemModel { var title: String { get set } var font: UIFont { get set } var fontColor: UIColor { get set } var height: CGFloat { get set } var selectAction: ((_ actionSheet: ActionSheetController) -> Void)? { get set } var backGroundColor: UIColor { get set } init(title: String, font: UIFont, fontColor: UIColor, backGroundColor: UIColor, height: CGFloat, selectAction: ((_ actionSheet: ActionSheetController) -> Void)?) } public struct ActionSheetItem: ActionSheetItemModel { public var title = "" public var font: UIFont public var fontColor: UIColor public var height: CGFloat public var selectAction: ((_ actionSheet: ActionSheetController) -> Void)? public var backGroundColor: UIColor public init(title: String, font: UIFont = .systemFont(ofSize: 14), fontColor: UIColor = .black, backGroundColor: UIColor = .white, height: CGFloat = 44, selectAction: ((_ actionSheet: ActionSheetController) -> Void)?) { self.title = title self.fontColor = fontColor self.height = height self.selectAction = selectAction self.backGroundColor = backGroundColor self.font = font } } public struct CancelActionSheetItem: ActionSheetItemModel { public var title = "" public var font: UIFont public var fontColor: UIColor public var height: CGFloat public var selectAction: ((_ actionSheet: ActionSheetController) -> Void)? public var backGroundColor: UIColor public init(title: String = "取消", font: UIFont = .boldSystemFont(ofSize: 14), fontColor: UIColor = .black, backGroundColor: UIColor = .white, height: CGFloat = 44, selectAction: ((_ actionSheet: ActionSheetController) -> Void)?) { self.title = title self.fontColor = fontColor self.height = height self.selectAction = selectAction self.backGroundColor = backGroundColor self.font = font } }
mit
1a1862b868201c318eefb22677d294a3
36.175439
223
0.684757
4.677704
false
false
false
false
shralpmeister/shralptide2
ShralpTide/Shared/Components/ChartView/LabeledChartViewModifier.swift
1
3719
// // LabeledChartViewModifier.swift // SwiftTides // // Created by Michael Parlee on 12/29/20. // import ShralpTideFramework import SwiftUI struct LabeledChartViewModifier: ViewModifier { private var hourFormatter = DateFormatter() private let tideData: SDTide private let labelInset: Int private let chartMinutes: Int init(tide: SDTide, labelInset: Int = 0) { tideData = tide self.labelInset = labelInset chartMinutes = tide.hoursToPlot() * ChartConstants.minutesPerHour hourFormatter.dateFormat = DateFormatter.dateFormat( fromTemplate: "j", options: 0, locale: Locale.current ) } private func xCoord(forTime time: Date, baseSeconds: TimeInterval, xratio: CGFloat) -> CGFloat { let minute = Int(time.timeIntervalSince1970 - baseSeconds) / ChartConstants.secondsPerMinute return CGFloat(minute) * xratio } private func makeLabels( _ intervals: [SDTideInterval], baseSeconds: TimeInterval, xratio: CGFloat ) -> [TimeLabel] { return intervals.filter { $0.time.isOnTheHour() } .reduce(into: []) { labels, interval in let x = xCoord(forTime: interval.time, baseSeconds: baseSeconds, xratio: xratio) if x == 0 || x - labels.last!.x > 40 { let hour = hourFormatter.string(from: interval.time) .replacingOccurrences(of: " ", with: "") return labels.append( TimeLabel( x: xCoord(forTime: interval.time, baseSeconds: baseSeconds, xratio: xratio), text: hour ) ) } } } func body(content: Content) -> some View { GeometryReader { proxy in let day = tideData.startTime let intervalsForDay = tideData.intervals(from: day, forHours: tideData.hoursToPlot())! let baseSeconds = intervalsForDay[0].time.timeIntervalSince1970 let xratio = proxy.size.width / CGFloat(self.chartMinutes) content.overlay( VStack { ZStack { let labels = self.makeLabels(intervalsForDay, baseSeconds: baseSeconds, xratio: xratio) ForEach(0 ..< labels.count, id: \.self) { index in let label = labels[index] Text(label.text) .font(.footnote) .frame(maxWidth: 100) .minimumScaleFactor(0.2) .foregroundColor(.white) .position(x: label.x, y: CGFloat(labelInset)) } } .frame(width: proxy.size.width, height: 25) ZStack { ForEach(0 ..< tideData.sunAndMoonEvents.count, id: \.self) { index in let event = tideData.sunAndMoonEvents[index] let minute = Int(event.eventTime!.timeIntervalSince1970 - baseSeconds) / ChartConstants.secondsPerMinute let x = CGFloat(minute) * xratio imageForEvent(event) .position(x: x) } } .frame(width: proxy.size.width, height: 15) Spacer() } ) } } } private struct TimeLabel { let x: CGFloat let text: String }
gpl-3.0
b5d3298af6f422a0aaf4939cb80cc55c
38.56383
111
0.50847
4.971925
false
false
false
false
jmfieldman/Brisk
Brisk/BriskGate.swift
1
2132
// // BriskGate.swift // Brisk // // Copyright (c) 2016-Present Jason Fieldman - https://github.com/jmfieldman/Brisk // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // BriskGate is an intelligent semaphore mechanism that can // perform waits from the main thread without freezing the // application (though it does so inefficiently). internal class BriskGate { var isMain: Bool var group: DispatchGroup? = nil var finished: Bool = false init() { isMain = Thread.current.isMainThread if !isMain { group = DispatchGroup() group!.enter() } } func signal() { finished = true if !isMain { group!.leave() } } func wait() { if isMain { while !finished { RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.1)) } } else { _ = group!.wait(timeout: DispatchTime.distantFuture) } } }
mit
d2e57cf584da6d598fd7057968ea85b7
32.3125
114
0.658537
4.441667
false
false
false
false
zyuanming/EffectDesignerX
EffectDesignerX/Model/EmitterCellModel.swift
1
5955
// // EmitterCellModel.swift // EffectDesignerX // // Created by Zhang Yuanming on 10/13/16. // Copyright © 2016 Zhang Yuanming. All rights reserved. // import Foundation class EmitterCellModel: NSObject { dynamic var birthRate: CGFloat = 0 dynamic var lifetime: CGFloat = 0 dynamic var lifetimeRange: CGFloat = 0 dynamic var velocity: CGFloat = 0 dynamic var velocityRange: CGFloat = 0 dynamic var emissionLatitude: CGFloat = 0 dynamic var emissionLongitude: CGFloat = 0 dynamic var emissionRange: CGFloat = 0 dynamic var xAcceleration: CGFloat = 0 dynamic var yAcceleration: CGFloat = 0 dynamic var zAcceleration: CGFloat = 0 dynamic var contents: String = "" dynamic var contentsRect: String = "" dynamic var name: String = "" dynamic var color: NSColor = NSColor.white dynamic var redRange: CGFloat = 0 dynamic var redSpeed: CGFloat = 0 dynamic var greenRange: CGFloat = 0 dynamic var greenSpeed: CGFloat = 0 dynamic var blueRange: CGFloat = 0 dynamic var blueSpeed: CGFloat = 0 dynamic var alpha: CGFloat = 0 dynamic var alphaRange: CGFloat = 0 dynamic var alphaSpeed: CGFloat = 0 dynamic var scale: CGFloat = 0 dynamic var scaleRange: CGFloat = 0 dynamic var scaleSpeed: CGFloat = 0 dynamic var spin: CGFloat = 0 dynamic var spinRange: CGFloat = 0 dynamic var contentsImage: NSImage? func toDictionary() -> [String: Any] { var dic: [String: Any] = [:] dic["birthRate"] = self.birthRate dic["lifetime"] = self.lifetime dic["lifetimeRange"] = self.lifetimeRange dic["velocity"] = self.velocity dic["velocityRange"] = self.velocityRange dic["emissionLatitude"] = self.emissionLatitude dic["emissionLongitude"] = self.emissionLongitude dic["emissionRange"] = self.emissionRange dic["xAcceleration"] = self.xAcceleration dic["yAcceleration"] = self.yAcceleration dic["zAcceleration"] = self.zAcceleration dic["contents"] = self.contents dic["contentsRect"] = self.contentsRect dic["name"] = self.name dic["color"] = self.color.getHexString(withAlpha: alpha) dic["redRange"] = self.redRange dic["redSpeed"] = self.redSpeed dic["greenRange"] = self.greenRange dic["greenSpeed"] = self.greenSpeed dic["blueRange"] = self.blueRange dic["blueSpeed"] = self.blueSpeed dic["alphaRange"] = self.alphaRange dic["alphaSpeed"] = self.alphaSpeed dic["scale"] = self.scale dic["scaleRange"] = self.scaleRange dic["scaleSpeed"] = self.scaleSpeed dic["spin"] = self.spin dic["spinRange"] = self.spinRange return dic } func allPropertyNames() -> [String] { return Mirror(reflecting: self).children.flatMap({ $0.label }) } func update(from effectModel: EmitterCellModel) { self.birthRate = effectModel.birthRate self.lifetime = effectModel.lifetime self.lifetimeRange = effectModel.lifetimeRange self.velocity = effectModel.velocity self.velocityRange = effectModel.velocityRange self.emissionRange = effectModel.emissionRange self.emissionLongitude = effectModel.emissionLongitude self.emissionLatitude = effectModel.emissionLatitude self.xAcceleration = effectModel.xAcceleration self.yAcceleration = effectModel.yAcceleration self.zAcceleration = effectModel.zAcceleration self.contents = effectModel.contents self.contentsRect = effectModel.contentsRect self.name = effectModel.name self.color = effectModel.color self.redRange = effectModel.redRange self.redSpeed = effectModel.redSpeed self.greenRange = effectModel.greenRange self.greenSpeed = effectModel.greenSpeed self.blueRange = effectModel.blueRange self.blueSpeed = effectModel.blueSpeed self.alpha = effectModel.alpha self.alphaRange = effectModel.alphaRange self.alphaSpeed = effectModel.alphaSpeed self.scale = effectModel.scale self.scaleRange = effectModel.scaleRange self.scaleSpeed = effectModel.scaleSpeed self.spin = effectModel.spin self.spinRange = effectModel.spinRange self.contentsImage = effectModel.contentsImage } func update2(from effectModel: BindingModel) { self.birthRate = effectModel.birthRate self.lifetime = effectModel.lifetime self.lifetimeRange = effectModel.lifetimeRange self.velocity = effectModel.velocity self.velocityRange = effectModel.velocityRange self.emissionRange = effectModel.emissionRange self.emissionLongitude = effectModel.emissionLongitude self.emissionLatitude = effectModel.emissionLatitude self.xAcceleration = effectModel.xAcceleration self.yAcceleration = effectModel.yAcceleration self.zAcceleration = effectModel.zAcceleration self.contents = effectModel.contents self.contentsRect = effectModel.contentsRect self.name = effectModel.name self.color = effectModel.color self.redRange = effectModel.redRange self.redSpeed = effectModel.redSpeed self.greenRange = effectModel.greenRange self.greenSpeed = effectModel.greenSpeed self.blueRange = effectModel.blueRange self.blueSpeed = effectModel.blueSpeed self.alpha = effectModel.alpha self.alphaRange = effectModel.alphaRange self.alphaSpeed = effectModel.alphaSpeed self.scale = effectModel.scale self.scaleRange = effectModel.scaleRange self.scaleSpeed = effectModel.scaleSpeed self.spin = effectModel.spin self.spinRange = effectModel.spinRange self.contentsImage = effectModel.contentsImage } }
mit
836a28f20b5253c4bc7c53aa3718242b
38.430464
70
0.680215
4.651563
false
false
false
false
zhouhao27/WOWRibbonView
Example/WOWRibbonView/ViewController.swift
1
1341
// // ViewController.swift // WOWRibbonView // // Created by Zhou Hao on 27/10/16. // Copyright © 2016年 Zhou Hao. All rights reserved. // import UIKit import WOWRibbonView class ViewController: UIViewController { var ribbon1 : WOWRibbonView! override func viewDidLoad() { super.viewDidLoad() self.ribbon1 = WOWRibbonView(frame: CGRect()) self.view.addSubview(self.ribbon1) let views : [String : UIView] = ["view" : self.ribbon1] // align ribbon from the left self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]", options:[], metrics: nil, views: views)); // align ribbon from the top self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-300-[view]", options: [], metrics: nil, views: views)); self.ribbon1.backgroundColor = UIColor.clear self.ribbon1.text = "Right Rift by code ..." self.ribbon1.isLeft = false self.ribbon1.isRift = true self.ribbon1.textColor = UIColor.blue self.ribbon1.fillColor = UIColor.lightGray } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3a71d42e1c8c601fba2a22be75a1efcc
28.086957
142
0.63154
4.261146
false
false
false
false
NellWatson/beddybutlerpub
Beddy Butler/ButlerTimer.swift
1
12528
// // ButlerTimer.swift // Beddy Butler // // Created by David Garces on 19/08/2015. // Copyright (c) 2015 Nell Watson Inc. All rights reserved. // import Foundation import Cocoa class ButlerTimer: NSObject { //MARK: Properties var numberOfRepeats = 5 var timer: NSTimer? /// the audio player that will be used in the play sound action var audioPlayer: AudioPlayer let butlerImage = NSImage(named: "Butler") //MARK: Computed properties //MARK: User Properties var userStartTime: Double? { get { return NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultKeys.startTimeValue.rawValue) as? Double } set { NSUserDefaults.standardUserDefaults().setDouble(newValue!, forKey: UserDefaultKeys.startTimeValue.rawValue) NSUserDefaults.standardUserDefaults().synchronize() NSNotificationCenter.defaultCenter().postNotificationName(NotificationKeys.userPreferenceChanged.rawValue, object: self) } } var userBedTime: Double? { get { return NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultKeys.bedTimeValue.rawValue) as? Double } set { NSUserDefaults.standardUserDefaults().setDouble(newValue!, forKey: UserDefaultKeys.bedTimeValue.rawValue) NSUserDefaults.standardUserDefaults().synchronize() NSNotificationCenter.defaultCenter().postNotificationName(NotificationKeys.userPreferenceChanged.rawValue, object: self) } } var userMuteSound: Bool? { set { NSUserDefaults.standardUserDefaults().setValue(newValue, forKey: UserDefaultKeys.isMuted.rawValue) } get { return NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultKeys.isMuted.rawValue) as? Bool } } ///TODO: Delete Temporary frequency variable var userSelectedFrequency: Double? { return NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultKeys.frequency.rawValue) as? Double } var userSelectedSound: AudioPlayer.AudioFiles { if let audioFile = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultKeys.selectedSound.rawValue) as? String { return AudioPlayer.AudioFiles(stringValue: audioFile) } else { return AudioPlayer.AudioFiles(stringValue: String()) } } /// Calculates the start date based on the current user value var startDate: NSDate { let calendar = NSCalendar.currentCalendar() let startOfDay = calendar.startOfDayForDate(self.currentDate) // Convert seconds to int, we are sure we will not exceed max int value as we only have 86,000 seconds or less let seconds = Int(self.userStartTime!) + NSTimeZone.systemTimeZone().secondsFromGMT return calendar.dateByAddingUnit(NSCalendarUnit.Second, value: seconds, toDate: startOfDay, options: NSCalendarOptions.MatchFirst)! } /// Gets today's date var currentDate: NSDate { let currentLocalTime = NSDate() let localTimeZone = NSTimeZone.systemTimeZone() let secondsFromGTM = NSTimeInterval.init(localTimeZone.secondsFromGMT) let resultDate = NSDate(timeInterval: secondsFromGTM, sinceDate: currentLocalTime) return resultDate } /// Calculates the end date based on the current user value var bedDate: NSDate { let calendar = NSCalendar.currentCalendar() let startOfDay = calendar.startOfDayForDate(self.currentDate) // Convert seconds to int, we are sure we will not exceed max int value as we only have 86,000 seconds or less let seconds = Int(self.userBedTime!) + NSTimeZone.systemTimeZone().secondsFromGMT return calendar.dateByAddingUnit(NSCalendarUnit.Second, value: seconds, toDate: startOfDay, options: NSCalendarOptions.MatchFirst)! } //MARK: Initialisers and deinitialisers override init() { self.audioPlayer = AudioPlayer() super.init() // Not to be called directly... calculateNewTimer() // Register observers to recalculate the timer NSNotificationCenter.defaultCenter().addObserver(self, selector: "calculateNewTimer", name: NotificationKeys.userPreferenceChanged.rawValue , object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "validateUserTimeValue", name: NSUserDefaultsDidChangeNotification , object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUserTimeValue:", name: NotificationKeys.startSliderChanged.rawValue , object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUserTimeValue:", name: NotificationKeys.endSliderChanged.rawValue , object: nil) } deinit { timer?.invalidate() NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Timer methods /// Play sound should invalidate the current timer and schedule the next timer func playSound() { //let previousImage = AppDelegate.statusItem?.image var result: String //AppDelegate.statusItem?.image = butlerImage if !userMuteSound! { audioPlayer.playFile(userSelectedSound) // TO DO: Remove temporary log result = "Sound played: \(userSelectedSound), Current time is: \(currentDate), Set Start Date: \(startDate), Set Bed Date: \(bedDate), Time between plays (frequency): \(userSelectedFrequency!) \n" } else { // TO DO: Remove temporary log result = "Muted by user: \(userSelectedSound), Current time is: \(currentDate), Set Start Date: \(startDate), Set Bed Date: \(bedDate), Time between plays (frequency): \(userSelectedFrequency!) \n" } writeToLogFile(result) NSLog(result) calculateNewTimer() //AppDelegate.statusItem?.image = previousImage } func calculateNewTimer() { //Invalidate curent timer if let theTimer = timer { theTimer.invalidate() } var newInterval = randomInterval let dateAfterInterval = NSDate(timeInterval: randomInterval, sinceDate: self.currentDate) //Analyse interval: // 1. If Now + interval or Now alone are before start time (date), create interval from now until after start date + (5-20min) if self.startDate.isGreaterThan(dateAfterInterval) { newInterval = self.startDate.timeIntervalSinceDate(self.currentDate) + newInterval setNewTimer(newInterval) } else if dateAfterInterval.isGreaterThan(self.startDate) && self.bedDate.isGreaterThan(dateAfterInterval) { setNewTimer(newInterval) } else { //the date will be after the interval so we calculate a new interval for tomorrow let calendar = NSCalendar.currentCalendar() let components = NSDateComponents() components.day = 1 components.second = Int(newInterval) let theNewDate = calendar.dateByAddingComponents(components, toDate: self.startDate, options: NSCalendarOptions.MatchFirst) newInterval = theNewDate!.timeIntervalSinceDate(self.currentDate) setNewTimer(newInterval) // finally we make sure that the sound is not muted anymore self.userMuteSound = false } } /// Invalidates the current timer and sets a new timer using the specified interval func setNewTimer(timeInterval: NSTimeInterval) { // Shcedule timer with the initial value self.timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "playSound", userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes) //TODO: Remove log entry NSLog("Timer created for interval: \(timeInterval)") } /** Create a random number of seconds from the range of 5 to 20 minutes (i.e. 300 to 1200 secs) arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two. - Returns: If the user has selected a frequency, a random number in that frequency, otherwise a random number between 5 and 20 minutes. ref: http://stackoverflow.com/questions/3420581/how-to-select-range-of-values-when-using-arc4random ref: https://en.wikipedia.org/wiki/Fisher–Yates_shuffle#Modulo_bias */ var randomInterval: NSTimeInterval { var randomStart: UInt32 var randomEnd: UInt32 if let theKey = userSelectedFrequency { randomStart = UInt32(theKey * 60) randomEnd = UInt32( ( (theKey * 0.7) + theKey) * 60 ) } else { randomStart = 300 randomEnd = 901 } let source = arc4random_uniform(randomEnd) // should return a random number between 0 and 900 return NSTimeInterval(source + randomStart) // adding 300 will ensure that it will always be from 300 to 1200 } //MARK: Ratio handling func updateUserTimeValue(notification: NSNotification) { if let newValue = notification.object as? Double { switch notification.name { case NotificationKeys.startSliderChanged.rawValue: //let convertedValue = newValue < 0.5 ? newValue * 86400 : (newValue + 0.080) * 86400 let convertedValue = newValue * 86400 / 0.92 self.userStartTime = convertedValue case NotificationKeys.endSliderChanged.rawValue: //let convertedValue = newValue > 0.5 ? newValue * 86400 : (newValue - 0.080) * 86400 let convertedValue = (newValue - 0.080) * 86400 / 0.92 self.userBedTime = convertedValue default: break; } } } func validateUserTimeValue() { let timeGap = 7200.00 let maxTime = 86400.00 if userBedTime < userStartTime { if userStartTime! + timeGap > maxTime { userStartTime = userBedTime! - timeGap } else { userBedTime! = userStartTime! + timeGap } } } // TODO: Remove test interval - var testInteval: NSTimeInterval { return NSTimeInterval(arc4random_uniform(100)) } //TODO: Remove log file and logging functionality - func writeToLogFile(message: String){ //Create file manager instance let fileManager = NSFileManager() let URLs = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask) let documentURL = URLs[0] let fileURL = documentURL.URLByAppendingPathComponent("BeddyButlerLog.txt") let data = message.dataUsingEncoding(NSUTF8StringEncoding) //if !fileManager.fileExistsAtPath(fileURL) { do { if !fileManager.fileExistsAtPath(fileURL.path!) { if !fileManager.createFileAtPath(fileURL.path!, contents: data , attributes: nil) { NSLog("File not created: \(fileURL.absoluteString)") } } let handle: NSFileHandle = try NSFileHandle(forWritingToURL: fileURL) handle.truncateFileAtOffset(handle.seekToEndOfFile()) handle.writeData(data!) handle.closeFile() } catch { NSLog("Error writing to file: \(error)") } } } extension NSDate { class func randomTimeBetweenDates(lhs: NSDate, _ rhs: NSDate) -> NSDate { let lhsInterval = lhs.timeIntervalSince1970 let rhsInterval = rhs.timeIntervalSince1970 let difference = fabs(rhsInterval - lhsInterval) let randomOffset = arc4random_uniform(UInt32(difference)) let minimum = min(lhsInterval, rhsInterval) let randomInterval = minimum + NSTimeInterval(randomOffset) return NSDate(timeIntervalSince1970: randomInterval) } }
bsd-3-clause
9e3b96449964204b8e9802b5e86ad1cf
41.175084
366
0.655596
5.230063
false
false
false
false
troystribling/BlueCap
Examples/PeripheralManager/PeripheralManager/ViewController.swift
1
10569
// // ViewController.swift // Beacon // // Created by Troy Stribling on 4/13/15. // Copyright (c) 2015 Troy Stribling. The MIT License (MIT). // import UIKit import CoreBluetooth import CoreMotion import BlueCapKit enum AppError: Error { case invalidState case resetting case poweredOff case unsupported } class ViewController: UITableViewController { @IBOutlet var xAccelerationLabel: UILabel! @IBOutlet var yAccelerationLabel: UILabel! @IBOutlet var zAccelerationLabel: UILabel! @IBOutlet var xRawAccelerationLabel: UILabel! @IBOutlet var yRawAccelerationLabel: UILabel! @IBOutlet var zRawAccelerationLabel: UILabel! @IBOutlet var rawUpdatePeriodlabel: UILabel! @IBOutlet var updatePeriodLabel: UILabel! @IBOutlet var startAdvertisingSwitch: UISwitch! @IBOutlet var startAdvertisingLabel: UILabel! @IBOutlet var enableLabel: UILabel! @IBOutlet var enabledSwitch: UISwitch! let manager = PeripheralManager(options: [CBPeripheralManagerOptionRestoreIdentifierKey : "us.gnos.BlueCap.peripheral-manager-example" as NSString]) let accelerometer = Accelerometer() let accelerometerService = MutableService(uuid: TiSensorTag.AccelerometerService.uuid) let accelerometerDataCharacteristic = MutableCharacteristic(profile: RawArrayCharacteristicProfile<TiSensorTag.AccelerometerService.Data>()) let accelerometerEnabledCharacteristic = MutableCharacteristic(profile: RawCharacteristicProfile<TiSensorTag.AccelerometerService.Enabled>()) let accelerometerUpdatePeriodCharacteristic = MutableCharacteristic(profile: RawCharacteristicProfile<TiSensorTag.AccelerometerService.UpdatePeriod>()) required init?(coder aDecoder:NSCoder) { super.init(coder: aDecoder) accelerometerService.characteristics = [accelerometerDataCharacteristic, accelerometerEnabledCharacteristic, accelerometerUpdatePeriodCharacteristic] } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.accelerometer.accelerometerAvailable { startAdvertisingSwitch.isEnabled = true startAdvertisingLabel.textColor = UIColor.black enabledSwitch.isEnabled = true enableLabel.textColor = UIColor.black updatePeriod() } else { startAdvertisingSwitch.isEnabled = false startAdvertisingSwitch.isOn = false startAdvertisingLabel.textColor = UIColor.lightGray enabledSwitch.isEnabled = false enabledSwitch.isOn = false enableLabel.textColor = UIColor.lightGray } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } @IBAction func toggleEnabled(_ sender: AnyObject) { if accelerometer.accelerometerActive { accelerometer.stopAccelerometerUpdates() } else { let accelrometerDataFuture = accelerometer.startAcceleromterUpdates() accelrometerDataFuture.onSuccess { [unowned self] data in self.updateAccelerometerData(data) } accelrometerDataFuture.onFailure { [unowned self] error in self.present(UIAlertController.alertOnError(error), animated: true, completion: nil) } } } @IBAction func toggleAdvertise(_ sender: AnyObject) { if manager.isAdvertising { accelerometerUpdatePeriodCharacteristic.stopRespondingToWriteRequests() _ = manager.stopAdvertising() } else { startAdvertising() } } func startAdvertising() { let uuid = CBUUID(string: TiSensorTag.AccelerometerService.uuid) let startAdvertiseFuture = manager.whenStateChanges().flatMap { [unowned self] state -> Future<Void> in switch state { case .poweredOn: self.manager.removeAllServices() return self.manager.add(self.accelerometerService) case .poweredOff: throw AppError.poweredOff case .unauthorized, .unknown: throw AppError.invalidState case .unsupported: throw AppError.unsupported case .resetting: throw AppError.resetting } }.flatMap { [unowned self] _ -> Future<Void> in self.manager.startAdvertising(TiSensorTag.AccelerometerService.name, uuids: [uuid]) } startAdvertiseFuture.onSuccess { [unowned self] in self.enableAdvertising() self.accelerometerEnabledCharacteristic.value = SerDe.serialize(TiSensorTag.AccelerometerService.Enabled(boolValue: self.enabledSwitch.isOn)) self.present(UIAlertController.alertWithMessage("poweredOn and started advertising"), animated: true, completion: nil) } startAdvertiseFuture.onFailure { [unowned self] error in switch error { case AppError.poweredOff: self.present(UIAlertController.alertWithMessage("PeripheralManager powered off") { _ in self.manager.reset() self.disableAdvertising() }, animated: true) case AppError.resetting: let message = "PeripheralManager state \"\(self.manager.state)\". The connection with the system bluetooth service was momentarily lost.\n Restart advertising." self.present(UIAlertController.alertWithMessage(message) { _ in self.manager.reset() }, animated: true) case AppError.unsupported: self.present(UIAlertController.alertWithMessage("Bluetooth not supported") { _ in self.disableAdvertising() }, animated: true) default: self.present(UIAlertController.alertOnError(error) { _ in self.manager.reset() }, animated: true, completion: nil) } _ = self.manager.stopAdvertising() if self.accelerometer.accelerometerActive { self.accelerometer.stopAccelerometerUpdates() self.enabledSwitch.isOn = false } } let accelerometerUpdatePeriodFuture = startAdvertiseFuture.flatMap { [unowned self] in self.accelerometerUpdatePeriodCharacteristic.startRespondingToWriteRequests(capacity: 2) } accelerometerUpdatePeriodFuture.onSuccess { [unowned self] (request, _) in guard let value = request.value, value.count > 0 && value.count <= 8 else { self.accelerometerUpdatePeriodCharacteristic.respondToRequest(request, withResult:CBATTError.invalidAttributeValueLength) return } self.accelerometerUpdatePeriodCharacteristic.value = value self.accelerometerUpdatePeriodCharacteristic.respondToRequest(request, withResult:CBATTError.success) self.updatePeriod() } let accelerometerEnabledFuture = startAdvertiseFuture.flatMap { [unowned self] in self.accelerometerEnabledCharacteristic.startRespondingToWriteRequests(capacity: 2) } accelerometerEnabledFuture.onSuccess { [unowned self] (request, _) in guard let value = request.value, value.count == 1 else { self.accelerometerEnabledCharacteristic.respondToRequest(request, withResult:CBATTError.invalidAttributeValueLength) return } self.accelerometerEnabledCharacteristic.value = request.value self.accelerometerEnabledCharacteristic.respondToRequest(request, withResult:CBATTError.success) self.updateEnabled() } } func updateAccelerometerData(_ data: CMAcceleration) { xAccelerationLabel.text = NSString(format: "%.2f", data.x) as String yAccelerationLabel.text = NSString(format: "%.2f", data.y) as String zAccelerationLabel.text = NSString(format: "%.2f", data.z) as String guard let xRaw = Int8(doubleValue: (-64.0*data.x)), let yRaw = Int8(doubleValue: (-64.0*data.y)), let zRaw = Int8(doubleValue: (64.0*data.z)) else { return } xRawAccelerationLabel.text = "\(xRaw)" yRawAccelerationLabel.text = "\(yRaw)" zRawAccelerationLabel.text = "\(zRaw)" guard let data = TiSensorTag.AccelerometerService.Data(rawValue: [xRaw, yRaw, zRaw]) else { return } if accelerometerDataCharacteristic.isUpdating { do { try accelerometerDataCharacteristic.update(withString: data.stringValue) } catch let error { Logger.debug("update failed for \(data.stringValue), \(error)") } } else { accelerometerDataCharacteristic.value = SerDe.serialize(data) } } func updatePeriod() { if let value = self.accelerometerUpdatePeriodCharacteristic.value { if let period: TiSensorTag.AccelerometerService.UpdatePeriod = SerDe.deserialize(value) { accelerometer.updatePeriod = Double(period.period)/1000.0 updatePeriodLabel.text = NSString(format: "%d", period.period) as String rawUpdatePeriodlabel.text = NSString(format: "%d", period.periodRaw) as String } } else { let updatePeriod = UInt8(accelerometer.updatePeriod * 100) if let period = TiSensorTag.AccelerometerService.UpdatePeriod(rawValue: updatePeriod) { updatePeriodLabel.text = NSString(format: "%d", period.period) as String rawUpdatePeriodlabel.text = NSString(format: "%d", period.periodRaw) as String } } } func updateEnabled() { guard let value = accelerometerEnabledCharacteristic.value, let enabled: TiSensorTag.AccelerometerService.Enabled = SerDe.deserialize(value), enabledSwitch.isOn != enabled.boolValue else { return } enabledSwitch.isOn = enabled.boolValue toggleEnabled(self) } func enableAdvertising() { startAdvertisingSwitch.isOn = true startAdvertisingSwitch.isEnabled = true startAdvertisingLabel.textColor = UIColor.black } func disableAdvertising() { startAdvertisingSwitch.isOn = false } }
mit
03966823d72900b936ab2a8b965957e6
42.673554
196
0.657489
5.232178
false
false
false
false
nathawes/swift
test/SILOptimizer/opt-remark-generator-yaml.swift
2
5123
// RUN: %target-swiftc_driver -O -Rpass-missed=sil-opt-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil %s -o /dev/null -Xfrontend -verify // RUN: %empty-directory(%t) // RUN: %target-swiftc_driver -wmo -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil -save-optimization-record=yaml -save-optimization-record-path %t/note.yaml %s -o /dev/null && %FileCheck --input-file=%t/note.yaml %s // This file is testing out the basic YAML functionality to make sure that it // works without burdening opt-remark-generator-yaml.swift with having to update all // of the yaml test cases everytime new code is added. public class Klass {} // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-opt-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 7 ]], Column: 21 } // CHECK-NEXT: Function: main // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'heap allocated ref of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: ... public var global = Klass() // expected-remark {{heap allocated ref of type 'Klass'}} // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-opt-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 12]], Column: 5 } // CHECK-NEXT: Function: 'getGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'retain of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: - InferredValue: 'of ''global''' // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE - 14]], Column: 12 } // CHECK-NEXT: ... @inline(never) public func getGlobal() -> Klass { return global // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-19:12 {{of 'global'}} } // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-opt-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 51]], Column: 11 } // CHECK-NEXT: Function: 'useGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'heap allocated ref of type ''' // CHECK-NEXT: - ValueType: // CHECK-NEXT: - String: '''' // CHECK-NEXT: ... // CHECK-NEXT: --- !Missed // CHECK-NEXT: Pass: sil-opt-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 40]], Column: 5 } // CHECK-NEXT: Function: 'useGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'retain of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: - InferredValue: 'of ''x''' // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 29]], Column: 9 } // CHECK-NEXT: ... // CHECK-NEXT: --- !Missed // CHECK-NEXT: Pass: sil-opt-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 26]], Column: 12 } // CHECK-NEXT: Function: 'useGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'release of type ''' // CHECK-NEXT: - ValueType: // CHECK-NEXT: - String: '''' // CHECK-NEXT: ... // CHECK-NEXT: --- !Missed // CHECK-NEXT: Pass: sil-opt-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 15]], Column: 12 } // CHECK-NEXT: Function: 'useGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'release of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: - InferredValue: 'of ''x''' // CHECK-NEXT: DebugLoc: { File: '{{.*}}opt-remark-generator-yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 4]], Column: 9 } // CHECK-NEXT: ... public func useGlobal() { let x = getGlobal() // Make sure that the retain msg is at the beginning of the print and the // releases are the end of the print. print(x) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-5:9 {{of 'x'}} // We test the type emission above since FileCheck can handle regex. // expected-remark @-4:12 {{release of type}} // expected-remark @-5:12 {{release of type 'Klass'}} // expected-note @-9:9 {{of 'x'}} }
apache-2.0
7a08961c0709ebb79a8d2f448d9e457f
46.878505
229
0.549483
3.456815
false
false
false
false
mathiasquintero/Sweeft
Example/Sweeft/MapColoring.swift
1
2311
// // MapColoring.swift // Sweeft // // Created by Mathias Quintero on 2/8/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Sweeft // Here's a small example on how to use the CSP Solver in Sweeft to solve map coloring // First here comes our actual work. Creating the constraints and calling the framework. protocol MapEntity: HashableNode, SimpleSyncNode { associatedtype Coloring: CSPValue, Equatable } extension MapEntity { var constraints: [Constraint<Self, Coloring>] { return neighbourIdentifiers => { .binary(self, $0, constraint: (!=)) } } static func color(entities: [Self]) -> [Self:Coloring]? { let constraints = entities.flatMap { $0.constraints } let csp = CSP<Self, Coloring>(constraints: constraints) return csp.solution() } } // Our Hardcoded Example. Coloring Australia with 3 colors enum Color: String, CSPValue { static var all: [Color] = [.red, .green, .blue] case red = "Red" case green = "Green" case blue = "Blue" } enum State: String { static var all: [State] { return [.westernAustralia, .northernTerritory, .southAustralia, .queensland, .newSouthWales, .victoria, .tasmania] } case westernAustralia = "Western Australia" case northernTerritory = "Northern Territory" case southAustralia = "South Australia" case queensland = "Queensland" case newSouthWales = "New South Wales" case victoria = "Victoria" case tasmania = "Tasmania" } extension State: MapEntity { typealias Coloring = Color var neighbourIdentifiers: [State] { switch self { case .westernAustralia: return [.northernTerritory, .southAustralia] case .northernTerritory: return [.westernAustralia, .southAustralia, .queensland] case .southAustralia: return [.westernAustralia, .northernTerritory, .queensland, .newSouthWales, .victoria] case .queensland: return [.northernTerritory, .southAustralia, .newSouthWales] case .newSouthWales: return [.queensland, .southAustralia, .victoria] case .victoria: return [.southAustralia, .newSouthWales] default: return .empty } } }
mit
23a7a89edd7feabdd92e9a553a845ec9
27.875
122
0.648918
3.780687
false
false
false
false
FromF/OlympusCameraKit
RecCameraSwift/RecCameraSwift/LiveView.swift
1
4219
// // LiveView.swift // RecCameraSwift // // Created by haruhito on 2015/04/12. // Copyright (c) 2015年 FromF. All rights reserved. // import UIKit class LiveView: UIViewController , OLYCameraLiveViewDelegate , OLYCameraRecordingSupportsDelegate { @IBOutlet weak var liveViewImage: UIImageView! @IBOutlet weak var recviewImage: UIImageView! @IBOutlet weak var infomation: UILabel! //AppDelegate instance var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Notification Regist NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationApplicationBackground:", name: UIApplicationDidEnterBackgroundNotification , object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationCameraKitDisconnect:", name: appDelegate.NotificationCameraKitDisconnect as String, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationRechabilityDisconnect:", name: appDelegate.NotificationNetworkDisconnected as String, object: nil) var camera = AppDelegate.sharedCamera camera.liveViewDelegate = self camera.recordingSupportsDelegate = self camera.connect(OLYCameraConnectionTypeWiFi, error: nil) if (camera.connected) { camera.changeRunMode(OLYCameraRunModeRecording, error: nil) camera.setCameraPropertyValue("TAKEMODE", value: "<TAKEMODE/P>", error: nil) let inquire = camera.inquireHardwareInformation(nil) as NSDictionary let modelname = inquire.objectForKey(OLYCameraHardwareInformationCameraModelNameKey) as? String let version = inquire.objectForKey(OLYCameraHardwareInformationCameraFirmwareVersionKey) as? String infomation.text = modelname! + " Ver." + version! } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) var camera = AppDelegate.sharedCamera camera.disconnectWithPowerOff(false, error: nil) } // MARK: - Button Action @IBAction func shutterButtonAction(sender: AnyObject) { var camera = AppDelegate.sharedCamera camera.takePicture(nil, progressHandler: nil, completionHandler: nil, errorHandler: nil) } // MARK: - 露出補正 @IBAction func exprevSlider(sender: AnyObject) { let slider = sender as! UISlider let index = Int(slider.value + 0.5) slider.value = Float(index) var value = NSString(format: "%+0.1f" , slider.value) if (slider.value == 0) { value = NSString(format: "%0.1f" , slider.value) } var camera = AppDelegate.sharedCamera camera.setCameraPropertyValue("EXPREV", value: "<EXPREV/" + (value as String) + ">", error: nil) } // MARK: - LiveView Update func camera(camera: OLYCamera!, didUpdateLiveView data: NSData!, metadata: [NSObject : AnyObject]!) { var image : UIImage = OLYCameraConvertDataToImage(data,metadata) self.liveViewImage.image = image } // MARK: - Recview func camera(camera: OLYCamera!, didReceiveCapturedImagePreview data: NSData!, metadata: [NSObject : AnyObject]!) { var image : UIImage = OLYCameraConvertDataToImage(data,metadata) recviewImage.image = image } // MARK: - Notification func NotificationApplicationBackground(notification : NSNotification?) { self.dismissViewControllerAnimated(true, completion: nil) } func NotificationCameraKitDisconnect(notification : NSNotification?) { self.dismissViewControllerAnimated(true, completion: nil) } func NotificationRechabilityDisconnect(notification : NSNotification?) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
9a6e33efc97f9b83769f36d3f9a49e2e
40.673267
184
0.690188
4.871528
false
false
false
false
KimBin/DTCollectionViewManager
DTCollectionViewManager/CollectionViewFactory.swift
1
6986
// // CollectionViewFactory.swift // DTCollectionViewManager // // Created by Denys Telezhkin on 23.08.15. // Copyright © 2015 Denys Telezhkin. 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 Foundation import UIKit import DTModelStorage /// Internal class, that is used to create collection view cells and supplementary views. class CollectionViewFactory { private let collectionView: UICollectionView private var mappings = [ViewModelMapping]() var bundle = NSBundle.mainBundle() init(collectionView: UICollectionView) { self.collectionView = collectionView } } private extension CollectionViewFactory { func mappingForViewType(type: ViewType,modelTypeMirror: _MirrorType) -> ViewModelMapping? { let adjustedModelTypeMirror = RuntimeHelper.classClusterReflectionFromMirrorType(modelTypeMirror) return self.mappings.filter({ (mapping) -> Bool in return mapping.viewType == type && mapping.modelTypeMirror.summary == adjustedModelTypeMirror.summary }).first } func addMappingForViewType<T:ModelTransfer>(type: ViewType, viewClass : T.Type) { if self.mappingForViewType(type, modelTypeMirror: _reflect(T.ModelType.self)) == nil { self.mappings.append(ViewModelMapping(viewType : type, viewTypeMirror : _reflect(T), modelTypeMirror: _reflect(T.ModelType.self), updateBlock: { (view, model) in (view as! T).updateWithModel(model as! T.ModelType) })) } } } // MARK: Registration extension CollectionViewFactory { func registerCellClass<T:ModelTransfer where T: UICollectionViewCell>(cellClass: T.Type) { let reuseIdentifier = RuntimeHelper.classNameFromReflection(_reflect(cellClass)) if UINib.nibExistsWithNibName(reuseIdentifier, inBundle: bundle) { collectionView.registerNib(UINib(nibName: reuseIdentifier, bundle: bundle), forCellWithReuseIdentifier: reuseIdentifier) } self.addMappingForViewType(.Cell, viewClass: T.self) } func registerNibNamed<T:ModelTransfer where T: UICollectionViewCell>(nibName: String, forCellClass cellClass: T.Type) { let reuseIdentifier = RuntimeHelper.classNameFromReflection(_reflect(cellClass)) assert(UINib.nibExistsWithNibName(reuseIdentifier, inBundle: bundle)) collectionView.registerNib(UINib(nibName: reuseIdentifier, bundle: bundle), forCellWithReuseIdentifier: reuseIdentifier) self.addMappingForViewType(.Cell, viewClass: T.self) } func registerSupplementaryClass<T:ModelTransfer where T:UICollectionReusableView>(supplementaryClass: T.Type, forKind kind: String) { let reuseIdentifier = RuntimeHelper.classNameFromReflection(_reflect(supplementaryClass)) if UINib.nibExistsWithNibName(reuseIdentifier, inBundle: bundle) { self.collectionView.registerNib(UINib(nibName: reuseIdentifier, bundle: bundle), forSupplementaryViewOfKind: kind, withReuseIdentifier: reuseIdentifier) } self.addMappingForViewType(ViewType.SupplementaryView(kind: kind), viewClass: T.self) } func registerNibNamed<T:ModelTransfer where T:UICollectionReusableView>(nibName: String, forSupplementaryClass supplementaryClass: T.Type, forKind kind: String) { let reuseIdentifier = RuntimeHelper.classNameFromReflection(_reflect(supplementaryClass)) assert(UINib.nibExistsWithNibName(nibName, inBundle: bundle)) self.collectionView.registerNib(UINib(nibName: nibName, bundle: bundle), forSupplementaryViewOfKind: kind, withReuseIdentifier: reuseIdentifier) self.addMappingForViewType(ViewType.SupplementaryView(kind: kind), viewClass: T.self) } } // MARK: View creation extension CollectionViewFactory { func cellForModel(model: Any, atIndexPath indexPath:NSIndexPath) -> UICollectionViewCell { guard let unwrappedModel = RuntimeHelper.recursivelyUnwrapAnyValue(model) else { assertionFailure("Received nil model at indexPath: \(indexPath)") return UICollectionViewCell() } let typeMirror = RuntimeHelper.mirrorFromModel(unwrappedModel) if let mapping = self.mappingForViewType(.Cell, modelTypeMirror: typeMirror) { let cellClassName = RuntimeHelper.classNameFromReflection(mapping.viewTypeMirror) let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellClassName, forIndexPath: indexPath) mapping.updateBlock(cell, unwrappedModel) return cell } assertionFailure("Unable to find cell mappings for type: \(_reflect(typeMirror.valueType).summary)") return UICollectionViewCell() } func supplementaryViewOfKind(kind: String, forModel model: Any, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { guard let unwrappedModel = RuntimeHelper.recursivelyUnwrapAnyValue(model) else { assertionFailure("Received nil model at indexPath: \(indexPath)") return UICollectionViewCell() } let typeMirror = RuntimeHelper.mirrorFromModel(unwrappedModel) if let mapping = self.mappingForViewType(ViewType.SupplementaryView(kind: kind), modelTypeMirror: typeMirror) { let viewClassName = RuntimeHelper.classNameFromReflection(mapping.viewTypeMirror) let reusableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: viewClassName, forIndexPath: indexPath) mapping.updateBlock(reusableView, unwrappedModel) return reusableView } assertionFailure("Unable to find cell mappings for type: \(_reflect(typeMirror.valueType).summary)") return UICollectionReusableView() } }
mit
d70087f9c18a51da42b925c78959bcf6
44.960526
164
0.723121
5.255831
false
false
false
false
codemonkey85/MyFirstApp
MyFirstApp/MasterViewController.swift
1
3660
// // MasterViewController.swift // MyFirstApp // // Created by Michael Bond on 3/28/15. // Copyright (c) 2015 Michael Bond. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] as NSDate let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let object = objects[indexPath.row] as NSDate cell.textLabel!.text = object.description return cell } 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 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) 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. } } }
unlicense
cc1e218fb6dd187237a76e75de3eb009
36.731959
157
0.686612
5.7277
false
false
false
false
benlangmuir/swift
test/SILOptimizer/existential_spl_witness_method.swift
4
1749
// RUN: %target-swift-frontend -O -Xllvm -sil-disable-pass=GenericSpecializer -Xllvm -sil-disable-pass=EarlyInliner -Xllvm -sil-disable-pass=PerfInliner -Xllvm -sil-disable-pass=LateInliner -emit-sil -sil-verify-all %s | %FileCheck %s // Test for ExistentialSpecializer when an existential type is passed to a witness_method func representation protocol P { @inline(never) func myfuncP(_ q:Q) -> Int } protocol Q { @inline(never) func myfuncQ() -> Int } class C : P { var id = 10 @inline(never) func myfuncP(_ q:Q) -> Int { return id } } class D : Q { var id = 20 @inline(never) func myfuncQ() -> Int { return id } } // CHECK-LABEL: @$s30existential_spl_witness_method1CCAA1PA2aDP7myfuncPySiAA1Q_pFTW : $@convention(witness_method: P) (@in_guaranteed any Q, @in_guaranteed C) -> Int { // CHECK: [[FR1:%.*]] = function_ref @$s30existential_spl_witness_method1CCAA1PA2aDP7myfuncPySiAA1Q_pFTWTf4en_n : $@convention(thin) <τ_0_0 where τ_0_0 : Q> (@in_guaranteed τ_0_0, @in_guaranteed C) -> Int // CHECK: apply [[FR1]] // CHECK-LABEL: } // end sil function '$s30existential_spl_witness_method1CCAA1PA2aDP7myfuncPySiAA1Q_pFTW' // CHECK-LABEL : @$s30existential_spl_witness_method3bazyyAA1P_p_AA1Q_ptFTf4ee_n : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : P, τ_0_1 : Q> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> () { // CHECK: [[FR2:%.*]] = function_ref @$s30existential_spl_witness_method1CCAA1PA2aDP7myfuncPySiAA1Q_pFTW : $@convention(witness_method: P) (@in_guaranteed any Q, @in_guaranteed C) -> Int // CHECK: apply [[FR2]] // CHECK-LABEL: } // end sil function '$s30existential_spl_witness_method3bazyyAA1P_p_AA1Q_ptFTf4ee_n' @inline(never) func baz(_ p : P, _ q : Q) { p.myfuncP(q) } baz(C(), D());
apache-2.0
abda40b13d8385f9693ba03fa499dec2
37.666667
234
0.687931
2.664625
false
false
false
false
kevinnguy/poppins
Poppins/Controllers/PoppinsCellController.swift
3
1153
import Runes class PoppinsCellController { let imageFetcher: ImageFetcher let path: String var observer: ViewModelObserver? var size = CGSizeZero var viewModel: PoppinsCellViewModel { didSet { observer?.viewModelDidChange() } } init(imageFetcher: ImageFetcher, path: String) { self.imageFetcher = imageFetcher self.path = path viewModel = PoppinsCellViewModel(image: .None) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func fetchImage(size: CGSize) { self.size = size if let image = imageFetcher.fetchImage(size, path: path) { viewModel = PoppinsCellViewModel(image: image) } else { NSNotificationCenter.defaultCenter().addObserver(self, selector: "cacheDidUpdate", name: "CacheDidUpdate", object: .None) } } @objc func cacheDidUpdate() { if let image = imageFetcher.fetchImage(size, path: path) { viewModel = PoppinsCellViewModel(image: image) NSNotificationCenter.defaultCenter().removeObserver(self) } } }
mit
b1867bbdff27b798a334e0a88f35d9af
27.825
133
0.638335
4.844538
false
false
false
false
gregomni/swift
test/Generics/requirement_inference.swift
3
13386
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=off // RUN: not %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s protocol P1 { func p1() } protocol P2 : P1 { } struct X1<T : P1> { func getT() -> T { } } class X2<T : P1> { func getT() -> T { } } class X3 { } struct X4<T : X3> { func getT() -> T { } } struct X5<T : P2> { } // Infer protocol requirements from the parameter type of a generic function. func inferFromParameterType<T>(_ x: X1<T>) { x.getT().p1() } // Infer protocol requirements from the return type of a generic function. func inferFromReturnType<T>(_ x: T) -> X1<T> { _ = 0 x.p1() } // Infer protocol requirements from the superclass of a generic parameter. func inferFromSuperclass<T, U : X2<T>>(_ t: T, u: U) -> T { _ = 0 t.p1() } // Infer protocol requirements from the parameter type of a constructor. struct InferFromConstructor { init<T> (x : X1<T>) { x.getT().p1() } } // Don't infer requirements for outer generic parameters. class Fox : P1 { func p1() {} } class Box<T : Fox, U> { func unpack(_ x: X1<T>) {} func unpackFail(_ X: X1<U>) { } // expected-error{{type 'U' does not conform to protocol 'P1'}} } // ---------------------------------------------------------------------------- // Superclass requirements // ---------------------------------------------------------------------------- // Compute meet of two superclass requirements correctly. class Carnivora {} class Canidae : Carnivora {} struct U<T : Carnivora> {} struct V<T : Canidae> {} // CHECK-LABEL: .inferSuperclassRequirement1@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae> func inferSuperclassRequirement1<T : Carnivora>( _ v: V<T>) {} // CHECK-LABEL: .inferSuperclassRequirement2@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae> func inferSuperclassRequirement2<T : Canidae>(_ v: U<T>) {} // ---------------------------------------------------------------------------- // Same-type requirements // ---------------------------------------------------------------------------- protocol P3 { associatedtype P3Assoc : P2 // expected-note{{declared here}} } protocol P4 { associatedtype P4Assoc : P1 } protocol PCommonAssoc1 { associatedtype CommonAssoc } protocol PCommonAssoc2 { associatedtype CommonAssoc } protocol PAssoc { associatedtype Assoc } struct Model_P3_P4_Eq<T : P3, U : P4> where T.P3Assoc == U.P4Assoc {} func inferSameType1<T, U>(_ x: Model_P3_P4_Eq<T, U>) { let u: U.P4Assoc? = nil let _: T.P3Assoc? = u! } func inferSameType2<T : P3, U : P4>(_: T, _: U) where U.P4Assoc : P2, T.P3Assoc == U.P4Assoc {} // expected-warning@-1{{redundant conformance constraint 'U.P4Assoc' : 'P2'}} // expected-note@-2{{conformance constraint 'U.P4Assoc' : 'P2' implied here}} func inferSameType3<T : PCommonAssoc1>(_: T) where T.CommonAssoc : P1, T : PCommonAssoc2 { } protocol P5 { associatedtype Element } protocol P6 { associatedtype AssocP6 : P5 } protocol P7 : P6 { associatedtype AssocP7: P6 } // CHECK-LABEL: P7@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P7, τ_0_0.[P6]AssocP6.[P5]Element : P6, τ_0_0.[P6]AssocP6.[P5]Element == τ_0_0.[P7]AssocP7.[P6]AssocP6.[P5]Element> extension P7 where AssocP6.Element : P6, // expected-note{{conformance constraint 'Self.AssocP7.AssocP6.Element' : 'P6' implied here}} AssocP7.AssocP6.Element : P6, // expected-warning{{redundant conformance constraint 'Self.AssocP7.AssocP6.Element' : 'P6'}} AssocP6.Element == AssocP7.AssocP6.Element { func nestedSameType1() { } } protocol P8 { associatedtype A associatedtype B } protocol P9 : P8 { associatedtype A associatedtype B } protocol P10 { associatedtype A associatedtype C } // CHECK-LABEL: sameTypeConcrete1@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.[P10]A == X3, τ_0_0.[P8]B == Int, τ_0_0.[P10]C == Int> func sameTypeConcrete1<T : P9 & P10>(_: T) where T.A == X3, T.C == T.B, T.C == Int { } // CHECK-LABEL: sameTypeConcrete2@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.[P8]B == X3, τ_0_0.[P10]C == X3> func sameTypeConcrete2<T : P9 & P10>(_: T) where T.B : X3, T.C == T.B, T.C == X3 { } // expected-warning@-1{{redundant superclass constraint 'T.B' : 'X3'}} // expected-note@-2{{superclass constraint 'T.B' : 'X3' implied here}} // Note: a standard-library-based stress test to make sure we don't inject // any additional requirements. // CHECK-LABEL: RangeReplaceableCollection // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : MutableCollection, τ_0_0 : RangeReplaceableCollection, τ_0_0.[Collection]SubSequence == Slice<τ_0_0>> extension RangeReplaceableCollection where Self: MutableCollection, Self.SubSequence == Slice<Self> { func f() { } } // CHECK-LABEL: X14.recursiveConcreteSameType // CHECK: Generic signature: <T, V where T == Range<Int>> // CHECK-NEXT: Canonical generic signature: <τ_0_0, τ_1_0 where τ_0_0 == Range<Int>> struct X14<T> where T.Iterator == IndexingIterator<T> { func recursiveConcreteSameType<V>(_: V) where T == Range<Int> { } } // rdar://problem/30478915 protocol P11 { associatedtype A } protocol P12 { associatedtype B: P11 } struct X6 { } struct X7 : P11 { typealias A = X6 } struct X8 : P12 { typealias B = X7 } struct X9<T: P12, U: P12> where T.B == U.B { // CHECK-LABEL: X9.upperSameTypeConstraint // CHECK: Generic signature: <T, U, V where T == X8, U : P12, U.[P12]B == X7> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 == X8, τ_0_1 : P12, τ_0_1.[P12]B == X7> func upperSameTypeConstraint<V>(_: V) where T == X8 { } } protocol P13 { associatedtype C: P11 } struct X10: P11, P12 { typealias A = X10 typealias B = X10 } struct X11<T: P12, U: P12> where T.B == U.B.A { // CHECK-LABEL: X11.upperSameTypeConstraint // CHECK: Generic signature: <T, U, V where T : P12, U == X10, T.[P12]B == X10> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P12, τ_0_1 == X10, τ_0_0.[P12]B == X10> func upperSameTypeConstraint<V>(_: V) where U == X10 { } } #if _runtime(_ObjC) // rdar://problem/30610428 @objc protocol P14 { } class X12<S: AnyObject> { func bar<V>(v: V) where S == P14 { } } @objc protocol P15: P14 { } class X13<S: P14> { func bar<V>(v: V) where S == P15 { } } #endif protocol P16 { associatedtype A } struct X15 { } struct X16<X, Y> : P16 { typealias A = (X, Y) } // CHECK-LABEL: .X17.bar@ // CHECK: Generic signature: <S, T, U, V where S == X16<X3, X15>, T == X3, U == X15> struct X17<S: P16, T, U> where S.A == (T, U) { func bar<V>(_: V) where S == X16<X3, X15> { } } // Same-type constraints that are self-derived via a parent need to be // suppressed in the resulting signature. protocol P17 { } protocol P18 { associatedtype A: P17 } struct X18: P18, P17 { typealias A = X18 } // CHECK-LABEL: .X19.foo@ // CHECK: Generic signature: <T, U where T == X18> struct X19<T: P18> where T == T.A { func foo<U>(_: U) where T == X18 { } } // rdar://problem/31520386 protocol P20 { } struct X20<T: P20> { } // CHECK-LABEL: .X21.f@ // CHECK: Generic signature: <T, U, V where T : P20, U == X20<T>> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P20, τ_0_1 == X20<τ_0_0>> struct X21<T, U> { func f<V>(_: V) where U == X20<T> { } } struct X22<T, U> { func g<V>(_: V) where T: P20, U == X20<T> { } } // CHECK: Generic signature: <Self where Self : P22> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P22> // CHECK: Protocol requirement signature: // CHECK: .P22@ // CHECK-NEXT: Requirement signature: <Self where Self.[P22]A == X20<Self.[P22]B>, Self.[P22]B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P22]A == X20<τ_0_0.[P22]B>, τ_0_0.[P22]B : P20> protocol P22 { associatedtype A associatedtype B: P20 where A == X20<B> } // CHECK: Generic signature: <Self where Self : P23> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P23> // CHECK: Protocol requirement signature: // CHECK: .P23@ // CHECK-NEXT: Requirement signature: <Self where Self.[P23]A == X20<Self.[P23]B>, Self.[P23]B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P23]A == X20<τ_0_0.[P23]B>, τ_0_0.[P23]B : P20> protocol P23 { associatedtype A associatedtype B: P20 where A == X20<B> } protocol P24 { associatedtype C: P20 } struct X24<T: P20> : P24 { typealias C = T } protocol P25c { associatedtype A: P24 associatedtype B where A == X<B> // expected-error{{cannot find type 'X' in scope}} } protocol P25d { associatedtype A associatedtype B where A == X24<B> // expected-error{{type 'Self.B' does not conform to protocol 'P20'}} } // ---------------------------------------------------------------------------- // Inference of associated type relationships within a protocol hierarchy // ---------------------------------------------------------------------------- struct X28 : P2 { func p1() { } } // CHECK-LABEL: .P28@ // CHECK-NEXT: Requirement signature: <Self where Self : P3, Self.[P3]P3Assoc == X28> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : P3, τ_0_0.[P3]P3Assoc == X28> protocol P28: P3 { typealias P3Assoc = X28 // expected-warning{{typealias overriding associated type}} } // ---------------------------------------------------------------------------- // Inference of associated types by name match // ---------------------------------------------------------------------------- protocol P29 { associatedtype X } protocol P30 { associatedtype X } protocol P31 { } // CHECK-LABEL: .sameTypeNameMatch1@ // CHECK: Generic signature: <T where T : P29, T : P30, T.[P29]X : P31> func sameTypeNameMatch1<T: P29 & P30>(_: T) where T.X: P31 { } // ---------------------------------------------------------------------------- // Infer requirements from conditional conformances // ---------------------------------------------------------------------------- protocol P32 {} protocol P33 { associatedtype A: P32 } protocol P34 {} struct Foo<T> {} extension Foo: P32 where T: P34 {} // Inference chain: U.A: P32 => Foo<V>: P32 => V: P34 // CHECK-LABEL: conditionalConformance1@ // CHECK: Generic signature: <U, V where U : P33, V : P34, U.[P33]A == Foo<V>> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1 where τ_0_0 : P33, τ_0_1 : P34, τ_0_0.[P33]A == Foo<τ_0_1>> func conditionalConformance1<U: P33, V>(_: U) where U.A == Foo<V> {} struct Bar<U: P32> {} // CHECK-LABEL: conditionalConformance2@ // CHECK: Generic signature: <V where V : P34> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P34> func conditionalConformance2<V>(_: Bar<Foo<V>>) {} // Mentioning a nested type that is conditional should infer that requirement (SR 6850) protocol P35 {} protocol P36 { func foo() } struct ConditionalNested<T> {} extension ConditionalNested where T: P35 { struct Inner {} } // CHECK: Generic signature: <T where T : P35, T : P36> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35, τ_0_0 : P36> extension ConditionalNested.Inner: P36 where T: P36 { func foo() {} struct Inner2 {} } // CHECK-LABEL: conditionalNested1@ // CHECK: Generic signature: <U where U : P35> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35> func conditionalNested1<U>(_: [ConditionalNested<U>.Inner?]) {} // CHECK-LABEL: conditionalNested2@ // CHECK: Generic signature: <U where U : P35, U : P36> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35, τ_0_0 : P36> func conditionalNested2<U>(_: [ConditionalNested<U>.Inner.Inner2?]) {} // // Generate typalias adds requirements that can be inferred // typealias X1WithP2<T: P2> = X1<T> // Inferred requirement T: P2 from the typealias func testX1WithP2<T>(_: X1WithP2<T>) { _ = X5<T>() // requires P2 } // Overload based on the inferred requirement. func testX1WithP2Overloading<T>(_: X1<T>) { _ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}} } func testX1WithP2Overloading<T>(_: X1WithP2<T>) { _ = X5<T>() // requires P2 } // Extend using the inferred requirement. extension X1WithP2 { func f() { _ = X5<T>() // okay: inferred T: P2 from generic typealias } } extension X1: P1 { func p1() { } } typealias X1WithP2Changed<T: P2> = X1<X1<T>> typealias X1WithP2MoreArgs<T: P2, U> = X1<T> extension X1WithP2Changed { func bad1() { _ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}} } } extension X1WithP2MoreArgs { func bad2() { _ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}} } } // Inference from protocol inheritance clauses is not allowed. typealias ExistentialP4WithP2Assoc<T: P4> = P4 where T.P4Assoc : P2 protocol P37 : ExistentialP4WithP2Assoc<Self> { } // expected-error@-1 {{type 'Self.P4Assoc' does not conform to protocol 'P2'}} extension P37 { func f() { _ = X5<P4Assoc>() // expected-error@-1 {{type 'Self.P4Assoc' does not conform to protocol 'P2'}} } }
apache-2.0
6c2be4366d624d8a55a9404c50292a76
26.784969
187
0.618679
2.971422
false
false
false
false
spritekitbook/spritekitbook-swift
Chapter 9/Start/SpaceRunner/SpaceRunner/GameTextures.swift
23
971
// // GameTextures.swift // SpaceRunner // // Created by Jeremy Novak on 8/26/16. // Copyright © 2016 Spritekit Book. All rights reserved. // import SpriteKit class GameTextures { static let sharedInstance = GameTextures() // MARK: - Private class constants private let gameSprites = "GameSprites" private let interfaceSprites = "InterfaceSprites" // MARK: - Private class variables private var interfaceSpritesAtlas = SKTextureAtlas() private var gameSpritesAtlas = SKTextureAtlas() // MARK: - Init init() { self.interfaceSpritesAtlas = SKTextureAtlas(named: interfaceSprites) self.gameSpritesAtlas = SKTextureAtlas(named: gameSprites) } // MARK: - Public convenience methods func texture(name: String) -> SKTexture { return SKTexture(imageNamed: name) } func sprite(name: String) -> SKSpriteNode { return SKSpriteNode(imageNamed: name) } }
apache-2.0
71084de3b27d1bced9257c62dd2bf0f5
25.216216
76
0.66701
4.511628
false
false
false
false
xeo-it/poggy
Poggy/ViewControllers/PoggyToolbar.swift
1
1343
// // PoggyToolbar.swift // Poggy // // Created by Francesco Pretelli on 30/04/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import Foundation import UIKit protocol PoggyToolbarDelegate{ func onPoggyToolbarButtonTouchUpInside() } class PoggyToolbar:UIToolbar{ var mainButton:UIButton = UIButton(type: UIButtonType.Custom) var poggyDelegate:PoggyToolbarDelegate? override func layoutSubviews() { super.layoutSubviews() barStyle = UIBarStyle.BlackOpaque backgroundColor = UIColor.clearColor()// PoggyConstants.POGGY_BLUE mainButton.backgroundColor = PoggyConstants.POGGY_BLUE //mainButton.titleLabel?.font = YNCSS.sharedInstance.getFont(21, style: YNCSS.FontStyle.REGULAR) mainButton.setTitleColor(UIColor.blackColor(), forState: .Normal) mainButton.frame = CGRect(x: 0,y: 0,width: frame.width, height: frame.height) mainButton.addTarget(self, action: #selector(self.onButtonTouchUpInside(_:)), forControlEvents: .TouchUpInside) addSubview(mainButton) } func setButtonTitle(title:String){ mainButton.setTitle(title,forState: UIControlState.Normal) } func onButtonTouchUpInside(sender: UIButton!) { poggyDelegate?.onPoggyToolbarButtonTouchUpInside() } }
apache-2.0
e0a80ce894d083995613f79c9b58644a
30.97619
119
0.707899
4.518519
false
false
false
false
AnarchyTools/atpm
atpm/src/lockfile.swift
1
10290
// Copyright (c) 2016 Anarchy Tools Contributors. // // 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 atfoundation import atpkg enum LockFileError: Error { case NonVectorImport case ParserFailed case NonLockFile } public struct LockedPackage { public let url: String var payloads: [LockedPayload] ///Gets a payload matching the key public func payloadMatching(key: String) -> LockedPayload? { if let payload = self.payloads.filter({$0.key == key}).first { return payload } return nil } public mutating func setPayload(_ payload: LockedPayload) { for (x,p) in payloads.enumerated() { if p.key == payload.key { payloads.remove(at: x) } } self.payloads.append(payload) } ///Gets or creates a payload matching the key public mutating func createPayloadMatching(key: String) -> LockedPayload { if let payload = self.payloadMatching(key: key) { return payload } let newPayload = LockedPayload(key: key) self.payloads.append(newPayload) return newPayload } public var gitPayload : LockedPayload { get { precondition(payloads.count == 1) precondition(payloads[0].key == "git") return payloads[0] } set { precondition(newValue.key == "git") switch(payloads.count) { case 1: precondition(payloads[0].key == "git") payloads.removeFirst() payloads.append(newValue) case 0: payloads.append(newValue) default: fatalError("Not supported") } } } init(url: String, payloads: [LockedPayload]) { self.url = url self.payloads = payloads } init(package: ParseValue) { guard let kvp = package.map else { fatalError("Non-map lock package") } guard let url = kvp[Option.URL.rawValue]?.string else { fatalError("No URL for package") } self.url = url guard let payloads = kvp[Option.Payloads.rawValue]?.vector else { fatalError("No payloads for package") } self.payloads = [] for payload in payloads { let lockedPayload = LockedPayload(payload: payload)! self.payloads.append(lockedPayload) } } func serialize() -> [String] { var result = [String]() result.append("{") result.append(" :\(Option.URL.rawValue) \"\(self.url)\"") result.append(" :\(Option.Payloads.rawValue) [") for payload in payloads { result.append(contentsOf: payload.serialize()) } result.append(" ]") result.append("}") return result } public enum Option: String { case URL = "url" case Payloads = "payloads" } } public func == (lhs: LockedPackage, rhs: LockedPackage) -> Bool { return lhs.url == rhs.url } extension LockedPackage: Hashable { public var hashValue: Int { return self.url.hashValue } } public struct LockedPayload { public let key: String internal(set) public var usedCommitID: String? = nil internal(set) public var pinned: Bool? = false internal(set) public var overrideURL:String? = nil ///For manifest-based packages, the URL we chose inside the manifest internal(set) public var usedURL: String? = nil ///For manifest-based packages, the channel we loaded internal(set) public var usedVersion: String? = nil ///For manifest-based packages, the shasum of the tarball internal(set) public var shaSum: String? = nil public enum Option: String { case Key = "key" case UsedCommit = "used-commit" case Pin = "pin" case OverrideURL = "override-url" case UsedURL = "used-url" case UsedVersion = "used-version" case ShaSum = "sha-sum" public static var allOptions: [Option] { return [ Key, UsedCommit, Pin, OverrideURL, UsedURL, UsedVersion, ShaSum ] } } init(key: String) { self.key = key } init?(payload: ParseValue) { guard let kvp = payload.map else { return nil } guard let key = kvp[Option.Key.rawValue]?.string else { fatalError("No key for locked package") } self.key = key if let usedCommitID = kvp[Option.UsedCommit.rawValue]?.string { self.usedCommitID = usedCommitID } if let pinned = kvp[Option.Pin.rawValue]?.bool { self.pinned = pinned } if let overrideURL = kvp[Option.OverrideURL.rawValue]?.string { self.overrideURL = overrideURL } if let usedURL = kvp[Option.UsedURL.rawValue]?.string { self.usedURL = usedURL } if let usedVersion = kvp[Option.UsedVersion.rawValue]?.string { self.usedVersion = usedVersion } if let shaSum = kvp[Option.ShaSum.rawValue]?.string { self.shaSum = shaSum } } func serialize() -> [String] { var result = [String]() result.append("{") result.append(" :\(Option.Key.rawValue) \"\(self.key)\"") if let usedCommitID = self.usedCommitID { result.append(" :\(Option.UsedCommit.rawValue) \"\(usedCommitID)\"") } if let pinned = self.pinned { result.append(" :\(Option.Pin.rawValue) \(pinned)") } if let overrideURL = self.overrideURL { result.append(" :\(Option.OverrideURL.rawValue) \"\(overrideURL)\"") } if let usedURL = self.usedURL { result.append(" :\(Option.UsedURL.rawValue) \"\(usedURL)\"") } if let usedVersion = self.usedVersion { result.append(" :\(Option.UsedVersion.rawValue) \"\(usedVersion)\"") } if let shaSum = self.shaSum { result.append(" :\(Option.ShaSum.rawValue) \"\(shaSum)\"") } result.append("}") return result } } public func == (lhs: LockedPayload, rhs: LockedPayload) -> Bool { return lhs.key == rhs.key } extension LockedPayload: Hashable { public var hashValue: Int { return self.key.hashValue } } final public class LockFile { public enum Key: String { case LockFileTypeName = "lock-file" case Packages = "packages" static var allKeys: [Key] { return [ LockFileTypeName, Packages, ] } } public var packages: [LockedPackage] = [] public convenience init(filepath: Path) throws { guard let parser = try Parser(filepath: filepath) else { throw LockFileError.ParserFailed } let result = try parser.parse() try self.init(type: result) } public init(type: ParseType) throws { //warn on unknown keys for (k,_) in type.properties { if !Key.allKeys.map({$0.rawValue}).contains(k) { print("Warning: unknown lock-file key \(k)") } } if type.name != "lock-file" { throw LockFileError.NonLockFile } if let parsedPackages = type.properties[Key.Packages.rawValue] { guard let packages = parsedPackages.vector else { throw LockFileError.NonVectorImport } for package in packages { let lockedPackage = LockedPackage(package: package) self.packages.append(lockedPackage) } } } public init() { } public subscript(url: String) -> LockedPackage? { get { for lock in self.packages { if lock.url == url { return lock } } return nil } set(newValue) { var index: Int? = nil for lock in self.packages { if lock.url == url { index = self.packages.index(of:lock) break } } if let v = newValue { if let index = index { self.packages[index] = v } else { self.packages.append(v) } } else { if let index = index { self.packages.remove(at:index) } } } } public func serialize() -> String { var result = ";; Anarchy Tools Package Manager lock file\n;;\n" result += ";; If you want to pin a package to a git commit add a ':pin'\n" result += ";; line to that package definition. This will override all version\n" result += ";; information the build files specify.\n;;\n" result += ";; You may override the repository URL for a package by specifying\n" result += ";; it in an ':override-url' line. This is very handy if you develop\n" result += ";; the dependency in parallel to the package that uses it\n\n" result += "(\(Key.LockFileTypeName.rawValue)\n" result += " :packages [\n" for pkg in self.packages { let serialized = pkg.serialize() for line in serialized { result += " \(line)\n" } } result += " ]\n" result += ")\n" return result } }
apache-2.0
f8c249f286d6cdd597076e8714fbc560
27.904494
99
0.546453
4.454545
false
false
false
false
leftdal/youslow
iOS/YouSlow/Models/VideoModel.swift
1
2779
// // VideoModel.swift // Demo // // Created by to0 on 2/7/15. // Copyright (c) 2015 to0. All rights reserved. // import Foundation protocol VideoListProtocol { func didReloadVideoData() // func didGetCurrentISP() } private class VideoItem { var thumbnail = "" var videoId = "" var title = "" var description = "" init(thumbnail th: String, videoId id: String, title ti: String, description de: String) { thumbnail = th videoId = id title = ti description = de } } class VideoList { private var videos = [VideoItem]() var delegate: VideoListProtocol? init() { } func isValidIndex(index: Int) -> Bool { return index >= 0 && index < videos.count } func numberOfVideos() -> Int { return videos.count } func videoTitleOfIndex(index: Int) -> String { if !isValidIndex(index) { return "" } let v = videos[index] return v.title } func videoIdOfIndex(index: Int) -> String { if !isValidIndex(index) { return "" } let v = videos[index] return v.videoId } func videoThumbnailOfIndex(index: Int) -> String { if !isValidIndex(index) { return "" } let v = videos[index] return v.thumbnail } func videoDescriptionOfIndex(index: Int) -> String { if !isValidIndex(index) { return "" } let v = videos[index] return v.description } func reloadVideosFromJson(jsonObject: NSDictionary) { videos = [] if let rawItems = jsonObject["items"] as? [NSDictionary] { for rawItem: NSDictionary in rawItems { let thumbnail = (((rawItem["snippet"] as? NSDictionary)?["thumbnails"] as? NSDictionary)?["medium"] as? NSDictionary)?["url"] as? String let id = (rawItem["id"] as? NSDictionary)?["videoId"] as? String let title = (rawItem["snippet"] as? NSDictionary)?["title"] as? String let description = (rawItem["snippet"] as? NSDictionary)?["description"] as? String if thumbnail != nil && id != nil && title != nil && description != nil { videos.append(VideoItem(thumbnail: thumbnail!, videoId: id!, title: title!, description: description!)) } } } } func requestDataForRefresh(query: String) { let api = DataApi.sharedInstance api.getList(query, success: {(data: NSDictionary) -> Void in self.reloadVideosFromJson(data) self.delegate?.didReloadVideoData() }) } // func requestCurrentISP() { // } }
gpl-3.0
c102afa9a7aad5749fb413971809fde3
27.070707
152
0.554156
4.453526
false
false
false
false
nguyenantinhbk77/practice-swift
HomeKit/Managing the User's Home/Managing the User's Home/AddHomeViewController.swift
2
1552
// // AddHomeViewController.swift // Managing the User's Home // // Created by Domenico Solazzo on 09/05/15. // License MIT // import UIKit import HomeKit class AddHomeViewController: UIViewController, UITextFieldDelegate { @IBOutlet var textField:UITextField! var homeManager: HMHomeManager! override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) textField.becomeFirstResponder() } @IBAction func addHome(){ if count(textField.text) == 0{ displayAlertWithTitle("Home name", message: "Please enter the home name") return } // Add the home to the Home Manager homeManager.addHomeWithName(textField.text, completionHandler: {[weak self] (home:HMHome!, error:NSError!) -> Void in let strongSelf = self! if error != nil{ strongSelf.displayAlertWithTitle("Error", message: "\(error)") }else{ strongSelf.navigationController?.popViewControllerAnimated(true) } }) } //- MARK: Helpers func displayAlertWithTitle(title:String, message:String){ let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) presentViewController(alertController, animated: true, completion: nil) } }
mit
23e9cb063213c74963eb199efc1259fb
30.04
125
0.636598
5.296928
false
false
false
false
LoopKit/LoopKit
LoopKitUI/Views/SegmentedGaugeBar.swift
1
1057
// // SegmentedGaugeBar.swift // LoopKitUI // // Created by Anna Quinlan on 11/7/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import SwiftUI struct SegmentedGaugeBar: UIViewRepresentable { let insulinNeedsScaler: Double let startColor: UIColor let endColor: UIColor init(insulinNeedsScaler: Double, startColor: UIColor, endColor: UIColor) { self.insulinNeedsScaler = insulinNeedsScaler self.startColor = startColor self.endColor = endColor } func makeUIView(context: Context) -> SegmentedGaugeBarView { let view = SegmentedGaugeBarView() view.numberOfSegments = 2 view.startColor = startColor view.endColor = endColor view.borderWidth = 1 view.borderColor = .systemGray view.progress = insulinNeedsScaler view.isUserInteractionEnabled = false // Don't allow slider to change value based on user taps return view } func updateUIView(_ view: SegmentedGaugeBarView, context: Context) { } }
mit
cee3d187d12922640ee29c573bdfb5bf
29.171429
102
0.681818
4.672566
false
false
false
false
bravelocation/yeltzland-ios
yeltzland/BaseHostingController.swift
1
1203
// // BaseHostingController.swift // Yeltzland // // Created by John Pollard on 19/06/2022. // Copyright © 2022 John Pollard. All rights reserved. // import Foundation #if canImport(SwiftUI) import SwiftUI #endif @available(iOS 13.0, *) class BaseHostingController<Content: View>: UIHostingController<Content> { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() appearance.backgroundColor = UIColor(named: "yeltz-blue") appearance.titleTextAttributes = [.foregroundColor: UIColor.white] let buttonAppearance = UIBarButtonItemAppearance(style: .plain) buttonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.white] appearance.buttonAppearance = buttonAppearance self.navigationController?.navigationBar.standardAppearance = appearance self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance self.navigationController?.navigationBar.tintColor = UIColor.white } }
mit
aae13a0a61f07c0b002dfceaa96c1e0f
35.424242
131
0.731281
5.488584
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyerTests/AppRouting/VisibilitySelectionViewControllerSpec.swift
1
2898
import XCTest import Quick import Nimble import Fleet import RxSwift @testable import FrequentFlyer class VisibilitySelectionViewControllerSpec: QuickSpec { override func spec() { describe("VisibilitySelectionViewController") { var subject: VisibilitySelectionViewController! var mockTeamsViewController: TeamsViewController! var mockPublicPipelinesViewController: PublicPipelinesViewController! beforeEach { let storyboard = UIStoryboard(name: "Main", bundle: nil) mockTeamsViewController = try! storyboard.mockIdentifier(TeamsViewController.storyboardIdentifier, usingMockFor: TeamsViewController.self) mockPublicPipelinesViewController = try! storyboard.mockIdentifier(PublicPipelinesViewController.storyboardIdentifier, usingMockFor: PublicPipelinesViewController.self) subject = storyboard.instantiateViewController(withIdentifier: VisibilitySelectionViewController.storyboardIdentifier) as! VisibilitySelectionViewController subject.concourseURLString = "concourseURLString" } describe("After the view loads") { var navigationController: UINavigationController! beforeEach { navigationController = UINavigationController(rootViewController: subject) Fleet.setAsAppWindowRoot(navigationController) } describe("Tapping the 'View public pipelines' button") { beforeEach { subject.viewPublicPipelinesButton?.tap() } it("disables the buttons") { expect(subject.viewPublicPipelinesButton?.isEnabled).toEventually(beFalse()) expect(subject.logIntoTeamButton?.isEnabled).toEventually(beFalse()) } it("presents the \(PublicPipelinesViewController.self)") { expect(Fleet.getApplicationScreen()?.topmostViewController).toEventually(beIdenticalTo(mockPublicPipelinesViewController)) expect(mockPublicPipelinesViewController.concourseURLString).toEventually(equal("concourseURLString")) } } describe("Tapping the 'Log in to a team button'") { beforeEach { subject.logIntoTeamButton?.tap() } it("presents the \(TeamsViewController.self)") { expect(Fleet.getApplicationScreen()?.topmostViewController).toEventually(beIdenticalTo(mockTeamsViewController)) expect(mockTeamsViewController.concourseURLString).toEventually(equal("concourseURLString")) } } } } } }
apache-2.0
48289debc20b81c7869c904c99924030
42.909091
184
0.629745
6.646789
false
false
false
false
TurfDb/Turf
Turf/Extensions/SecondaryIndex/IndexedPropertyFromCollection.swift
1
940
public struct IndexedPropertyFromCollection<IndexedCollection: TurfCollection> { // MARK: Internal properties internal let propertyValueForValue: ((IndexedCollection.Value) -> SQLiteType) internal let sqliteTypeName: SQLiteTypeName internal let isNullable: Bool internal let name: String // MARK: Object lifecycle public init<T>(property: IndexedProperty<IndexedCollection, T>) { self.sqliteTypeName = T.sqliteTypeName self.isNullable = T.isNullable self.propertyValueForValue = property.propertyValueForValue self.name = property.name } // MARK: Internal methods /// TODO: Remove `@discardableResult`. @discardableResult func bindPropertyValue(_ value: IndexedCollection.Value, toSQLiteStmt stmt: OpaquePointer, atIndex index: Int32) -> Int32 { let value = propertyValueForValue(value) return value.sqliteBind(stmt, index: index) } }
mit
6616a0e7a709f48f8190741b4bd4059c
35.153846
127
0.720213
4.845361
false
false
false
false
tigerraj32/RTWebService
Example/RTWebService/ViewController.swift
1
3129
// // ViewController.swift // RTWebService // // Created by Rajan Twanabashu on 01/23/2017. // Copyright (c) 2017 Rajan Twanabashu. All rights reserved. // import UIKit import RTWebService import AEXML class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() /* let payload = RTPayload.init(parameter: ["page":2], parameterEncoding:.defaultUrl) let req = RTRequest.init(requestUrl: "https://reqres.in/api/user", requestMethod: .get, header: ["language":"en"], payload: payload) RTWebService.restCall(request: req) { (response) in print("actual output ------------------------") switch response { case .success(let res): print("response value") print(res) case .failure(let error): print("error value") print(error) } } */ //SOAP Call // Create XML Document let soap = AEXMLDocument() let envelope = soap.addChild(name: "soap:Envelope", attributes: ["xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd":"http://www.w3.org/2001/XMLSchema", "xmlns:soap":"http://schemas.xmlsoap.org/soap/envelope/"]) //let header = envelope.addChild(name: "soap:Header") let body = envelope.addChild(name: "soap:Body") let geoIp = body.addChild(name:"GetGeoIP", attributes:["xmlns":"http://www.webservicex.net/"]) geoIp.addChild(name: "IPAddress", value: "124.41.219.215", attributes: [:]) let soapPayload = RTPayload(parameter: ["soapdata" : soap.xml], parameterEncoding: .defaultUrl) let req1 = RTRequest.init(requestUrl: "http://www.webservicex.net/geoipservice.asmx", requestMethod: .post, header: ["language":"en", "SOAPAction":"http://www.webservicex.net/GetGeoIP", "length": String(soap.xml.characters.count), "Content-Type": "text/xml"], payload: soapPayload) RTWebService.soapCall(request: req1) { (response) in print("actual output ------------------------") switch response { case .success(let res): print("response value") print(res) case .failure(let error): print("error value") print(error) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f306ec673523426a8277870ced4f1923
32.645161
108
0.47619
4.998403
false
false
false
false
PeteShearer/SwiftNinja
008-Intro to Tableview/B1GTeams/B1GTeams/ViewController.swift
1
1814
// // ViewController.swift // B1GTeams // // Created by Peter Shearer on 5/14/16. // Copyright © 2016 Peter Shearer. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let b1gTeams = ["Michigan State Spartans", "Ohio State Buckeyes", "Michigan Wolverines", "Penn State Nittany Lions", "Indiana Hoosiers", "Rutgers Scarlet Knights", "Maryland Terrapins", "Iowa Hawkeyes", "Northwestern Wildcats", "Wisconsin Badgers", "Nebraska Cornhuskers", "Minnesota Golden Gophers", "Illinois Illini", "Purdue Boilermakers"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return number of rows return b1gTeams.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // dequeue a cell to use (if this is the first time, we will get a shiny new one) let cell = tableView.dequeueReusableCell(withIdentifier: "team", for: indexPath) let team = b1gTeams[indexPath.row] cell.textLabel?.text = team return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Un-highlight the row tableView.deselectRow(at: indexPath, animated: true) // Print out the team to show this is working let team = b1gTeams[indexPath.row] print(team) } }
bsd-2-clause
a46c46b3550e65c59e8f4dc6596992ff
32.574074
116
0.639272
4.368675
false
false
false
false
skladek/SKWebServiceController
Pods/Nimble/Sources/Nimble/Utils/Await.swift
10
13953
import CoreFoundation import Dispatch import Foundation #if !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) import CDispatch #endif private let timeoutLeeway = DispatchTimeInterval.milliseconds(1) private let pollLeeway = DispatchTimeInterval.milliseconds(1) /// Stores debugging information about callers internal struct WaitingInfo: CustomStringConvertible { let name: String let file: FileString let lineNumber: UInt var description: String { return "\(name) at \(file):\(lineNumber)" } } internal protocol WaitLock { func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) func releaseWaitingLock() func isWaitingLocked() -> Bool } internal class AssertionWaitLock: WaitLock { private var currentWaiter: WaitingInfo? init() { } func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) { let info = WaitingInfo(name: fnName, file: file, lineNumber: line) #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let isMainThread = Thread.isMainThread #else let isMainThread = _CFIsMainThread() #endif nimblePrecondition( isMainThread, "InvalidNimbleAPIUsage", "\(fnName) can only run on the main thread." ) nimblePrecondition( currentWaiter == nil, "InvalidNimbleAPIUsage", "Nested async expectations are not allowed to avoid creating flaky tests.\n\n" + "The call to\n\t\(info)\n" + "triggered this exception because\n\t\(currentWaiter!)\n" + "is currently managing the main run loop." ) currentWaiter = info } func isWaitingLocked() -> Bool { return currentWaiter != nil } func releaseWaitingLock() { currentWaiter = nil } } internal enum AwaitResult<T> { /// Incomplete indicates None (aka - this value hasn't been fulfilled yet) case incomplete /// TimedOut indicates the result reached its defined timeout limit before returning case timedOut /// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger /// the timeout code. /// /// This may also mean the async code waiting upon may have never actually ran within the /// required time because other timers & sources are running on the main run loop. case blockedRunLoop /// The async block successfully executed and returned a given result case completed(T) /// When a Swift Error is thrown case errorThrown(Error) /// When an Objective-C Exception is raised case raisedException(NSException) func isIncomplete() -> Bool { switch self { case .incomplete: return true default: return false } } func isCompleted() -> Bool { switch self { case .completed: return true default: return false } } } /// Holds the resulting value from an asynchronous expectation. /// This class is thread-safe at receiving an "response" to this promise. internal class AwaitPromise<T> { private(set) internal var asyncResult: AwaitResult<T> = .incomplete private var signal: DispatchSemaphore init() { signal = DispatchSemaphore(value: 1) } deinit { signal.signal() } /// Resolves the promise with the given result if it has not been resolved. Repeated calls to /// this method will resolve in a no-op. /// /// @returns a Bool that indicates if the async result was accepted or rejected because another /// value was received first. func resolveResult(_ result: AwaitResult<T>) -> Bool { if signal.wait(timeout: .now()) == .success { self.asyncResult = result return true } else { return false } } } internal struct AwaitTrigger { let timeoutSource: DispatchSourceTimer let actionSource: DispatchSourceTimer? let start: () throws -> Void } /// Factory for building fully configured AwaitPromises and waiting for their results. /// /// This factory stores all the state for an async expectation so that Await doesn't /// doesn't have to manage it. internal class AwaitPromiseBuilder<T> { let awaiter: Awaiter let waitLock: WaitLock let trigger: AwaitTrigger let promise: AwaitPromise<T> internal init( awaiter: Awaiter, waitLock: WaitLock, promise: AwaitPromise<T>, trigger: AwaitTrigger) { self.awaiter = awaiter self.waitLock = waitLock self.promise = promise self.trigger = trigger } func timeout(_ timeoutInterval: TimeInterval, forcefullyAbortTimeout: TimeInterval) -> Self { // = Discussion = // // There's a lot of technical decisions here that is useful to elaborate on. This is // definitely more lower-level than the previous NSRunLoop based implementation. // // // Why Dispatch Source? // // // We're using a dispatch source to have better control of the run loop behavior. // A timer source gives us deferred-timing control without having to rely as much on // a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.) // which is ripe for getting corrupted by application code. // // And unlike dispatch_async(), we can control how likely our code gets prioritized to // executed (see leeway parameter) + DISPATCH_TIMER_STRICT. // // This timer is assumed to run on the HIGH priority queue to ensure it maintains the // highest priority over normal application / test code when possible. // // // Run Loop Management // // In order to properly interrupt the waiting behavior performed by this factory class, // this timer stops the main run loop to tell the waiter code that the result should be // checked. // // In addition, stopping the run loop is used to halt code executed on the main run loop. #if swift(>=4.0) trigger.timeoutSource.schedule( deadline: DispatchTime.now() + timeoutInterval, repeating: .never, leeway: timeoutLeeway ) #else trigger.timeoutSource.scheduleOneshot( deadline: DispatchTime.now() + timeoutInterval, leeway: timeoutLeeway ) #endif trigger.timeoutSource.setEventHandler { guard self.promise.asyncResult.isIncomplete() else { return } let timedOutSem = DispatchSemaphore(value: 0) let semTimedOutOrBlocked = DispatchSemaphore(value: 0) semTimedOutOrBlocked.signal() let runLoop = CFRunLoopGetMain() #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let runLoopMode = CFRunLoopMode.defaultMode.rawValue #else let runLoopMode = kCFRunLoopDefaultMode #endif CFRunLoopPerformBlock(runLoop, runLoopMode) { if semTimedOutOrBlocked.wait(timeout: .now()) == .success { timedOutSem.signal() semTimedOutOrBlocked.signal() if self.promise.resolveResult(.timedOut) { CFRunLoopStop(CFRunLoopGetMain()) } } } // potentially interrupt blocking code on run loop to let timeout code run CFRunLoopStop(runLoop) let now = DispatchTime.now() + forcefullyAbortTimeout let didNotTimeOut = timedOutSem.wait(timeout: now) != .success let timeoutWasNotTriggered = semTimedOutOrBlocked.wait(timeout: .now()) == .success if didNotTimeOut && timeoutWasNotTriggered { if self.promise.resolveResult(.blockedRunLoop) { CFRunLoopStop(CFRunLoopGetMain()) } } } return self } /// Blocks for an asynchronous result. /// /// @discussion /// This function must be executed on the main thread and cannot be nested. This is because /// this function (and it's related methods) coordinate through the main run loop. Tampering /// with the run loop can cause undesirable behavior. /// /// This method will return an AwaitResult in the following cases: /// /// - The main run loop is blocked by other operations and the async expectation cannot be /// be stopped. /// - The async expectation timed out /// - The async expectation succeeded /// - The async expectation raised an unexpected exception (objc) /// - The async expectation raised an unexpected error (swift) /// /// The returned AwaitResult will NEVER be .incomplete. func wait(_ fnName: String = #function, file: FileString = #file, line: UInt = #line) -> AwaitResult<T> { waitLock.acquireWaitingLock( fnName, file: file, line: line) let capture = NMBExceptionCapture(handler: ({ exception in _ = self.promise.resolveResult(.raisedException(exception)) }), finally: ({ self.waitLock.releaseWaitingLock() })) capture.tryBlock { do { try self.trigger.start() } catch let error { _ = self.promise.resolveResult(.errorThrown(error)) } self.trigger.timeoutSource.resume() while self.promise.asyncResult.isIncomplete() { // Stopping the run loop does not work unless we run only 1 mode #if swift(>=4.2) _ = RunLoop.current.run(mode: .default, before: .distantFuture) #else _ = RunLoop.current.run(mode: .defaultRunLoopMode, before: .distantFuture) #endif } self.trigger.timeoutSource.cancel() if let asyncSource = self.trigger.actionSource { asyncSource.cancel() } } return promise.asyncResult } } internal class Awaiter { let waitLock: WaitLock let timeoutQueue: DispatchQueue let asyncQueue: DispatchQueue internal init( waitLock: WaitLock, asyncQueue: DispatchQueue, timeoutQueue: DispatchQueue) { self.waitLock = waitLock self.asyncQueue = asyncQueue self.timeoutQueue = timeoutQueue } private func createTimerSource(_ queue: DispatchQueue) -> DispatchSourceTimer { return DispatchSource.makeTimerSource(flags: .strict, queue: queue) } func performBlock<T>( file: FileString, line: UInt, _ closure: @escaping (@escaping (T) -> Void) throws -> Void ) -> AwaitPromiseBuilder<T> { let promise = AwaitPromise<T>() let timeoutSource = createTimerSource(timeoutQueue) var completionCount = 0 let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) { try closure { completionCount += 1 if completionCount < 2 { if promise.resolveResult(.completed($0)) { CFRunLoopStop(CFRunLoopGetMain()) } } else { fail("waitUntil(..) expects its completion closure to be only called once", file: file, line: line) } } } return AwaitPromiseBuilder( awaiter: self, waitLock: waitLock, promise: promise, trigger: trigger) } func poll<T>(_ pollInterval: TimeInterval, closure: @escaping () throws -> T?) -> AwaitPromiseBuilder<T> { let promise = AwaitPromise<T>() let timeoutSource = createTimerSource(timeoutQueue) let asyncSource = createTimerSource(asyncQueue) let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) { let interval = DispatchTimeInterval.nanoseconds(Int(pollInterval * TimeInterval(NSEC_PER_SEC))) #if swift(>=4.0) asyncSource.schedule(deadline: .now(), repeating: interval, leeway: pollLeeway) #else asyncSource.scheduleRepeating(deadline: .now(), interval: interval, leeway: pollLeeway) #endif asyncSource.setEventHandler { do { if let result = try closure() { if promise.resolveResult(.completed(result)) { CFRunLoopStop(CFRunLoopGetCurrent()) } } } catch let error { if promise.resolveResult(.errorThrown(error)) { CFRunLoopStop(CFRunLoopGetCurrent()) } } } asyncSource.resume() } return AwaitPromiseBuilder( awaiter: self, waitLock: waitLock, promise: promise, trigger: trigger) } } internal func pollBlock( pollInterval: TimeInterval, timeoutInterval: TimeInterval, file: FileString, line: UInt, fnName: String = #function, expression: @escaping () throws -> Bool) -> AwaitResult<Bool> { let awaiter = NimbleEnvironment.activeInstance.awaiter let result = awaiter.poll(pollInterval) { () throws -> Bool? in if try expression() { return true } return nil }.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval / 2.0).wait(fnName, file: file, line: line) return result }
mit
68b17939c64325126f048e4d445883af
35.622047
118
0.599011
5.01726
false
false
false
false
Drakken-Engine/GameEngine
DrakkenEngine_Editor/TransformsView.swift
1
11892
// // InspectorView.swift // DrakkenEngine // // Created by Allison Lindner on 14/10/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import Cocoa public let TRANSFORM_PASTEBOARD_TYPE = "drakkenengine.transforms.item.transform" class TransformsView: NSOutlineView, NSOutlineViewDataSource, NSOutlineViewDelegate, NSPasteboardItemDataProvider, NSMenuDelegate { let appDelegate = NSApplication.shared().delegate as! AppDelegate override func awakeFromNib() { setup() } private func setup() { self.dataSource = self self.delegate = self self.register(forDraggedTypes: [TRANSFORM_PASTEBOARD_TYPE, SCRIPT_PASTEBOARD_TYPE, IMAGE_PASTEBOARD_TYPE, SPRITEDEF_PASTEBOARD_TYPE]) } override func draw(_ dirtyRect: NSRect) { if self.tableColumns[0].headerCell.controlView != nil { if self.tableColumns[0].headerCell.controlView!.frame.width != superview!.frame.width - 3 { self.tableColumns[0].headerCell.controlView!.setFrameSize( NSSize(width: superview!.frame.width - 3, height: self.tableColumns[0].headerCell.controlView!.frame.size.height) ) self.tableColumns[0].sizeToFit() } } super.draw(dirtyRect) } func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { if item != nil { if let i = item as? dTransform { return i.childrenTransforms.sorted(by: { (t1, t2) -> Bool in if t1.key < t2.key { return true } return false }).flatMap({ (transform) -> dTransform in return transform.value }).count } } if let editorVC = appDelegate.editorViewController { return editorVC.editorView.scene.root.childrenTransforms.sorted(by: { (t1, t2) -> Bool in if t1.key < t2.key { return true } return false }).flatMap({ (transform) -> dTransform in return transform.value }).count } return 0 } func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { if item != nil { if let i = item as? dTransform { return i.childrenTransforms.sorted(by: { (t1, t2) -> Bool in if t1.key < t2.key { return true } return false }).flatMap({ (transform) -> dTransform in return transform.value })[index] } } if let editorVC = appDelegate.editorViewController { return editorVC.editorView.scene.root.childrenTransforms.sorted(by: { (t1, t2) -> Bool in if t1.key < t2.key { return true } return false }).flatMap({ (transform) -> dTransform in return transform.value })[index] } return 0 } func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { if let i = item as? dTransform { return i.childrenTransforms.sorted(by: { (t1, t2) -> Bool in if t1.key < t2.key { return true } return false }).flatMap({ (transform) -> dTransform in return transform.value }).count > 0 } return false } func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { var text:String = "" var cellIdentifier: String = "" if let i = item as? dTransform { if tableColumn == outlineView.tableColumns[0] { text = i.name cellIdentifier = "TransformCellID" } if let cell = outlineView.make(withIdentifier: cellIdentifier, owner: nil) as? TTransformCell { cell.transform = i cell.textField?.stringValue = text return cell } } return nil } func outlineViewSelectionDidChange(_ notification: Notification) { if let transform = item(atRow: selectedRow) as? dTransform { appDelegate.editorViewController?.selectedSpriteDef = nil appDelegate.editorViewController?.selectedTransform = transform appDelegate.editorViewController?.fileViewer.deselectAll(nil) appDelegate.editorViewController?.inspectorView.reloadData() } else { appDelegate.editorViewController?.selectedTransform = nil appDelegate.editorViewController?.inspectorView.reloadData() } } //MARK: Drag and Drop Setup func outlineView(_ outlineView: NSOutlineView, pasteboardWriterForItem item: Any) -> NSPasteboardWriting? { let pbItem = NSPasteboardItem() pbItem.setDataProvider(self, forTypes: [TRANSFORM_PASTEBOARD_TYPE]) return pbItem } func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) { appDelegate.editorViewController?.draggedTransform = draggedItems[0] as? dTransform session.draggingPasteboard.setData(Data(), forType: TRANSFORM_PASTEBOARD_TYPE) } func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: String) { let s = TRANSFORM_PASTEBOARD_TYPE item.setString(s, forType: type) } func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation { return .generic } func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool { if item == nil { if appDelegate.editorViewController!.draggedTransform != nil { appDelegate.editorViewController!.draggedTransform!.parentTransform!.remove(child: appDelegate.editorViewController!.draggedTransform!) appDelegate.editorViewController!.editorView.scene.add(transform: appDelegate.editorViewController!.draggedTransform!) endDragging() return true } return false } if let transform = item as? dTransform { if appDelegate.editorViewController?.draggedTransform != nil { if appDelegate.editorViewController!.draggedTransform!.has(child: transform) { return false } if appDelegate.editorViewController?.draggedTransform != transform { if transform.parentTransform != nil { appDelegate.editorViewController!.draggedTransform!.parentTransform!.remove(child: appDelegate.editorViewController!.draggedTransform!) transform.add(child: appDelegate.editorViewController!.draggedTransform!) transform._scene.DEBUG_MODE = false endDragging() return true } } } else if appDelegate.editorViewController!.draggedScript != nil { transform._scene.DEBUG_MODE = false transform.add(script: appDelegate.editorViewController!.draggedScript!) endDragging() return true } else if appDelegate.editorViewController!.draggedImage != nil { transform._scene.DEBUG_MODE = false let spriteDef = dSpriteDef(appDelegate.editorViewController!.draggedImage!, texture: appDelegate.editorViewController!.draggedImage!) DrakkenEngine.Register(sprite: spriteDef) DrakkenEngine.Setup() transform.add( component: dSprite.init( sprite: appDelegate.editorViewController!.draggedImage!, scale: spriteDef.scale) ) endDragging() return true } else if let spriteDef = appDelegate.editorViewController!.draggedSpriteDef { transform._scene.DEBUG_MODE = false DrakkenEngine.Register(sprite: spriteDef) DrakkenEngine.Setup() transform.add(component: dSprite(sprite: spriteDef.name, scale: spriteDef.scale, frame: 0)) endDragging() return true } } return false } private func endDragging() { appDelegate.editorViewController!.editorView.Reload() if appDelegate.editorViewController!.draggedTransform != nil { appDelegate.editorViewController!.draggedTransform = nil } else if appDelegate.editorViewController!.draggedScript != nil { appDelegate.editorViewController!.draggedScript = nil appDelegate.editorViewController?.inspectorView.reloadData() } else if appDelegate.editorViewController!.draggedImage != nil { appDelegate.editorViewController!.draggedImage = nil appDelegate.editorViewController?.inspectorView.reloadData() } else if appDelegate.editorViewController!.draggedSpriteDef != nil { appDelegate.editorViewController!.draggedSpriteDef = nil appDelegate.editorViewController?.inspectorView.reloadData() } reloadData() if self.tableColumns[0].headerCell.controlView != nil { if self.tableColumns[0].headerCell.controlView!.frame.width != superview!.frame.width - 5 { self.tableColumns[0].headerCell.controlView!.setFrameSize( NSSize(width: superview!.frame.width - 5, height: self.tableColumns[0].headerCell.controlView!.frame.size.height) ) self.tableColumns[0].sizeToFit() } } } func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) { } //Mark: Menu override func menu(for event: NSEvent) -> NSMenu? { if becomeFirstResponder() { let point = NSApplication.shared().mainWindow!.contentView!.convert(event.locationInWindow, to: self) let column = self.column(at: point) let row = self.row(at: point) if column >= 0 && row >= 0 { if let cell = self.view(atColumn: column, row: row, makeIfNecessary: false) as? TTransformCell { NSLog("\(cell.transform.name)") if self.selectedRow != row { self.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) } if let menu = cell.menu as? TransformMenu { menu.selectedTransform = cell.transform return menu } return nil } } } return nil } }
gpl-3.0
c50dc81d589551f8bb6bebd4956a4930
39.583618
162
0.564713
5.489843
false
false
false
false
nineteen-apps/swift
lessons-01/lesson4/Sources/cpf.swift
1
2551
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created: 2017-06-20 by Ronaldo Faria Lima // // This file purpose: Classe que realiza o cálculo do dígito verificador do CPF // para verificação de sua validade. import Foundation struct CPF { let cpf: String var checkDigits: Int? { return Int(cpf.substring(from: cpf.index(cpf.endIndex, offsetBy: -2))) } var calculatedCheckDigits: Int? { if let firstDigit = calculateCheckDigit(for: 10), let secondDigit = calculateCheckDigit(for: 11) { return firstDigit * 10 + secondDigit } return nil } init(cpf: String) { self.cpf = cpf } func cpfIsValid() -> Bool { if let checkDigits = checkDigits, let calculatedCheckDigits = calculatedCheckDigits { return checkDigits == calculatedCheckDigits } return false } private func calculateCheckDigit(for weight: Int) -> Int? { var ckDigit = 0 var currWeight = weight for i in cpf.characters.indices { if currWeight < 1 { break } if let digit = Int(String(cpf[i])) { ckDigit += digit * currWeight } else { return nil } currWeight -= 1 } let remainder = ckDigit % 11 ckDigit = remainder < 2 ? 0 : 11 - remainder return ckDigit } }
mit
7f244cdc6729a8084d76c78b2971afbb
33.890411
106
0.649784
4.421875
false
false
false
false
Bajocode/ExploringModerniOSArchitectures
Architectures/MVP/View/MovieCollectionViewCell.swift
1
1267
// // MovieCollectionViewCell.swift // Architectures // // Created by Fabijan Bajo on 29/05/2017. // // import UIKit class MovieCollectionViewCell: UICollectionViewCell, CellConfigurable { // MARK: - Properties @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var ratingLabel: UILabel! @IBOutlet fileprivate var thumbImageView: UIImageView! @IBOutlet fileprivate var activityIndicator: UIActivityIndicatorView! // MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() activityIndicator.startAnimating() } override func prepareForReuse() { super.prepareForReuse() activityIndicator.startAnimating() } // MARK: - Methods func configure(with object: Transportable) { let instance = object as! MovieResultsPresenter.PresentableInstance titleLabel.text = instance.title ratingLabel.text = instance.ratingText thumbImageView.downloadImage(from: instance.thumbnailURL) { if self.thumbImageView.image == nil { self.activityIndicator.startAnimating() } else { self.activityIndicator.stopAnimating() } } } }
mit
b3a9f1d72c3bb0c92cf2901ac65cd271
25.957447
75
0.654301
5.557018
false
false
false
false
Candyroot/HanekeSwift
Haneke/Haneke.swift
1
1374
// // Haneke.swift // Haneke // // Created by Hermes Pique on 9/9/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public struct HanekeGlobals { public static let Domain = "io.haneke" } public struct Shared { public static var imageCache : Cache<UIImage> { struct Static { static let name = "shared-images" static let cache = Cache<UIImage>(name: name) } return Static.cache } public static var dataCache : Cache<NSData> { struct Static { static let name = "shared-data" static let cache = Cache<NSData>(name: name) } return Static.cache } public static var stringCache : Cache<String> { struct Static { static let name = "shared-strings" static let cache = Cache<String>(name: name) } return Static.cache } public static var JSONCache : Cache<JSONData> { struct Static { static let name = "shared-json" static let cache = Cache<JSONData>(name: name) } return Static.cache } } func errorWithCode(code : Int, description : String) -> NSError { let userInfo = [NSLocalizedDescriptionKey: description] return NSError(domain: HanekeGlobals.Domain, code: code, userInfo: userInfo) }
apache-2.0
ca4f2adaf9db58bc86153d474b8dc65c
23.981818
80
0.592431
4.418006
false
false
false
false
liuguya/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBTalentCell.swift
1
2874
// // CBTalentCell.swift // TestKitchen // // Created by 阳阳 on 16/8/22. // Copyright © 2016年 liuguyang. All rights reserved. // import UIKit class CBTalentCell: UITableViewCell { @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var talentImageView: UIImageView! @IBOutlet weak var fansLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } var dataArray:Array<CGRecommendWidgetDataModel>? { didSet{ showData() } } func showData(){ //图片 if dataArray?.count>0{ let imageModel = dataArray![0] if imageModel.type == "image"{ let url = NSURL(string: imageModel.content!) let dImage = UIImage(named: "sdefaultImage") talentImageView.kf_setImageWithURL(url, placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } //名字 if dataArray?.count>1{ let nameModel = dataArray![1] if nameModel.type == "text"{ nameLabel.text = nameModel.content! } } //描述文字 if dataArray?.count>2{ let descModel = dataArray![2] if descModel.type == "text"{ descLabel.text = descModel.content! } } //粉丝数 if dataArray?.count>3{ let fansModel = dataArray![3] if fansModel.type == "text"{ fansLabel.text = fansModel.content! } } } //显示cell class func CBTalentCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withlistModel listModel:CBRecommendWidgetListModel) -> CBTalentCell{ //滚动视图 let cellId = "talentCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBTalentCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("CBTalentCell", owner: nil, options: nil).last as? CBTalentCell } //indexPath.row*4 ,4 //防止越界 if listModel.widget_data?.count > indexPath.row*4+3{ let array = NSArray(array: listModel.widget_data!) let curArray = array.subarrayWithRange(NSMakeRange(indexPath.row*4, 4)) cell?.dataArray = curArray as? Array<CGRecommendWidgetDataModel> } //cell?.dataArray = listModel return cell! } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
376a361a96c79ccd71354810f63a2111
26.970297
155
0.562124
4.72408
false
false
false
false
jixuhui/HJPlayground
HJPlayground.playground/Contents.swift
1
7118
import UIKit //@objc protocol CarProtocol { // optional var name: String{get} // optional var speed: Float{get} // optional var price: Float{get} // // optional func printMe() // optional func descriptionMe() -> String //} // //extension CarProtocol { // func printMe() { // print("The car's name is \(self.name), speed is \(String(self.speed)) km/s and price is \(String(self.price)) thousand dollar") // } // // func descriptionMe() -> String { // return "The car's name is \(self.name), speed is \(String(self.speed)) km/s and price is \(String(self.price)) thousand dollar" // } //} // //class Benz: CarProtocol { // // @objc var name: String{ // return "Mercedes-Benz" // } // // @objc var speed: Float{ // return 100.0 // } // // @objc var price: Float{ // return 100 // } //} // //class Bmw: CarProtocol { // // @objc var name: String{ // return "BMW" // } // // @objc var speed: Float{ // return 120.0 // } // // @objc var price: Float{ // return 130 // } //} // //class RichMan { // var moneyCount: String // var car: CarProtocol //protocol is type // // init(moneyCount: String, car: CarProtocol){ // self.moneyCount = moneyCount // self.car = car // } //} // //protocol TextFormator { // func textFormat() -> String? //} // //extension RichMan: TextFormator { // func textFormat() -> String? { // return self.car.name // } //} // //extension CollectionType where Generator.Element: TextFormator { // func printFormateElements() -> String { // let itemsAsText: [String] = self.map { $0.textFormat()! }//此处必须定义itemsAsText的类型为[String],否则下一句无法执行 // return "[" + itemsAsText.joinWithSeparator("、") + "]" // } //} // //var benzRich: RichMan = RichMan(moneyCount: "just a number", car: Benz()) //var bmwRich: RichMan = RichMan(moneyCount: "10 billion", car: Bmw()) // //let richMans = [benzRich,bmwRich] //print(richMans.printFormateElements()) /** * @author hubbert, 15-12-21 11:12:09 * * @brief protocol dice game * * @since */ //protocol RandomNumberGenerator { // func random() -> Double //} // ////线性同余法生成随机数:http://www.cnblogs.com/xkfz007/archive/2012/03/27/2420154.html //class LinearCongruentialGenerator: RandomNumberGenerator { // var lastRandom = 42.0 // let m = 139968.0 // let a = 3877.0 // let c = 29573.0 // func random() -> Double { // lastRandom = ((lastRandom * a + c) % m)//线性同余方程式 // return lastRandom / m // } //} // ////骰子[tóu zǐ] 色子[shǎi zǐ] // //class Dice { // let sides: Int // let generator: RandomNumberGenerator // init(sides: Int, generator: RandomNumberGenerator) { // self.sides = sides // self.generator = generator // } // func roll() -> Int { // return Int(generator.random() * Double(sides)) + 1 // } //} ////Class-Only Protocols //@objc protocol TextRepresentable: class { // optional var textualDescription: String { get } //} // //extension Dice: TextRepresentable { // @objc var textualDescription: String { // return "A \(sides)-sided dice" // } //} // //protocol DiceGame { // var dice: Dice { get } // func play() //} //protocol DiceGameDelegate { // func gameDidStart(game: DiceGame) // func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) // func gameDidEnd(game: DiceGame) //} // //class SnakesAndLadders: DiceGame { // let finalSquare = 25 // let dice = Dice(sides: 6, generator: LinearCongruentialGenerator()) // var square = 0 // var board: [Int] // init() { // board = [Int](count: finalSquare + 1, repeatedValue: 0) // board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 // board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 // } // var delegate: DiceGameDelegate? // func play() { // square = 0 // delegate?.gameDidStart(self) // gameLoop: while square != finalSquare { // let diceRoll = dice.roll() // delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll) // switch square + diceRoll { // case finalSquare: // break gameLoop // case let newSquare where newSquare > finalSquare: // continue gameLoop // default: // square += diceRoll // square += board[square] // } // } // delegate?.gameDidEnd(self) // } //} // //protocol PrettyTextRepresentable: TextRepresentable { // var prettyTextualDescription: String { get } //} // //extension SnakesAndLadders: TextRepresentable { // @objc var textualDescription: String { // return "A game of Snakes and Ladders with \(finalSquare) squares" // } //} // //extension SnakesAndLadders: PrettyTextRepresentable { // var prettyTextualDescription: String { // var output = textualDescription + ":\n" // for index in 1...finalSquare { // switch board[index] { // case let ladder where ladder > 0: // output += "▲ " // case let snake where snake < 0: // output += "▼ " // default: // output += "○ " // } // } // return output // } //} // //class DiceGameTracker: DiceGameDelegate { // var numberOfTurns = 0 // func gameDidStart(game: DiceGame) { // numberOfTurns = 0 // if game is SnakesAndLadders { // print("Started a new game of Snakes and Ladders") // } // print("The game is using a \(game.dice.sides)-sided dice") // } // func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { // ++numberOfTurns // print("Rolled a \(diceRoll)") // } // func gameDidEnd(game: DiceGame) { // print("The game lasted for \(numberOfTurns) turns") // } //} // //extension RandomNumberGenerator { // func randomBool() -> Bool { // return random() > 0.5 // } //} // //let tracker = DiceGameTracker() //let game = SnakesAndLadders() //var strTemp: String? // //if let str = strTemp as? DiceGameDelegate { // print("strTemp is adopt to DiceGameDelegate") //}else { // print("strTemp is not adopt to DiceGameDelegate") //} // //print(game.textualDescription) //print(game.prettyTextualDescription) //game.delegate = tracker //game.play() // //print("Here is a random boolean value:\(game.dice.generator.randomBool())") struct SomeStruct { var name: String var age: Int } let instanceStruct = SomeStruct(name: "Boy", age: 11) var anotherInstance = instanceStruct anotherInstance.age = 12 print(instanceStruct.name + String(instanceStruct.age)) class SomeClass { var name: String? var age: Int = 11 } let instanceClass = SomeClass() instanceClass.name = "Tom" var anotherClassIns = instanceClass anotherClassIns.name = "Bill" print(instanceClass.name)
mit
ede359b6a41bf40f5333f6cd85f8205f
25.406015
137
0.586845
3.456693
false
false
false
false
thislooksfun/Tavi
Tavi/Main/Menu/Notifications/NotificationController.swift
1
1971
// // NotificationController.swift // Tavi // // Copyright (C) 2016 thislooksfun // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import Foundation /// The `UITableViewController` in charge of the 'Notifications' section of the menu class NotificationController: PortraitTableViewController { override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if indexPath.section == 0 { let filterStateRaw = Settings.NoteType(rawValue: Settings.NotificationTypes.getWithDefault(Settings.NoteType.All.rawValue)) cell.accessoryType = (filterStateRaw.contains(Settings.NoteType.fromPos(indexPath.row))) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { var types = Settings.NoteType(rawValue: Settings.NotificationTypes.getWithDefault(Settings.NoteType.All.rawValue)) let typeForRow = Settings.NoteType.fromPos(indexPath.row) if types.contains(typeForRow) { types.remove(typeForRow) } else { types.insert(typeForRow) } Settings.NotificationTypes.set(types.rawValue) self.tableView.reloadData() } } }
gpl-3.0
62489351390dcbfce5f6c396fa1c5fa6
35.518519
168
0.760528
4.123431
false
false
false
false
jamesharrop/linear-algebra
matrix-tests.swift
1
1461
// // matrix-tests.swift // // // Created by James Harrop on 14/01/2017. // // import Foundation import Accelerate // Creating random numbers and matrices for testing func randomPositiveInt(max: Int) -> Int { var rand = Int(arc4random_uniform(UInt32(max)))+1 return rand } func randomDouble(max: Int) -> Double { let multiplyConstant = 20 var rand = Int(arc4random_uniform(UInt32(max*multiplyConstant)))+1 rand -= (max*multiplyConstant)/2 return 2*Double(rand)/Double(multiplyConstant) } func randomMatrix(rows: Int, columns: Int, maxElement: Int) -> Matrix { var returnMatrix = Matrix(rows: rows, columns: columns) for element in 0..<returnMatrix.grid.count { returnMatrix.grid[element] = randomDouble(max: maxElement) } return returnMatrix } func randomSquareMatrix(maxRow: Int, maxElement: Int) -> Matrix { let size = randomPositiveInt(max: maxRow) return randomMatrix(rows: size, columns: size, maxElement: maxElement) } // Matrix test functions func testInverseAndMultiplication() -> Bool { // Create a square matrix let m1 = randomSquareMatrix(maxRow: 10, maxElement: 100) // Invert the matrix and multiply it by itself - the answer should be the identiy matrix let m2 = (m1.inverse()*m1) // Return true if successful (to within a small tolerance) let sum = sumAllElements(m2)-Double(m2.rows) return(sum<0.000001) } testInverseAndMultiplication()
apache-2.0
daeb546d0c40b9e4f0d80f9b016fd8b7
26.055556
92
0.700205
3.589681
false
true
false
false
coryoso/HanekeSwift
Haneke/UIImageView+Haneke.swift
1
6085
// // UIImageView+Haneke.swift // Haneke // // Created by Hermes Pique on 9/17/14. // Copyright (c) 2014 Haneke. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif public extension ImageView { public var hnk_format : Format<Image> { let viewSize = self.bounds.size assert(viewSize.width > 0 && viewSize.height > 0, "[\(Mirror(reflecting: self).description) \(__FUNCTION__)]: UImageView size is zero. Set its frame, call sizeToFit or force layout first.") let scaleMode = self.hnk_scaleMode return HanekeGlobals.UIKit.formatWithSize(viewSize, scaleMode: scaleMode) } public func hnk_setImageFromURL(URL: NSURL, placeholder : Image? = nil, format : Format<Image>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((Image) -> ())? = nil) { let fetcher = NetworkFetcher<Image>(URL: URL) self.hnk_setImageFromFetcher(fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImage(@autoclosure(escaping) image: () -> Image, key: String, placeholder : Image? = nil, format : Format<Image>? = nil, success succeed : ((Image) -> ())? = nil) { let fetcher = SimpleFetcher<Image>(key: key, value: image) self.hnk_setImageFromFetcher(fetcher, placeholder: placeholder, format: format, success: succeed) } public func hnk_setImageFromFile(path: String, placeholder : Image? = nil, format : Format<Image>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((Image) -> ())? = nil) { let fetcher = DiskFetcher<Image>(path: path) self.hnk_setImageFromFetcher(fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImageFromFetcher(fetcher : Fetcher<Image>, placeholder : Image? = nil, format : Format<Image>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((Image) -> ())? = nil) { self.hnk_cancelSetImage() self.hnk_fetcher = fetcher let didSetImage = self.hnk_fetchImageForFetcher(fetcher, format: format, failure: fail, success: succeed) if didSetImage { return } if let placeholder = placeholder { self.image = placeholder } } public func hnk_cancelSetImage() { if let fetcher = self.hnk_fetcher { fetcher.cancelFetch() self.hnk_fetcher = nil } } // MARK: Internal // See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances var hnk_fetcher : Fetcher<Image>! { get { let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey) as? ObjectWrapper let fetcher = wrapper?.value as? Fetcher<Image> return fetcher } set (fetcher) { var wrapper : ObjectWrapper? if let fetcher = fetcher { wrapper = ObjectWrapper(value: fetcher) } objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var hnk_scaleMode : ImageResizer.ScaleMode { #if os(iOS) switch (self.contentMode) { case .ScaleToFill: return .Fill case .ScaleAspectFit: return .AspectFit case .ScaleAspectFill: return .AspectFill case .Redraw, .Center, .Top, .Bottom, .Left, .Right, .TopLeft, .TopRight, .BottomLeft, .BottomRight: return .None } #else switch (self.imageScaling) { case .ScaleAxesIndependently: return .Fill case .ScaleProportionallyDown, .ScaleProportionallyUpOrDown: return .AspectFit case .ScaleNone: return .None } #endif } func hnk_fetchImageForFetcher(fetcher : Fetcher<Image>, format : Format<Image>? = nil, failure fail : ((NSError?) -> ())?, success succeed : ((Image) -> ())?) -> Bool { let cache = Shared.imageCache let format = format ?? self.hnk_format if cache.formats[format.name] == nil { cache.addFormat(format) } var animated = false let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in if let strongSelf = self { if strongSelf.hnk_shouldCancelForKey(fetcher.key) { return } strongSelf.hnk_fetcher = nil fail?(error) } }) { [weak self] image in if let strongSelf = self { if strongSelf.hnk_shouldCancelForKey(fetcher.key) { return } strongSelf.hnk_setImage(image, animated: animated, success: succeed) } } animated = true return fetch.hasSucceeded } func hnk_setImage(image : Image, animated : Bool, success succeed : ((Image) -> ())?) { self.hnk_fetcher = nil if let succeed = succeed { succeed(image) } else { #if os(iOS) let duration : NSTimeInterval = animated ? 0.1 : 0 UIView.transitionWithView(self, duration: duration, options: .TransitionCrossDissolve, animations: { self.image = image }, completion: nil) #else // implement like http://stackoverflow.com/questions/2795882/how-can-i-animate-a-content-switch-in-an-nsimageview #endif } } func hnk_shouldCancelForKey(key:String) -> Bool { if self.hnk_fetcher?.key == key { return false } Log.debug("Cancelled set image for \((key as NSString).lastPathComponent)") return true } }
apache-2.0
ce901b3ac022dbdaf0e3aaf0bb43f0e1
37.757962
201
0.579622
4.677171
false
false
false
false
lvogelzang/Blocky
Blocky/Levels/Level63.swift
1
877
// // Level63.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level63: Level { let levelNumber = 63 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
747e1586b1e41e47983ce254f0dcf1cd
24.794118
89
0.573546
2.649547
false
false
false
false
JornWu/ZhiBo_Swift
ZhiBo_Swift/Class/Live/ViewController/LiveCaptureViewController.swift
1
7081
// // LiveCaptureViewController.swift // ZhiBo_Swift // // Created by JornWu on 2017/6/3. // Copyright © 2017年 Jorn.Wu([email protected]). All rights reserved. // import UIKit import LFLiveKit class LiveCaptureViewController: BaseViewController, LFLiveSessionDelegate { private lazy var session: LFLiveSession = { let audioConfiguration = LFLiveAudioConfiguration.default() let videoConfiguration = LFLiveVideoConfiguration.defaultConfiguration(for: .medium2) let session = LFLiveSession(audioConfiguration: audioConfiguration, videoConfiguration: videoConfiguration) session?.delegate = self return session! }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.gray self.setupTopControlView() self.session.preView = self.view } override func viewWillAppear(_ animated: Bool) { self.requstAVAuthorization() self.startLive() } /// /// 注意一定要在plist文件中加入获取麦克风和摄像头权限的字段 /// 开打此模块,程序会挂 /// private func requstAVAuthorization() { let videoStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) switch videoStatus { /// /// 未认证 /// case .notDetermined: AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (isAllow) in if isAllow { //self.session.running = true } }) /// /// 已经认证 /// case .authorized: //self.session.running = true break /// /// 用户拒绝 /// case .denied: self.session.running = false /// /// 用户拒绝 /// case .restricted: self.session.running = false } let audioStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeAudio) switch audioStatus { case .notDetermined: AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (isAllow) in /// /// asynchronous /// if isAllow { self.session.running = true } }) case .authorized: self.session.running = true case .denied: self.session.running = false case .restricted: self.session.running = false } } private func setupTopControlView() { let controlView = { () -> UIView in let view = UIView() view.backgroundColor = UIColor.clear self.view.addSubview(view) view.snp.makeConstraints({ (make) in make.top.left.width.equalToSuperview() make.height.equalTo(64) }) return view }() /*let openBeautifulFaceBtn*/_ = { () -> UIButton in let button = UIButton(type: .custom) button.titleLabel?.font = UIFont.systemFont(ofSize: 13) button.setImage(#imageLiteral(resourceName: "camra_beauty"), for: .normal) button.setImage(#imageLiteral(resourceName: "camra_beauty_close"), for: .selected) controlView.addSubview(button) button.snp.makeConstraints({ (make) in make.left.top.equalTo(24) make.height.equalTo(40) make.width.equalTo(40) }) button.reactive.controlEvents(.touchUpInside).observeValues { [unowned self] (btn) in btn.isSelected = !btn.isSelected self.session.beautyFace = !self.session.beautyFace } return button }() let closeBtn = { () -> UIButton in let button = UIButton(type: .custom) button.setImage(#imageLiteral(resourceName: "talk_close_40x40"), for: .normal) controlView.addSubview(button) button.snp.makeConstraints({ (make) in make.top.equalTo(24) make.right.equalTo(-24) make.height.equalTo(40) make.width.equalTo(40) }) button.reactive.controlEvents(.touchUpInside).observeValues { [unowned self] (btn) in self.stopLive() self.dismiss(animated: true, completion: nil) } return button }() /*let cameraChangeBtn*/_ = { () -> UIButton in let button = UIButton(type: .custom) button.setImage(#imageLiteral(resourceName: "camera_change_40x40"), for: .normal) controlView.addSubview(button) button.snp.makeConstraints({ (make) in make.top.equalTo(24) make.right.equalTo(closeBtn.snp.left).offset(-24) make.height.equalTo(40) make.width.equalTo(40) }) button.reactive.controlEvents(.touchUpInside).observeValues { [unowned self] (btn) in btn.isSelected = !btn.isSelected self.session.captureDevicePosition = btn.isSelected ? .back : .front } return button }() } func startLive() { let stream = LFLiveStreamInfo() stream.url = "rtmp://daniulive.com:1935/live/stream238"; session.startLive(stream) } func stopLive() { session.running = false session.stopLive() } /// /// LFLiveSessionDelegate /// func liveSession(_ session: LFLiveSession?, debugInfo: LFLiveDebug?) { print("debugInfo:", debugInfo ?? "nil") } /// /// LFLiveSessionDelegate /// func liveSession(_ session: LFLiveSession?, errorCode: LFLiveSocketErrorCode) { print("errorCode:", errorCode) } /// /// LFLiveSessionDelegate /// func liveSession(_ session: LFLiveSession?, liveStateDidChange state: LFLiveState) { print("liveStateDidChange:", state) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
62d6e37c51d346e5488c23046dd8f823
29.740088
107
0.541416
5.153619
false
false
false
false
qutheory/vapor
Sources/Development/routes.swift
1
8134
import Vapor import _Vapor3 struct Creds: Content { var email: String var password: String } public func routes(_ app: Application) throws { app.on(.GET, "ping") { req -> StaticString in return "123" as StaticString } // ( echo -e 'POST /slow-stream HTTP/1.1\r\nContent-Length: 1000000000\r\n\r\n'; dd if=/dev/zero; ) | nc localhost 8080 app.on(.POST, "slow-stream", body: .stream) { req -> EventLoopFuture<String> in let done = req.eventLoop.makePromise(of: String.self) var total = 0 req.body.drain { result in let promise = req.eventLoop.makePromise(of: Void.self) switch result { case .buffer(let buffer): req.eventLoop.scheduleTask(in: .milliseconds(1000)) { total += buffer.readableBytes promise.succeed(()) } case .error(let error): done.fail(error) case .end: promise.succeed(()) done.succeed(total.description) } // manually return pre-completed future // this should balloon in memory // return req.eventLoop.makeSucceededFuture(()) // return real future that indicates bytes were handled // this should use very little memory return promise.futureResult } return done.futureResult } app.post("login") { req -> String in let creds = try req.content.decode(Creds.self) return "\(creds)" } app.on(.POST, "large-file", body: .collect(maxSize: 1_000_000_000)) { req -> String in return req.body.data?.readableBytes.description ?? "none" } app.get("json") { req -> [String: String] in return ["foo": "bar"] }.description("returns some test json") app.webSocket("ws") { req, ws in ws.onText { ws, text in ws.send(text.reversed()) if text == "close" { ws.close(promise: nil) } } let ip = req.remoteAddress?.description ?? "<no ip>" ws.send("Hello 👋 \(ip)") } app.on(.POST, "file", body: .stream) { req -> EventLoopFuture<String> in let promise = req.eventLoop.makePromise(of: String.self) req.body.drain { result in switch result { case .buffer(let buffer): debugPrint(buffer) case .error(let error): promise.fail(error) case .end: promise.succeed("Done") } return req.eventLoop.makeSucceededFuture(()) } return promise.futureResult } app.get("shutdown") { req -> HTTPStatus in guard let running = req.application.running else { throw Abort(.internalServerError) } running.stop() return .ok } let cache = MemoryCache() app.get("cache", "get", ":key") { req -> String in guard let key = req.parameters.get("key") else { throw Abort(.internalServerError) } return "\(key) = \(cache.get(key) ?? "nil")" } app.get("cache", "set", ":key", ":value") { req -> String in guard let key = req.parameters.get("key") else { throw Abort(.internalServerError) } guard let value = req.parameters.get("value") else { throw Abort(.internalServerError) } cache.set(key, to: value) return "\(key) = \(value)" } app.get("hello", ":name") { req in return req.parameters.get("name") ?? "<nil>" } app.get("search") { req in return req.query["q"] ?? "none" } let sessions = app.grouped("sessions") .grouped(app.sessions.middleware) sessions.get("set", ":value") { req -> HTTPStatus in req.session.data["name"] = req.parameters.get("value") return .ok } sessions.get("get") { req -> String in req.session.data["name"] ?? "n/a" } sessions.get("del") { req -> String in req.session.destroy() return "done" } app.get("client") { req in return req.client.get("http://httpbin.org/status/201").map { $0.description } } app.get("client-json") { req -> EventLoopFuture<String> in struct HTTPBinResponse: Decodable { struct Slideshow: Decodable { var title: String } var slideshow: Slideshow } return req.client.get("http://httpbin.org/json") .flatMapThrowing { try $0.content.decode(HTTPBinResponse.self) } .map { $0.slideshow.title } } let users = app.grouped("users") users.get { req in return "users" } users.get(":userID") { req in return req.parameters.get("userID") ?? "no id" } app.directory.viewsDirectory = "/Users/tanner/Desktop" app.get("view") { req in req.view.render("hello.txt", ["name": "world"]) } app.get("error") { req -> String in throw TestError() } app.get("secret") { (req) -> EventLoopFuture<String> in return Environment .secret(key: "PASSWORD_SECRET", fileIO: req.application.fileio, on: req.eventLoop) .unwrap(or: Abort(.badRequest)) } app.on(.POST, "max-256", body: .collect(maxSize: 256)) { req -> HTTPStatus in print("in route") return .ok } app.on(.POST, "upload", body: .stream) { req -> EventLoopFuture<HTTPStatus> in enum BodyStreamWritingToDiskError: Error { case streamFailure(Error) case fileHandleClosedFailure(Error) case multipleFailures([BodyStreamWritingToDiskError]) } return req.application.fileio.openFile( path: "/Users/tanner/Desktop/foo.txt", mode: .write, flags: .allowFileCreation(), eventLoop: req.eventLoop ).flatMap { fileHandle in let promise = req.eventLoop.makePromise(of: HTTPStatus.self) req.body.drain { part in switch part { case .buffer(let buffer): return req.application.fileio.write( fileHandle: fileHandle, buffer: buffer, eventLoop: req.eventLoop ) case .error(let drainError): do { try fileHandle.close() promise.fail(BodyStreamWritingToDiskError.streamFailure(drainError)) } catch { promise.fail(BodyStreamWritingToDiskError.multipleFailures([ .fileHandleClosedFailure(error), .streamFailure(drainError) ])) } return req.eventLoop.makeSucceededFuture(()) case .end: do { try fileHandle.close() promise.succeed(.ok) } catch { promise.fail(BodyStreamWritingToDiskError.fileHandleClosedFailure(error)) } return req.eventLoop.makeSucceededFuture(()) } } return promise.futureResult } } } struct TestError: AbortError, DebuggableError { var status: HTTPResponseStatus { .internalServerError } var reason: String { "This is a test." } var source: ErrorSource? var stackTrace: StackTrace? init( file: String = #file, function: String = #function, line: UInt = #line, column: UInt = #column, range: Range<UInt>? = nil, stackTrace: StackTrace? = .capture(skip: 1) ) { self.source = .init( file: file, function: function, line: line, column: column, range: range ) self.stackTrace = stackTrace } }
mit
07cd3f6c22e671fb614ec3e164ef9332
30.638132
123
0.525889
4.484832
false
false
false
false
imxieyi/waifu2x-ios
waifu2x/UIImage+Bicubic.swift
1
1588
// // UIImage+Bicubic.swift // waifu2x // // Created by 谢宜 on 2017/12/29. // Copyright © 2017年 xieyi. All rights reserved. // import Foundation extension UIImage { /// Resize image using Hermite Bicubic Interpolation /// /// - Parameter scale: Scale factor /// - Returns: Generated image func bicubic(scale: Float) -> UIImage { let width = Int(self.size.width) let height = Int(self.size.height) let outw = Int(Float(width) * scale) let outh = Int(Float(height) * scale) let pixels = self.cgImage?.dataProvider?.data let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixels!) let buffer = UnsafeBufferPointer(start: data, count: 4 * width * height) let arr = Array(buffer) let bicubic = Bicubic(image: arr, channels: 4, width: width, height: height) let scaled = bicubic.resize(scale: scale) // Generate output image let cfbuffer = CFDataCreate(nil, scaled, outw * outh * 4)! let dataProvider = CGDataProvider(data: cfbuffer)! let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo.byteOrder32Big let cgImage = CGImage(width: outw, height: outh, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: outw * 4, space: colorSpace, bitmapInfo: bitmapInfo, provider: dataProvider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) let outImage = UIImage(cgImage: cgImage!) return outImage } }
mit
7dc7d6c2dcc55cc84d30c4564bf23f64
34.931818
269
0.638836
4.18254
false
false
false
false
shoheiyokoyama/SYBlinkAnimationKit
Source/Animatable.swift
2
10145
// // Animatable.swift // Pods // // Created by Shohei Yokoyama on 2016/07/29. // // import UIKit struct AnimationConstants { static let borderWidthHalf: CGFloat = 1 static let defaultDuration: CFTimeInterval = 1.5 static let rippleDiameterRatio: CGFloat = 0.7 static let rippleBorderWidth: CGFloat = 1 static let subRippleDiameterRatio: CGFloat = 0.85 static let shadowRadiusIfNotClear: CGFloat = 4 static let shadowRadius: CGFloat = 2.5 static let shadowOpacity: CGFloat = 0.5 static let fromTextColorAlpha: CGFloat = 0.15 static let rippleToAlpha: CGFloat = 0 static let rippleToScale: CGFloat = 1 } public enum SYMediaTimingFunction: Int { case linear, easeIn, easeOut, easeInEaseOut var timingFunction : CAMediaTimingFunction { switch self { case .linear: return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) case .easeIn: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) case .easeOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) case .easeInEaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } } } enum AnimationType { case border, borderWithShadow, background, ripple, text } // MARK: - Protocol - protocol Animatable { var borderColorAnimtion: CABasicAnimation { get set } var borderWidthAnimation: CABasicAnimation { get set } var shadowAnimation: CABasicAnimation { get set } var animationType: AnimationType { get set } var superLayer: CALayer { get set } var textLayer: CATextLayer { get set } var subRippleLayer: CALayer { get set } var rippleLayer: CALayer { get set } var animationDuration: CFTimeInterval { get set } var animationTimingFunction: SYMediaTimingFunction { get set } var textColor: UIColor { get set } var backgroundColor: UIColor { get set } var animationBorderColor: UIColor { get set } var animationBackgroundColor: UIColor { get set } var animationTextColor: UIColor { get set } } extension Animatable { func startAnimating() { switch animationType { case .border, .borderWithShadow: animateBorder() case .background: animateBackground() case .text: animateText() case .ripple: animateRipple() } } func stopAnimating() { superLayer.removeAllAnimations() textLayer.removeAllAnimations() subRippleLayer.removeAllAnimations() rippleLayer.removeAllAnimations() textLayer.foregroundColor = textColor.cgColor } func configureBorderAnimation() { configureBorderColorAnimation() configureBorderWidthAnimation() } func configureBorderWithShadowAnimation() { configureBorderColorAnimation() configureShadowAnimation() configureBorderWidthAnimation() } func animateBorder() { let groupAnimation = CAAnimationGroup() groupAnimation.duration = animationDuration groupAnimation.animations = [borderColorAnimtion, borderWidthAnimation] groupAnimation.timingFunction = animationTimingFunction.timingFunction groupAnimation.autoreverses = true groupAnimation.isRemovedOnCompletion = false groupAnimation.repeatCount = 1e100 animationType == .borderWithShadow ? animateBorderWithShadow(groupAnimation) : superLayer.add(groupAnimation, forKey: nil) } func animateBorderWithShadow(_ groupAnimation: CAAnimationGroup) { resetSuperLayerShadow() superLayer.masksToBounds = false superLayer.backgroundColor = backgroundColor.cgColor groupAnimation.animations?.append(shadowAnimation) superLayer.add(groupAnimation, forKey: nil) } func animateBackground() { let backgroundColorAnimation = CABasicAnimation(type: .backgroundColor) backgroundColorAnimation.fromValue = UIColor.clear.cgColor backgroundColorAnimation.toValue = animationBackgroundColor.cgColor backgroundColorAnimation.duration = animationDuration backgroundColorAnimation.autoreverses = true backgroundColorAnimation.isRemovedOnCompletion = false backgroundColorAnimation.repeatCount = 1e100 backgroundColorAnimation.timingFunction = animationTimingFunction.timingFunction superLayer.add(backgroundColorAnimation, forKey: nil) } func animateText() { let textColorAnimation = CABasicAnimation(type: .foregroundColor) textColorAnimation.duration = animationDuration textColorAnimation.autoreverses = true textColorAnimation.repeatCount = 1e100 textColorAnimation.isRemovedOnCompletion = false textColorAnimation.timingFunction = animationTimingFunction.timingFunction textColorAnimation.fromValue = animationTextColor.withAlphaComponent(AnimationConstants.fromTextColorAlpha).cgColor textColorAnimation.toValue = animationTextColor.cgColor textLayer.foregroundColor = animationTextColor.cgColor textLayer.add(textColorAnimation, forKey: nil) } func animateRipple() { let fadeOutOpacity = CABasicAnimation(type: .opacity) fadeOutOpacity.fromValue = 1 fadeOutOpacity.toValue = AnimationConstants.rippleToAlpha let scale = CABasicAnimation(type: .transformScale) scale.fromValue = 0.4 scale.toValue = AnimationConstants.rippleToScale let animationGroup = CAAnimationGroup() animationGroup.duration = animationDuration animationGroup.repeatCount = 1e100 animationGroup.isRemovedOnCompletion = false animationGroup.timingFunction = animationTimingFunction.timingFunction animationGroup.animations = [fadeOutOpacity, scale] rippleLayer.add(animationGroup, forKey: nil) subRippleLayer.add(animationGroup, forKey: nil) } func resetSuperLayerShadow() { if backgroundColor.cgColor.alpha == 1 { superLayer.shadowPath = UIBezierPath(rect: superLayer.bounds).cgPath superLayer.shadowRadius = AnimationConstants.shadowRadiusIfNotClear return } let widthHalf = AnimationConstants.borderWidthHalf let width = superLayer.frame.width let height = superLayer.frame.height let cornerRadius = superLayer.cornerRadius let pathRef = CGMutablePath() pathRef.move(to: CGPoint(x: -widthHalf, y: -widthHalf + cornerRadius)) pathRef.addArc(tangent1End: CGPoint(x: -widthHalf, y: -widthHalf), tangent2End: CGPoint(x: -widthHalf + cornerRadius, y: -widthHalf), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: width + widthHalf - cornerRadius, y: -widthHalf)) pathRef.addArc(tangent1End: CGPoint(x: width+widthHalf, y: -widthHalf), tangent2End: CGPoint(x: width + widthHalf, y: -widthHalf + cornerRadius), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: width - widthHalf, y: widthHalf + cornerRadius)) pathRef.addArc(tangent1End: CGPoint(x: width - widthHalf, y: widthHalf), tangent2End: CGPoint(x: width - widthHalf - cornerRadius, y: widthHalf), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: widthHalf + cornerRadius, y: widthHalf)) pathRef.addArc(tangent1End: CGPoint(x: widthHalf, y: widthHalf), tangent2End: CGPoint(x: widthHalf, y: widthHalf + cornerRadius), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: widthHalf, y: height - widthHalf - cornerRadius)) pathRef.addArc(tangent1End: CGPoint(x: widthHalf, y: height - widthHalf), tangent2End: CGPoint(x: widthHalf + cornerRadius, y: height - widthHalf), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: width - widthHalf - cornerRadius, y: height - widthHalf)) pathRef.addArc(tangent1End: CGPoint(x: width - widthHalf, y: height - widthHalf), tangent2End: CGPoint(x: width - widthHalf, y: height - widthHalf - cornerRadius), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: width - widthHalf, y: widthHalf + cornerRadius)) pathRef.addLine(to: CGPoint(x: width + widthHalf, y: -widthHalf + cornerRadius)) pathRef.addLine(to: CGPoint(x: width + widthHalf, y: height + widthHalf - cornerRadius)) pathRef.addArc(tangent1End: CGPoint(x: width + widthHalf, y: height + widthHalf), tangent2End: CGPoint(x: width + widthHalf - cornerRadius, y: height + widthHalf), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: -widthHalf + cornerRadius, y: height + widthHalf)) pathRef.addArc(tangent1End: CGPoint(x: -widthHalf, y: height + widthHalf), tangent2End: CGPoint(x: -widthHalf, y: height + widthHalf - cornerRadius), radius: cornerRadius) pathRef.addLine(to: CGPoint(x: -widthHalf, y: -widthHalf + cornerRadius)) pathRef.closeSubpath() superLayer.shadowPath = pathRef superLayer.shadowRadius = AnimationConstants.shadowRadius } fileprivate func configureBorderColorAnimation() { borderColorAnimtion.fromValue = UIColor.clear.cgColor borderColorAnimtion.toValue = animationBorderColor.cgColor } fileprivate func configureBorderWidthAnimation() { borderWidthAnimation.fromValue = 0 borderWidthAnimation.toValue = AnimationConstants.borderWidthHalf } fileprivate func configureShadowAnimation() { shadowAnimation.fromValue = 0 shadowAnimation.toValue = AnimationConstants.shadowOpacity } }
mit
7364db1b4b94ac9de95b037fe12da103
42.540773
193
0.674618
5.191914
false
false
false
false
Zingoer/ContainerViewApp
ContainerViewApp/ContainerViewApp/SecondViewController.swift
1
1093
// // SecondViewController.swift // ContainerViewResearchApp // // Created by Xiaoxi Pang on 10/23/15. // import Foundation import UIKit class SecondViewController: UIViewController, FooterViewDelegate { override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "secondembeddedSegue"){ if let viewController: ContainerViewController = segue.destinationViewController as? ContainerViewController{ viewController.delegate = self viewController.nextButtonTitle = "" viewController.backButtonTitle = "Back To First" viewController.backButtonTitleColor = UIColor(red: 74/255, green: 171/255, blue: 247/255, alpha: 1) } } } // MARK: - FooterView delegate methods func clickBackButton(viewController: ContainerViewController) { navigationController?.popViewControllerAnimated(true) } func clickNextButton(viewController: ContainerViewController) { print("Press the Next Button") } }
mit
cf0d29271102742a4d98a985f107a0bf
31.176471
121
0.67978
5.384236
false
false
false
false
stephentyrone/swift
test/SILGen/property_wrapper_observers.swift
7
5038
// RUN: %target-swift-emit-silgen %s | %FileCheck %s // 1. Make sure the wrapped property setter calls the observers // 2. Make sure the synthesized _modify coroutine calls the wrapped property setter @propertyWrapper struct Foo { private var _storage: [Int] = [] init(wrappedValue value: [Int]) { self._storage = value } var wrappedValue: [Int] { get { _storage } set { _storage = newValue } } } class Bar { @Foo var someArray = [1, 2, 3] { willSet {} didSet {} } } // Bar.someArray.setter // CHECK-LABEL: sil hidden [ossa] @$s26property_wrapper_observers3BarC9someArraySaySiGvs : $@convention(method) (@owned Array<Int>, @guaranteed Bar) -> () { // CHECK: bb0([[VALUE:%.*]] : @owned $Array<Int>, [[BAR:%.*]] : @guaranteed $Bar): // CHECK: [[WILLSET:%.*]] = function_ref @$s26property_wrapper_observers3BarC9someArraySaySiGvw : $@convention(method) (@guaranteed Array<Int>, @guaranteed Bar) -> () // CHECK-NEXT: [[RESULT_WS:%.*]] = apply [[WILLSET]](%{{[0-9]+}}, [[BAR]]) : $@convention(method) (@guaranteed Array<Int>, @guaranteed Bar) -> () // CHECK: [[WRAPPED_VALUE_SETTER:%.*]] = function_ref @$s26property_wrapper_observers3FooV12wrappedValueSaySiGvs : $@convention(method) (@owned Array<Int>, @inout Foo) -> () // CHECK-NEXT: [[RESULT_WVS:%.*]] = apply [[WRAPPED_VALUE_SETTER]](%{{[0-9]+}}, %{{[0-9]+}}) : $@convention(method) (@owned Array<Int>, @inout Foo) -> () // CHECK: [[DIDSET:%.*]] = function_ref @$s26property_wrapper_observers3BarC9someArraySaySiGvW : $@convention(method) (@guaranteed Bar) -> () // CHECK-NEXT: [[RESULT_DS:%.*]] = apply [[DIDSET]]([[BAR]]) : $@convention(method) (@guaranteed Bar) -> () // CHECK: } // Bar.someArray.modify // CHECK-LABEL: sil hidden [ossa] @$s26property_wrapper_observers3BarC9someArraySaySiGvM : $@yield_once @convention(method) (@guaranteed Bar) -> @yields @inout Array<Int> { // CHECK: bb0([[BAR:%.*]] : @guaranteed $Bar): // CHECK-NEXT: debug_value [[BAR]] : $Bar, let, name "self", argno 1 // CHECK-NEXT: [[ALLOC_STACK:%.*]] = alloc_stack $Array<Int> // CHECK-NEXT: // function_ref Bar.someArray.getter // CHECK-NEXT: [[GETTER:%.*]] = function_ref @$s26property_wrapper_observers3BarC9someArraySaySiGvg : $@convention(method) (@guaranteed Bar) -> @owned Array<Int> // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[BAR]]) : $@convention(method) (@guaranteed Bar) -> @owned Array<Int> // CHECK-NEXT: store [[RESULT]] to [init] [[ALLOC_STACK]] : $*Array<Int> // CHECK-NEXT: yield [[ALLOC_STACK]] : $*Array<Int>, resume bb1, unwind bb2 // CHECK: bb1: // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[ALLOC_STACK]] : $*Array<Int> // CHECK-NEXT: // function_ref Bar.someArray.setter // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s26property_wrapper_observers3BarC9someArraySaySiGvs : $@convention(method) (@owned Array<Int>, @guaranteed Bar) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[SETTER]]([[VALUE]], [[BAR]]) : $@convention(method) (@owned Array<Int>, @guaranteed Bar) -> () // CHECK-NEXT: dealloc_stack [[ALLOC_STACK]] : $*Array<Int> // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK: bb2: // CHECK-NEXT: [[NEWVALUE:%.*]] = load [copy] [[ALLOC_STACK]] : $*Array<Int> // CHECK-NEXT: // function_ref Bar.someArray.setter // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s26property_wrapper_observers3BarC9someArraySaySiGvs : $@convention(method) (@owned Array<Int>, @guaranteed Bar) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[SETTER]]([[NEWVALUE]], [[BAR]]) : $@convention(method) (@owned Array<Int>, @guaranteed Bar) -> () // CHECK-NEXT: destroy_addr [[ALLOC_STACK]] : $*Array<Int> // CHECK-NEXT: dealloc_stack [[ALLOC_STACK]] : $*Array<Int> // CHECK-NEXT: unwind // CHECK-END: } @propertyWrapper struct State { var wrappedValue: Int { get { 0 } nonmutating set {} } } struct MutatingDidSet { @State private var value: Int { mutating didSet {} } mutating func test() { value = 10 } } // MutatingDidSet.value.setter // CHECK-LABEL: sil private [ossa] @$s26property_wrapper_observers14MutatingDidSetV5value33_{{.*}} : $@convention(method) (Int, @inout MutatingDidSet) -> () { // CHECK: function_ref @$s26property_wrapper_observers5StateV12wrappedValueSivs : $@convention(method) (Int, State) -> () // CHECK: function_ref @$s26property_wrapper_observers14MutatingDidSetV5value33_{{.*}} : $@convention(method) (@inout MutatingDidSet) -> () struct MutatingWillSet { @State private var value: Int { mutating willSet {} } mutating func test() { value = 10 } } // MutatingWillSet.value.setter // CHECK-LABEL: sil private [ossa] @$s26property_wrapper_observers15MutatingWillSetV5value33_{{.*}}Sivs : $@convention(method) (Int, @inout MutatingWillSet) -> () { // CHECK: function_ref @$s26property_wrapper_observers15MutatingWillSetV5value33_{{.*}}Sivw : $@convention(method) (Int, @inout MutatingWillSet) -> () // CHECK: function_ref @$s26property_wrapper_observers5StateV12wrappedValueSivs : $@convention(method) (Int, State) -> ()
apache-2.0
41d6af5496d257157702539fbe34a6d3
44.8
173
0.653831
3.424881
false
false
false
false
andreyvit/ExpressiveCasting.swift
Sources/Casting.swift
2
6540
// // ExpressiveCasting // // Copyright (c) 2014-2015 Andrey Tarantsov <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public typealias JSONObject = [String: AnyObject] public typealias JSONArray = [AnyObject] public protocol JSONObjectConvertible { init(raw: JSONObject) throws } // MARK: Simple values public func BoolValue(optionalValue: AnyObject?) -> Bool? { if let value: AnyObject = optionalValue { if let v = value as? Bool { return v } else if let v = value as? Int { return v != 0 } else if let v = value as? String { #if swift(>=3.0) let u = v.uppercased() #else let u = v.uppercaseString #endif if (u == "YES" || u == "TRUE" || u == "ON" || u == "Y" || u == "1") { return true } else if (u == "NO" || u == "FALSE" || u == "OFF" || u == "N" || u == "0") { return false } else { return nil } } else { return nil } } else { return nil } } public func IntValue(optionalValue: AnyObject?) -> Int? { if let value: AnyObject = optionalValue { if let v = value as? Int { return v } else if let v = value as? String { if let num = Int(v) { return num } else { return nil } } else { return nil } } else { return nil } } public func DoubleValue(optionalValue: AnyObject?) -> Double? { if let value: AnyObject = optionalValue { if let v = value as? Double { return v } else if let v = value as? Int { return Double(v) } else if let v = value as? String { let scanner = NSScanner(string: v) var num: Double = 0.0 #if swift(>=3.0) let isAtEnd = scanner.isAtEnd #else let isAtEnd = scanner.atEnd #endif if scanner.scanDouble(&num) && isAtEnd { return num } else { return nil } } else { return nil } } else { return nil } } public func StringValue(optionalValue: AnyObject?) -> String? { if let value: AnyObject = optionalValue { if let v = value as? String { return v } else if let v = value as? Int { return "\(v)" } else if let v = value as? Double { return "\(v)" } else { return nil } } else { return nil } } public func NonEmptyString(optionalValue: String?, trimWhitespace: Bool = true) -> String? { if let value = optionalValue { #if swift(>=3.0) let trimmedValue: String = (trimWhitespace ? value.trimmingCharacters(in: NSCharacterSet.whitespaceAndNewline()) : value); #else let trimmedValue: String = (trimWhitespace ? value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) : value); #endif if trimmedValue.isEmpty { return nil } else { return trimmedValue } } else { return nil } } public func NonEmptyStringValue(optionalValue: AnyObject?, trimWhitespace: Bool = true) -> String? { if let value = StringValue(optionalValue) { return NonEmptyString(value, trimWhitespace: trimWhitespace) } else { return nil } } // MARK: Foundation values public func URLValue(optionalValue: AnyObject?) -> NSURL? { if let string = NonEmptyStringValue(optionalValue) { return NSURL(string: string) } else { return nil } } // MARK: Collection values public func ArrayValue<T>(optionalValue: AnyObject?, itemMapper: (AnyObject) -> T?) -> [T]? { if let value: AnyObject = optionalValue { if let array = value as? [AnyObject] { var result: [T] = [] for item in array { if let mapped = itemMapper(item) { result.append(mapped) } else { return nil } } return result } else { return nil } } else { return nil } } public func JSONObjectValue(optionalValue: AnyObject?) -> JSONObject? { return optionalValue as? [String: AnyObject] } public func JSONObjectsArrayValue(optionalValue: AnyObject?) -> [JSONObject]? { return ArrayValue(optionalValue) { JSONObjectValue($0) } } // MARK: JSONObjectConvertible public func JSONConvertibleObjectValue <T: JSONObjectConvertible> (optional: AnyObject?) -> T? { if let raw: JSONObject = JSONObjectValue(optional) { return try? T(raw: raw) } else { return nil } } public func JSONConvertibleObjectsArrayValue <T: JSONObjectConvertible> (optional: AnyObject?) -> [T]? { if let raw: [JSONObject] = JSONObjectsArrayValue(optional) { var result: [T] = [] #if swift(>=3.0) result.reserveCapacity(raw.underestimatedCount) #else result.reserveCapacity(raw.underestimateCount()) #endif for el in raw { if let output: T = try? T(raw: el) { result.append(output) } } return result } else { return nil } }
mit
7b3ef59f3c9fceda01d9974ab81292c4
28.59276
151
0.572936
4.44898
false
false
false
false
NghiaTranUIT/PullToMakeSoup
PullToMakeSoup/PullToRefresh/PullToMakeSoup/PocketSVG/PocketSVG+Extension.swift
1
1170
// // PocketSVG+Extension.swift // PullToMakeSoup // // Created by Anastasiya Gorban on 4/21/15. // Copyright (c) 2015 Yalantis. All rights reserved. // extension PocketSVG { class func pathFromSVGFileNamed( named: String, origin: CGPoint, mirrorX: Bool, mirrorY: Bool, scale: CGFloat) -> CGPath { let path = PocketSVG.pathFromSVGFileNamed(named) let bezierPath = UIBezierPath(CGPath: path.takeUnretainedValue()) bezierPath.applyTransform(CGAffineTransformMakeScale(scale, scale)) if mirrorX { let mirrorOverXOrigin = CGAffineTransformMakeScale(-1.0, 1.0) bezierPath.applyTransform(mirrorOverXOrigin) } if mirrorY { let mirrorOverYOrigin = CGAffineTransformMakeScale(1.0, -1.0) bezierPath.applyTransform(mirrorOverYOrigin) } let translate = CGAffineTransformMakeTranslation(origin.x - bezierPath.bounds.origin.x, origin.y - bezierPath.bounds.origin.y) bezierPath.applyTransform(translate) return bezierPath.CGPath } }
mit
01a0531ff45645f2ab799a457cb4ab0f
29.789474
134
0.626496
4.736842
false
false
false
false
iwheelbuy/VK
VK/Object/VK+Object+Wall.swift
1
16268
import Foundation public extension Object { /// Запись на стене пользователя или сообщества public struct Wall: Decodable { /// Информация о комментариях к записи public struct Comments: Decodable { /// Количество комментариев let count: Int? /// Информация о том, может ли текущий пользователь комментировать запись let can_post: Object.Boolean? /// Информация о том, могут ли сообщества комментировать запись let groups_can_post: Bool? } /// Информация о местоположении public struct Geo: Decodable { /// Тип места public enum Typе: Decodable { /// Место case place /// Точка case point /// Неизвестное значение case unexpected(String) init(rawValue: String) { switch rawValue { case "place": self = .place case "point": self = .point default: self = .unexpected(rawValue) } } public var rawValue: String { switch self { case .place: return "place" case .point: return "point" case .unexpected(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: String = try container.decode() self = Object.Wall.Geo.Typе(rawValue: rawValue) } } /// public enum Place { /// Описание места public struct Place: Decodable { /// Адрес public let address: String? /// Количество чекинов public let checkins: Int? /// Идентификатор города public let city: Int? /// Идентификатор страны public let country: Int? /// Дата создания (если назначено) public let created: Int? /// Идентификатор сообщества public let group_id: Int? /// URL миниатюры главной фотографии сообщества public let group_photo: String? /// URL изображения-иконки public let icon: String? /// Идентификатор места (если назначено) public let id: Int? /// Географическая широта public let latitude: Double? /// Географическая долгота public let longitude: Double? /// Название места (если назначено) public let title: String? /// Тип чекина public let type: Int? /// Время последнего чекина в Unixtime public let updated: Int? } /// Описание точки public struct Point: Decodable { /// Название города public let city: String? /// Название страны public let country: String? /// Дата создания (если назначено) public let created: Int? /// URL изображения-иконки public let icon: String? /// Идентификатор места (если назначено) public let id: Int? /// Географическая широта public let latitude: Double? /// Географическая долгота public let longitude: Double? /// Название места (если назначено) public let title: String? } /// Описание места case place(Object.Wall.Geo.Place.Place?) /// Описание точки case point(Object.Wall.Geo.Place.Point?) } private enum Key: String, CodingKey { case coordinates case place case showmap case type } /// Координаты места public let coordinates: String? /// Описание места public let place: Object.Wall.Geo.Place /// Showmap public let showmap: Object.Positive? /// Тип места public let type: Object.Wall.Geo.Typе public init(from decoder: Decoder) throws { let container = try Key.container(decoder: decoder) coordinates = try container.decode(key: Key.coordinates) if container.contains(Key.showmap) { showmap = try container.decode(key: Key.showmap) } else { showmap = nil } type = try container.decode(key: Key.type) switch type { case .place: if container.contains(Key.place) { let place: Object.Wall.Geo.Place.Place? = try container.decode(key: Key.place) self.place = .place(place) } else { self.place = .place(nil) } case .point: if container.contains(Key.place) { let point: Object.Wall.Geo.Place.Point? = try container.decode(key: Key.place) self.place = .point(point) } else { self.place = .point(nil) } case .unexpected: let place: Object.Wall.Geo.Place.Place = try container.decode(key: Key.place) self.place = .place(place) } } } /// Информация о лайках к записи public struct Likes: Decodable { /// Число пользователей, которым понравилась запись let count: Int? /// Информация о том, может ли текущий пользователь поставить отметку «Мне нравится» let can_like: Object.Boolean? /// Информация о том, может ли текущий пользователь сделать репост записи let can_publish: Object.Boolean? /// Наличие отметки «Мне нравится» от текущего пользователя let user_likes: Object.Boolean? } /// Тип записи public enum PostType: String, Decodable { case copy case note case photo case post case postpone case reply case suggest case video } /// Способ размещения записи на стене public struct PostSource: Decodable { /// Тип действия (только для type = vk или widget) public enum Data: String, Decodable { /// Донат case donation /// Изменение статуса под именем пользователя (для type = vk) case profile_activity /// Изменение профильной фотографии пользователя (для type = vk) case profile_photo /// Виджет комментариев (для type = widget) case comments /// Виджет «Мне нравится» (для type = widget) case like /// Виджет опросов (для type = widget) case poll /// Добавление в wishlist case wishlist_add /// Покупка из wishlist case wishlist_buy } /// Link public struct Link: Decodable { /// Description public let description: String? /// Title public let title: String? /// Url public let url: String? } /// Название платформы, если оно доступно public enum Platform: String, Decodable { /// Admin_app case admin_app /// Android case android /// Chronicle case chronicle /// Instagram case instagram /// Ipad case ipad /// Iphone case iphone /// Windows case windows /// Windows phone case wphone } /// Тип источника public enum Typе: String, Decodable { /// Запись создана приложением через API case api /// Мобильная версия m.vk.com case mvk /// Запись создана посредством импорта RSS-ленты со стороннего сайта case rss /// Запись создана посредством отправки SMS-сообщения на специальный номер case sms /// Запись создана через основной интерфейс сайта case vk /// Запись создана через виджет на стороннем сайте case widget } /// Тип действия (только для type = vk или widget) let data: Object.Wall.PostSource.Data? /// Link let link: Object.Wall.PostSource.Link? /// Название платформы, если оно доступно let platform: Object.Wall.PostSource.Platform? /// Тип источника let type: Object.Wall.PostSource.Typе /// URL ресурса, с которого была опубликована запись let url: String? } /// Информация о репостах записи («Рассказать друзьям») public struct Reposts: Decodable { /// Число пользователей, скопировавших запись let count: Int? /// наличие репоста от текущего пользователя let user_reposted: Object.Boolean? } /// Информация о просмотрах записи public struct Views: Decodable { /// Число просмотров записи let count: Int? } /// Медиавложения записи (фотографии, ссылки и т.п.) public let attachments: [Object.Attachment]? /// Информация о том, может ли текущий пользователь удалить запись public let can_delete: Object.Boolean? /// Информация о том, может ли текущий пользователь редактировать запись public let can_edit: Object.Boolean? /// Информация о том, может ли текущий пользователь закрепить запись public let can_pin: Object.Boolean? /// Информация о комментариях к записи public let comments: Object.Wall.Comments? /// Массив, содержащий историю репостов для записи. Возвращается только в том случае, если запись является репостом. Каждый из объектов массива, в свою очередь, является объектом-записью стандартного формата public let copy_history: [Object.Wall]? /// Идентификатор администратора, который опубликовал запись public let created_by: Int? /// Время публикации записи в формате unixtime public let date: TimeInterval /// Final_post public let final_post: Object.Positive? /// Запись была создана с опцией «Только для друзей» public let friends_only: Object.Positive? /// Идентификатор автора записи (от чьего имени опубликована запись) public let from_id: Int /// Информация о местоположении public let geo: Object.Wall.Geo? /// Идентификатор записи public let id: Int? /// Информация о том, что запись закреплена public let is_pinned: Object.Positive? /// Информация о лайках к записи public let likes: Object.Wall.Likes? /// Информация о том, содержит ли запись отметку "реклама" public let marked_as_ads: Object.Boolean? /// Информация о способе размещения записи public let post_source: Object.Wall.PostSource /// Тип записи public let post_type: Object.Wall.PostType? /// Идентификатор владельца записи, в ответ на которую была оставлена текущая public let reply_owner_id: Int? /// Идентификатор записи, в ответ на которую была оставлена текущая public let reply_post_id: Int? /// Информация о репостах записи («Рассказать друзьям») public let reposts: Object.Wall.Reposts? /// Идентификатор автора, если запись была опубликована от имени сообщества и подписана пользователем public let signer_id: Int? /// Идентификатор владельца стены, на которой размещена запись public let owner_id: Int /// Текст записи public let text: String /// Информация о просмотрах записи public let views: Object.Wall.Views? } }
mit
510821e9448a6abd91b267d501e6704e
40.908805
215
0.503189
4.204101
false
false
false
false
SPECURE/rmbt-ios-client
Sources/RMBTHelpers.swift
1
7244
/***************************************************************************************************** * Copyright 2013 appscape gmbh * Copyright 2014-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 /// taken from http://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary /// this should be in the swift standard library! // func +=<K, V>(inout left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> { // for (k, v) in right { // left.updateValue(v, forKey: k) // } // // return left // } func +=<K, V>(left: inout [K: V], right: [K: V]) { for (k, v) in right { left[k] = v } } /// /// Returns a string containing git commit, branch and commit count from Info.plist fields written by the build script public func RMBTBuildInfoString() -> String { let info = Bundle.main.infoDictionary! let gitBranch = info["GitBranch"] as? String ?? "none" let gitCommitCount = info["GitCommitCount"] as? String ?? "-1" let gitCommit = info["GitCommit"] as? String ?? "none" return "\(gitBranch)-\(gitCommitCount)-\(gitCommit)" // return String(format: "%@-%@-%@", info["GitBranch"], info["GitCommitCount"], info["GitCommit"]) } /// public func RMBTBuildDateString() -> String { let info = Bundle.main.infoDictionary! let buildDate = info["BuildDate"] as? String ?? "none" return buildDate } /// public func RMBTVersionString() -> String { let info = Bundle.main.infoDictionary! let versionString = "\(info["CFBundleShortVersionString"] as! String) (\(info["CFBundleVersion"] as! String))" var environment = "" switch currentEnvironment { case .Beta: environment = "BETA" case .Debug: environment = "DEBUG" case .Test: environment = "TEST" default: break } #if DEBUG return "\(versionString) [\(environment) \(RMBTBuildInfoString()) (\(RMBTBuildDateString()))]" #else return "\(versionString) \(environment)" #endif } ///// // public func RMBTPreferredLanguage() -> String? { let preferredLanguages = Locale.preferredLanguages Log.logger.debug("\(preferredLanguages)") if preferredLanguages.count < 1 { return nil } let sep = preferredLanguages[0].components(separatedBy: "-") var lang = sep[0] // becuase sometimes (ios9?) there's "en-US" instead of en if sep.count > 1 && sep[1] == "Latn" { // add Latn if available, but don't add other country codes lang += "-Latn" } // experiment need to test // lang = PREFFERED_LANGUAGE return lang } /// Replaces $lang in template with the current locale. /// Fallback to english for non-translated languages is done on the server side. public func RMBTLocalizeURLString(_ urlString: String) -> String { if urlString.range(of: LANGUAGE_PREFIX) != nil { var lang = PREFFERED_LANGUAGE if RMBTConfig.sharedInstance.RMBT_USE_MAIN_LANGUAGE == true { lang = RMBTConfig.sharedInstance.RMBT_MAIN_LANGUAGE } let replacedURL = urlString.replacingOccurrences(of: LANGUAGE_PREFIX, with: lang) return replacedURL } return urlString } /// Returns bundle name from Info.plist (e.g. SPECURE NetTest) public func RMBTAppTitle() -> String { let info = Bundle.main.infoDictionary! return info["CFBundleDisplayName"] as! String } /// public func RMBTAppCustomerName() -> String { let info = Bundle.main.infoDictionary! return info["CFCustomerName"] as! String } /// public func RMBTValueOrNull(_ value: AnyObject!) -> Any { // return value ?? NSNUll() return (value != nil) ? value : NSNull() } /// public func RMBTValueOrString(_ value: AnyObject!, _ result: String) -> Any { // return value ?? result return (value != nil) ? value : result } /// public func RMBTCurrentNanos() -> UInt64 { var info = mach_timebase_info(numer: 0, denom: 0) mach_timebase_info(&info) // TODO: dispatch_once? // static dispatch_once_t onceToken; // static mach_timebase_info_data_t info; // dispatch_once(&onceToken, ^{ // mach_timebase_info(&info); // }); var now = mach_absolute_time() now *= UInt64(info.numer) now /= UInt64(info.denom) return now } /// public func RMBTMillisecondsStringWithNanos(_ nanos: UInt64) -> String { return RMBTMillisecondsString(nanos) + " ms" } /// public func RMBTMillisecondsString(_ nanos: UInt64) -> String { let ms = NSNumber(value: Double(nanos) * 1.0e-6 as Double) return "\(RMBTFormatNumber(ms))" } public func RMBTNanos(_ millisecondsString: String) -> UInt64 { let s = millisecondsString.replacingOccurrences(of: ",", with: ".") let ms = NSNumber(value: (Double(s) ?? 0.0) * 1.0e+6) return UInt64(truncating: ms) } public func RMBTMbps(_ mbps: String) -> Double { let s = mbps.replacingOccurrences(of: ",", with: ".") return Double(s) ?? 0.0 } /// public func RMBTSecondsStringWithNanos(_ nanos: UInt64) -> String { return NSString(format: "%f s", Double(nanos) * 1.0e-9) as String } /// public func RMBTTimestampWithNSDate(_ date: Date) -> NSNumber { return NSNumber(value: UInt64(date.timeIntervalSince1970) * 1000 as UInt64) } /// public func NKOMTimestampWithNSDate(_ date: Date) -> NSNumber { return NSNumber(value: UInt64(date.timeIntervalSince1970) as UInt64) } /// Format a number to two significant digits. See https://trac.rtr.at/iosrtrnetztest/ticket/17 public func RMBTFormatNumber(_ number: NSNumber, _ maxDigits: Int = 2) -> String { let formatter = NumberFormatter() var signif = maxDigits if number.doubleValue > 10 { signif -= 1 } if number.doubleValue > 100 { signif -= 1 } if signif < 0 { signif = 0 } // TODO: dispatch_once formatter.decimalSeparator = "." formatter.minimumFractionDigits = signif formatter.maximumFractionDigits = signif formatter.minimumIntegerDigits = 1 // return formatter.string(from: number)! } /// Normalize hexadecimal identifier, i.e. 0:1:c -> 00:01:0c public func RMBTReformatHexIdentifier(_ identifier: String!) -> String! { // ! if identifier == nil { return nil } var tmp = [String]() for c in identifier.components(separatedBy: ":") { if c.count == 0 { tmp.append("00") } else if c.count == 1 { tmp.append("0\(c)") } else { tmp.append(c) } } return tmp.joined(separator: ":") }
apache-2.0
ce5a8a94319098551c39bdb6db10c07f
28.209677
119
0.627278
3.94124
false
false
false
false
jmayoralas/Sems
Sems/Tape/TapeData.swift
1
13275
// // NSData+TapeLoader.swift // Sems // // Created by Jose Luis Fernandez-Mayoralas on 26/8/16. // Copyright © 2016 Jose Luis Fernandez-Mayoralas. All rights reserved. // import Foundation private let kPilotToneHeaderPulsesCount = 8063 private let kPilotToneDataPulsesCount = 3223 private let kPilotTonePulseLength = 2168 private let kPilotTonePause = 1000 private let kSyncPulseFirstLength = 667 private let kSyncPulseSecondLength = 735 private let kResetBitLength = 855 private let kSetBitLength = kResetBitLength * 2 private enum TapeFormat: UInt8 { case Tap case Tzx } private enum TzxBlockId: UInt8 { case StandardSpeed = 0x10 case TurboSpeed = 0x11 case PureTone = 0x12 case PulseSequence = 0x13 case PureData = 0x14 case PauseOrStopTape = 0x20 case GroupStart = 0x21 case GroupEnd = 0x22 case LoopStart = 0x24 case LoopEnd = 0x25 case TextDescription = 0x30 case ArchiveInfo = 0x32 } final class TapeData { var eof: Bool { get { return self.location >= self.data.length } } private var location: Int = 0 private var data: NSData private var groupStarted: Bool = false private var loopCount: Int = 0 private var loopStartLocation: Int = 0 init?(contentsOfFile path: String) { guard let data = NSData(contentsOfFile: path) else { return nil } self.data = data self.location = self.getLocationFirstTapeDataBlock() } private var tapeFormat: TapeFormat { get { // get first 8 bytes and search for TZX signature let range = NSRange(location: 0, length: 7) var tapeFormat: TapeFormat = .Tap var signatureBytes = [UInt8](repeating: 0, count: 7) self.data.getBytes(&signatureBytes, range: range) if let signature = String(bytes: signatureBytes, encoding: String.Encoding.utf8) { if signature == "ZXTape!" { tapeFormat = .Tzx } } return tapeFormat } } // MARK: Public methods func getNextTapeBlock() throws -> TapeBlock { var tapeBlock: TapeBlock repeat { tapeBlock = try self.getTapeBlock(atLocation: self.location) self.location += tapeBlock.size } while tapeBlock.description == "dummy" return tapeBlock } // MARK: Private methods private func getDataFromTapeBlock(tapeBlock: TapeBlock) -> [UInt8] { var data = [UInt8]() for part in tapeBlock.parts { if part.type == .Data { data.append(contentsOf: (part as! TapeBlockPartData).data) } } return data } private func getLocationFirstTapeDataBlock() -> Int { var firstDataBlock: Int = 0 switch tapeFormat { case .Tap: firstDataBlock = 0 case .Tzx: firstDataBlock = 10 } return firstDataBlock } private func getTapeBlock(atLocation location: Int) throws -> TapeBlock { let tapeBlock: TapeBlock switch self.tapeFormat { case .Tap: tapeBlock = self.getTapTapeBlock(atLocation: location) case .Tzx: tapeBlock = try self.getTzxTapeBlock(atLocation: location) } return tapeBlock } private func getNumber(location: Int, size: Int) -> Int { var number: Int = 0 let range = NSRange(location: location, length: size) var bytes = [UInt8](repeatElement(0, count: size)) self.data.getBytes(&bytes, range: range) for i in (0 ..< size).reversed() { number += Int(bytes[i]) << (8 * i) } return number } private func getBytes(location: Int, size: Int) -> [UInt8] { let range = NSRange(location: location, length: Int(size)) var data = [UInt8](repeating: 0, count: Int(size)) self.data.getBytes(&data, range: range) return data } private func getTapTapeBlock(atLocation location: Int) -> TapeBlock { let size = self.getNumber(location: location, size: 2) let data = self.getBytes(location: location + 2, size: size) return self.getStandardSpeedDataBlock(data: data) } private func getStandardSpeedDataBlock(data: [UInt8]) -> TapeBlock { let flagByte = data[0] let pilotTonePulsesCount = flagByte < 128 ? kPilotToneHeaderPulsesCount : kPilotToneDataPulsesCount // a standard speed data block consists of: // a pilot tone let pilotTone = TapeBlockPartPulse(size: 1, pulsesCount: pilotTonePulsesCount, tStatesDuration: kPilotTonePulseLength) // a two pulse sync signal let syncPulse = TapeBlockPartPulse(size: 1, firstPulseTStates: kSyncPulseFirstLength, secondPulseTStates: kSyncPulseSecondLength) // a pure data block let dataBlock = TapeBlockPartData(size: data.count, resetBitPulseLength: kResetBitLength, setBitPulseLength: kSetBitLength, usedBitsLastByte: 8, data: data) return TapeBlock(description: self.getDescription(data: data), parts: [pilotTone, syncPulse, dataBlock], pauseAfterBlock: kPilotTonePause) } private func getTurboSpeedDataBlock(atLocation location: Int) -> TapeBlock { let size = self.getNumber(location: location + 0x0F, size: 3) let data = self.getBytes(location: location + 0x12, size: size) // a turbo speed data block consists of: // a pilot tone let pilotTonePulsesLength = self.getNumber(location: location, size: 2) let pilotTonePulsesCount = self.getNumber(location: location + 0x0A, size: 2) let pilotTone = TapeBlockPartPulse(size: 1, pulsesCount: pilotTonePulsesCount, tStatesDuration: pilotTonePulsesLength) // a two pulse sync signal let firstPulseLength = self.getNumber(location: location + 0x02, size: 2) let secondPulseLength = self.getNumber(location: location + 0x04, size: 2) let syncPulse = TapeBlockPartPulse(size: 1, firstPulseTStates: firstPulseLength, secondPulseTStates: secondPulseLength) // a pure data block let resetBitLength = self.getNumber(location: location + 0x06, size: 2) let setBitLength = self.getNumber(location: location + 0x08, size: 2) let usedBitsLastByte = self.getNumber(location: location + 0x0C, size: 1) let dataBlock = TapeBlockPartData( size: data.count, resetBitPulseLength: resetBitLength, setBitPulseLength: setBitLength, usedBitsLastByte: usedBitsLastByte, data: data ) let pause = self.getNumber(location: location + 0x0D, size: 2) var block = TapeBlock(description: self.getDescription(data: data), parts: [pilotTone, syncPulse, dataBlock], pauseAfterBlock: pause) block.size += 0x11 return block } private func getDescription(data: [UInt8]) -> String { let flagByte = data[0] let blockType = Int(data[1]) let description: String if flagByte < 128 { let name : [UInt8] = Array(data[2...11]) let identifier = String(data: Data(name), encoding: String.Encoding.ascii)! if let descriptionFromData = TapeBlockDescription(rawValue: blockType) { description = String(format: "%@: %@", descriptionFromData.description, identifier) } else { description = String(format: "Unknown block type: %d", Int(data[1])) } } else { description = "[DATA]" } return description } private func getTzxTapeBlock(atLocation location: Int) throws -> TapeBlock { let blockIdValue = UInt8(self.getNumber(location: location, size: 1)) guard let blockId = TzxBlockId(rawValue: blockIdValue) else { throw TapeLoaderError.UnsupportedTapeBlockFormat(blockId: blockIdValue, location: location) } return try self.getTzxTapeBlock(blockId: blockId, location: location + 1) } private func getTzxTapeBlock(blockId: TzxBlockId, location: Int) throws -> TapeBlock { var block: TapeBlock switch blockId { case .StandardSpeed: let pause = self.getNumber(location: location, size: 2) block = self.getTapTapeBlock(atLocation: location + 2) block.size += 3 if pause > 0 { block.pauseAfterBlock = pause } case .TurboSpeed: block = self.getTurboSpeedDataBlock(atLocation: location) case .ArchiveInfo: let size = self.getNumber(location: location, size: 2) let part = TapeBlockPartInfo(size: size + 3, description: "") block = TapeBlock(description: "Archive Info", parts: [part], pauseAfterBlock: nil) case .PauseOrStopTape: let pause = self.getNumber(location: location, size: 2) block = TapeBlock(description: "Pause", parts: [], pauseAfterBlock: pause) block.size = 3 case .TextDescription: let size = self.getNumber(location: location, size: 1) let part = TapeBlockPartInfo(size: size + 2, description: "") block = TapeBlock(description: "Description", parts: [part], pauseAfterBlock: nil) case .GroupStart: let size = self.getNumber(location: location, size: 1) self.groupStarted = true let part = TapeBlockPartInfo(size: size + 2, description: "") block = TapeBlock(description: "Group start", parts: [part], pauseAfterBlock: nil) case .GroupEnd: self.groupStarted = false let part = TapeBlockPartInfo(size: 1, description: "") block = TapeBlock(description: "Group end", parts: [part], pauseAfterBlock: nil) case .LoopStart: let size = 3 guard self.loopCount == 0 else { throw TapeLoaderError.DataIncoherent(blockId: blockId.rawValue, location: location) } self.loopCount = self.getNumber(location: location, size: 2) guard self.loopCount > 1 else { throw TapeLoaderError.DataIncoherent(blockId: blockId.rawValue, location: location) } block = TapeBlock(size: size) self.loopStartLocation = location + size - 1 case .LoopEnd: self.loopCount -= 1 self.location = self.loopCount > 0 ? self.loopStartLocation : self.location + 1 block = TapeBlock(size: 0) case .PureTone: let toneLength = self.getNumber(location: location, size: 2) let tonePulsesCount = self.getNumber(location: location + 2, size: 2) let part = TapeBlockPartPulse(size: 5, pulsesCount: tonePulsesCount, tStatesDuration: toneLength) block = TapeBlock(description: "Pure tone", parts: [part], pauseAfterBlock: nil) case .PulseSequence: let pulsesCount = self.getNumber(location: location, size: 1) var parts = [TapeBlockPart]() for i in 1 ... pulsesCount / 2 { let firstPulseLength = self.getNumber(location: location + (i * 4 - 4) + 1, size: 2) let secondPulseLength = self.getNumber(location: location + (i * 4 - 4) + 3, size: 2) parts.append(TapeBlockPartPulse(size: 4, firstPulseTStates: firstPulseLength, secondPulseTStates: secondPulseLength)) } block = TapeBlock(description: "Pulse sequence", parts: parts, pauseAfterBlock: nil) block.size += 2 case .PureData: let resetBitLength = self.getNumber(location: location, size: 2) let setBitLength = self.getNumber(location: location + 2, size: 2) let usedBitsLastByte = self.getNumber(location: location + 4, size: 1) let pause = self.getNumber(location: location + 5, size: 2) let size = self.getNumber(location: location + 7, size: 3) let data = self.getBytes(location: location + 10, size: size) let dataPart = TapeBlockPartData(size: data.count + 10, resetBitPulseLength: resetBitLength, setBitPulseLength: setBitLength, usedBitsLastByte: usedBitsLastByte, data: data) block = TapeBlock(description: "Pure data", parts: [dataPart], pauseAfterBlock: pause) block.size += 1 } return block } }
gpl-3.0
62678b8df9bd3c4a93c1e4d5b8da115d
36.078212
185
0.59334
4.391002
false
false
false
false
allbto/ios-swiftility
SwiftilityTests/Type Safe UIKIt/NibTests.swift
2
952
// // NibTests.swift // SwiftilityTests // // Created by Allan Barbato on 12/14/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import XCTest import Nimble @testable import Swiftility class NibTests: XCTestCase { let storyboard = UIStoryboard(name: "MainStoryboard", bundle: Bundle(for: StoryboardTests.self)) func testNibConvertible() { let nib = NibsDefault.TestCell XCTAssert(nib.nibName == "TestCell") XCTAssert(nib.bundle == nil) } func testInstantiateFromNib() { // Instantiate non existing nib expect { _ = TestNonExistingCell.instantiateFromNib(NibContainer("TestNonExistingCell", bundle: Bundle(for: StoryboardTests.self))) }.to(throwAssertion()) // Instantiate existing nib _ = TestCell.instantiateFromNib() XCTAssert(true, "cell instantiation should not crash") } }
mit
776f57c9eb72897dfa15748584728995
20.133333
134
0.640379
4.661765
false
true
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/Weather Station Meteorology Details Scene/Table Cells/Weather Station Meteorology Details Sun-Cycle/WeatherStationMeteorologyDetailsSunCycleCell.swift
1
7919
// // WeatherStationCurrentInformationSunCycleCell.swift // NearbyWeather // // Created by Erik Maximilian Martens on 14.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift // MARK: - Definitions private extension WeatherStationMeteorologyDetailsSunCycleCell { struct Definitions { static let symbolWidth: CGFloat = 20 } } // MARK: - Class Definition final class WeatherStationMeteorologyDetailsSunCycleCell: UITableViewCell, BaseCell { typealias CellViewModel = WeatherStationMeteorologyDetailsSunCycleCellViewModel private typealias CellContentInsets = Constants.Dimensions.Spacing.ContentInsets private typealias CellInterelementSpacing = Constants.Dimensions.Spacing.InterElementSpacing // MARK: - UIComponents private lazy var sunriseSymbolImageView = Factory.ImageView.make(fromType: .symbol(systemImageName: "sunrise.fill")) private lazy var sunriseDescriptionLabel = Factory.Label.make(fromType: .body(text: R.string.localizable.sunrise(), textColor: Constants.Theme.Color.ViewElement.Label.titleDark)) private lazy var sunriseTimeLabel = Factory.Label.make(fromType: .subtitle(alignment: .right)) private lazy var sunsetSymbolImageView = Factory.ImageView.make(fromType: .symbol(systemImageName: "sunset.fill")) private lazy var sunsetDescriptionLabel = Factory.Label.make(fromType: .body(text: R.string.localizable.sunset(), textColor: Constants.Theme.Color.ViewElement.Label.titleDark)) private lazy var sunsetTimeLabel = Factory.Label.make(fromType: .subtitle(alignment: .right)) // MARK: - Assets private var disposeBag = DisposeBag() // MARK: - Properties var cellViewModel: CellViewModel? // MARK: - Initialization override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutUserInterface() setupAppearance() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Cell Life Cycle func configure(with cellViewModel: BaseCellViewModelProtocol?) { guard let cellViewModel = cellViewModel as? WeatherStationMeteorologyDetailsSunCycleCellViewModel else { return } self.cellViewModel = cellViewModel cellViewModel.observeEvents() bindContentFromViewModel(cellViewModel) bindUserInputToViewModel(cellViewModel) } } // MARK: - ViewModel Bindings extension WeatherStationMeteorologyDetailsSunCycleCell { func bindContentFromViewModel(_ cellViewModel: CellViewModel) { cellViewModel.cellModelDriver .drive(onNext: { [setContent] in setContent($0) }) .disposed(by: disposeBag) } } // MARK: - Cell Composition private extension WeatherStationMeteorologyDetailsSunCycleCell { func setContent(for cellModel: WeatherStationMeteorologyDetailsSunCycleCellModel) { sunriseTimeLabel.text = cellModel.sunriseTimeString sunsetTimeLabel.text = cellModel.sunsetTimeString } func layoutUserInterface() { // line 1 contentView.addSubview(sunriseSymbolImageView, constraints: [ sunriseSymbolImageView.topAnchor.constraint(greaterThanOrEqualTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), sunriseSymbolImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .medium)), sunriseSymbolImageView.widthAnchor.constraint(equalToConstant: Definitions.symbolWidth), sunriseSymbolImageView.heightAnchor.constraint(equalTo: sunriseSymbolImageView.widthAnchor) ]) contentView.addSubview(sunriseDescriptionLabel, constraints: [ sunriseDescriptionLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), sunriseDescriptionLabel.leadingAnchor.constraint(equalTo: sunriseSymbolImageView.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), sunriseDescriptionLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), sunriseDescriptionLabel.centerYAnchor.constraint(equalTo: sunriseSymbolImageView.centerYAnchor) ]) contentView.addSubview(sunriseTimeLabel, constraints: [ sunriseTimeLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), sunriseTimeLabel.leadingAnchor.constraint(equalTo: sunriseDescriptionLabel.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), sunriseTimeLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .medium)), sunriseTimeLabel.widthAnchor.constraint(equalTo: sunriseDescriptionLabel.widthAnchor, multiplier: 4/5), sunriseTimeLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), sunriseTimeLabel.centerYAnchor.constraint(equalTo: sunriseDescriptionLabel.centerYAnchor), sunriseTimeLabel.centerYAnchor.constraint(equalTo: sunriseSymbolImageView.centerYAnchor) ]) // line 2 contentView.addSubview(sunsetSymbolImageView, constraints: [ sunsetSymbolImageView.topAnchor.constraint(greaterThanOrEqualTo: sunriseSymbolImageView.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), sunsetSymbolImageView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), sunsetSymbolImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .medium)), sunsetSymbolImageView.widthAnchor.constraint(equalToConstant: Definitions.symbolWidth), sunsetSymbolImageView.heightAnchor.constraint(equalTo: sunsetSymbolImageView.widthAnchor) ]) contentView.addSubview(sunsetDescriptionLabel, constraints: [ sunsetDescriptionLabel.topAnchor.constraint(equalTo: sunriseDescriptionLabel.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), sunsetDescriptionLabel.leadingAnchor.constraint(equalTo: sunsetSymbolImageView.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), sunsetDescriptionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), sunsetDescriptionLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), sunsetDescriptionLabel.centerYAnchor.constraint(equalTo: sunsetSymbolImageView.centerYAnchor) ]) contentView.addSubview(sunsetTimeLabel, constraints: [ sunsetTimeLabel.topAnchor.constraint(equalTo: sunriseTimeLabel.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), sunsetTimeLabel.leadingAnchor.constraint(equalTo: sunsetDescriptionLabel.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), sunsetTimeLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .medium)), sunsetTimeLabel.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), sunsetTimeLabel.widthAnchor.constraint(equalTo: sunsetDescriptionLabel.widthAnchor, multiplier: 4/5), sunsetTimeLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), sunsetTimeLabel.centerYAnchor.constraint(equalTo: sunsetDescriptionLabel.centerYAnchor), sunsetTimeLabel.centerYAnchor.constraint(equalTo: sunsetSymbolImageView.centerYAnchor) ]) } func setupAppearance() { selectionStyle = .none backgroundColor = .clear contentView.backgroundColor = Constants.Theme.Color.ViewElement.primaryBackground } }
mit
8fd6f9c61751e47195e0ba17a981ac61
51.437086
180
0.798308
5.475795
false
false
false
false
gokselkoksal/Lightning
LightningTests/ExtensionTests/BundleHelpersTests.swift
1
493
// // BundleHelpersTests.swift // Lightning // // Created by Göksel Köksal on 10/12/2016. // Copyright © 2016 GK. All rights reserved. // import XCTest @testable import Lightning class BundleHelpersTests: XCTestCase { func testVersionStrings() { let bundle = Bundle(for: BundleHelpersTests.self) let shortVersion = bundle.zap_shortVersionString let buildVersion = bundle.zap_versionString XCTAssert(shortVersion == "1.0") XCTAssert(buildVersion == "1") } }
mit
a1a7cd762232b2e5b86f553566e15510
22.333333
53
0.712245
3.740458
false
true
false
false
tomomura/TimeSheet
Classes/Views/WorkTimes/FTWorkTimesTableViewDayCell.swift
1
1389
// // FTWorkTimesTableViewDayCell.swift // TimeSheet // // Created by TomomuraRyota on 2015/04/04. // Copyright (c) 2015年 TomomuraRyota. All rights reserved. // import UIKit class FTWorkTimesTableViewDayCell: UITableViewCell { @IBOutlet weak var dayLabel: UILabel! @IBOutlet weak var wdayLabel: UILabel! @IBOutlet weak var startTimeLabel: UILabel! @IBOutlet weak var endTimeLabel: UILabel! @IBOutlet weak var totalTimeLabel: UILabel! @IBOutlet weak var overtimeLabel: UILabel! var date : NSDate! var workTime : WorkTime? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func drawRect(rect: CGRect) { super.drawRect(rect) self.startTimeLabel.text = self.workTime?.startTime?.timeHuman() self.endTimeLabel.text = self.workTime?.endTime?.timeHuman() self.dayLabel.text = String(format: "%02d日", date.day) self.wdayLabel.text = "\(self.date.week().name())" self.totalTimeLabel.text = workTime?.totalTimeHuman() self.overtimeLabel.text = workTime?.overTimeHuman() self.dayLabel.textColor = self.date.week().color() self.wdayLabel.textColor = self.date.week().color() } }
mit
7b93ddd7414acacc15acfdeb1e17b4dd
29.108696
72
0.66426
4.00289
false
false
false
false
svdo/ReRxSwift
ReRxSwift/Connection.swift
1
15416
// Copyright © 2017 Stefan van den Oord. All rights reserved. import ReSwift import RxSwift import RxCocoa /// A ReRxSwift Connection that manages the mapping between ReSwift application state /// and ReSwift actions on the one hand, and view controller props and actions on the /// other hand. /// /// In order to use this, you have to make your view controller conform to /// `Connectable` and add a `Connection` instance. In your view controller /// you need to call `connect()` and `disconnect()` at the right time. /// /// Examples /// ======== /// The folder [`Example`](https://github.com/svdo/ReRxSwift/tree/master/Example) /// contains example of how to use this. /// /// Usage /// ===== /// 1. Create an extension to your view controller to make it `Connectable`, /// defining the `Props` and `Actions` that your view controller needs: /// /// ```swift /// extension MyViewController: Connectable { /// struct Props { /// let text: String /// } /// struct Actions { /// let updatedText: (String) -> Void /// } /// } /// ``` /// /// 2. Define how your state is mapped to the above `Props` type: /// /// ```swift /// private let mapStateToProps = { (appState: AppState) in /// return MyViewController.Props( /// text: appState.content /// ) /// } /// ``` /// /// 3. Define the actions that are dispatched: /// /// ```swift /// private let mapDispatchToActions = { (dispatch: @escaping DispatchFunction) in /// return MyViewController.Actions( /// updatedText: { newText in dispatch(SetContent(newContent: newText)) } /// ) /// } /// ``` /// /// 4. Define the connection and hook it up: /// /// ```swift /// class MyViewController: UIViewController { /// @IBOutlet weak var textField: UITextField! /// /// let connection = Connection( /// store: store, /// mapStateToProps: mapStateToProps, /// mapDispatchToActions: mapDispatchToActions /// ) /// /// override func viewWillAppear(_ animated: Bool) { /// super.viewWillAppear(animated) /// connection.connect() /// } /// /// override func viewDidDisappear(_ animated: Bool) { /// super.viewDidDisappear(animated) /// connection.disconnect() /// } /// } /// ``` /// /// 5. Bind the text field's text, using a Swift 4 key path to refer to the /// `text` property of `Props`: /// /// ```swift /// override func viewDidLoad() { /// super.viewDidLoad() /// connection.bind(\Props.text, to: textField.rx.text) /// } /// ``` /// /// 6. Call the action: /// /// ```swift /// @IBAction func editingChanged(_ sender: UITextField) { /// actions.updatedText(sender.text ?? "") /// } /// ``` public class Connection<State: StateType, Props, Actions>: StoreSubscriber { /// The RxSwift `BehaviorRelay` that holds your view controller props. /// Normally you don't use this this directly, you use it through `Connectable.props` /// instead. This variable is public so that you can use it for unit testing. /// In cases where you don't want to use the `bind(_:to:)` methods in this class and want /// to create your own RxSwift observing code, you do need to use this variable /// directly. public let props: BehaviorRelay<Props> /// This holds you view controller's actions. Don't use this directly, use /// `Connectable.actions` instead. This variable is public so that you can use it /// for unit testing. public var actions: Actions! /// The ReSwift store used by this connection object. Normally you pass /// your global app store as a parameter to the constructor. This variable /// is public so that you can inject a different store during unit testing. /// It is not intended to be used directly from production code. public var store: Store<State> { didSet { self.actions = self.mapDispatchToActions(store.dispatch) } } /// This is the mapping function that takes your global ReSwift state, and maps /// it into your view controller's `Connectable.props`. let mapStateToProps: (State) -> (Props) /// This is the mapping function that maps actions in your view controller /// to ReSwift actions. let mapDispatchToActions: (@escaping DispatchFunction) -> (Actions) /// RxSwift memory management. public let disposeBag = DisposeBag() /// Constructs a new `Connection` object. For examples see the class documentation /// above, or the code examples in /// [`SimpleTextFieldViewController`](https://github.com/svdo/ReRxSwift/blob/master/Example/SimpleTextField/SimpleTextFieldViewController.swift) and /// [`SteppingUpViewController`](https://github.com/svdo/ReRxSwift/blob/master/Example/SteppingUp/SteppingUpViewController.swift). /// /// - Parameters: /// - store: Your application's global store. /// - mapStateToProps: A mapping function that takes the global application state, /// and maps it into a view controller specific structure `Connectable.props`. /// Whenever a new state comes in from your ReSwift store, the connection calls /// this function to map it to the `Connectable.props` needed by your view /// controller. /// - mapDispatchToActions: A mapping function that specifies which ReSwift action /// needs to be dispatched when your view controller calls its /// `Connectable.actions`. public init(store: Store<State>, mapStateToProps: @escaping (State) -> (Props), mapDispatchToActions: @escaping (@escaping DispatchFunction) -> (Actions) ) { self.store = store self.mapStateToProps = mapStateToProps self.mapDispatchToActions = mapDispatchToActions let initialState = store.state! let props = mapStateToProps(initialState) self.props = BehaviorRelay(value: props) self.actions = mapDispatchToActions(store.dispatch) } deinit { disconnect() } /// "Activates" the connection in the sense that it subscribes to the store so that /// store updates are received and can be processed. Failing to call this method /// will mean that your view controller does not get new `Connectable.props` when /// the global state changes. Call this method from your view controller's /// `viewWillAppear()` or `viewDidAppear()`. public func connect() { store.subscribe(self) } /// "Deactivates" the connection: unsubscribes from the store so that state updates /// are no longer processed for your view controller. Call this method from your view /// controller's `viewWillDisappear()` or `viewDidDisappear()`. public func disconnect() { store.unsubscribe(self) } /// ReSwift's callback method. Don't call this yourself. public func newState(state: State) { props.accept(mapStateToProps(state)) } // MARK: - Helper functions public func propsEntry<T>(at keyPath: KeyPath<Props, T>, isEqual: @escaping (T,T) -> Bool) -> Observable<T> { return self.props .asObservable() .distinctUntilChanged { isEqual($0[keyPath: keyPath], $1[keyPath: keyPath]) } .map { $0[keyPath: keyPath] } } // MARK: - Binding Observers of Optionals /// Bind a RxSwift observer to one of your `Connectable.props` entries. /// Convenience method for `bind(keyPath, to: observer, mapping: nil)`. /// /// - Parameters: /// - keyPath: Swift 4 `KeyPath` that points to the entry in your view /// controllers `Connectable.props` that you want to bind. /// - observer: The RxSwift observer that you want to bind to. public func bind<T: Equatable, O>(_ keyPath: KeyPath<Props, T>, to observer: O) where O: ObserverType, O.Element == T? { self.bind(keyPath, to: observer, mapping: nil) } /// Bind a RxSwift observer to one of your `Connectable.props` entries. /// /// All `bind()` functions are variants of the following basic implementation: /// /// ```swift /// self.props /// .asObservable() /// .distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] } /// .map { $0[keyPath: keyPath] } /// .map(mapping) // if not nil /// .bind(to: binder) /// .disposed(by: disposeBag) /// ``` /// /// - Parameters: /// - keyPath: Swift 4 `KeyPath` that points to the entry in your view /// controllers `Connectable.props` that you want to bind. /// - observer: The RxSwift observer that you want to bind to. /// - mapping: An optional function that takes the entry in your /// `Connectable.props` and converts it to the thing needed by the /// observable. This is useful if your `Connectable.props` entry is a different /// type that needs to be converted before it can be put into the observer, for /// example converting a `Float` into a `String` so that it can be put in a /// text field's `text`. public func bind<T: Equatable, O, M>(_ keyPath: KeyPath<Props, T>, to observer: O, mapping: ((T)->M)? = nil) where O: ObserverType, O.Element == M? { let distinctAtKeyPath = self.propsEntry(at: keyPath) { $0 == $1} let afterMapping: Observable<M> if let mapping = mapping { afterMapping = distinctAtKeyPath.map(mapping) } else { afterMapping = distinctAtKeyPath as! Observable<M> } afterMapping .bind(to: observer) .disposed(by: disposeBag) } // MARK: - Subscribing and Binding Observers of Non-Optionals to Non-Optional Prop /// Subscribe to one of your `Connectable.props` entries, having a closure /// called whenever it changes. Variant for non-optional entries. /// /// - Parameters: /// - keyPath: Swift 4 `KeyPath` that points to the entry in your view /// controllers `Connectable.props` that you want to subscribe to. /// - onNext: The closure that is called whenever the entry at the given /// key path changes. The new value is passed into the closure as a parameter. public func subscribe<T: Equatable>(_ keyPath: KeyPath<Props, T>, onNext: @escaping (T)->()) { self.propsEntry(at: keyPath) { $0 == $1} .subscribe(onNext: onNext) .disposed(by: disposeBag) } /// Bind a RxSwift observer to one of your `Connectable.props` entries. /// Convenience method for `bind(keyPath, to: observer, mapping: nil)`. /// /// - Parameters: /// - keyPath: Swift 4 `KeyPath` that points to the entry in your view /// controllers `Connectable.props` that you want to bind. /// - observer: The RxSwift observer that you want to bind to. public func bind<T: Equatable, O>(_ keyPath: KeyPath<Props, T>, to observer: O) where O: ObserverType, O.Element == T { self.bind(keyPath, to: observer, mapping: nil) } /// Bind a RxSwift observer to one of your `Connectable.props` entries. /// /// All `bind()` functions are variants of the following basic implementation: /// /// ```swift /// self.props /// .asObservable() /// .distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] } /// .map { $0[keyPath: keyPath] } /// .map(mapping) // if not nil /// .bind(to: binder) /// .disposed(by: disposeBag) /// ``` /// /// - Parameters: /// - keyPath: Swift 4 `KeyPath` that points to the entry in your view /// controllers `Connectable.props` that you want to bind. /// - observer: The RxSwift observer that you want to bind to. /// - mapping: An optional function that takes the entry in your /// `Connectable.props` and converts it to the thing needed by the /// observable. This is useful if your `Connectable.props` entry is a different /// type that needs to be converted before it can be put into the observer, for /// example converting a `Float` into a `String` so that it can be put in a /// text field's `text`. public func bind<T: Equatable, O, M>(_ keyPath: KeyPath<Props, T>, to observer: O, mapping: ((T)->M)? = nil) where O: ObserverType, O.Element == M { let distinctAtKeyPath = self.propsEntry(at: keyPath) { $0 == $1} let afterMapping: Observable<M> if let mapping = mapping { afterMapping = distinctAtKeyPath.map(mapping) } else { afterMapping = distinctAtKeyPath as! Observable<M> } afterMapping .bind(to: observer) .disposed(by: disposeBag) } // MARK: - Subscribing and binding sequences using binder function // (e.g. collectionView.rx.items) /// Subscribe to one of your `Connectable.props` entries, having a closure /// called whenever it changes. Variant for non-optional entries. /// /// - Parameters: /// - keyPath: Swift 4 `KeyPath` that points to the entry in your view /// controllers `Connectable.props` that you want to subscribe to. /// - onNext: The closure that is called whenever the entry at the given /// key path changes. The new value is passed into the closure as a parameter. public func subscribe<T: Equatable>(_ keyPath: KeyPath<Props, [T]>, onNext: @escaping ([T])->()) { self.propsEntry(at: keyPath) { $0.elementsEqual($1) } .subscribe(onNext: onNext) .disposed(by: disposeBag) } /// Bind a RxSwift observer to one of your `Connectable.props` entries. /// /// - Parameters: /// - keyPath: Swift 4 `KeyPath` that points to the entry in your view /// controllers `Connectable.props` that you want to bind. /// - binder: The RxSwift binder function such as used by `UICollectionView.rx.items` /// and `UITableView.rx.items`. public func bind<S: Sequence,M>(_ keyPath: KeyPath<Props, S>, to binder: (Observable<M>) -> Disposable, mapping: ((S)->M)? = nil) where S.Element: Equatable { let distinctAtKeyPath = self.propsEntry(at: keyPath) { $0.elementsEqual($1) } let afterMapping: Observable<M> if let mapping = mapping { afterMapping = distinctAtKeyPath.map(mapping) } else { afterMapping = distinctAtKeyPath as! Observable<M> } afterMapping .bind(to: binder) .disposed(by: disposeBag) } }
mit
456eb50edc8d2d3ba8e4b0ff32a94b20
40.106667
152
0.598378
4.435971
false
false
false
false
guccyon/SwiftSideMenu
SwiftSideMenu/Overlay.swift
1
2145
// // Overlay.swift // SwiftSideMenu // // Created by Tetsuro Higuchi on 2/21/16. // Copyright © 2016 wistail. All rights reserved. // import UIKit class Overlay: UIView, UIGestureRecognizerDelegate { private var swipeRecognizer: UISwipeGestureRecognizer? private var tapRecognizer: UITapGestureRecognizer? override init(frame: CGRect) { super.init(frame: frame) setup() hidden = true alpha = 0 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func show() -> Overlay { alpha = 1 return self } func hide() -> Overlay { alpha = 0 return self } func enableSwipeRecognizer(direction: UISwipeGestureRecognizerDirection, target: AnyObject, action: Selector) -> Overlay { if swipeRecognizer != nil { disableSwipeRecognizer() } swipeRecognizer = UISwipeGestureRecognizer(target: target, action: action) swipeRecognizer!.direction = direction addGestureRecognizer(swipeRecognizer!) return self } func disableSwipeRecognizer() -> Overlay { guard let swipeRecognizer = swipeRecognizer else { return self } removeGestureRecognizer(swipeRecognizer) self.swipeRecognizer = nil return self } func enableTapRecognizer(target: AnyObject, action: Selector) -> Overlay { if tapRecognizer != nil { disableTapRecognizer() } tapRecognizer = UITapGestureRecognizer(target: target, action: action) tapRecognizer?.delegate = self addGestureRecognizer(tapRecognizer!) return self } func disableTapRecognizer() -> Overlay { guard let tapRecognizer = tapRecognizer else { return self } removeGestureRecognizer(tapRecognizer) self.tapRecognizer = nil return self } private func setup() { self.backgroundColor = UIColor(hue:0, saturation:0, brightness:0.02, alpha:0.8) } static func view() -> Overlay { let frame = UIScreen.mainScreen().bounds return Overlay(frame: frame) } }
mit
c54e6cc5584a92bb7982ed1b8be07979
27.972973
126
0.645522
5.104762
false
false
false
false
festrs/Tubulus
Tubulus/DetailDocumentViewController.swift
1
3502
// // DetailDocumentType1ViewController.swift // IBoleto-Project // // Created by Felipe Dias Pereira on 2016-02-29. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import UIKit import RSBarcodes_Swift import AVFoundation class DetailDocumentViewController: UIViewController { @IBOutlet weak var expDateLabel: UILabel! @IBOutlet weak var bankLabel: UILabel! @IBOutlet weak var barCodeImageView: UIImageView! @IBOutlet weak var barCodeLineLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! var document: Document! //MARK: - APP Life override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) totalLabel.text = "\((document.value?.toMaskReais())!)" barCodeLineLabel.text = document.barCodeLine let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle self.expDateLabel.text = "\(dateFormatter.stringFromDate(document.expDate!))" let image = RSUnifiedCodeGenerator.shared.generateCode(document.remoteID!, machineReadableCodeObjectType: AVMetadataObjectTypeInterleaved2of5Code) barCodeImageView.image = image let monthName = monthsName[document.expDate!.getComponent(.Month)!] self.title = "\(document.expDate!.getComponent(.Day)!)/\(monthName!)" let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(DetailDocumentViewController.didClickBarCode(_:))) self.bankLabel.text = "\(self.document.bank!)" self.barCodeImageView.addGestureRecognizer(tapGestureRecognizer) } @IBAction func didClickBarCodeLine(sender: AnyObject) { UIPasteboard.generalPasteboard().string = document.barCodeLine let screenSize: CGRect = self.view.bounds let point = CGPoint(x: self.view.center.x, y: screenSize.height-(74)) self.view.makeToast("Número do boleto cópiado com sucesso", duration: 3.0, position: point) } func didClickBarCode(sender: UITapGestureRecognizer) { let screenSize: CGRect = self.view.bounds let backView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)) backView.backgroundColor = .whiteColor() backView.contentMode = .ScaleAspectFit backView.userInteractionEnabled = true let imageView = self.barCodeImageView let newImageView = UIImageView(image: imageView.image) newImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) newImageView.frame = CGRectMake(0, 0, screenSize.width-(screenSize.width*0.25), screenSize.height-(screenSize.height*0.2)) newImageView.center = CGPointMake(0,backView.center.y); backView.addSubview(newImageView) let tap = UITapGestureRecognizer(target: self, action: #selector(DetailDocumentViewController.dismissFullscreenImage(_:))) backView.addGestureRecognizer(tap) let viewController = UIViewController() viewController.view.addSubview(backView) let modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical viewController.modalTransitionStyle = modalStyle self.presentViewController(viewController, animated: true, completion: nil) } func dismissFullscreenImage(sender: UITapGestureRecognizer) { //sender.view?.removeFromSuperview() self.dismissViewControllerAnimated(true, completion: nil) } }
mit
7701ebb585088deb5707d38719e3feaa
46.931507
154
0.721349
4.998571
false
false
false
false
fatalhck/findr
Findr/Classes/BeaconController.swift
1
1886
// // BeaconController.swift // iBeacons // // Created by Jonathan Nobre on 9/3/16. // Copyright © 2016 JNF. All rights reserved. // import Foundation import CoreLocation public protocol BeaconDelegate { } open class BeaconController: NSObject, CLLocationManagerDelegate { static let sharedInstance = BeaconController() let locationManager = CLLocationManager() let advertisingBeacon = AdvertisingBeacon() let rangingBeacon = RangingBeacon() fileprivate override init() { super.init() self.locationManager.delegate = self } func requestAuthorization() { self.locationManager.requestAlwaysAuthorization() } func startRanging(_ beaconRegion: CLBeaconRegion!){ beaconRegion.notifyEntryStateOnDisplay = true self.rangingBeacon.startRanging(inRegion: beaconRegion, usingLocationManager: self.locationManager) } func stopRanging(_ beaconRegion: CLBeaconRegion!) { self.rangingBeacon.stopRanging(inRegion: beaconRegion, locationManager: self.locationManager) } // CLLocationManagerDelegate Delegates open func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { print("Failed monitoring region: \(error.localizedDescription)") } open func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Location manager failed: \(error.localizedDescription)") } open func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) { //print("Region Major: \(region.major!) + Region Minor: \(region.minor!) + Region: \(region.proximityUUID.UUIDString)") for beacon in beacons { print(beacon.fullDetails()) } } }
mit
0029ecafb80bcb17ee161d26d4177af6
30.949153
127
0.69443
5.37037
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/General/JS/WalletCryptoJS.swift
1
3801
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import JavaScriptCore import Localization import ToolKit extension Notification.Name { public static let walletInitialized = Notification.Name("notification_wallet_initialized") public static let walletMetadataLoaded = Notification.Name("notification_wallet_metadata_loaded") } @objc public class WalletCryptoJS: NSObject { typealias CryptoResultToJSMapper = (Result<String, PayloadCryptoError>) -> String private let payloadCrypto: PayloadCryptoAPI private let decryptionMapper: CryptoResultToJSMapper @objc override public convenience init() { self.init( payloadCrypto: resolve(), decryptionMapper: { decryptionResult in decryptionResult.walletCryptoResultJSON } ) } init(payloadCrypto: PayloadCryptoAPI, decryptionMapper: @escaping CryptoResultToJSMapper) { self.payloadCrypto = payloadCrypto self.decryptionMapper = decryptionMapper super.init() } @objc public func setup(with context: JSContext) { context.setJsFn2Pure(named: "objc_decrypt_wallet" as NSString) { [weak self] encryptedWalletData, password -> Any in self?.decryptWallet( encryptedWalletData: encryptedWalletData, password: password ) ?? PayloadCryptoError.unknown.walletCryptoResult } context.setJsFn0(named: "objc_set_is_initialized" as NSString) { let walletInitializedNotification = Notification(name: .walletInitialized) NotificationCenter.default.post(walletInitializedNotification) } context.setJsFn0(named: "objc_metadata_loaded" as NSString) { let walletMetadataLoadedNotification = Notification(name: .walletMetadataLoaded) NotificationCenter.default.post(walletMetadataLoadedNotification) } } private func decryptWallet(encryptedWalletData data: JSValue, password pw: JSValue) -> String { guard let encryptedWalletData = data.toString() else { return decryptionMapper(.failure(.noEncryptedWalletData)) } guard let password = pw.toString() else { return decryptionMapper(.failure(.noPassword)) } return payloadCrypto.decryptWallet( encryptedWalletData: encryptedWalletData, password: password ) .reduce(decryptionMapper) } } extension Result where Success == String, Failure == PayloadCryptoError { fileprivate var walletCryptoResultJSON: String { walletCryptoResult.encodedJSON } private var walletCryptoResult: WalletCryptoResult { switch self { case .success(let decryptedWallet): return WalletCryptoResult(success: decryptedWallet) case .failure(let error): return error.walletCryptoResult } } } extension PayloadCryptoError { fileprivate var walletCryptoResult: WalletCryptoResult { WalletCryptoResult(failure: localisedErrorMessage) } private var localisedErrorMessage: String { switch self { case .decryptionFailed: return LocalizationConstants.WalletPayloadKit.Error.decryptionFailed default: return LocalizationConstants.WalletPayloadKit.Error.unknown } } } private struct WalletCryptoResult: Codable { var encodedJSON: String { // swiftlint:disable:next force_try try! encodeToString(encoding: .utf8) } let success: String? let failure: String? init(success: String) { self.success = success failure = nil } init(failure: String) { success = nil self.failure = failure } }
lgpl-3.0
fb56308b06e3281fdde7e006bedb76c7
30.666667
124
0.678421
5.006588
false
false
false
false
TwistFate6/RxPersonalPhoneNum
RxContracts/RxContracts/RxLoginViewController.swift
1
4292
// // ViewController.swift // PocketContracts // // Created by RXL on 16/4/6. // Copyright © 2016年 RXL. All rights reserved. // import UIKit private let RxAccount : String = "rxl" private let RxPassword : String = "123" private let RmbSwitch :String = "RmbSwitch" private let autoLogin :String = "autoLogin" class RxLoginViewController: UIViewController { /// 密码文本输入框 @IBOutlet weak var passwordTextFiled: UITextField! /// 账号文本输入框 @IBOutlet weak var accountTextFiled: UITextField! /// 记住密码开关 @IBOutlet weak var rmbPasswordSwitch: UISwitch! /// 自动登录开关 @IBOutlet weak var autoLoginSwitch: UISwitch! /** 记住密码开关点击 */ @IBAction func rmbPasswordSwitchClick() { // 当记住密码按钮关闭,自动登录按钮关闭 if (!self.rmbPasswordSwitch.on) { self.autoLoginSwitch.setOn(false, animated: true) } } /** 自动登录开关点击 */ @IBAction func autoLoginSwitchClick() { // 当自动登录按钮打开,记住密码开关打开 if (self.autoLoginSwitch.on) { self.rmbPasswordSwitch.setOn(true, animated: true) } } /** 登录按钮点击 */ @IBAction func LoginBtnClick() { view.endEditing(true) if accountTextFiled.text == RxAccount && passwordTextFiled.text == RxPassword { if accountTextFiled.text == RxAccount { MBProgressHUD .showMessage("正在登录") // 模仿延时登录 let time: NSTimeInterval = 1 let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))) dispatch_after(delay, dispatch_get_main_queue()) { MBProgressHUD.hideHUD() MBProgressHUD.showSuccess("登录成功") self.performSegueWithIdentifier("Login", sender: self.accountTextFiled.text) } } self.saveUserInfo() }else{ MBProgressHUD .showError("账号或者密码错误") } } func saveUserInfo () { let defalut = NSUserDefaults.standardUserDefaults() defalut.setObject(accountTextFiled.text, forKey: RxAccount) defalut.setObject(passwordTextFiled.text, forKey: RxPassword) defalut.setBool(rmbPasswordSwitch.on, forKey: RmbSwitch) defalut.setBool(autoLoginSwitch.on, forKey: autoLogin) defalut.synchronize() } func loadUserInfo () { let defalut = NSUserDefaults.standardUserDefaults() accountTextFiled.text = defalut.objectForKey(RxAccount) as? String // passwordTextFiled.text = defalut.objectForKey(RxPassword) as? String rmbPasswordSwitch.on = defalut.boolForKey(RmbSwitch) autoLoginSwitch.on = defalut.boolForKey(autoLogin) // 判断是否记住密码 if (self.rmbPasswordSwitch.on) { // 密码框赋值 self.passwordTextFiled.text=defalut.valueForKey(RxPassword) as? String } if autoLoginSwitch.on { LoginBtnClick() } } @IBAction func registerBtnClick() { self.performSegueWithIdentifier("register", sender: nil) } // 准备跳转的时候调用 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.destinationViewController.isKindOfClass(RxContractsViewController) { segue.destinationViewController.title = String(format: "\(sender!)的联系人") } } override func viewDidLoad() { super.viewDidLoad() // 加载数据 loadUserInfo() } }
mit
d56d6163cf5563fdc4ba7a935c5df1f1
23.820988
96
0.536682
4.933742
false
false
false
false
mattgallagher/CwlPreconditionTesting
Sources/CwlPosixPreconditionTesting/CwlCatchBadInstructionPosix.swift
2
5812
// // CwlCatchBadInstructionPosix.swift // CwlPreconditionTesting // // Created by Matt Gallagher on 8/02/2016. // Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #if arch(x86_64) || arch(arm64) import Foundation // This file is an alternative implementation to CwlCatchBadInstruction.swift that uses a SIGILL signal action and setenv/longjmp instead of a Mach exception handler and Objective-C exception raising. // // WARNING: // This code is quick and dirty. It's a proof of concept for using a SIGILL handler and setjmp/longjmp where Mach exceptions and the Obj-C runtime aren't available. I ran the automated tests when I first wrote this code but I don't personally use it at all so by the time you're reading this comment, it probably broke and I didn't notice. // Obvious limitations: // * It doesn't work when debugging with lldb. // * It doesn't scope correctly to the thread (it's global) // * In violation of rules for signal handlers, it writes to the "red zone" on the stack // * It isn't re-entrant // * Plus all of the same caveats as the Mach exceptions version (doesn't play well with other handlers, probably leaks ARC memory, etc) // Treat it like a loaded shotgun. Don't point it at your face. // This function is called from the signal handler to shut down the thread and return 1 (indicating a SIGILL was received). let callThreadExit = { pthread_exit(UnsafeMutableRawPointer(bitPattern: 1)) } as @convention(c) () -> Void // When called, this signal handler simulates a function call to `callThreadExit` private func sigIllHandler(code: Int32, info: UnsafeMutablePointer<__siginfo>?, uap: UnsafeMutableRawPointer?) -> Void { guard let context = uap?.bindMemory(to: ucontext64_t.self, capacity: 1) else { return } #if arch(x86_64) // 1. Decrement the stack pointer context.pointee.uc_mcontext64.pointee.__ss.__rsp -= UInt64(MemoryLayout<Int>.size) // 2. Save the old Instruction Pointer to the stack. let rsp = context.pointee.uc_mcontext64.pointee.__ss.__rsp if let ump = UnsafeMutablePointer<UInt64>(bitPattern: UInt(rsp)) { ump.pointee = rsp } // 3. Set the Instruction Pointer to the new function's address context.pointee.uc_mcontext64.pointee.__ss.__rip = unsafeBitCast(callThreadExit, to: UInt64.self) #elseif arch(arm64) // 1. Set the link register to the current address. context.pointee.uc_mcontext64.pointee.__ss.__lr = context.pointee.uc_mcontext64.pointee.__ss.__pc // 2. Set the Instruction Pointer to the new function's address. context.pointee.uc_mcontext64.pointee.__ss.__pc = unsafeBitCast(callThreadExit, to: UInt64.self) #endif } /// Without Mach exceptions or the Objective-C runtime, there's nothing to put in the exception object. It's really just a boolean – either a SIGILL was caught or not. public class BadInstructionException { } #if arch(x86_64) public let nativeSignal = SIGILL #elseif arch(arm64) public let nativeSignal = SIGTRAP #endif /// Run the provided block. If a POSIX SIGILL is received, handle it and return a BadInstructionException (which is just an empty object in this POSIX signal version). Otherwise return nil. /// NOTE: This function is only intended for use in test harnesses – use in a distributed build is almost certainly a bad choice. If a SIGILL is received, the block will be interrupted using a C `longjmp`. The risks associated with abrupt jumps apply here: most Swift functions are *not* interrupt-safe. Memory may be leaked and the program will not necessarily be left in a safe state. /// - parameter block: a function without parameters that will be run /// - returns: if an SIGILL is raised during the execution of `block` then a BadInstructionException will be returned, otherwise `nil`. public func catchBadInstruction(block: @escaping () -> Void) -> BadInstructionException? { // Construct the signal action var sigActionPrev = sigaction() let action = __sigaction_u(__sa_sigaction: sigIllHandler) var sigActionNew = sigaction(__sigaction_u: action, sa_mask: sigset_t(), sa_flags: SA_SIGINFO) // Install the signal action if sigaction(nativeSignal, &sigActionNew, &sigActionPrev) != 0 { fatalError("Sigaction error: \(errno)") } defer { // Restore the previous signal action if sigaction(nativeSignal, &sigActionPrev, nil) != 0 { fatalError("Sigaction error: \(errno)") } } var b = block let caught: Bool = withUnsafeMutablePointer(to: &b) { blockPtr in // Run the block on its own thread var handlerThread: pthread_t? = nil let e = pthread_create(&handlerThread, nil, { arg in arg.bindMemory(to: (() -> Void).self, capacity: 1).pointee() return nil }, blockPtr) precondition(e == 0, "Unable to create thread") // Wait for completion and get the result. It will be either `nil` or bitPattern 1 var rawResult: UnsafeMutableRawPointer? = nil let e2 = pthread_join(handlerThread!, &rawResult) precondition(e2 == 0, "Thread join failed") return Int(bitPattern: rawResult) != 0 } return caught ? BadInstructionException() : nil } #endif
isc
930d44b274e6943fbf8d1a9fcfdf91e2
47.798319
386
0.744102
3.85591
false
false
false
false
rogeriopr/app-anti-corrupcao
ios/Impactar/FiscalizarViewController.swift
1
4236
// // FiscalizarViewController.swift // Impactar // // Created by Davi Rodrigues on 13/04/16. // Copyright © 2016 Davi Rodrigues. All rights reserved. // import UIKit import MapKit import CoreLocation class FiscalizarViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate { /// @IBOutlet weak var mapaFiscalizar: MKMapView! @IBOutlet weak var fiscalizatTitleLabel: UINavigationItem! var locationManager = CLLocationManager() var zoom = false override func viewDidLoad() { super.viewDidLoad() self.mapaFiscalizar.showsUserLocation = true self.mapaFiscalizar.zoomEnabled = true locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self locationManager.startUpdatingLocation() locationManager.requestAlwaysAuthorization() } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKCircle { let circleRenderer = MKCircleRenderer(overlay: overlay) circleRenderer.lineWidth = 1.0 //Cor do circulo circleRenderer.strokeColor = Styles.azulOverlay circleRenderer.fillColor = Styles.azulOverlay.colorWithAlphaComponent(0.2) return circleRenderer } return MKOverlayRenderer() } func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) { } func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { self.mapaFiscalizar.removeOverlays(self.mapaFiscalizar.overlays) self.mapaFiscalizar.removeAnnotations(self.mapaFiscalizar.annotations) if(self.zoom == false) { let coor = self.mapaFiscalizar.userLocation.location?.coordinate let region = MKCoordinateRegionMakeWithDistance(coor!, 2500, 2500) self.mapaFiscalizar.setRegion(region, animated: true) self.zoom = true } //Adiciona circulo em torno da localização let circleOverlay = MKCircle(centerCoordinate: mapaFiscalizar.userLocation.coordinate, radius: 1000) circleOverlay.title = "" circleOverlay.subtitle = "" mapaFiscalizar.addOverlay(circleOverlay) //Adiciona alguns pins let annotation1 = MKPointAnnotation() annotation1.coordinate = mapaFiscalizar.userLocation.coordinate annotation1.coordinate.latitude = annotation1.coordinate.latitude + 0.0010 annotation1.coordinate.longitude = annotation1.coordinate.longitude + 0.0027 annotation1.title = "Investimento escola Padre Anchieta" annotation1.subtitle = "Detalhes da ação sendo realizada nesta localização" mapaFiscalizar.addAnnotation(annotation1) let annotation2 = MKPointAnnotation() annotation2.coordinate = mapaFiscalizar.userLocation.coordinate annotation2.coordinate.latitude = annotation1.coordinate.latitude + 0.0038 annotation2.coordinate.longitude = annotation1.coordinate.longitude - 0.0050 annotation2.title = "Reforma praça pública" annotation2.subtitle = "Detalhes da ação sendo realizada nesta localização" mapaFiscalizar.addAnnotation(annotation2) let annotation3 = MKPointAnnotation() annotation3.coordinate = mapaFiscalizar.userLocation.coordinate annotation3.coordinate.latitude = annotation3.coordinate.latitude - 0.0018 annotation3.coordinate.longitude = annotation3.coordinate.longitude + 0.0027 annotation3.title = "Contratação de funcionários" annotation3.subtitle = "Detalhes da ação sendo realizada nesta localização" mapaFiscalizar.addAnnotation(annotation3) } }
gpl-3.0
002dce31cbc4db47410f6149512f9d9d
35.344828
117
0.684535
5.067308
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Browser/URLBarView.swift
2
34113
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SnapKit private struct URLBarViewUX { static let TextFieldBorderColor = UIColor.Photon.Grey40 static let TextFieldActiveBorderColor = UIColor.Photon.Blue40 static let LocationLeftPadding: CGFloat = 8 static let Padding: CGFloat = 10 static let LocationHeight: CGFloat = 40 static let ButtonHeight: CGFloat = 44 static let LocationContentOffset: CGFloat = 8 static let TextFieldCornerRadius: CGFloat = 8 static let TextFieldBorderWidth: CGFloat = 0 static let TextFieldBorderWidthSelected: CGFloat = 4 static let ProgressBarHeight: CGFloat = 3 static let TabsButtonRotationOffset: CGFloat = 1.5 static let TabsButtonHeight: CGFloat = 18.0 static let ToolbarButtonInsets = UIEdgeInsets(equalInset: Padding) } protocol URLBarDelegate: AnyObject { func urlBarDidPressTabs(_ urlBar: URLBarView) func urlBarDidPressReaderMode(_ urlBar: URLBarView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool func urlBarDidPressStop(_ urlBar: URLBarView) func urlBarDidPressReload(_ urlBar: URLBarView) func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) func urlBarDidLongPressLocation(_ urlBar: URLBarView) func urlBarDidPressQRButton(_ urlBar: URLBarView) func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) func urlBarDidTapShield(_ urlBar: URLBarView) func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? func urlBarDidPressScrollToTop(_ urlBar: URLBarView) func urlBar(_ urlBar: URLBarView, didRestoreText text: String) func urlBar(_ urlBar: URLBarView, didEnterText text: String) func urlBar(_ urlBar: URLBarView, didSubmitText text: String) // Returns either (search query, true) or (url, false). func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) func urlBarDidBeginDragInteraction(_ urlBar: URLBarView) } class URLBarView: UIView { // Additional UIAppearance-configurable properties @objc dynamic var locationBorderColor: UIColor = URLBarViewUX.TextFieldBorderColor { didSet { if !inOverlayMode { locationContainer.layer.borderColor = locationBorderColor.cgColor } } } @objc dynamic var locationActiveBorderColor: UIColor = URLBarViewUX.TextFieldActiveBorderColor { didSet { if inOverlayMode { locationContainer.layer.borderColor = locationActiveBorderColor.cgColor } } } weak var delegate: URLBarDelegate? weak var tabToolbarDelegate: TabToolbarDelegate? var helper: TabToolbarHelper? var isTransitioning: Bool = false { didSet { if isTransitioning { // Cancel any pending/in-progress animations related to the progress bar self.progressBar.setProgress(1, animated: false) self.progressBar.alpha = 0.0 } } } var toolbarIsShowing = false var topTabsIsShowing = false fileprivate var locationTextField: ToolbarTextField? /// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown, /// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode /// is *not* tied to the location text field's editing state; for instance, when selecting /// a panel, the first responder will be resigned, yet the overlay mode UI is still active. var inOverlayMode = false lazy var locationView: TabLocationView = { let locationView = TabLocationView() locationView.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius locationView.translatesAutoresizingMaskIntoConstraints = false locationView.delegate = self return locationView }() lazy var locationContainer: UIView = { let locationContainer = TabLocationContainerView() locationContainer.translatesAutoresizingMaskIntoConstraints = false locationContainer.backgroundColor = .clear return locationContainer }() let line = UIView() lazy var tabsButton: TabsButton = { let tabsButton = TabsButton.tabTrayButton() tabsButton.accessibilityIdentifier = "URLBarView.tabsButton" tabsButton.inTopTabs = false return tabsButton }() fileprivate lazy var progressBar: GradientProgressBar = { let progressBar = GradientProgressBar() progressBar.clipsToBounds = false return progressBar }() fileprivate lazy var cancelButton: UIButton = { let cancelButton = InsetButton() cancelButton.setImage(UIImage.templateImageNamed("goBack"), for: .normal) cancelButton.accessibilityIdentifier = "urlBar-cancel" cancelButton.accessibilityLabel = Strings.BackTitle cancelButton.addTarget(self, action: #selector(didClickCancel), for: .touchUpInside) cancelButton.alpha = 0 return cancelButton }() fileprivate lazy var showQRScannerButton: InsetButton = { let button = InsetButton() button.setImage(UIImage.templateImageNamed("menu-ScanQRCode"), for: .normal) button.accessibilityIdentifier = "urlBar-scanQRCode" button.accessibilityLabel = Strings.ScanQRCodeViewTitle button.clipsToBounds = false button.addTarget(self, action: #selector(showQRScanner), for: .touchUpInside) button.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .horizontal) button.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) return button }() fileprivate lazy var scrollToTopButton: UIButton = { let button = UIButton() // This button interferes with accessibility of the URL bar as it partially overlays it, and keeps getting the VoiceOver focus instead of the URL bar. // @TODO: figure out if there is an iOS standard way to do this that works with accessibility. button.isAccessibilityElement = false button.addTarget(self, action: #selector(tappedScrollToTopArea), for: .touchUpInside) return button }() var appMenuButton = ToolbarButton() var libraryButton = ToolbarButton() var bookmarkButton = ToolbarButton() var forwardButton = ToolbarButton() var stopReloadButton = ToolbarButton() var backButton: ToolbarButton = { let backButton = ToolbarButton() backButton.accessibilityIdentifier = "URLBarView.backButton" return backButton }() lazy var actionButtons: [Themeable & UIButton] = [self.tabsButton, self.libraryButton, self.appMenuButton, self.forwardButton, self.backButton, self.stopReloadButton] var currentURL: URL? { get { return locationView.url as URL? } set(newURL) { locationView.url = newURL if let url = newURL, InternalURL(url)?.isAboutHomeURL ?? false { line.isHidden = true } else { line.isHidden = false } } } fileprivate let privateModeBadge = BadgeWithBackdrop(imageName: "privateModeBadge", backdropCircleColor: UIColor.Defaults.MobilePrivatePurple) fileprivate let appMenuBadge = BadgeWithBackdrop(imageName: "menuBadge") fileprivate let warningMenuBadge = BadgeWithBackdrop(imageName: "menuWarning", imageMask: "warning-mask") override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { locationContainer.addSubview(locationView) [scrollToTopButton, line, tabsButton, progressBar, cancelButton, showQRScannerButton, libraryButton, appMenuButton, forwardButton, backButton, stopReloadButton, locationContainer].forEach { addSubview($0) } privateModeBadge.add(toParent: self) appMenuBadge.add(toParent: self) warningMenuBadge.add(toParent: self) helper = TabToolbarHelper(toolbar: self) setupConstraints() // Make sure we hide any views that shouldn't be showing in non-overlay mode. updateViewsForOverlayModeAndToolbarChanges() } fileprivate func setupConstraints() { line.snp.makeConstraints { make in make.bottom.leading.trailing.equalTo(self) make.height.equalTo(1) } scrollToTopButton.snp.makeConstraints { make in make.top.equalTo(self) make.left.right.equalTo(self.locationContainer) } progressBar.snp.makeConstraints { make in make.top.equalTo(self.snp.bottom).inset(URLBarViewUX.ProgressBarHeight / 2) make.height.equalTo(URLBarViewUX.ProgressBarHeight) make.left.right.equalTo(self) } locationView.snp.makeConstraints { make in make.edges.equalTo(self.locationContainer) } cancelButton.snp.makeConstraints { make in make.leading.equalTo(self.safeArea.leading) make.centerY.equalTo(self.locationContainer) make.size.equalTo(URLBarViewUX.ButtonHeight) } backButton.snp.makeConstraints { make in make.leading.equalTo(self.safeArea.leading).offset(URLBarViewUX.Padding) make.centerY.equalTo(self) make.size.equalTo(URLBarViewUX.ButtonHeight) } forwardButton.snp.makeConstraints { make in make.leading.equalTo(self.backButton.snp.trailing) make.centerY.equalTo(self) make.size.equalTo(URLBarViewUX.ButtonHeight) } stopReloadButton.snp.makeConstraints { make in make.leading.equalTo(self.forwardButton.snp.trailing) make.centerY.equalTo(self) make.size.equalTo(URLBarViewUX.ButtonHeight) } libraryButton.snp.makeConstraints { make in make.trailing.equalTo(self.appMenuButton.snp.leading) make.centerY.equalTo(self) make.size.equalTo(URLBarViewUX.ButtonHeight) } appMenuButton.snp.makeConstraints { make in make.trailing.equalTo(self.safeArea.trailing).offset(-URLBarViewUX.Padding) make.centerY.equalTo(self) make.size.equalTo(URLBarViewUX.ButtonHeight) } tabsButton.snp.makeConstraints { make in make.trailing.equalTo(self.appMenuButton.snp.leading) make.centerY.equalTo(self) make.size.equalTo(URLBarViewUX.ButtonHeight) } showQRScannerButton.snp.makeConstraints { make in make.trailing.equalTo(self.safeArea.trailing) make.centerY.equalTo(self.locationContainer) make.size.equalTo(URLBarViewUX.ButtonHeight) } privateModeBadge.layout(onButton: tabsButton) appMenuBadge.layout(onButton: appMenuButton) warningMenuBadge.layout(onButton: appMenuButton) } override func updateConstraints() { super.updateConstraints() if inOverlayMode { // In overlay mode, we always show the location view full width self.locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidthSelected self.locationContainer.snp.remakeConstraints { make in let height = URLBarViewUX.LocationHeight + (URLBarViewUX.TextFieldBorderWidthSelected * 2) make.height.equalTo(height) make.trailing.equalTo(self.showQRScannerButton.snp.leading) make.leading.equalTo(self.cancelButton.snp.trailing) make.centerY.equalTo(self) } self.locationView.snp.remakeConstraints { make in make.edges.equalTo(self.locationContainer).inset(UIEdgeInsets(equalInset: URLBarViewUX.TextFieldBorderWidthSelected)) } self.locationTextField?.snp.remakeConstraints { make in make.edges.equalTo(self.locationView).inset(UIEdgeInsets(top: 0, left: URLBarViewUX.LocationLeftPadding, bottom: 0, right: URLBarViewUX.LocationLeftPadding)) } } else { self.locationContainer.snp.remakeConstraints { make in if self.toolbarIsShowing { // If we are showing a toolbar, show the text field next to the forward button make.leading.equalTo(self.stopReloadButton.snp.trailing).offset(URLBarViewUX.Padding) if self.topTabsIsShowing { make.trailing.equalTo(self.libraryButton.snp.leading).offset(-URLBarViewUX.Padding) } else { make.trailing.equalTo(self.tabsButton.snp.leading).offset(-URLBarViewUX.Padding) } } else { // Otherwise, left align the location view make.leading.trailing.equalTo(self).inset(UIEdgeInsets(top: 0, left: URLBarViewUX.LocationLeftPadding-1, bottom: 0, right: URLBarViewUX.LocationLeftPadding-1)) } make.height.equalTo(URLBarViewUX.LocationHeight+2) make.centerY.equalTo(self) } self.locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth self.locationView.snp.remakeConstraints { make in make.edges.equalTo(self.locationContainer).inset(UIEdgeInsets(equalInset: URLBarViewUX.TextFieldBorderWidth)) } } } @objc func showQRScanner() { self.delegate?.urlBarDidPressQRButton(self) } func createLocationTextField() { guard locationTextField == nil else { return } locationTextField = ToolbarTextField() guard let locationTextField = locationTextField else { return } locationTextField.clipsToBounds = true locationTextField.translatesAutoresizingMaskIntoConstraints = false locationTextField.autocompleteDelegate = self locationTextField.keyboardType = .webSearch locationTextField.autocorrectionType = .no locationTextField.autocapitalizationType = .none locationTextField.returnKeyType = .go locationTextField.clearButtonMode = .whileEditing locationTextField.textAlignment = .left locationTextField.font = UIConstants.DefaultChromeFont locationTextField.accessibilityIdentifier = "address" locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.") locationTextField.attributedPlaceholder = self.locationView.placeholder locationContainer.addSubview(locationTextField) locationTextField.snp.remakeConstraints { make in make.edges.equalTo(self.locationView) } // Disable dragging urls on iPhones because it conflicts with editing the text if UIDevice.current.userInterfaceIdiom != .pad { locationTextField.textDragInteraction?.isEnabled = false } locationTextField.applyTheme() locationTextField.backgroundColor = UIColor.theme.textField.backgroundInOverlay } override func becomeFirstResponder() -> Bool { return self.locationTextField?.becomeFirstResponder() ?? false } func removeLocationTextField() { locationTextField?.removeFromSuperview() locationTextField = nil } // Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without // However, switching views dynamically at runtime is a difficult. For now, we just use one view // that can show in either mode. func setShowToolbar(_ shouldShow: Bool) { toolbarIsShowing = shouldShow setNeedsUpdateConstraints() // when we transition from portrait to landscape, calling this here causes // the constraints to be calculated too early and there are constraint errors if !toolbarIsShowing { updateConstraintsIfNeeded() } updateViewsForOverlayModeAndToolbarChanges() } func updateAlphaForSubviews(_ alpha: CGFloat) { locationContainer.alpha = alpha self.alpha = alpha } func updateProgressBar(_ progress: Float) { progressBar.alpha = 1 progressBar.isHidden = false progressBar.setProgress(progress, animated: !isTransitioning) } func hideProgressBar() { progressBar.isHidden = true progressBar.setProgress(0, animated: false) } func updateReaderModeState(_ state: ReaderModeState) { locationView.readerModeState = state } func setAutocompleteSuggestion(_ suggestion: String?) { locationTextField?.setAutocompleteSuggestion(suggestion) } func setLocation(_ location: String?, search: Bool) { guard let text = location, !text.isEmpty else { locationTextField?.text = location return } if search { locationTextField?.text = text // Not notifying when empty agrees with AutocompleteTextField.textDidChange. delegate?.urlBar(self, didRestoreText: text) } else { locationTextField?.setTextWithoutSearching(text) } } func enterOverlayMode(_ locationText: String?, pasted: Bool, search: Bool) { createLocationTextField() // Show the overlay mode UI, which includes hiding the locationView and replacing it // with the editable locationTextField. animateToOverlayState(overlayMode: true) delegate?.urlBarDidEnterOverlayMode(self) applyTheme() // Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens // won't take the initial frame of the label into consideration, which makes the label // look squished at the start of the animation and expand to be correct. As a workaround, // we becomeFirstResponder as the next event on UI thread, so the animation starts before we // set a first responder. if pasted { // Clear any existing text, focus the field, then set the actual pasted text. // This avoids highlighting all of the text. self.locationTextField?.text = "" DispatchQueue.main.async { self.locationTextField?.becomeFirstResponder() self.setLocation(locationText, search: search) } } else { DispatchQueue.main.async { self.locationTextField?.becomeFirstResponder() // Need to set location again so text could be immediately selected. self.setLocation(locationText, search: search) self.locationTextField?.selectAll(nil) } } } func leaveOverlayMode(didCancel cancel: Bool = false) { locationTextField?.resignFirstResponder() animateToOverlayState(overlayMode: false, didCancel: cancel) delegate?.urlBarDidLeaveOverlayMode(self) applyTheme() } func prepareOverlayAnimation() { // Make sure everything is showing during the transition (we'll hide it afterwards). bringSubviewToFront(self.locationContainer) cancelButton.isHidden = false showQRScannerButton.isHidden = false progressBar.isHidden = false appMenuButton.isHidden = !toolbarIsShowing libraryButton.isHidden = !toolbarIsShowing || !topTabsIsShowing forwardButton.isHidden = !toolbarIsShowing backButton.isHidden = !toolbarIsShowing tabsButton.isHidden = !toolbarIsShowing || topTabsIsShowing stopReloadButton.isHidden = !toolbarIsShowing } func transitionToOverlay(_ didCancel: Bool = false) { locationView.contentView.alpha = inOverlayMode ? 0 : 1 cancelButton.alpha = inOverlayMode ? 1 : 0 showQRScannerButton.alpha = inOverlayMode ? 1 : 0 progressBar.alpha = inOverlayMode || didCancel ? 0 : 1 tabsButton.alpha = inOverlayMode ? 0 : 1 appMenuButton.alpha = inOverlayMode ? 0 : 1 libraryButton.alpha = inOverlayMode ? 0 : 1 forwardButton.alpha = inOverlayMode ? 0 : 1 backButton.alpha = inOverlayMode ? 0 : 1 stopReloadButton.alpha = inOverlayMode ? 0 : 1 let borderColor = inOverlayMode ? locationActiveBorderColor : locationBorderColor locationContainer.layer.borderColor = borderColor.cgColor if inOverlayMode { line.isHidden = inOverlayMode // Make the editable text field span the entire URL bar, covering the lock and reader icons. locationTextField?.snp.remakeConstraints { make in make.edges.equalTo(self.locationView) } } else { // Shrink the editable text field back to the size of the location view before hiding it. locationTextField?.snp.remakeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } } } func updateViewsForOverlayModeAndToolbarChanges() { // This ensures these can't be selected as an accessibility element when in the overlay mode. locationView.overrideAccessibility(enabled: !inOverlayMode) cancelButton.isHidden = !inOverlayMode showQRScannerButton.isHidden = !inOverlayMode progressBar.isHidden = inOverlayMode appMenuButton.isHidden = !toolbarIsShowing || inOverlayMode libraryButton.isHidden = !toolbarIsShowing || inOverlayMode || !topTabsIsShowing forwardButton.isHidden = !toolbarIsShowing || inOverlayMode backButton.isHidden = !toolbarIsShowing || inOverlayMode tabsButton.isHidden = !toolbarIsShowing || inOverlayMode || topTabsIsShowing stopReloadButton.isHidden = !toolbarIsShowing || inOverlayMode // badge isHidden is tied to private mode on/off, use alpha to hide in this case [privateModeBadge, appMenuBadge, warningMenuBadge].forEach { $0.badge.alpha = (!toolbarIsShowing || inOverlayMode) ? 0 : 1 $0.backdrop.alpha = (!toolbarIsShowing || inOverlayMode) ? 0 : BadgeWithBackdrop.backdropAlpha } } func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) { prepareOverlayAnimation() layoutIfNeeded() inOverlayMode = overlay if !overlay { removeLocationTextField() } UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { self.transitionToOverlay(cancel) self.setNeedsUpdateConstraints() self.layoutIfNeeded() }, completion: { _ in self.updateViewsForOverlayModeAndToolbarChanges() }) } func didClickAddTab() { delegate?.urlBarDidPressTabs(self) } @objc func didClickCancel() { leaveOverlayMode(didCancel: true) } @objc func tappedScrollToTopArea() { delegate?.urlBarDidPressScrollToTop(self) } } extension URLBarView: TabToolbarProtocol { func privateModeBadge(visible: Bool) { if UIDevice.current.userInterfaceIdiom != .pad { privateModeBadge.show(visible) } } func appMenuBadge(setVisible: Bool) { // Warning badges should take priority over the standard badge guard warningMenuBadge.badge.isHidden else { return } appMenuBadge.show(setVisible) } func warningMenuBadge(setVisible: Bool) { // Disable other menu badges before showing the warning. if !appMenuBadge.badge.isHidden { appMenuBadge.show(false) } warningMenuBadge.show(setVisible) } func updateBackStatus(_ canGoBack: Bool) { backButton.isEnabled = canGoBack } func updateForwardStatus(_ canGoForward: Bool) { forwardButton.isEnabled = canGoForward } func updateTabCount(_ count: Int, animated: Bool = true) { tabsButton.updateTabCount(count, animated: animated) } func updateReloadStatus(_ isLoading: Bool) { helper?.updateReloadStatus(isLoading) if isLoading { stopReloadButton.setImage(helper?.ImageStop, for: .normal) } else { stopReloadButton.setImage(helper?.ImageReload, for: .normal) } } func updatePageStatus(_ isWebPage: Bool) { stopReloadButton.isEnabled = isWebPage } var access: [Any]? { get { if inOverlayMode { guard let locationTextField = locationTextField else { return nil } return [locationTextField, cancelButton] } else { if toolbarIsShowing { return [backButton, forwardButton, stopReloadButton, locationView, tabsButton, libraryButton, appMenuButton, progressBar] } else { return [locationView, progressBar] } } } set { super.accessibilityElements = newValue } } } extension URLBarView: TabLocationViewDelegate { func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool { return delegate?.urlBarDidLongPressReaderMode(self) ?? false } func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView) { guard let (locationText, isSearchQuery) = delegate?.urlBarDisplayTextForURL(locationView.url as URL?) else { return } var overlayText = locationText // Make sure to use the result from urlBarDisplayTextForURL as it is responsible for extracting out search terms when on a search page if let text = locationText, let url = URL(string: text), let host = url.host, AppConstants.MOZ_PUNYCODE { overlayText = url.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8()) } enterOverlayMode(overlayText, pasted: false, search: isSearchQuery) } func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView) { delegate?.urlBarDidLongPressLocation(self) } func tabLocationViewDidTapReload(_ tabLocationView: TabLocationView) { delegate?.urlBarDidPressReload(self) } func tabLocationViewDidTapStop(_ tabLocationView: TabLocationView) { delegate?.urlBarDidPressStop(self) } func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView) { delegate?.urlBarDidPressReaderMode(self) } func tabLocationViewDidTapPageOptions(_ tabLocationView: TabLocationView, from button: UIButton) { delegate?.urlBarDidPressPageOptions(self, from: tabLocationView.pageOptionsButton) } func tabLocationViewDidLongPressPageOptions(_ tabLocationView: TabLocationView) { delegate?.urlBarDidLongPressPageOptions(self, from: tabLocationView.pageOptionsButton) } func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? { return delegate?.urlBarLocationAccessibilityActions(self) } func tabLocationViewDidBeginDragInteraction(_ tabLocationView: TabLocationView) { delegate?.urlBarDidBeginDragInteraction(self) } func tabLocationViewDidTapShield(_ tabLocationView: TabLocationView) { delegate?.urlBarDidTapShield(self) } } extension URLBarView: AutocompleteTextFieldDelegate { func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool { guard let text = locationTextField?.text else { return true } if !text.trimmingCharacters(in: .whitespaces).isEmpty { delegate?.urlBar(self, didSubmitText: text) return true } else { return false } } func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String) { delegate?.urlBar(self, didEnterText: text) } func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool { delegate?.urlBar(self, didEnterText: "") return true } func autocompleteTextFieldDidCancel(_ autocompleteTextField: AutocompleteTextField) { leaveOverlayMode(didCancel: true) } func autocompletePasteAndGo(_ autocompleteTextField: AutocompleteTextField) { if let pasteboardContents = UIPasteboard.general.string { self.delegate?.urlBar(self, didSubmitText: pasteboardContents) } } } // MARK: UIAppearance extension URLBarView { @objc dynamic var cancelTintColor: UIColor? { get { return cancelButton.tintColor } set { return cancelButton.tintColor = newValue } } @objc dynamic var showQRButtonTintColor: UIColor? { get { return showQRScannerButton.tintColor } set { return showQRScannerButton.tintColor = newValue } } } extension URLBarView: Themeable { func applyTheme() { locationView.applyTheme() locationTextField?.applyTheme() actionButtons.forEach { $0.applyTheme() } tabsButton.applyTheme() cancelTintColor = UIColor.theme.browser.tint showQRButtonTintColor = UIColor.theme.browser.tint backgroundColor = UIColor.theme.browser.background line.backgroundColor = UIColor.theme.browser.urlBarDivider locationBorderColor = UIColor.theme.urlbar.border locationView.backgroundColor = inOverlayMode ? UIColor.theme.textField.backgroundInOverlay : UIColor.theme.textField.background locationContainer.backgroundColor = UIColor.theme.textField.background privateModeBadge.badge.tintBackground(color: UIColor.theme.browser.background) appMenuBadge.badge.tintBackground(color: UIColor.theme.browser.background) warningMenuBadge.badge.tintBackground(color: UIColor.theme.browser.background) } } extension URLBarView: PrivateModeUI { func applyUIMode(isPrivate: Bool) { if UIDevice.current.userInterfaceIdiom != .pad { privateModeBadge.show(isPrivate) } locationActiveBorderColor = UIColor.theme.urlbar.activeBorder(isPrivate) progressBar.setGradientColors(startColor: UIColor.theme.loadingBar.start(isPrivate), endColor: UIColor.theme.loadingBar.end(isPrivate)) ToolbarTextField.applyUIMode(isPrivate: isPrivate) applyTheme() } } // We need a subclass so we can setup the shadows correctly // This subclass creates a strong shadow on the URLBar class TabLocationContainerView: UIView { private struct LocationContainerUX { static let CornerRadius: CGFloat = 8 } override init(frame: CGRect) { super.init(frame: frame) let layer = self.layer layer.cornerRadius = LocationContainerUX.CornerRadius layer.masksToBounds = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ToolbarTextField: AutocompleteTextField { @objc dynamic var clearButtonTintColor: UIColor? { didSet { // Clear previous tinted image that's cache and ask for a relayout tintedClearImage = nil setNeedsLayout() } } fileprivate var tintedClearImage: UIImage? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() guard let image = UIImage.templateImageNamed("topTabs-closeTabs") else { return } if tintedClearImage == nil { if let clearButtonTintColor = clearButtonTintColor { tintedClearImage = image.tinted(withColor: clearButtonTintColor) } else { tintedClearImage = image } } // Since we're unable to change the tint color of the clear image, we need to iterate through the // subviews, find the clear button, and tint it ourselves. // https://stackoverflow.com/questions/55046917/clear-button-on-text-field-not-accessible-with-voice-over-swift if let clearButton = value(forKey: "_clearButton") as? UIButton { clearButton.setImage(tintedClearImage, for: []) } } // The default button size is 19x19, make this larger override func clearButtonRect(forBounds bounds: CGRect) -> CGRect { let r = super.clearButtonRect(forBounds: bounds) let grow: CGFloat = 16 let r2 = CGRect(x: r.minX - grow/2, y:r.minY - grow/2, width: r.width + grow, height: r.height + grow) return r2 } } extension ToolbarTextField: Themeable { func applyTheme() { backgroundColor = UIColor.theme.textField.backgroundInOverlay textColor = UIColor.theme.textField.textAndTint clearButtonTintColor = textColor tintColor = AutocompleteTextField.textSelectionColor.textFieldMode } // ToolbarTextField is created on-demand, so the textSelectionColor is a static prop for use when created static func applyUIMode(isPrivate: Bool) { textSelectionColor = UIColor.theme.urlbar.textSelectionHighlight(isPrivate) } }
mpl-2.0
10b923ec94334dc847f37745adefbcbe
38.898246
198
0.679096
5.517225
false
false
false
false
zhenghuadong11/firstGitHub
旅游app_useSwift/旅游app_useSwift/MYScenicViewController.swift
1
7178
// // MYScenicViewController.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/4/17. // Copyright © 2016年 zhenghuadong. All rights reserved. // import Foundation import UIKit class MYScenicViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate{ weak var _tableView:UITableView? var _searchTextField:UITextField? var _scenicSpotMessageModels:Array<MYScenicSpotMessageModel>? var _searchScenicSpotMessageModels:Array<MYScenicSpotMessageModel>? func setUpScenicSpotMessageModels() ->Void{ let path = NSBundle.mainBundle().pathForResource("scenicSpotMessage.plist", ofType: nil) if let _ = path { let array = NSArray(contentsOfFile:path!) as! Array<[String:AnyObject]> var dict:[String:AnyObject] var mArray:Array<MYScenicSpotMessageModel> = Array<MYScenicSpotMessageModel>() for var i1 in 0..<array.count { dict = array[i1] let recommendModel = MYScenicSpotMessageModel(dict: dict) mArray.append(recommendModel) } _scenicSpotMessageModels = mArray _searchScenicSpotMessageModels = mArray } } override func viewDidLoad() { let titleLabel = UILabel() titleLabel.text = "景点" titleLabel.frame = CGRectMake(0, 0, 100, 30) titleLabel.textAlignment = NSTextAlignment.Center titleLabel.textColor = UIColor.init(red: CGFloat(3*16+3)/256, green: CGFloat(3*16+3)/256, blue: CGFloat(3*16+3)/256, alpha: 1.0) self.navigationItem.titleView = titleLabel super.viewDidLoad() let searchTextField = UITextField() searchTextField.backgroundColor=UIColor.grayColor() let searchButton = UIButton() searchButton.setImage(UIImage.init(named: "search"), forState: UIControlState.Normal) searchButton.addTarget(self, action: #selector(searchButtonClick), forControlEvents: UIControlEvents.TouchUpInside) searchButton.frame = CGRectMake(0, 0, 30, 30) searchTextField.leftView = searchButton searchTextField.leftViewMode = UITextFieldViewMode.Always _searchTextField = searchTextField _searchTextField?.keyboardType = UIKeyboardType.Alphabet _searchTextField?.frame = CGRectMake(0, 0, 30, 30) let rightBarButtonItem = UIBarButtonItem.init(customView: _searchTextField!) self.navigationItem.rightBarButtonItem = rightBarButtonItem _searchTextField?.delegate = self _searchTextField?.placeholder = "输入景点名称" self.setUpScenicSpotMessageModels() self.createTableView() } func createTableView() -> Void { let tableView = UITableView() self.view .addSubview(tableView) _tableView = tableView tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height) } func searchButtonClick() -> Void { if _searchTextField?.frame.width > 50.0 { UIView.animateWithDuration(1.5, animations: { self._searchTextField?.frame = CGRectMake(0, 0, 30, 30) }) } else { UIView.animateWithDuration(1.5, animations: { self._searchTextField?.frame = CGRectMake(-150, 0, 150, 40) }) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self._searchScenicSpotMessageModels!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:MYScenicViewCell = MYScenicViewCell.scenicViewCellWithTableView(tableView) cell._viewController = self cell._scenicSpotMessageModel = self._searchScenicSpotMessageModels![indexPath.row] cell.collectButtonState() cell.luckeyButtonState() return cell } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var headerLabel = UILabel() headerLabel.text = "所有景点" headerLabel.textColor = UIColor.whiteColor() headerLabel.backgroundColor = UIColor.init(red: (CGFloat)(7*16+12)/256, green: (CGFloat)(12*16+13)/256, blue: (CGFloat)(7*16+12)/256, alpha: 1.0) return headerLabel } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 120 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let numString:String = _searchScenicSpotMessageModels![indexPath.row].num! self.pushShowScenicSpotViewControllerWithNum(numString) } func pushShowScenicSpotViewControllerWithNum(num:String) ->Void { let showScenicSpotViewController = MYScenicSpotShowViewController() showScenicSpotViewController._num = num self.navigationController?.pushViewController(showScenicSpotViewController, animated: true) } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { var trueString = string var newString:String = textField.text! if ((textField.text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) <= range.location) { newString = newString + trueString } else { newString = (newString as! NSString).substringToIndex(range.location) as!String } if newString == "" { _searchScenicSpotMessageModels = _scenicSpotMessageModels } else { _searchScenicSpotMessageModels?.removeAll(keepCapacity: true) for var scenicSpotMessageModel:MYScenicSpotMessageModel in _scenicSpotMessageModels! { if scenicSpotMessageModel.name!.containsString(newString) { _searchScenicSpotMessageModels?.append(scenicSpotMessageModel) } } } _tableView?.reloadData() return true } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { _searchTextField?.resignFirstResponder() } func textFieldShouldReturn(textField: UITextField) -> Bool { return textField.resignFirstResponder() } override func viewWillAppear(animated: Bool) { self._tableView?.reloadData() } }
apache-2.0
8f717880b1a8648438f2f3bda6f84523
32.24186
153
0.631594
5.011921
false
false
false
false
afarber/ios-newbie
TopsMultiple/TopsMultiple/Views/TopRow.swift
1
1613
// // TopRow.swift // TopsMultiple // // Created by Alexander Farber on 14.07.21. // import SwiftUI struct TopRow: View { let topEntity:TopEntity var body: some View { HStack { DownloadImage(url: topEntity.photo ?? "TODO") .frame(width: 60, height: 60) Spacer() Text(topEntity.given ?? "Unknown Person") .frame(minWidth: 60, maxWidth: .infinity, alignment: .leading) Spacer() VStack { Text("elo-rating \(topEntity.elo)") Text("avg-time \(topEntity.avg_time ?? "00:00")") Text("avg-score \(topEntity.avg_score)") }.fixedSize(horizontal: true, vertical: false) }.font(.footnote) } } struct TopRow_Previews: PreviewProvider { static var topEntity : TopEntity { let topEntity = TopEntity(context: PersistenceController.preview.container.viewContext) topEntity.uid = 19265 topEntity.elo = 2659 topEntity.given = "Alex" topEntity.motto = "TODO" topEntity.photo = "https://slova.de/words/images/female_happy.png" topEntity.avg_score = 18.8 topEntity.avg_time = "03:06" return topEntity } static var previews: some View { ForEach(["en", "de", "ru"], id: \.self) { localeId in TopRow(topEntity: topEntity) .environment(\.locale, .init(identifier: localeId)) .padding() .previewLayout(.sizeThatFits) .previewDisplayName("locale: \(localeId)") } } }
unlicense
ce32a474258d1e7b659ceda47240800c
28.87037
95
0.559826
4.002481
false
false
false
false
artyom-stv/TextInputKit
TextInputKit/TextInputKit/Code/SpecializedTextInput/BankCardExpiryDate/BankCardExpiryDate.swift
1
6371
// // BankCardExpiryDate.swift // TextInputKit // // Created by Artem Starosvetskiy on 22/12/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // import Foundation public struct BankCardExpiryDate { /// An error thrown by `BankCardExpiryDate` initializers. /// /// - invalidMonth: The provided integer doesn't represent a valid month. /// - invalidYear: The provided integer doesn't represent a valid year. public enum InitializationError : Error { case invalidMonth case invalidYear } /// The expiration date month. public let month: Int /// The expiration date year. public let year: Int /// Creates a `BankCardExpiryDate` using a month and a year. /// /// - Parameters: /// - month: The expiration date month. /// - year: The expiration date year. /// - Throws: /// - `InitializationError.invalidMonth` if the provided integer doesn't represent a valid month /// (doesn't fit 1...12). /// - `InitializationError.invalidYear` if the provided integer doesn't represent a valid year. public init(month: Int, year: Int) throws { guard month >= 1 && month <= 12 else { throw InitializationError.invalidMonth } guard year >= 1900 else { throw InitializationError.invalidYear } self.init(rawMonth: month, rawYear: year) } /// Creates a `BankCardExpiryDate` using a month and the last two digits of a year. /// /// - Parameters: /// - month: The expiration date month. /// - lastTwoDigitsOfYear: The last two ditis of the expiration date year. /// - `InitializationError.invalidMonth` if the provided integer doesn't represent a valid month /// (doesn't fit 1...12). /// - `InitializationError.invalidYear` if the provided integer doesn't represent a valid year /// (doesn't fit 0...99). public init(month: Int, lastTwoDigitsOfYear: Int) throws { guard month >= 1 && month <= 12 else { throw InitializationError.invalidMonth } guard lastTwoDigitsOfYear >= 0 && lastTwoDigitsOfYear <= 99 else { throw InitializationError.invalidYear } let year = type(of: self).year(fromTwoDigits: lastTwoDigitsOfYear) self.init(rawMonth: month, rawYear: year) } private init(rawMonth: Int, rawYear: Int) { self.month = rawMonth self.year = rawYear } } extension BankCardExpiryDate.InitializationError : CustomStringConvertible { public var description: String { switch self { case .invalidMonth: return "The provided integer doesn't represent a valid month." case .invalidYear: return "The provided integer doesn't represent a valid year." } } } private extension BankCardExpiryDate { static func year(fromTwoDigits lastTwoDigitsOfYear: Int) -> Int { assert(lastTwoDigitsOfYear >= 0 && lastTwoDigitsOfYear <= 99) // TODO: Find the rule and implement correctly. // The reason to use a magic number 67: the first bank card was issued in 1967. return lastTwoDigitsOfYear >= 67 ? lastTwoDigitsOfYear + 1900 : lastTwoDigitsOfYear + 2000 } } extension BankCardExpiryDate { /// An error thrown by `BankCardExpiryDate` factory methods. /// /// - missingMonth: The provided `DateComponents` should have non-nil `month`. /// - missingYear: The provided `DateComponents` should have non-nil `year`. public enum FactoryMethodError : Error { case missingMonth case missingYear } /// Creates a `BankCardExpiryDate` using `DateComponents` `month` and `year`. /// /// - Parameters: /// - dateComponents: The `DateComponents`. /// - Returns: The created `BankCardExpiryDate`. /// - Throws: /// - `FactoryMethodError.missingMonth` if `month` in `DateComponents` is nil. /// - `FactoryMethodError.missingYear` if `year` in `DateComponents` is nil. public static func from(_ dateComponents: DateComponents) throws -> BankCardExpiryDate { guard let month = dateComponents.month else { throw FactoryMethodError.missingMonth } guard let year = dateComponents.year else { throw FactoryMethodError.missingYear } return try self.init(month: month, year: year) } /// Creates a `BankCardExpiryDate` using a `Date` and a `Calendar`. /// /// - Parameters: /// - date: The `Date`. /// - calendar: The `Calendar` which is used to extract `DateComponents` from the `Date`. /// - Returns: The created `BankCardExpiryDate`. public static func from(_ date: Date, calendar: Calendar) -> BankCardExpiryDate { let dateComponents = calendar.dateComponents([.month, .year], from: date) return try! from(dateComponents) } /// Creates `DateComponents` corresponding to the `BankCardExpiryDate`. /// /// - Returns: The created `DateComponents`. public func toDateComponents() -> DateComponents { return DateComponents(year: year, month: month) } /// Creates a `Date` corresponding to the `BankCardExpiryDate`. /// /// - Parameters: /// - calendar: The `Calendar` which is used to create a `Date` from `DateComponents`. /// - Returns: The created `Date`. public func toDate(using calendar: Calendar) -> Date { let dateComponents = toDateComponents() return calendar.date(from: dateComponents)! } } extension BankCardExpiryDate.FactoryMethodError : CustomStringConvertible { public var description: String { switch self { case .missingMonth: return "The provided `DateComponents` should have non-nil `month`." case .missingYear: return "The provided `DateComponents` should have non-nil `year`." } } } extension BankCardExpiryDate: Equatable { public static func ==(lhs: BankCardExpiryDate, rhs: BankCardExpiryDate) -> Bool { return (lhs.year == rhs.year) && (lhs.month == rhs.month) } } extension BankCardExpiryDate: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(year) hasher.combine(month) } }
mit
aaee8a13f5dea3d63ebbad277ccd7d04
31.171717
102
0.639874
4.460784
false
false
false
false
robbdimitrov/pixelgram-ios
PixelGram/Classes/Shared/Extensions/FullWidthCell.swift
1
2496
// // FullWidthCell.swift // PixelGram // // Created by Robert Dimitrov on 10/31/17. // Copyright © 2017 Robert Dimitrov. All rights reserved. // import UIKit protocol FullWidth {} extension FullWidth where Self: UICollectionReusableView { func calculatePreferredLayoutFrame(_ origin: CGPoint, targetWidth: CGFloat) -> CGRect { let targetSize = CGSize(width: targetWidth, height: 0) let horizontalFittingPriority = UILayoutPriority.required let verticalFittingPriority = UILayoutPriority.defaultLow var autoLayoutSize: CGSize if let contentView = (self as? UICollectionViewCell)?.contentView { autoLayoutSize = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) } else { autoLayoutSize = systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) } let autoLayoutFrame = CGRect(origin: origin, size: autoLayoutSize) return autoLayoutFrame } } class FullWidthCollectionReusableView: UICollectionReusableView, FullWidth { override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes) autoLayoutAttributes.frame = calculatePreferredLayoutFrame(layoutAttributes.frame.origin, targetWidth: layoutAttributes.frame.width) return autoLayoutAttributes } } class FullWidthCollectionViewCell: UICollectionViewCell, FullWidth { override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes) autoLayoutAttributes.frame = calculatePreferredLayoutFrame(layoutAttributes.frame.origin, targetWidth: layoutAttributes.frame.width) return autoLayoutAttributes } }
mit
01a0ef2f49b7c50ca9a87d0cf527d29e
39.241935
142
0.671343
7.252907
false
false
false
false