repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Alloc-Studio/Hypnos
Hypnos/Pods/SlideMenuControllerSwift/Source/SlideMenuController.swift
2
40667
// // SlideMenuController.swift // // Created by Yuji Hato on 12/3/14. // import Foundation import UIKit @objc public protocol SlideMenuControllerDelegate { optional func leftWillOpen() optional func leftDidOpen() optional func leftWillClose() optional func leftDidClose() optional func rightWillOpen() optional func rightDidOpen() optional func rightWillClose() optional func rightDidClose() } public struct SlideMenuOptions { public static var leftViewWidth: CGFloat = 270.0 public static var leftBezelWidth: CGFloat? = 16.0 public static var contentViewScale: CGFloat = 0.96 public static var contentViewOpacity: CGFloat = 0.5 public static var shadowOpacity: CGFloat = 0.0 public static var shadowRadius: CGFloat = 0.0 public static var shadowOffset: CGSize = CGSizeMake(0,0) public static var panFromBezel: Bool = true public static var animationDuration: CGFloat = 0.4 public static var rightViewWidth: CGFloat = 270.0 public static var rightBezelWidth: CGFloat? = 16.0 public static var rightPanFromBezel: Bool = true public static var hideStatusBar: Bool = true public static var pointOfNoReturnWidth: CGFloat = 44.0 public static var simultaneousGestureRecognizers: Bool = true public static var opacityViewBackgroundColor: UIColor = UIColor.blackColor() } public class SlideMenuController: UIViewController, UIGestureRecognizerDelegate { public enum SlideAction { case Open case Close } public enum TrackAction { case LeftTapOpen case LeftTapClose case LeftFlickOpen case LeftFlickClose case RightTapOpen case RightTapClose case RightFlickOpen case RightFlickClose } struct PanInfo { var action: SlideAction var shouldBounce: Bool var velocity: CGFloat } public weak var delegate: SlideMenuControllerDelegate? public var opacityView = UIView() public var mainContainerView = UIView() public var leftContainerView = UIView() public var rightContainerView = UIView() public var mainViewController: UIViewController? public var leftViewController: UIViewController? public var leftPanGesture: UIPanGestureRecognizer? public var leftTapGesture: UITapGestureRecognizer? public var rightViewController: UIViewController? public var rightPanGesture: UIPanGestureRecognizer? public var rightTapGesture: UITapGestureRecognizer? public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController initView() } public convenience init(mainViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController rightViewController = rightMenuViewController initView() } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController rightViewController = rightMenuViewController initView() } public override func awakeFromNib() { initView() } deinit { } public func initView() { mainContainerView = UIView(frame: view.bounds) mainContainerView.backgroundColor = UIColor.clearColor() mainContainerView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] view.insertSubview(mainContainerView, atIndex: 0) var opacityframe: CGRect = view.bounds let opacityOffset: CGFloat = 0 opacityframe.origin.y = opacityframe.origin.y + opacityOffset opacityframe.size.height = opacityframe.size.height - opacityOffset opacityView = UIView(frame: opacityframe) opacityView.backgroundColor = SlideMenuOptions.opacityViewBackgroundColor opacityView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] opacityView.layer.opacity = 0.0 view.insertSubview(opacityView, atIndex: 1) if leftViewController != nil { var leftFrame: CGRect = view.bounds leftFrame.size.width = SlideMenuOptions.leftViewWidth leftFrame.origin.x = leftMinOrigin(); let leftOffset: CGFloat = 0 leftFrame.origin.y = leftFrame.origin.y + leftOffset leftFrame.size.height = leftFrame.size.height - leftOffset leftContainerView = UIView(frame: leftFrame) leftContainerView.backgroundColor = UIColor.clearColor() leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(leftContainerView, atIndex: 2) addLeftGestures() } if rightViewController != nil { var rightFrame: CGRect = view.bounds rightFrame.size.width = SlideMenuOptions.rightViewWidth rightFrame.origin.x = rightMinOrigin() let rightOffset: CGFloat = 0 rightFrame.origin.y = rightFrame.origin.y + rightOffset; rightFrame.size.height = rightFrame.size.height - rightOffset rightContainerView = UIView(frame: rightFrame) rightContainerView.backgroundColor = UIColor.clearColor() rightContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(rightContainerView, atIndex: 3) addRightGestures() } } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) leftContainerView.hidden = true rightContainerView.hidden = true coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.closeLeftNonAnimation() self.closeRightNonAnimation() self.leftContainerView.hidden = false self.rightContainerView.hidden = false if self.leftPanGesture != nil && self.leftPanGesture != nil { self.removeLeftGestures() self.addLeftGestures() } if self.rightPanGesture != nil && self.rightPanGesture != nil { self.removeRightGestures() self.addRightGestures() } }) } public override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge.None } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if let mainController = self.mainViewController{ return mainController.supportedInterfaceOrientations() } return UIInterfaceOrientationMask.All } public override func viewWillLayoutSubviews() { // topLayoutGuideの値が確定するこのタイミングで各種ViewControllerをセットする setUpViewController(mainContainerView, targetViewController: mainViewController) setUpViewController(leftContainerView, targetViewController: leftViewController) setUpViewController(rightContainerView, targetViewController: rightViewController) } public override func openLeft() { guard let _ = leftViewController else { // If leftViewController is nil, then return return } self.delegate?.leftWillOpen?() setOpenWindowLevel() // for call viewWillAppear of leftViewController leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) openLeftWithVelocity(0.0) track(.LeftTapOpen) } public override func openRight() { guard let _ = rightViewController else { // If rightViewController is nil, then return return } self.delegate?.rightWillOpen?() setOpenWindowLevel() rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) openRightWithVelocity(0.0) track(.RightTapOpen) } public override func closeLeft() { guard let _ = leftViewController else { // If leftViewController is nil, then return return } self.delegate?.leftWillClose?() leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) closeLeftWithVelocity(0.0) setCloseWindowLebel() } public override func closeRight() { guard let _ = rightViewController else { // If rightViewController is nil, then return return } self.delegate?.rightWillClose?() rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) closeRightWithVelocity(0.0) setCloseWindowLebel() } public func addLeftGestures() { if (leftViewController != nil) { if leftPanGesture == nil { leftPanGesture = UIPanGestureRecognizer(target: self, action: #selector(self.handleLeftPanGesture(_:))) leftPanGesture!.delegate = self view.addGestureRecognizer(leftPanGesture!) } if leftTapGesture == nil { leftTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.toggleLeft)) leftTapGesture!.delegate = self view.addGestureRecognizer(leftTapGesture!) } } } public func addRightGestures() { if (rightViewController != nil) { if rightPanGesture == nil { rightPanGesture = UIPanGestureRecognizer(target: self, action: #selector(self.handleRightPanGesture(_:))) rightPanGesture!.delegate = self view.addGestureRecognizer(rightPanGesture!) } if rightTapGesture == nil { rightTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.toggleRight)) rightTapGesture!.delegate = self view.addGestureRecognizer(rightTapGesture!) } } } public func removeLeftGestures() { if leftPanGesture != nil { view.removeGestureRecognizer(leftPanGesture!) leftPanGesture = nil } if leftTapGesture != nil { view.removeGestureRecognizer(leftTapGesture!) leftTapGesture = nil } } public func removeRightGestures() { if rightPanGesture != nil { view.removeGestureRecognizer(rightPanGesture!) rightPanGesture = nil } if rightTapGesture != nil { view.removeGestureRecognizer(rightTapGesture!) rightTapGesture = nil } } public func isTagetViewController() -> Bool { // Function to determine the target ViewController // Please to override it if necessary return true } public func track(trackAction: TrackAction) { // function is for tracking // Please to override it if necessary } struct LeftPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false static var lastState : UIGestureRecognizerState = .Ended } func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isRightOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: if LeftPanState.lastState != .Ended && LeftPanState.lastState != .Cancelled && LeftPanState.lastState != .Failed { return } if isLeftHidden() { self.delegate?.leftWillOpen?() } else { self.delegate?.leftWillClose?() } LeftPanState.frameAtStartOfPan = leftContainerView.frame LeftPanState.startPointOfPan = panGesture.locationInView(view) LeftPanState.wasOpenAtStartOfPan = isLeftOpen() LeftPanState.wasHiddenAtStartOfPan = isLeftHidden() leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(leftContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: if LeftPanState.lastState != .Began && LeftPanState.lastState != .Changed { return } let translation: CGPoint = panGesture.translationInView(panGesture.view!) leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan) applyLeftOpacity() applyLeftContentViewScale() case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled: if LeftPanState.lastState != .Changed { return } let velocity:CGPoint = panGesture.velocityInView(panGesture.view) let panInfo: PanInfo = panLeftResultInfoForVelocity(velocity) if panInfo.action == .Open { if !LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(true, animated: true) } openLeftWithVelocity(panInfo.velocity) track(.LeftFlickOpen) } else { if LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(false, animated: true) } closeLeftWithVelocity(panInfo.velocity) setCloseWindowLebel() track(.LeftFlickClose) } case UIGestureRecognizerState.Failed, UIGestureRecognizerState.Possible: break } LeftPanState.lastState = panGesture.state } struct RightPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false static var lastState : UIGestureRecognizerState = .Ended } func handleRightPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isLeftOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: if RightPanState.lastState != .Ended && RightPanState.lastState != .Cancelled && RightPanState.lastState != .Failed { return } if isRightHidden() { self.delegate?.rightWillOpen?() } else { self.delegate?.rightWillClose?() } RightPanState.frameAtStartOfPan = rightContainerView.frame RightPanState.startPointOfPan = panGesture.locationInView(view) RightPanState.wasOpenAtStartOfPan = isRightOpen() RightPanState.wasHiddenAtStartOfPan = isRightHidden() rightViewController?.beginAppearanceTransition(RightPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(rightContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: if RightPanState.lastState != .Began && RightPanState.lastState != .Changed { return } let translation: CGPoint = panGesture.translationInView(panGesture.view!) rightContainerView.frame = applyRightTranslation(translation, toFrame: RightPanState.frameAtStartOfPan) applyRightOpacity() applyRightContentViewScale() case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled: if RightPanState.lastState != .Changed { return } let velocity: CGPoint = panGesture.velocityInView(panGesture.view) let panInfo: PanInfo = panRightResultInfoForVelocity(velocity) if panInfo.action == .Open { if !RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(true, animated: true) } openRightWithVelocity(panInfo.velocity) track(.RightFlickOpen) } else { if RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(false, animated: true) } closeRightWithVelocity(panInfo.velocity) setCloseWindowLebel() track(.RightFlickClose) } case UIGestureRecognizerState.Failed, UIGestureRecognizerState.Possible: break } RightPanState.lastState = panGesture.state } public func openLeftWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = leftContainerView.frame.origin.x let finalXOrigin: CGFloat = 0.0 var frame = leftContainerView.frame; frame.origin.x = finalXOrigin; var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(leftContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() strongSelf.delegate?.leftDidOpen?() } } } public func openRightWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = rightContainerView.frame.origin.x // CGFloat finalXOrigin = SlideMenuOptions.rightViewOverlapWidth; let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width var frame = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(rightContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() strongSelf.delegate?.rightDidOpen?() } } } public func closeLeftWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = leftContainerView.frame.origin.x let finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.leftContainerView) strongSelf.enableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() strongSelf.delegate?.leftDidClose?() } } } public func closeRightWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = rightContainerView.frame.origin.x let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.rightContainerView) strongSelf.enableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() strongSelf.delegate?.rightDidClose?() } } } public override func toggleLeft() { if isLeftOpen() { closeLeft() setCloseWindowLebel() // Tracking of close tap is put in here. Because closeMenu is due to be call even when the menu tap. track(.LeftTapClose) } else { openLeft() } } public func isLeftOpen() -> Bool { return leftViewController != nil && leftContainerView.frame.origin.x == 0.0 } public func isLeftHidden() -> Bool { return leftContainerView.frame.origin.x <= leftMinOrigin() } public override func toggleRight() { if isRightOpen() { closeRight() setCloseWindowLebel() // Tracking of close tap is put in here. Because closeMenu is due to be call even when the menu tap. track(.RightTapClose) } else { openRight() } } public func isRightOpen() -> Bool { return rightViewController != nil && rightContainerView.frame.origin.x == CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width } public func isRightHidden() -> Bool { return rightContainerView.frame.origin.x >= CGRectGetWidth(view.bounds) } public func changeMainViewController(mainViewController: UIViewController, close: Bool) { removeViewController(self.mainViewController) self.mainViewController = mainViewController setUpViewController(mainContainerView, targetViewController: mainViewController) if (close) { closeLeft() closeRight() } } public func changeLeftViewWidth(width: CGFloat) { SlideMenuOptions.leftViewWidth = width; var leftFrame: CGRect = view.bounds leftFrame.size.width = width leftFrame.origin.x = leftMinOrigin(); let leftOffset: CGFloat = 0 leftFrame.origin.y = leftFrame.origin.y + leftOffset leftFrame.size.height = leftFrame.size.height - leftOffset leftContainerView.frame = leftFrame; } public func changeRightViewWidth(width: CGFloat) { SlideMenuOptions.rightBezelWidth = width; var rightFrame: CGRect = view.bounds rightFrame.size.width = width rightFrame.origin.x = rightMinOrigin() let rightOffset: CGFloat = 0 rightFrame.origin.y = rightFrame.origin.y + rightOffset; rightFrame.size.height = rightFrame.size.height - rightOffset rightContainerView.frame = rightFrame; } public func changeLeftViewController(leftViewController: UIViewController, closeLeft:Bool) { removeViewController(self.leftViewController) self.leftViewController = leftViewController setUpViewController(leftContainerView, targetViewController: leftViewController) if closeLeft { self.closeLeft() } } public func changeRightViewController(rightViewController: UIViewController, closeRight:Bool) { removeViewController(self.rightViewController) self.rightViewController = rightViewController; setUpViewController(rightContainerView, targetViewController: rightViewController) if closeRight { self.closeRight() } } private func leftMinOrigin() -> CGFloat { return -SlideMenuOptions.leftViewWidth } private func rightMinOrigin() -> CGFloat { return CGRectGetWidth(view.bounds) } private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo { let thresholdVelocity: CGFloat = 1000.0 let pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + SlideMenuOptions.pointOfNoReturnWidth let leftOrigin: CGFloat = leftContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open; if velocity.x >= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if velocity.x <= (-1.0 * thresholdVelocity) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func panRightResultInfoForVelocity(velocity: CGPoint) -> PanInfo { let thresholdVelocity: CGFloat = -1000.0 let pointOfNoReturn: CGFloat = CGFloat(floor(CGRectGetWidth(view.bounds)) - SlideMenuOptions.pointOfNoReturnWidth) let rightOrigin: CGFloat = rightContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = rightOrigin >= pointOfNoReturn ? .Close : .Open if velocity.x <= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if (velocity.x >= (-1.0 * thresholdVelocity)) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x let minOrigin: CGFloat = leftMinOrigin() let maxOrigin: CGFloat = 0.0 var newFrame: CGRect = toFrame if newOrigin < minOrigin { newOrigin = minOrigin } else if newOrigin > maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func applyRightTranslation(translation: CGPoint, toFrame: CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x let minOrigin: CGFloat = rightMinOrigin() let maxOrigin: CGFloat = rightMinOrigin() - rightContainerView.frame.size.width var newFrame: CGRect = toFrame if newOrigin > minOrigin { newOrigin = minOrigin } else if newOrigin < maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func getOpenedLeftRatio() -> CGFloat { let width: CGFloat = leftContainerView.frame.size.width let currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin() return currentPosition / width } private func getOpenedRightRatio() -> CGFloat { let width: CGFloat = rightContainerView.frame.size.width let currentPosition: CGFloat = rightContainerView.frame.origin.x return -(currentPosition - CGRectGetWidth(view.bounds)) / width } private func applyLeftOpacity() { let openedLeftRatio: CGFloat = getOpenedLeftRatio() let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedLeftRatio opacityView.layer.opacity = Float(opacity) } private func applyRightOpacity() { let openedRightRatio: CGFloat = getOpenedRightRatio() let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedRightRatio opacityView.layer.opacity = Float(opacity) } private func applyLeftContentViewScale() { let openedLeftRatio: CGFloat = getOpenedLeftRatio() let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedLeftRatio); mainContainerView.transform = CGAffineTransformMakeScale(scale, scale) } private func applyRightContentViewScale() { let openedRightRatio: CGFloat = getOpenedRightRatio() let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedRightRatio) mainContainerView.transform = CGAffineTransformMakeScale(scale, scale) } private func addShadowToView(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = false targetContainerView.layer.shadowOffset = SlideMenuOptions.shadowOffset targetContainerView.layer.shadowOpacity = Float(SlideMenuOptions.shadowOpacity) targetContainerView.layer.shadowRadius = SlideMenuOptions.shadowRadius targetContainerView.layer.shadowPath = UIBezierPath(rect: targetContainerView.bounds).CGPath } private func removeShadow(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = true mainContainerView.layer.opacity = 1.0 } private func removeContentOpacity() { opacityView.layer.opacity = 0.0 } private func addContentOpacity() { opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) } private func disableContentInteraction() { mainContainerView.userInteractionEnabled = false } private func enableContentInteraction() { mainContainerView.userInteractionEnabled = true } private func setOpenWindowLevel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelStatusBar + 1 } }) } } private func setCloseWindowLebel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelNormal } }) } } private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) { if let viewController = targetViewController { addChildViewController(viewController) viewController.view.frame = targetView.bounds targetView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) } } private func removeViewController(viewController: UIViewController?) { if let _viewController = viewController { _viewController.view.layer.removeAllAnimations() _viewController.willMoveToParentViewController(nil) _viewController.view.removeFromSuperview() _viewController.removeFromParentViewController() } } public func closeLeftNonAnimation(){ setCloseWindowLebel() let finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin leftContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(leftContainerView) enableContentInteraction() } public func closeRightNonAnimation(){ setCloseWindowLebel() let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin rightContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(rightContainerView) enableContentInteraction() } // MARK: UIGestureRecognizerDelegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { let point: CGPoint = touch.locationInView(view) if gestureRecognizer == leftPanGesture { return slideLeftForGestureRecognizer(gestureRecognizer, point: point) } else if gestureRecognizer == rightPanGesture { return slideRightViewForGestureRecognizer(gestureRecognizer, withTouchPoint: point) } else if gestureRecognizer == leftTapGesture { return isLeftOpen() && !isPointContainedWithinLeftRect(point) } else if gestureRecognizer == rightTapGesture { return isRightOpen() && !isPointContainedWithinRightRect(point) } return true } // returning true here helps if the main view is fullwidth with a scrollview public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return SlideMenuOptions.simultaneousGestureRecognizers } private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{ return isLeftOpen() || SlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point) } private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{ if let bezelWidth = SlideMenuOptions.leftBezelWidth { var leftBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(leftBezelRect, point) } else { return true } } private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool { return CGRectContainsPoint(leftContainerView.frame, point) } private func slideRightViewForGestureRecognizer(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool { return isRightOpen() || SlideMenuOptions.rightPanFromBezel && isRightPointContainedWithinBezelRect(point) } private func isRightPointContainedWithinBezelRect(point: CGPoint) -> Bool { if let rightBezelWidth = SlideMenuOptions.rightBezelWidth { var rightBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero let bezelWidth: CGFloat = CGRectGetWidth(view.bounds) - rightBezelWidth CGRectDivide(view.bounds, &tempRect, &rightBezelRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(rightBezelRect, point) } else { return true } } private func isPointContainedWithinRightRect(point: CGPoint) -> Bool { return CGRectContainsPoint(rightContainerView.frame, point) } } extension UIViewController { public func slideMenuController() -> SlideMenuController? { var viewController: UIViewController? = self while viewController != nil { if viewController is SlideMenuController { return viewController as? SlideMenuController } viewController = viewController?.parentViewController } return nil; } public func addLeftBarButtonWithImage(buttonImage: UIImage) { let leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.toggleLeft)) navigationItem.leftBarButtonItem = leftButton; } public func addRightBarButtonWithImage(buttonImage: UIImage) { let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.toggleRight)) navigationItem.rightBarButtonItem = rightButton; } public func toggleLeft() { slideMenuController()?.toggleLeft() } public func toggleRight() { slideMenuController()?.toggleRight() } public func openLeft() { slideMenuController()?.openLeft() } public func openRight() { slideMenuController()?.openRight() } public func closeLeft() { slideMenuController()?.closeLeft() } public func closeRight() { slideMenuController()?.closeRight() } // Please specify if you want menu gesuture give priority to than targetScrollView public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) { guard let slideController = slideMenuController(), let recognizers = slideController.view.gestureRecognizers else { return } for recognizer in recognizers where recognizer is UIPanGestureRecognizer { targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer) } } }
mit
f06a1ce81dde957d8f2dcffcbe48e9ea
37.613118
179
0.63802
6.217817
false
false
false
false
roddi/FURRDataSource
RushingCells/RushingCells/Rusher.swift
1
1917
// swiftlint:disable line_length // // Rusher.swift // RushingCells // // Created by Deecke,Roddi on 26.08.15. // Copyright © 2015-2016 Ruotger Deecke. All rights reserved. // // // TL/DR; BSD 2-clause license // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import UIKit class Rusher: DataItem { let identifier: String var date: Date var additionalString = "" init(inIdentifier: String) { self.identifier = inIdentifier self.date = Date.distantPast } } extension Rusher: Equatable { } func == (lhs: Rusher, rhs: Rusher) -> Bool { return (lhs.identifier == rhs.identifier) && (lhs.additionalString == rhs.additionalString) }
bsd-2-clause
4f2f6b8496ef17e39c0d17266d6a4210
38.916667
119
0.744781
4.286353
false
false
false
false
MTTHWBSH/Gaggle
Gaggle/Controllers/Intro/LoginSignupViewController.swift
1
7322
// // LoginSignupViewController.swift // Gaggle // // Created by Matthew Bush on 9/19/15. // Copyright © 2015 Matthew Bush. All rights reserved. // import UIKit import Parse import SVProgressHUD class LoginSignupViewController: ViewController, UITextFieldDelegate, UIScrollViewDelegate { @IBOutlet var usernameTextField: UITextField! @IBOutlet var passwordTextField: UITextField! @IBOutlet var brandLabel: UILabel! @IBOutlet var loginSignupButton: PrimaryButton! @IBOutlet var scrollView: UIScrollView! var selectedLogin: Bool! var loginSignupButtonText = "" @IBAction func closeButtonPressed(_ sender: BarButtonItem) { dismiss(animated: true, completion: nil) } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewDidLoad() { super.viewDidLoad() setupView() styleView() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Analytics.logScreen("Login/Signup") } func setupView() { setupLogo() usernameTextField.delegate = self passwordTextField.delegate = self scrollView.delegate = self usernameTextField.autocapitalizationType = .none usernameTextField.autocorrectionType = .no passwordTextField.autocapitalizationType = .none passwordTextField.autocorrectionType = .no loginSignupButton.setTitle(loginSignupButtonText, for: UIControlState()) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tap) } override func styleView() { Style.addBottomBorder(toLayer: usernameTextField.layer, onFrame: usernameTextField.frame, color: Style.grayColor.cgColor) Style.addBottomBorder(toLayer: passwordTextField.layer, onFrame: passwordTextField.frame, color: Style.grayColor.cgColor) usernameTextField.tintColor = Style.blueColor passwordTextField.tintColor = Style.blueColor brandLabel.textColor = Style.blueColor brandLabel.font = Style.brandFontWithSize(72.0) } func setupLogo() { let attachment:NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: "GooseWordMark") guard let image = attachment.image else { return } attachment.bounds = CGRect(x: 0, y: -18.0, width: image.size.width, height: image.size.height) let attachmentString = NSAttributedString(attachment: attachment) let brandString = NSMutableAttributedString(string: "ga") let brandStringFinish = NSMutableAttributedString(string: "gle") brandString.append(attachmentString) brandString.append(brandStringFinish) brandLabel.attributedText = brandString } func dismissKeyboard() { view.endEditing(true) } @IBAction func loginSignupButtonPressed(_ sender: AnyObject) { tryLoginSignup() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == usernameTextField { passwordTextField.becomeFirstResponder() } else if textField == passwordTextField { textField.resignFirstResponder() tryLoginSignup() } return true } // MARK: Keyboard Avoidance func keyboardWillShow(_ note: Notification) { var keyboardFrame = (note.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue keyboardFrame = view.convert(keyboardFrame, from: nil) var contentInset:UIEdgeInsets = scrollView.contentInset contentInset.bottom = keyboardFrame.size.height + 20 scrollView.contentInset = contentInset if let activeView = activeView() { scrollView.scrollRectToVisible(activeView.frame, animated: false) } } func activeView() -> UIView? { return [usernameTextField, passwordTextField].filter { return $0.isFirstResponder }.first } func keyboardWillHide(_ note: Notification) { let contentInset:UIEdgeInsets = UIEdgeInsets.zero scrollView.contentInset = contentInset } // MARK: Login/Signup func tryLoginSignup() { if usernameTextField.text != "" && passwordTextField.text != "" { if let user = usernameTextField.text, let password = passwordTextField.text { if !selectedLogin { trySignup(user, password: password) } else { tryLogin(user, password: password) } } } else { let alertText = "Looks like there are some empty fields, please fill them out and try again." SVProgressHUD.showError(withStatus: alertText) } } func tryLogin(_ user: String, password: String) { Analytics.logEvent("Login/Signup", action: "Login", Label: "Login Button Pressed", key: "") SVProgressHUD.show(withStatus: "Logging in") PFUser.logInWithUsername(inBackground: user, password: password, block: { (user, error) -> Void in if ((user) != nil) { DispatchQueue.main.async(execute: { () -> Void in SVProgressHUD.dismiss() self.showFeed() }) } else if ((error) != nil) { if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } } else { SVProgressHUD.showError(withStatus: "Login failed, please try again") } }) } func trySignup(_ user: String, password: String) { Analytics.logEvent("Login/Signup", action: "Signup", Label: "Signup Button Pressed", key: "") SVProgressHUD.show(withStatus: "Signing up") let newUser = PFUser() newUser.username = user newUser.password = password newUser.signUpInBackground(block: { (succeed, error) -> Void in if ((error) != nil) { if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) } } else { DispatchQueue.main.async(execute: { () -> Void in SVProgressHUD.dismiss() self.showFeed() }) } }) } func showFeed() { if let nc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Main") as? TabBarController { self.present(nc, animated: true, completion: nil) } } }
gpl-2.0
de42380b1d2ebedcccd8d8d8350c68d4
36.352041
150
0.629559
5.36337
false
false
false
false
hellogaojun/Swift-coding
swift学习教材案例/Swifter.playground/Pages/multiple-optional.xcplaygroundpage/Contents.swift
1
321
import Foundation var string: String? = "string" var anotherString: String?? = string var literalOptional: String?? = "string" var aNil: String? = nil var anotherNil: String?? = aNil var literalNil: String?? = nil if let a = anotherNil { print("anotherNil") } if let b = literalNil { print("literalNil") }
apache-2.0
f37cb7453d44d010f7dc2cf7250cee54
15.05
40
0.679128
3.21
false
false
false
false
rsbauer/Newsy
Newsy/ViewControllers/StoriesTableViewController.swift
1
5091
// // StoryTableViewController.swift // Newsy // // Created by Astro on 8/25/15. // Copyright (c) 2015 Rock Solid Bits. All rights reserved. // import UIKit import SDWebImage class StoriesTableViewController: UITableViewController { var stories: Array<ChannelItem> = Array<ChannelItem>() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() var newsService = NewsService() newsService.getNews(ABCNewsService()).response = { (result: AnyObject?, error: NSError?) in var newsFeed: Feed = result as! Feed // find top stories if let topStories = newsFeed.topStories { self.topStoriesDidLoad(topStories) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return stories.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("HeadlineTableViewCell", forIndexPath: indexPath) as! HeadlineTableViewCell // Configure the cell... var item = self.stories[indexPath.row] var imageUrl = "" if item.abcn_images?.count > 0 { imageUrl = item.abcn_images?[0].abcn_image?.url ?? "" } var title = item.title ?? "" cell.titleLabel?.text = title if imageUrl != "" { cell.storyImageView?.sd_setImageWithURL(NSURL(string: imageUrl), placeholderImage: UIImage(named: "Loading")) cell.imageViewWidthConstraint.constant = 87 } else { cell.storyImageView.image = nil cell.imageViewWidthConstraint.constant = 0 } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ func topStoriesDidLoad(topStories: Story) { var newsService = NewsService() var url = topStories.url ?? "" newsService.getNews(ABCNewsStoryService(storyUrl: url)).response = { (result: AnyObject?, error: NSError?) in var feedCategory = result as! FeedCategory var channels: Array<Channel> = feedCategory.channels ?? Array<Channel>() for channel in channels { if channel.title == "Top Stories" { self.stories = channel.items ?? Array<ChannelItem>() } } self.tableView.reloadData() } } }
mit
8773d129e2b28568371e50342ed1d5bb
34.601399
157
0.63956
5.314196
false
false
false
false
frankcjw/CJWLib
CJWLib/Source/CJWUtils.swift
1
7073
// // YGUtils.swift // YuanGuangProject // // Created by Frank on 6/26/15. // Copyright (c) 2015 YG. All rights reserved. // import UIKit let UIControlEventsTouchUpInside = UIControlEvents.TouchUpInside let UIControlStateNormal = UIControlState.Normal let UIControlStateSelected = UIControlState.Selected let UIControlStateHighlighted = UIControlState.Highlighted let IS_SIMULATOR = CJWUtils.isSimnulator() ? true : false // MARK: - KEY let KEY_CourseCategorySelection = "CourseCategorySelection" let KEY_CourseCategory = "CourseCategory" let KEY_CourseCategorySelectionId = "CourseCategorySelectionId" let KEY_QuestionInfo = "QuestionInfo" let KEY_Questions = "Questions" let KEY_BeginId = "BeginId" class CJWUtils: NSObject { var cacheObject : AnyObject? class var sharedInstance : CJWUtils { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : CJWUtils? = nil } dispatch_once(&Static.onceToken) { Static.instance = CJWUtils() } return Static.instance! } } extension CJWUtils { // class func getSystemCacheSize() -> String { // let units = ["B","K","M","G"] // var size = SDImageCache.sharedImageCache().getSize() // var calc = NSNumber(unsignedLong: size).integerValue // var value = "" // var unitIndex = 0 // for index in 0...units.count - 1 { // if calc > 1024 * 2 { // calc = calc / 1024 // unitIndex++ // }else{ // break // } // } // value = "\(calc)\(units[unitIndex])" // println("缓存大小:\(value) \(size)") // return value // } // // class func clearSystemCache(block:()->()){ // let tmpView = UIApplication.sharedApplication().keyWindow?.rootViewController?.view // tmpView?.showHUDwith("正在清理缓存") // YGExcuteDelay.excute(2, block: { () -> () in // SDImageCache.sharedImageCache().clearDiskOnCompletion { () -> Void in // tmpView!.showTemporary("清除成功") // block() // } // }) // } } let DATE_FORMAT = "HH:mm" /// Array<NSDictionary> typealias NSInfoArray = Array<NSDictionary> extension String { private var MAX_HEIGHT:CGFloat { return 9999 } private var MAX_WIDTH : CGFloat { return SCREEN_WIDTH } func calculateSizeHeight(font:UIFont,width:CGFloat) -> CGFloat{ return calculateSize(font, width: width).height } func calculateWidth(font:UIFont,height:CGFloat) -> CGFloat{ var size = CGSizeMake(MAX_WIDTH, height) let dict = [NSFontAttributeName:font] size = self.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: dict, context: nil).size return size.width } func calculateSize(font:UIFont,width:CGFloat) -> CGSize{ var size = CGSizeMake(width, MAX_HEIGHT) let dict = [NSFontAttributeName:font] size = self.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: dict, context: nil).size return size } func length()->Int{ return self.characters.count } } extension Double { func convertToDateString() -> NSString{ let time = self / 1000 - NSTimeIntervalSince1970 let date = NSDate(timeIntervalSinceReferenceDate: time) let fmt = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd HH:mm:ss" let realDate = fmt.stringFromDate(date) return realDate } func convertToDateString(formatt:String) -> String{ let time = self / 1000 - NSTimeIntervalSince1970 let date = NSDate(timeIntervalSinceReferenceDate: time) let fmt = NSDateFormatter() fmt.dateFormat = formatt as String let realDate = fmt.stringFromDate(date) return realDate } } extension NSDate { func convertToDateString() -> NSString{ let date = self let fmt = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd HH:mm:ss" let realDate = fmt.stringFromDate(date) return realDate } } class YGExcuteDelay : NSObject { typealias DelayBlock = () -> () class func excute(timeDelay:NSTimeInterval,block:DelayBlock){ let ttt:Int64 = Int64(timeDelay) let time = dispatch_time(DISPATCH_TIME_NOW, ttt * (Int64)(1 * NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { () -> Void in block() } } } extension Int { func character() -> String{ let character = Character(UnicodeScalar(65 + self)) return "\(character)" } } extension Int { func random() -> Int { return Int(arc4random_uniform(UInt32(abs(self)))) } func indexRandom() -> [Int] { var newIndex = 0 var shuffledIndex:[Int] = [] while shuffledIndex.count < self { newIndex = Int(arc4random_uniform(UInt32(self))) if !(shuffledIndex.indexOf(newIndex) > -1 ) { shuffledIndex.append(newIndex) } } return shuffledIndex } } extension Array { func shuffle() -> [Element] { var shuffledContent:[Element] = [] let shuffledIndex:[Int] = self.count.indexRandom() for i in 0...shuffledIndex.count-1 { shuffledContent.append(self[shuffledIndex[i]]) } return shuffledContent } mutating func shuffled() { var shuffledContent:[Element] = [] let shuffledIndex:[Int] = self.count.indexRandom() for i in 0...shuffledIndex.count-1 { shuffledContent.append(self[shuffledIndex[i]]) } self = shuffledContent } func chooseOne() -> Element { return self[Int(arc4random_uniform(UInt32(self.count)))] } func choose(x:Int) -> [Element] { var shuffledContent:[Element] = [] let shuffledIndex:[Int] = x.indexRandom() for i in 0...shuffledIndex.count-1 { shuffledContent.append(self[shuffledIndex[i]]) } return shuffledContent } } extension CJWUtils{ class func passwordValidator(password:String) -> Bool{ var letterCounter = 0 var digitCount = 0 let phrase = password for scalar in phrase.unicodeScalars { let value = scalar.value if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) { letterCounter++ } if (value >= 48 && value <= 57) { digitCount++ } } if digitCount > 0 && letterCounter > 0 && password.length() > 7 { return true }else{ return false } } } extension CJWUtils { class func isSimnulator() -> Bool { let model = UIDevice.currentDevice().model if model == "iPhone Simulator" { return true }else{ return false } } }
mit
8f0f7d99c5fd65c59f367a99d325f5a1
28.11157
139
0.597871
4.256798
false
false
false
false
jbruce2112/cutlines
Cutlines/View/PhotoContainerView.swift
1
2706
// // PhotoContainerView.swift // Cutlines // // Created by John on 3/13/17. // Copyright © 2017 Bruce32. All rights reserved. // import UIKit /// PhotoContainerView combines a /// CaptionView and PolaroidView subviews /// on opposite sides of a single container view. class PhotoContainerView: UIView { var captionView = CaptionView() var polaroidView = PolaroidView() private var constraintsSet = false override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override func updateConstraints() { super.updateConstraints() // We only need to set these once if constraintsSet { return } guard let superview = superview else { return } var constraints = [NSLayoutConstraint]() // width = self.width + 20 @750 let widthConstraint = superview.widthAnchor.constraint(equalTo: widthAnchor, constant: 20) widthConstraint.priority = UILayoutPriority.defaultHigh constraints.append(widthConstraint) // superview.width >= self.width + 20 constraints.append(superview.widthAnchor.constraint(greaterThanOrEqualTo: widthAnchor, constant: 20)) // superview.centerX = self.centerXAnchor constraints.append(superview.centerXAnchor.constraint(equalTo: centerXAnchor)) // superview.centerY = self.centerYAnchor constraints.append(superview.centerYAnchor.constraint(equalTo: centerYAnchor)) // aspect 1:1 constraints.append(widthAnchor.constraint(equalTo: heightAnchor)) NSLayoutConstraint.activate(constraints) constraintsSet = true } override func layoutSubviews() { super.layoutSubviews() polaroidView.frame = bounds captionView.frame = bounds } @objc func flip() { // Set up the views as a tuple in case we want to // flip this view again later on var subViews: (frontView: UIView, backView: UIView) if polaroidView.superview != nil { subViews = (frontView: polaroidView, backView: captionView) } else { subViews = (frontView: captionView, backView: polaroidView) } UIView.transition(from: subViews.frontView, to: subViews.backView, duration: 0.4, options: [.transitionFlipFromRight, .curveEaseOut], completion: nil) } private func setup() { addSubview(captionView) backgroundColor = UIColor(red: 255.0 / 255.0, green: 254.0 / 255.0, blue: 245.0 / 255.0, alpha: 1.0) polaroidView.setNeedsLayout() layer.borderWidth = 0.75 layer.borderColor = UIColor.gray.cgColor layer.shadowRadius = 10 layer.shadowColor = UIColor.gray.cgColor layer.shadowOpacity = 0.6 translatesAutoresizingMaskIntoConstraints = false } }
mit
dbe48893342b453d2b34c49fb018a85c
23.816514
103
0.716821
3.954678
false
false
false
false
russbishop/swift
test/type/types.swift
1
4601
// RUN: %target-parse-verify-swift var a : Int func test() { var y : a // expected-error {{use of undeclared type 'a'}} var z : y // expected-error {{use of undeclared type 'y'}} var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}} } var b : (Int) -> Int = { $0 } var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}} var d2 : () -> Int = { 4 } var d3 : () -> Float = { 4 } var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}} var e0 : [Int] e0[] // expected-error {{cannot subscript a value of type '[Int]' with an index of type '()'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>),}} var f0 : [Float] var f1 : [(Int,Int)] var g : Swift // expected-error {{use of undeclared type 'Swift'}} expected-note {{cannot use module 'Swift' as a type}} var h0 : Int? _ = h0 == nil // no-warning var h1 : Int?? _ = h1! == nil // no-warning var h2 : [Int?] var h3 : [Int]? var h3a : [[Int?]] var h3b : [Int?]? var h4 : ([Int])? var h5 : ([([[Int??]])?])? var h7 : (Int,Int)? var h8 : ((Int) -> Int)? var h9 : (Int?) -> Int? var h10 : Int?.Type?.Type var i = Int?(42) var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' is only valid in parameter lists}} func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' is only valid in parameter lists}} // <rdar://problem/15588967> Array type sugar default construction syntax doesn't work func test_array_construct<T>(_: T) { _ = [T]() // 'T' is a local name _ = [Int]() // 'Int is a global name' _ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name. _ = [UnsafeMutablePointer<Int?>]() // Nesting. _ = [([UnsafeMutablePointer<Int>])]() _ = [(String, Float)]() } extension Optional { init() { self = .none } } // <rdar://problem/15295763> default constructing an optional fails to typecheck func test_optional_construct<T>(_: T) { _ = T?() // Local name. _ = Int?() // Global name _ = (Int?)() // Parenthesized name. } // Test disambiguation of generic parameter lists in expression context. struct Gen<T> {} var y0 : Gen<Int?> var y1 : Gen<Int??> var y2 : Gen<[Int?]> var y3 : Gen<[Int]?> var y3a : Gen<[[Int?]]> var y3b : Gen<[Int?]?> var y4 : Gen<([Int])?> var y5 : Gen<([([[Int??]])?])?> var y7 : Gen<(Int,Int)?> var y8 : Gen<((Int) -> Int)?> var y8a : Gen<[([Int]?) -> Int]> var y9 : Gen<(Int?) -> Int?> var y10 : Gen<Int?.Type?.Type> var y11 : Gen<Gen<Int>?> var y12 : Gen<Gen<Int>?>? var y13 : Gen<Gen<Int?>?>? var y14 : Gen<Gen<Int?>>? var y15 : Gen<Gen<Gen<Int?>>?> var y16 : Gen<Gen<Gen<Int?>?>> var y17 : Gen<Gen<Gen<Int?>?>>? var z0 = Gen<Int?>() var z1 = Gen<Int??>() var z2 = Gen<[Int?]>() var z3 = Gen<[Int]?>() var z3a = Gen<[[Int?]]>() var z3b = Gen<[Int?]?>() var z4 = Gen<([Int])?>() var z5 = Gen<([([[Int??]])?])?>() var z7 = Gen<(Int,Int)?>() var z8 = Gen<((Int) -> Int)?>() var z8a = Gen<[([Int]?) -> Int]>() var z9 = Gen<(Int?) -> Int?>() var z10 = Gen<Int?.Type?.Type>() var z11 = Gen<Gen<Int>?>() var z12 = Gen<Gen<Int>?>?() var z13 = Gen<Gen<Int?>?>?() var z14 = Gen<Gen<Int?>>?() var z15 = Gen<Gen<Gen<Int?>>?>() var z16 = Gen<Gen<Gen<Int?>?>>() var z17 = Gen<Gen<Gen<Int?>?>>?() y0 = z0 y1 = z1 y2 = z2 y3 = z3 y3a = z3a y3b = z3b y4 = z4 y5 = z5 y7 = z7 y8 = z8 y8a = z8a y9 = z9 y10 = z10 y11 = z11 y12 = z12 y13 = z13 y14 = z14 y15 = z15 y16 = z16 y17 = z17 // Type repr formation. // <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr) let tupleTypeWithNames = (age:Int, count:Int)(4, 5) let dictWithTuple = [String: (age:Int, count:Int)]() // <rdar://problem/21684837> typeexpr not being formed for postfix ! let bb2 = [Int!](repeating: nil, count: 2) // <rdar://problem/21560309> inout allowed on function return type func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' is only valid in parameter lists}} r21560309 { x in x } // <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties class r21949448 { var myArray: inout [Int] = [] // expected-error {{'inout' is only valid in parameter lists}} } // SE-0066 - Standardize function type argument syntax to require parentheses let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}}
apache-2.0
7b428931043c8a2acdbe180566c90f8a
27.226994
136
0.597913
2.802071
false
false
false
false
wunshine/FoodStyle
FoodStyle/FoodStyle/Classes/Viewcontroller/WXNavigationController.swift
1
1970
// // NavigationController.swift // FoodStyle // // Created by Woz Wong on 16/3/5. // Copyright © 2016年 code4Fun. All rights reserved. // import UIKit class WXNavigationController: UINavigationController { override class func initialize(){ let bar = UINavigationBar.appearance() bar.tintColor = UIColor.whiteColor() let backImage = UIImage().imageWithColor(GLOBAL_COLOR()) bar.setBackgroundImage(backImage, forBarMetrics: .Default) let dict = [NSForegroundColorAttributeName:UIColor.whiteColor()] bar.titleTextAttributes = dict let barButtonItem = UIBarButtonItem.appearance() let dict2 = [NSForegroundColorAttributeName : UIColor.whiteColor(),NSFontAttributeName:UIFont.systemFontOfSize(14)] barButtonItem.setTitleTextAttributes(dict2, forState: UIControlState.Normal) super.initialize() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func pushViewController(viewController: UIViewController, animated: Bool) { if self.childViewControllers.count>0 { viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } 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. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
881b936e1ae42c0117b06b4844420644
31.245902
123
0.693442
5.572238
false
false
false
false
jangsy7883/KMYouTubeActivity
JLYoutubeActivity/JLYoutubeActivity.swift
2
2743
// // JLYoutubeActivity.swift // JLYoutubeActivityDemo // // Created by Woody on 2018. 4. 24.. // Copyright © 2018년 Woody. All rights reserved. // import UIKit class JLYoutubeActivity: UIActivity { var YoutubeURLSchema: String = "youtube://" var YoutubeBaseURL: String = "youtube://watch?v=" var url:URL? // override activity override var activityType: UIActivityType? { return UIActivityType(String(describing: self.self)) } override var activityTitle: String?{ return "Youtube" } override var activityImage: UIImage? { return UIImage(named: "JLYoutubeActivity.bundle/youtube", in: Bundle(for: JLYoutubeActivity.self), compatibleWith: nil) } override func canPerform(withActivityItems activityItems: [Any]) -> Bool { guard let opneURL = URL(string: YoutubeURLSchema) else { return false } if UIApplication.shared.canOpenURL(opneURL) { return activityItems.contains { (item) -> Bool in guard let url = item as? URL else { return false } return url.isYoutube } } return false } override func prepare(withActivityItems activityItems: [Any]) { for item in activityItems { if let url = item as? URL, let identifier = url.videoIdentifier { self.url = URL(string: YoutubeBaseURL+identifier) } } } override func perform() { guard let url = url else { return } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [String:Any]()) { (success) in self.activityDidFinish(success) } } else { UIApplication.shared.openURL(url) } } } extension URL { fileprivate var videoIdentifier: String? { guard isYoutube != false else { return nil} if let identifier = parameters?["v"] { return identifier } return nil } fileprivate var isYoutube: Bool { if let feature = parameters?["feature"], feature == "youtu.be" { return true } return false } fileprivate var parameters: [String:String]? { guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else { return nil } guard let items = components.queryItems, items.isEmpty == false else { return nil } var parameters = [String:String]() for item in items { if let value = item.value { parameters[item.name] = value } } return parameters; } }
mit
18a8f8989e690b3fb7663cc67097681b
27.842105
127
0.574818
4.699828
false
false
false
false
gilserrap/Bigotes
Pods/GRMustache.swift/Mustache/Goodies/Logger.swift
1
3866
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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. extension StandardLibrary { /** StandardLibrary.Logger is a tool intended for debugging templates. It logs the rendering of variable and section tags such as `{{name}}` and `{{#name}}...{{/name}}`. To activate logging, add a Logger to the base context of a template: let template = try! Template(string: "{{name}} died at {{age}}.") // Logs all tag renderings with NSLog(): let logger = StandardLibrary.Logger() template.extendBaseContext(Box(logger)) // Render let data = ["name": "Freddy Mercury", "age": 45] let rendering = try! template.render(Box(data)) // In NSLog: // {{name}} at line 1 did render "Freddy Mercury" as "Freddy Mercury" // {{age}} at line 1 did render 45 as "45" */ public final class Logger : MustacheBoxable { /** Returns a Logger. - parameter log: A closure that takes a String. Default one logs that string with NSLog(). - returns: a Logger */ public init(log: ((String) -> Void)? = nil) { if let log = log { self.log = log } else { self.log = { NSLog($0) } } } /** Logger adopts the `MustacheBoxable` protocol so that it can feed Mustache templates. You should not directly call the `mustacheBox` property. Always use the `Box()` function instead: localizer.mustacheBox // Valid, but discouraged Box(localizer) // Preferred */ public var mustacheBox: MustacheBox { return MustacheBox( willRender: { (tag, box) in if tag.type == .Section { self.log("\(self.indentationPrefix)\(tag) will render \(box.valueDescription)") self.indentationLevel++ } return box }, didRender: { (tag, box, string) in if tag.type == .Section { self.indentationLevel-- } if let string = string { self.log("\(self.indentationPrefix)\(tag) did render \(box.valueDescription) as \(string.debugDescription)") } } ) } var indentationPrefix: String { return String(count: indentationLevel * 2, repeatedValue: " " as Character) } private let log: (String) -> Void private var indentationLevel: Int = 0 } }
mit
a421b1cba9ecfa23f0dab012fdb01a55
36.892157
132
0.573868
5.092227
false
false
false
false
jingyichushi/IOsSweetAlert
SweetAlert/ViewController.swift
2
2764
// // ViewController.swift // SweetAlert // // Created by Codester on 11/3/14. // Copyright (c) 2014 Codester. All rights reserved. // import UIKit class ViewController: UIViewController { var alert = SweetAlert() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor(red: 242.0/255.0, green: 244.0/255.0, blue: 246.0/255.0, alpha: 1.0) } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func aBasicMessageAlert(sender: AnyObject) { SweetAlert().showAlert("Here's a message!") } @IBAction func subtitleAlert(sender: AnyObject) { SweetAlert().showAlert("Here's a message!", subTitle: "It's pretty, isn't it?", style: AlertStyle.None) } @IBAction func sucessAlert(sender: AnyObject) { SweetAlert().showAlert("Good job!", subTitle: "You clicked the button!", style: AlertStyle.Success) } @IBAction func warningAlert(sender: AnyObject) { SweetAlert().showAlert("Are you sure?", subTitle: "You file will permanently delete!", style: AlertStyle.Warning, buttonTitle:"Cancel", buttonColor:UIColorFromRGB(0xD0D0D0) , otherButtonTitle: "Yes, delete it!", otherButtonColor: UIColorFromRGB(0xDD6B55)) { (isOtherButton) -> Void in if isOtherButton == true { println("Cancel Button Pressed") } else { SweetAlert().showAlert("Deleted!", subTitle: "Your imaginary file has been deleted!", style: AlertStyle.Success) } } } @IBAction func cancelAndConfirm(sender: AnyObject) { SweetAlert().showAlert("Are you sure?", subTitle: "You file will permanently delete!", style: AlertStyle.Warning, buttonTitle:"No, cancel plx!", buttonColor:UIColorFromRGB(0xD0D0D0) , otherButtonTitle: "Yes, delete it!", otherButtonColor: UIColorFromRGB(0xDD6B55)) { (isOtherButton) -> Void in if isOtherButton == true { SweetAlert().showAlert("Cancelled!", subTitle: "Your imaginary file is safe", style: AlertStyle.Error) } else { SweetAlert().showAlert("Deleted!", subTitle: "Your imaginary file has been deleted!", style: AlertStyle.Success) } } } @IBAction func customIconAlert(sender: AnyObject) { SweetAlert().showAlert("Sweet!", subTitle: "Here's a custom image.", style: AlertStyle.CustomImag(imageFile: "thumb.jpg")) } }
mit
f8fdd3f95f5a60ace87a78b40dcc74f1
35.853333
302
0.634588
4.599002
false
false
false
false
rechsteiner/Parchment
Example/Examples/LargeTitles/LargeTitlesViewController.swift
1
9988
import Parchment import UIKit // This example shows how to use Parchment togehter with // "prefersLargeTitles" on UINavigationBar. It works by creating a // "hidden" scroll view that is added as a subview to the view // controller. Apparently, UIKit will look for a scroll view that is // the first subview of the selected view controller and update // the navigation bar according to the content offset. // // Note: this approach will cause the navigation bar to jump to the // small title state when scrolling down. I haven't figured out any // of getting around this. Any ideas are welcome. // This first thing we need to do is to create our own custom paging // view and override the layout constraints. The default // implementation positions the menu view above the page view // controller, but since we're going to put the menu view inside the // navigation bar we don't want to setup any layout constraints for // the menu view. class LargeTitlesPagingView: PagingView { override func setupConstraints() { pageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ pageView.leadingAnchor.constraint(equalTo: leadingAnchor), pageView.trailingAnchor.constraint(equalTo: trailingAnchor), pageView.bottomAnchor.constraint(equalTo: bottomAnchor), pageView.topAnchor.constraint(equalTo: topAnchor), ]) } } // Create a custom paging view controller and override the view with // our own custom subclass. class LargeTitlesPagingViewController: PagingViewController { override func loadView() { view = LargeTitlesPagingView( options: options, collectionView: collectionView, pageView: pageViewController.view ) } } class LargeTitlesViewController: UIViewController { // Create an instance of UIScrollView that we will be used to // "trick" the navigation bar to update. private let hiddenScrollView = UIScrollView() // Create an instance of our custom paging view controller that // does not setup any constraints for the menu view. private let pagingViewController = LargeTitlesPagingViewController() override func viewDidLoad() { super.viewDidLoad() guard let navigationController = navigationController else { return } // Tell the navigation bar that we want to have large titles navigationController.navigationBar.prefersLargeTitles = true // Customize the menu to match the navigation bar color let blue = UIColor(red: 3 / 255, green: 125 / 255, blue: 233 / 255, alpha: 1) if #available(iOS 13.0, *) { let appearance = UINavigationBarAppearance() appearance.backgroundColor = blue appearance.titleTextAttributes = [.foregroundColor: UIColor.white] appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().compactAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance } else { UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().barTintColor = blue UINavigationBar.appearance().isTranslucent = false } view.backgroundColor = .white pagingViewController.menuBackgroundColor = blue pagingViewController.menuItemSize = .fixed(width: 150, height: 30) pagingViewController.textColor = UIColor.white.withAlphaComponent(0.7) pagingViewController.selectedTextColor = UIColor.white pagingViewController.borderOptions = .hidden pagingViewController.indicatorColor = UIColor(red: 10 / 255, green: 0, blue: 105 / 255, alpha: 1) // Add the "hidden" scroll view to the root of the UIViewController. view.addSubview(hiddenScrollView) hiddenScrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ hiddenScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), hiddenScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), hiddenScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), hiddenScrollView.topAnchor.constraint(equalTo: view.topAnchor), ]) // Add the PagingViewController and constrain it to all edges. addChild(pagingViewController) view.addSubview(pagingViewController.view) pagingViewController.didMove(toParent: self) pagingViewController.dataSource = self pagingViewController.delegate = self pagingViewController.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ pagingViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), pagingViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), pagingViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), pagingViewController.view.topAnchor.constraint(equalTo: view.topAnchor), ]) // Add the menu view as a subview to the navigation // controller and constrain it to the bottom of the navigation // bar. This is the best way I've found to make a view scroll // alongside the navigation bar. navigationController.view.addSubview(pagingViewController.collectionView) pagingViewController.collectionView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ pagingViewController.collectionView.heightAnchor.constraint(equalToConstant: pagingViewController.options.menuItemSize.height), pagingViewController.collectionView.leadingAnchor.constraint(equalTo: navigationController.view.leadingAnchor), pagingViewController.collectionView.trailingAnchor.constraint(equalTo: navigationController.view.trailingAnchor), pagingViewController.collectionView.topAnchor.constraint(equalTo: navigationController.navigationBar.bottomAnchor), ]) extendedLayoutIncludesOpaqueBars = true } override func viewDidAppear(_: Bool) { guard let viewController = pagingViewController.pageViewController.selectedViewController as? TableViewController else { return } // When switching to another view controller, update the hidden // scroll view to match the current table view. hiddenScrollView.contentSize = viewController.tableView.contentSize hiddenScrollView.contentInset = viewController.tableView.contentInset hiddenScrollView.contentOffset = viewController.tableView.contentOffset // Set the UITableViewDelegate to the currenly visible table view. viewController.tableView.delegate = self } } extension LargeTitlesViewController: PagingViewControllerDataSource { func pagingViewController(_: PagingViewController, viewControllerAt _: Int) -> UIViewController { let viewController = TableViewController(style: .plain) // Inset the table view with the height of the menu height. let insets = UIEdgeInsets(top: pagingViewController.options.menuItemSize.height, left: 0, bottom: 0, right: 0) viewController.tableView.scrollIndicatorInsets = insets viewController.tableView.contentInset = insets return viewController } func pagingViewController(_: PagingViewController, pagingItemAt index: Int) -> PagingItem { return PagingIndexItem(index: index, title: "View \(index)") } func numberOfViewControllers(in _: PagingViewController) -> Int { return 3 } } extension LargeTitlesViewController: PagingViewControllerDelegate { func pagingViewController(_: PagingViewController, willScrollToItem _: PagingItem, startingViewController: UIViewController, destinationViewController _: UIViewController) { guard let startingViewController = startingViewController as? TableViewController else { return } // Remove the UITableViewDelegate delegate when starting to // scroll to another page. startingViewController.tableView.delegate = nil } func pagingViewController(_: PagingViewController, didScrollToItem _: PagingItem, startingViewController: UIViewController?, destinationViewController: UIViewController, transitionSuccessful: Bool) { guard let destinationViewController = destinationViewController as? TableViewController else { return } guard let startingViewController = startingViewController as? TableViewController else { return } // Set the UITableViewDelegate back to the currenly selected // view controller when the page scroll ended. if transitionSuccessful { destinationViewController.tableView.delegate = self // When switching to another view controller, update the // hidden scroll view to match the current table view. hiddenScrollView.contentSize = destinationViewController.tableView.contentSize hiddenScrollView.contentOffset = destinationViewController.tableView.contentOffset hiddenScrollView.contentInset = destinationViewController.tableView.contentInset } else { startingViewController.tableView.delegate = self } return } } extension LargeTitlesViewController: UITableViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // When the current table view is scrolling, we update the // content offset of the hidden scroll view to trigger the // large titles to update. hiddenScrollView.contentOffset = scrollView.contentOffset hiddenScrollView.panGestureRecognizer.state = scrollView.panGestureRecognizer.state } }
mit
6130afdc34b41c59169a8b35561a4589
48.691542
203
0.730677
6.09396
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/InputBar/ConversationInputBarViewController+KeyCommand.swift
1
3658
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit extension ConversationInputBarViewController { private typealias Shortcut = L10n.Localizable.Conversation.InputBar.Shortcut override var keyCommands: [UIKeyCommand]? { var commands: [UIKeyCommand] = [] commands.append( UIKeyCommand(action: #selector(commandReturnPressed), input: "\r", modifierFlags: .command, discoverabilityTitle: Shortcut.send) ) if UIDevice.current.userInterfaceIdiom == .pad { commands.append( UIKeyCommand(action: #selector(shiftReturnPressed), input: "\r", modifierFlags: .shift, discoverabilityTitle: Shortcut.newline) ) } if inputBar.isEditing { commands.append( UIKeyCommand(action: #selector(escapePressed), input: UIKeyCommand.inputEscape, modifierFlags: [], discoverabilityTitle: Shortcut.cancelEditingMessage) ) } else if inputBar.textView.text.isEmpty { commands.append( UIKeyCommand(action: #selector(upArrowPressed), input: UIKeyCommand.inputUpArrow, modifierFlags: [], discoverabilityTitle: Shortcut.editLastMessage) ) } else if let mentionsView = mentionsView as? UIViewController, !mentionsView.view.isHidden { commands.append( UIKeyCommand(action: #selector(upArrowPressedForMention), input: UIKeyCommand.inputUpArrow, modifierFlags: [], discoverabilityTitle: Shortcut.choosePreviousMention) ) commands.append( UIKeyCommand(action: #selector(downArrowPressedForMention), input: UIKeyCommand.inputDownArrow, modifierFlags: [], discoverabilityTitle: Shortcut.chooseNextMention) ) } return commands } @objc func upArrowPressedForMention() { mentionsView?.selectPreviousUser() } @objc func downArrowPressedForMention() { mentionsView?.selectNextUser() } @objc func commandReturnPressed() { sendText() } @objc func shiftReturnPressed() { guard let selectedTextRange = inputBar.textView.selectedTextRange else { return } inputBar.textView.replace(selectedTextRange, withText: "\n") } @objc private func upArrowPressed() { delegate?.conversationInputBarViewControllerEditLastMessage() } @objc func escapePressed() { endEditingMessageIfNeeded() } }
gpl-3.0
2d26f74d9117da98aa9a0404616ca0bd
32.87037
101
0.587479
5.627692
false
false
false
false
icylydia/PlayWithLeetCode
448. Find All Numbers Disappeared in an Array/Solution.swift
1
489
class Solution { func findDisappearedNumbers(_ nums: [Int]) -> [Int] { if nums.count == 0 { return nums } var ans = [Int]() var s = nums var i = 0 while i < s.count { if s[i] < 0 { i += 1 } else if s[i] == i + 1 { s[i] = -(i + 1) i += 1 } else if s[s[i] - 1] < 0 { i += 1 } else { let t = s[i] s[i] = s[t - 1] s[t - 1] = -t } } for i in 1...s.count { if s[i-1] > 0 { ans.append(i) } } return ans } }
mit
29c43aca4cda3c8d3d439cb5f80d808a
15.333333
57
0.404908
2.222727
false
false
false
false
TVGSoft/Architecture-iOS
View/View/Cell/RestaurantCell.swift
1
905
// // RestaurantCell.swift // View // // Created by Giáp Trần on 9/17/16. // Copyright © 2016 TVG Soft, Inc. All rights reserved. // import UIKit class RestaurantCell: BaseTableViewCell { // MARK: Property @IBOutlet weak var containerView: UIView! override func awakeFromNib() { super.awakeFromNib() containerView.layer.masksToBounds = false containerView.layer.shadowColor = UIColor.blackColor().CGColor containerView.layer.shadowRadius = 5 containerView.layer.shadowOffset = CGSize(width: 5, height: 5) containerView.layer.shadowOpacity = 0.6 containerView.layer.shadowPath = UIBezierPath(rect: containerView.frame).CGPath } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
0b4be7c366f26a183b6b05cb31eb4cdb
25.5
87
0.680355
4.460396
false
false
false
false
ksco/swift-algorithm-club-cn
Topological Sort/TopologicalSort3.swift
2
941
/* An alternative implementation of topological sort using depth-first search. This does not start at vertices with in-degree 0 but simply at the first one it finds. It uses a stack to build up the sorted list, but in reverse order. */ extension Graph { public func topologicalSortAlternative() -> [Node] { var stack = [Node]() var visited = [Node: Bool]() for (node, _) in adjacencyLists { visited[node] = false } func depthFirstSearch(source: Node) { if let adjacencyList = adjacencyList(forNode: source) { for neighbor in adjacencyList { if let seen = visited[neighbor] where !seen { depthFirstSearch(neighbor) } } } stack.append(source) visited[source] = true } for (node, _) in visited { if let seen = visited[node] where !seen { depthFirstSearch(node) } } return stack.reverse() } }
mit
33a6f28e9db081f455926ee2e22195a5
25.885714
78
0.617428
4.41784
false
false
false
false
Noobish1/KeyedMapper
Playgrounds/KeyedMapper.playground/Contents.swift
1
4920
import UIKit import KeyedMapper // Convertible extension NSTimeZone: Convertible { public static func fromMap(_ value: Any) throws -> NSTimeZone { guard let name = value as? String else { throw MapperError.convertible(value: value, expectedType: String.self) } guard let timeZone = self.init(name: name) else { throw MapperError.custom(field: nil, message: "Unsupported timezone \(name)") } return timeZone } } // NilConvertible enum NilConvertibleEnum { case something case nothing } extension NilConvertibleEnum: NilConvertible { static func fromMap(_ value: Any?) throws -> NilConvertibleEnum { if let _ = value { return .something } else { return .nothing } } } // DefaultConvertible enum DefaultConvertibleEnum: Int, DefaultConvertible { case firstCase = 0 } // Mappable struct SubObject { let property: String } extension SubObject: Mappable { enum Key: String, JSONKey { case property } init(map: KeyedMapper<SubObject>) throws { self.property = try map.from(.property) } } extension SubObject: ReverseMappable { func toKeyedJSON() -> [SubObject.Key : Any?] { return [.property : property] } } struct Object { let property: String let optionalProperty: String? let convertibleProperty: NSTimeZone let optionalConvertibleProperty: NSTimeZone? let nilConvertibleProperty: NilConvertibleEnum let arrayProperty: [String] let optionalArrayProperty: [String]? let mappableProperty: SubObject let optionalMappableProperty: SubObject? let defaultConvertibleProperty: DefaultConvertibleEnum let optionalDefaultConvertibleProperty: DefaultConvertibleEnum? let twoDArrayProperty: [[String]] let optionalTwoDArrayProperty: [[String]]? } extension Object: Mappable { enum Key: String, JSONKey { case property case optionalProperty case convertibleProperty case optionalConvertibleProperty case nilConvertibleProperty case arrayProperty case optionalArrayProperty case mappableProperty case optionalMappableProperty case defaultConvertibleProperty case optionalDefaultConvertibleProperty case twoDArrayProperty case optionalTwoDArrayProperty } init(map: KeyedMapper<Object>) throws { self.property = try map.from(.property) self.optionalProperty = map.optionalFrom(.optionalProperty) self.convertibleProperty = try map.from(.convertibleProperty) self.optionalConvertibleProperty = map.optionalFrom(.optionalConvertibleProperty) self.nilConvertibleProperty = try map.from(.nilConvertibleProperty) self.arrayProperty = try map.from(.arrayProperty) self.optionalArrayProperty = map.optionalFrom(.optionalArrayProperty) self.mappableProperty = try map.from(.mappableProperty) self.optionalMappableProperty = map.optionalFrom(.optionalMappableProperty) self.defaultConvertibleProperty = try map.from(.defaultConvertibleProperty) self.optionalDefaultConvertibleProperty = map.optionalFrom(.optionalDefaultConvertibleProperty) self.twoDArrayProperty = try map.from(.twoDArrayProperty) self.optionalTwoDArrayProperty = map.optionalFrom(.optionalTwoDArrayProperty) } } let JSON: NSDictionary = [ "property" : "propertyValue", "convertibleProperty" : NSTimeZone(forSecondsFromGMT: 0).abbreviation as Any, "arrayProperty" : ["arrayPropertyValue1", "arrayPropertyValue2"], "mappableProperty" : ["property" : "propertyValue"], "defaultConvertibleProperty" : DefaultConvertibleEnum.firstCase.rawValue, "twoDArrayProperty" : [["twoDArrayPropertyValue1"], ["twoDArrayPropertyValue2"]] ] let object = try Object.from(JSON) print(object) // ReverseMappable extension Object: ReverseMappable { func toKeyedJSON() -> [Object.Key : Any?] { return [ .property : property, .optionalProperty : optionalProperty, .convertibleProperty : convertibleProperty, .optionalConvertibleProperty : optionalConvertibleProperty, .nilConvertibleProperty : nilConvertibleProperty, .arrayProperty : arrayProperty, .optionalArrayProperty : optionalArrayProperty, .mappableProperty : mappableProperty.toJSON(), .optionalMappableProperty : optionalMappableProperty?.toJSON(), .defaultConvertibleProperty : defaultConvertibleProperty, .optionalDefaultConvertibleProperty : optionalDefaultConvertibleProperty, .twoDArrayProperty : twoDArrayProperty, .optionalTwoDArrayProperty : optionalTwoDArrayProperty ] } } let outJSON = object.toJSON() print(outJSON)
mit
77be04e822a8da2e31431e843da852e3
31.368421
103
0.7
4.915085
false
false
false
false
JJCoderiOS/CollectionViewPhotoBrowse
Swift版本的CollectionView/DDCollectionFlowLayout.swift
1
4409
// // DDCollectionFlowLayout.swift // Swift版本的CollectionView // // Created by majianjie on 2016/12/7. // Copyright © 2016年 ddtc. All rights reserved. // import UIKit protocol UICollectionViewLayoutDelegate : class { func waterFlow(_ layout : DDCollectionFlowLayout,_ width : CGFloat,_ indexPath : NSIndexPath) -> CGFloat } class DDCollectionFlowLayout: UICollectionViewLayout { weak var delegate : UICollectionViewLayoutDelegate? var columnMargin :CGFloat = 10 var rowMargin : CGFloat = 10 var columnsCount : Int = 3 var edgeInset : UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) fileprivate lazy var maxYDic : NSMutableDictionary = { let maxYDic = NSMutableDictionary() for i in 0..<self.columnsCount{ let cloumn = String(i) maxYDic[cloumn] = self.edgeInset.top } return maxYDic }() fileprivate var attrsArray: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]() override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } } extension DDCollectionFlowLayout{ // MARK:- 将要布局时候调用 override func prepare() { super.prepare() //清空最大的Y值 for i in 0..<self.columnsCount{ let cloumn :String = String(i) //字典可以存放 基本数据类型当做 value self.maxYDic[cloumn] = self.edgeInset.top } self.attrsArray.removeAll() let count : Int! = self.collectionView?.numberOfItems(inSection: 0) for j in 0..<count { let indexPath : NSIndexPath = NSIndexPath(item: j, section: 0) let attr : UICollectionViewLayoutAttributes = self.layoutAttributesForItem(at: indexPath as IndexPath)! self.attrsArray.append(attr) } } } extension DDCollectionFlowLayout{ // MARK:- 返回所有的尺寸 ,否则不能滚动 override var collectionViewContentSize: CGSize{ var maxCloumn = "0" for (column,maxY) in self.maxYDic{ let ab : CGFloat = self.maxYDic[maxCloumn] as! CGFloat if maxY as! CGFloat > CGFloat(ab) { maxCloumn = column as! String } } let size = CGSize(width: 0, height: self.maxYDic[maxCloumn] as! CGFloat + self.edgeInset.bottom) return size } } extension DDCollectionFlowLayout{ override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return self.attrsArray } } extension DDCollectionFlowLayout{ override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { var minColumn = "0" for (column,maxY) in self.maxYDic{ let ab = self.maxYDic[minColumn] as! CGFloat let max = maxY as! CGFloat//((maxY as! String) as NSString).floatValue if CGFloat(max) < ab { minColumn = column as! String } } //计算尺寸 let left = self.edgeInset.left let right = self.edgeInset.right let totalW = CGFloat(self.columnsCount - 1) * self.columnMargin let w : CGFloat = CGFloat((self.collectionView?.frame.size.width)! - left - right - totalW) / CGFloat(self.columnsCount) let h = self.delegate?.waterFlow(self, w, indexPath as NSIndexPath) ?? 100 //计算位置 let x: Float = Float(self.edgeInset.left) + Float(w + self.columnMargin) * (minColumn as NSString).floatValue let y : CGFloat = self.maxYDic[minColumn] as! CGFloat + self.rowMargin //更新 最大 Y 值 self.maxYDic[minColumn] = ((CGFloat(y) + h) as CGFloat) let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath) attr.frame = CGRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(w), height: CGFloat(h)) return attr } }
apache-2.0
b46b62ecb68a25e245d69dad191e95bb
26.33758
128
0.577819
4.790179
false
false
false
false
clappr/clappr-ios
Sources/Clappr/Classes/Base/Layers/LayerComposer.swift
1
1370
import UIKit public class LayerComposer { private weak var rootView: UIView? private let backgroundLayer = BackgroundLayer() private let playbackLayer = PlaybackLayer() private let mediaControlLayer = MediaControlLayer() private let coreLayer = CoreLayer() private let overlayLayer = OverlayLayer() public init() { } func compose(inside rootView: UIView) { self.rootView = rootView backgroundLayer.attach(to: rootView, at: 0) playbackLayer.attach(to: rootView, at: 1) mediaControlLayer.attach(to: rootView, at: 2) coreLayer.attach(to: rootView, at: 3) overlayLayer.attach(to: rootView, at: 4) } func attachContainer(_ view: UIView) { playbackLayer.attach(view) } func attachUICorePlugin(_ plugin: UICorePlugin) { coreLayer.attachPlugin(plugin) } func attachMediaControl(_ view: UIView) { mediaControlLayer.attachMediaControl(view) } func attachOverlay(_ view: UIView) { overlayLayer.attachOverlay(view) } func showUI() { mediaControlLayer.isHidden = false coreLayer.isHidden = false overlayLayer.isHidden = false } func hideUI() { mediaControlLayer.isHidden = true coreLayer.isHidden = true overlayLayer.isHidden = true } }
bsd-3-clause
678659dc402426b1892db8774e0b1afe
26.4
55
0.645255
4.628378
false
false
false
false
Ferrari-lee/firefox-ios
Client/Frontend/Home/RemoteTabsPanel.swift
4
21283
/* 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 Account import Shared import SnapKit import Storage import Sync import XCGLogger private let log = Logger.browserLogger private struct RemoteTabsPanelUX { static let HeaderHeight = SiteTableViewControllerUX.RowHeight // Not HeaderHeight! static let RowHeight = SiteTableViewControllerUX.RowHeight static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8) static let EmptyStateTitleFont = UIFont.systemFontOfSize(UIConstants.DeviceFontSize, weight: UIFontWeightMedium) static let EmptyStateTitleTextColor = UIColor.darkGrayColor() static let EmptyStateInstructionsFont = UIFont.systemFontOfSize(UIConstants.DeviceFontSize - 1, weight: UIFontWeightLight) static let EmptyStateInstructionsTextColor = UIColor.grayColor() static let EmptyStateInstructionsWidth = 226 static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 // UX TODO I set this to 8 so that it all fits on landscape static let EmptyStateSignInButtonColor = UIColor(red:0.3, green:0.62, blue:1, alpha:1) static let EmptyStateSignInButtonTitleFont = UIFont.systemFontOfSize(16) static let EmptyStateSignInButtonTitleColor = UIColor.whiteColor() static let EmptyStateSignInButtonCornerRadius: CGFloat = 4 static let EmptyStateSignInButtonHeight = 44 static let EmptyStateSignInButtonWidth = 200 static let EmptyStateCreateAccountButtonFont = UIFont.systemFontOfSize(12) // Temporary placeholder for strings removed in Bug 1193456. private let CreateAccountString = NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j") } private let RemoteClientIdentifier = "RemoteClient" private let RemoteTabIdentifier = "RemoteTab" class RemoteTabsPanel: UITableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? = nil var profile: Profile! init() { super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil) } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier) tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier) tableView.rowHeight = RemoteTabsPanelUX.RowHeight tableView.separatorInset = UIEdgeInsetsZero tableView.delegate = nil tableView.dataSource = nil refreshControl = UIRefreshControl() view.backgroundColor = UIConstants.PanelBackgroundColor } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) refreshControl?.addTarget(self, action: "SELrefreshTabs", forControlEvents: UIControlEvents.ValueChanged) refreshTabs() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) refreshControl?.removeTarget(self, action: "SELrefreshTabs", forControlEvents: UIControlEvents.ValueChanged) } func notificationReceived(notification: NSNotification) { switch notification.name { case NotificationFirefoxAccountChanged: refreshTabs() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } var tableViewDelegate: RemoteTabsPanelDataSource? { didSet { self.tableView.delegate = tableViewDelegate self.tableView.dataSource = tableViewDelegate } } func refreshTabs() { tableView.scrollEnabled = false tableView.allowsSelection = false tableView.tableFooterView = UIView(frame: CGRectZero) // Short circuit if the user is not logged in if !profile.hasAccount() { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NotLoggedIn) self.endRefreshing() return } self.profile.getCachedClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in if let clientAndTabs = result.successValue { self.updateDelegateClientAndTabData(clientAndTabs) } // Otherwise, fetch the tabs cloud if its been more than 1 minute since last sync let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime) if NSDate.now() - (lastSyncTime ?? 0) > OneMinuteInMilliseconds && !(self.refreshControl?.refreshing ?? false) { self.startRefreshing() self.profile.getClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in if let clientAndTabs = result.successValue { self.profile.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime) self.updateDelegateClientAndTabData(clientAndTabs) } self.endRefreshing() } } else { // If we failed before and didn't sync, show the failure delegate if let _ = result.failureValue { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .FailedToSync) } self.endRefreshing() } } } private func startRefreshing() { if let refreshControl = self.refreshControl { let height = -refreshControl.bounds.size.height self.tableView.setContentOffset(CGPointMake(0, height), animated: true) refreshControl.beginRefreshing() } } func endRefreshing() { if self.refreshControl?.refreshing ?? false { self.refreshControl?.endRefreshing() } self.tableView.scrollEnabled = true self.tableView.reloadData() } func updateDelegateClientAndTabData(clientAndTabs: [ClientAndTabs]) { if clientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoClients) } else { let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 } if nonEmptyClientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoTabs) } else { self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: self, clientAndTabs: nonEmptyClientAndTabs) self.tableView.allowsSelection = true } } } @objc private func SELrefreshTabs() { refreshTabs() } } enum RemoteTabsError { case NotLoggedIn case NoClients case NoTabs case FailedToSync func localizedString() -> String { switch self { case NotLoggedIn: return "" // This does not have a localized string because we have a whole specific screen for it. case NoClients: return NSLocalizedString("You don't have any other devices connected to this Firefox Account available to sync.", comment: "Error message in the remote tabs panel") case NoTabs: return NSLocalizedString("You don't have any tabs open in Firefox on your other devices.", comment: "Error message in the remote tabs panel") case FailedToSync: return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel") } } } protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate { } class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? private var clientAndTabs: [ClientAndTabs] init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) { self.homePanel = homePanel self.clientAndTabs = clientAndTabs } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.clientAndTabs.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.clientAndTabs[section].tabs.count } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return RemoteTabsPanelUX.HeaderHeight } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let clientTabs = self.clientAndTabs[section] let client = clientTabs.client let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(RemoteClientIdentifier) as! TwoLineHeaderFooterView view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight) view.textLabel?.text = client.name view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor /* * A note on timestamps. * We have access to two timestamps here: the timestamp of the remote client record, * and the set of timestamps of the client's tabs. * Neither is "last synced". The client record timestamp changes whenever the remote * client uploads its record (i.e., infrequently), but also whenever another device * sends a command to that client -- which can be much later than when that client * last synced. * The client's tabs haven't necessarily changed, but it can still have synced. * Ideally, we should save and use the modified time of the tabs record itself. * This will be the real time that the other client uploaded tabs. */ let timestamp = clientTabs.approximateLastSyncTime() let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.") view.detailTextLabel?.text = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString()) let image: UIImage? if client.type == "desktop" { image = UIImage(named: "deviceTypeDesktop") image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list") } else { image = UIImage(named: "deviceTypeMobile") image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list") } view.imageView.image = image view.mergeAccessibilityLabels() return view } private func tabAtIndexPath(indexPath: NSIndexPath) -> RemoteTab { return clientAndTabs[indexPath.section].tabs[indexPath.item] } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(RemoteTabIdentifier, forIndexPath: indexPath) as! TwoLineTableViewCell let tab = tabAtIndexPath(indexPath) cell.setLines(tab.title, detailText: tab.URL.absoluteString) // TODO: Bug 1144765 - Populate image with cached favicons. return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let tab = tabAtIndexPath(indexPath) if let homePanel = self.homePanel { // It's not a bookmark, so let's call it Typed (which means History, too). homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.Typed) } } } // MARK: - class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? var error: RemoteTabsError var notLoggedCell: UITableViewCell? init(homePanel: HomePanel, error: RemoteTabsError) { self.homePanel = homePanel self.error = error self.notLoggedCell = nil } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if let cell = self.notLoggedCell { cell.updateConstraints() } return tableView.bounds.height } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Making the footer height as small as possible because it will disable button tappability if too high. return 1 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch error { case .NotLoggedIn: let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel) self.notLoggedCell = cell return cell default: let cell = RemoteTabsErrorCell(error: self.error) self.notLoggedCell = nil return cell } } } // MARK: - class RemoteTabsErrorCell: UITableViewCell { static let Identifier = "RemoteTabsErrorCell" init(error: RemoteTabsError) { super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier) separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0) let containerView = UIView() contentView.addSubview(containerView) let imageView = UIImageView() imageView.image = UIImage(named: "emptySync") containerView.addSubview(imageView) imageView.snp_makeConstraints { (make) -> Void in make.top.equalTo(containerView) make.centerX.equalTo(containerView) } let instructionsLabel = UILabel() instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont instructionsLabel.text = error.localizedString() instructionsLabel.textAlignment = NSTextAlignment.Center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 containerView.addSubview(instructionsLabel) instructionsLabel.snp_makeConstraints { make in make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(containerView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } containerView.snp_makeConstraints { make in // Let the container wrap around the content make.top.equalTo(imageView.snp_top) make.left.bottom.right.equalTo(instructionsLabel) // And then center it in the overlay view that sits on top of the UITableView make.center.equalTo(contentView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - class RemoteTabsNotLoggedInCell: UITableViewCell { static let Identifier = "RemoteTabsNotLoggedInCell" var homePanel: HomePanel? var instructionsLabel: UILabel var signInButton: UIButton var titleLabel: UILabel init(homePanel: HomePanel?) { let titleLabel = UILabel() let instructionsLabel = UILabel() let signInButton = UIButton() self.instructionsLabel = instructionsLabel self.signInButton = signInButton self.titleLabel = titleLabel super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier) self.homePanel = homePanel let imageView = UIImageView() imageView.image = UIImage(named: "emptySync") contentView.addSubview(imageView) titleLabel.font = RemoteTabsPanelUX.EmptyStateTitleFont titleLabel.text = NSLocalizedString("Welcome to Sync", comment: "See http://mzl.la/1Qtkf0j") titleLabel.textAlignment = NSTextAlignment.Center titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor contentView.addSubview(titleLabel) instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont instructionsLabel.text = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "See http://mzl.la/1Qtkf0j") instructionsLabel.textAlignment = NSTextAlignment.Center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 contentView.addSubview(instructionsLabel) signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal) signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, forState: .Normal) signInButton.titleLabel?.font = RemoteTabsPanelUX.EmptyStateSignInButtonTitleFont signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius signInButton.clipsToBounds = true signInButton.addTarget(self, action: "SELsignIn", forControlEvents: UIControlEvents.TouchUpInside) contentView.addSubview(signInButton) imageView.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(instructionsLabel) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(contentView.snp_centerY).offset(-180).priorityMedium() // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp_top).offset(50).priorityHigh() } titleLabel.snp_makeConstraints { make in make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(imageView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func SELsignIn() { if let homePanel = self.homePanel { homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel) } } override func updateConstraints() { if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) && !(DeviceInfo.deviceModel().rangeOfString("iPad") != nil) { instructionsLabel.snp_remakeConstraints { make in make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.left.lessThanOrEqualTo(contentView.snp_left).offset(80).priorityMedium() // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.right.lessThanOrEqualTo(contentView.snp_centerX).offset(-10).priorityHigh() } signInButton.snp_remakeConstraints { make in make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) make.centerY.equalTo(titleLabel.snp_centerY) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.right.greaterThanOrEqualTo(contentView.snp_right).offset(-80).priorityMedium() // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.left.greaterThanOrEqualTo(contentView.snp_centerX).offset(10).priorityHigh() } } else { instructionsLabel.snp_remakeConstraints { make in make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(contentView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } signInButton.snp_remakeConstraints { make in make.centerX.equalTo(contentView) make.top.equalTo(instructionsLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) } } super.updateConstraints() } }
mpl-2.0
78879b6e0f02475451e4adf766ca1fe4
41.481038
178
0.691162
5.314107
false
false
false
false
tokorom/partial-swift
partial-swiftTests/partial_swiftTests.swift
1
2776
// // partial_swiftTests.swift // partial-swiftTests // // Created by ytokoro on 7/30/14. // Copyright (c) 2014 tokoro. All rights reserved. // import UIKit import XCTest func add(a: Int, b: Int) -> Int { return a + b } class partial_swiftTests: XCTestCase { private func substract(a: Int, b: Int) -> Int { return a - b } private class func add(a: Int, b: Int) -> Int { return a + b } func testPartialToFunction() { let add1 = partial(add, 1) XCTAssertEqual(2, add1(1), "add1(1) is failed") XCTAssertEqual(3, add1(2), "add1(2) is failed") } func testPartialToInstanceMethod() { let substract10 = partial(self.substract, 10) XCTAssertEqual(9, substract10(1), "substract10(1) is failed") XCTAssertEqual(-10, substract10(20), "substract10(20) is failed") } func testPartialToClassMethod() { let add10 = partial(partial_swiftTests.add, 10) XCTAssertEqual(11, add10(1), "add10(1) is failed") XCTAssertEqual(12, add10(2), "add10(2) is failed") } func testPartialWithLazy() { class Stub { var times = 0 func call() -> Int { ++self.times return self.times } } let stub = Stub() XCTAssertEqual(0, stub.times, "stub.times is invalid") XCTAssertEqual(1, stub.call(), "stub.call() is invalid") XCTAssertEqual(2, stub.call(), "stub.call() is invalid") let add3 = partial(partial_swiftTests.add, stub.call()) XCTAssertEqual(2, stub.times, "stub.times is invalid") XCTAssertEqual(4, add3(1), "add3(1) is failed") } func test3Args() { func add3Ints(a: Int, b: Int, c: Int) -> Int { return a + b + c } let add1 = partial(add3Ints, 1) XCTAssertEqual(6, add1(2, 3), "add1(2, 3) is failed") let add1and2 = partial(add1, 2) XCTAssertEqual(6, add1and2(3), "add1and2(3) is failed") } func test3ArgsWith2Args() { func add3Ints(a: Int, b: Int, c: Int) -> Int { return a + b + c } let add1and2 = partial(add3Ints, 1, 2) XCTAssertEqual(6, add1and2(3), "add1and2(3) is failed") } func test4Args() { func add4Ints(a: Int, b: Int, c: Int, d: Int) -> Int { return a + b + c + d } let add1 = partial(add4Ints, 1) XCTAssertEqual(10, add1(2, 3, 4), "add1(2, 3, 4) is failed") let add1and2 = partial(add4Ints, 1, 2) XCTAssertEqual(10, add1and2(3, 4), "add1and2(3, 4) is failed") let add1and2and3 = partial(add4Ints, 1, 2, 3) XCTAssertEqual(10, add1and2and3(4), "add1and2and3(4) is failed") } }
mit
42aba2f3c10cb9e3d854a1b544cb34ae
27.040404
73
0.56232
3.308701
false
true
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 25 - Intermediate WebKit/RWPedia-Starter/RWPedia_swift/ViewController.swift
1
5211
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import WebKit class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView @IBOutlet weak var authorsButton: UIBarButtonItem! @IBOutlet weak var backButton: UIBarButtonItem! @IBOutlet weak var forwardButton: UIBarButtonItem! @IBOutlet weak var stopReloadButton: UIBarButtonItem! required init?(coder aDecoder: NSCoder) { // self.webView = WKWebView(frame: CGRectZero) let hideBioScriptURL = NSBundle.mainBundle().pathForResource("hideBio", ofType: "js") let hideBioJS = try! String(contentsOfFile: hideBioScriptURL!, encoding: NSUTF8StringEncoding) let hideBioScript = WKUserScript(source: hideBioJS, injectionTime: .AtDocumentStart, forMainFrameOnly: true) let configuration = WKWebViewConfiguration() configuration.userContentController.addUserScript(hideBioScript) self.webView = WKWebView(frame: CGRectZero, configuration: configuration) super.init(coder: aDecoder) self.webView.navigationDelegate = self } override func viewDidLoad() { super.viewDidLoad() authorsButton.enabled = false backButton.enabled = false forwardButton.enabled = false; view.addSubview(webView) webView.translatesAutoresizingMaskIntoConstraints = false let widthConstraint = NSLayoutConstraint(item: webView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0) view.addConstraint(widthConstraint) let heightConstraint = NSLayoutConstraint(item: webView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: -44) view.addConstraint(heightConstraint) webView.addObserver(self, forKeyPath: "loading", options: .New, context: nil) webView.addObserver(self, forKeyPath: "title", options: .New, context: nil) let URL = NSURL(string:"http://www.raywenderlich.com") let request = NSURLRequest(URL:URL!) webView.loadRequest(request) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<()>) { if (keyPath == "loading") { forwardButton.enabled = webView.canGoForward backButton.enabled = webView.canGoBack stopReloadButton.image = webView.loading ? UIImage(named: "icon_stop") : UIImage(named: "icon_refresh") UIApplication.sharedApplication().networkActivityIndicatorVisible = webView.loading } else if (keyPath == "title") { if (webView.URL!.absoluteString.hasPrefix("http://www.raywenderlich.com/u")) { title = webView.title!.stringByReplacingOccurrencesOfString("Ray Wenderlich | ", withString: "") } } } func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) { if navigationAction.navigationType == .LinkActivated && navigationAction.request.URL?.host?.lowercaseString.hasPrefix("www.raywenderlich.com") == false { UIApplication.sharedApplication().openURL(navigationAction.request.URL!); decisionHandler(.Cancel) } else { decisionHandler(.Allow) } } @IBAction func authorsButtonTapped(sender: UIBarButtonItem) { print("Authors tapped") } @IBAction func goBack(sender: UIBarButtonItem) { webView.goBack() } @IBAction func goForward(sender: UIBarButtonItem) { webView.goForward() } @IBAction func stopReload(sender: UIBarButtonItem) { if (webView.loading) { webView.stopLoading() } else { let request = NSURLRequest(URL:webView.URL!) webView.loadRequest(request) } } }
mit
6ee110355e94c3802a65599c6773b0c6
41.713115
163
0.735559
4.861007
false
false
false
false
PlutoMa/SwiftProjects
012.Emoji Slot Machine/EmojiSlotMachine/EmojiSlotMachine/ViewController.swift
1
3987
// // ViewController.swift // EmojiSlotMachine // // Created by Dareway on 2017/10/19. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit class ViewController: UIViewController { let slotMachine = UIPickerView() let emojiArray = ["😀","😎","😈","👻","🙈","🐶","🌚","🍎","🎾","🐥","🐔"] let resultLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() -> Void { slotMachine.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 220) slotMachine.center = CGPoint(x: view.bounds.width / 2.0, y: view.bounds.height / 2.0 - 50) slotMachine.delegate = self slotMachine.dataSource = self view.addSubview(slotMachine) randomRow(animation: false, equal: false) let actionBtn = UIButton(type: .system) actionBtn.frame = CGRect(x: 0, y: 0, width: 275, height: 40) actionBtn.center = CGPoint(x: slotMachine.center.x, y: view.bounds.height / 2.0 + 140) actionBtn.backgroundColor = UIColor.green actionBtn.setTitle("Go", for: .normal) actionBtn.setTitleColor(UIColor.white, for: .normal) actionBtn.addTarget(self, action: #selector(actionBtnAction), for: .touchUpInside) view.addSubview(actionBtn) let doubleTapGR = UITapGestureRecognizer(target: self, action: #selector(doubleTapGRAction)) doubleTapGR.numberOfTapsRequired = 2 actionBtn.addGestureRecognizer(doubleTapGR) resultLabel.frame = CGRect(x: 0, y: 0, width: 200, height: 50) resultLabel.textAlignment = .center resultLabel.font = UIFont.systemFont(ofSize: 20) resultLabel.text = "" resultLabel.textColor = UIColor.black self.view.addSubview(resultLabel) resultLabel.center.x = self.view.center.x resultLabel.center.y = actionBtn.center.y + 100 } @objc func actionBtnAction() -> Void { randomRow(animation: true, equal: false) } @objc func doubleTapGRAction() -> Void { randomRow(animation: true, equal: true) } func randomRow(animation: Bool, equal: Bool) -> Void { let row1 = Int(arc4random()) % (emojiArray.count - 2) + 1 var row2 = 0 var row3 = 0 if equal == true { row2 = row1 row3 = row1 } else { row2 = Int(arc4random()) % (emojiArray.count - 2) + 1 row3 = Int(arc4random()) % (emojiArray.count - 2) + 1 } slotMachine.selectRow(row1, inComponent: 0, animated: animation) slotMachine.selectRow(row2, inComponent: 1, animated: animation) slotMachine.selectRow(row3, inComponent: 2, animated: animation) judge() } func judge() -> Void { if slotMachine.selectedRow(inComponent: 0) == slotMachine.selectedRow(inComponent: 1) && slotMachine.selectedRow(inComponent: 1) == slotMachine.selectedRow(inComponent: 2) { resultLabel.text = "👏👏👏" } else { resultLabel.text = "💔💔💔" } } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return emojiArray.count } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 90 } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let pickerLabel = UILabel() pickerLabel.text = emojiArray[row] pickerLabel.textAlignment = .center pickerLabel.font = UIFont.systemFont(ofSize: 60) return pickerLabel } }
mit
d6473db236f49de21825cd0b63171d8a
33.5
181
0.616578
4.197439
false
false
false
false
moriturus/Ainu
Sources/Ainu/Strength.swift
1
5945
// // Strength.swift // Ainu // // Copyright (c) 2017 Henrique Sasaki Yuya ([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 import CoreGraphics /// Strength of password public enum Strength: CustomStringConvertible, Comparable { /// The password is empty. case empty /// The password is very weak. case veryWeak /// The password is weak. case weak /// The password is not bad. case reasonable /// The password is strong. case strong /// The password is very strong. case veryStrong fileprivate var intValue: Int { switch self { case .empty: return -1 case .veryWeak: return 0 case .weak: return 1 case .reasonable: return 2 case .strong: return 3 case .veryStrong: return 4 } } public var description: String { switch self { case .empty: return NSLocalizedString("Empty", tableName: "Ainu", comment: "Empty") case .veryWeak: return NSLocalizedString("Very Weak Password", tableName: "Ainu", comment: "very weak password") case .weak: return NSLocalizedString("Weak Password", tableName: "Ainu", comment: "weak password") case .reasonable: return NSLocalizedString("Reasonable Password", tableName: "Ainu", comment: "reasonable password") case .strong: return NSLocalizedString("Strong Password", tableName: "Ainu", comment: "strong password") case .veryStrong: return NSLocalizedString("Very Strong Password", tableName: "Ainu", comment: "very strong password") } } /** Initializes with password string. - parameter password: password string */ public init(password: String) { self.init(entropy: Strength.entropy(password)) } /** Initializes with password's entropy value. - parameter entropy: password's entropy value */ private init(entropy: CGFloat) { switch entropy { case -(CGFloat.greatestFiniteMagnitude) ..< 0.0: self = .empty case 0.0 ..< 28.0: self = .veryWeak case 28.0 ..< 36.0: self = .weak case 36.0 ..< 60.0: self = .reasonable case 60.0 ..< 128.0: self = .strong default: self = .veryStrong } } /** Computes entopy value for the given string. - parameter string: string to be computed entropy - returns: entropy */ private static func entropy(_ string: String) -> CGFloat { guard !string.isEmpty else { return -CGFloat.greatestFiniteMagnitude } var includesLowercaseCharacter = false var includesUppercaseCharacter = false var includesDecimalDigitCharacter = false var includesPunctuationCharacter = false var includesSymbolCharacter = false var includesWhitespaceCharacter = false var includesNonBaseCharacter = false let base: UInt = string.unicodeScalars.reduce(0) { (accm, c) in var accm = accm if !includesLowercaseCharacter && CharacterSet.lowercaseLetters.contains(c) { includesLowercaseCharacter = true accm += 26 } if !includesUppercaseCharacter && CharacterSet.uppercaseLetters.contains(c) { includesUppercaseCharacter = true accm += 2 } if !includesDecimalDigitCharacter && CharacterSet.decimalDigits.contains(c) { includesDecimalDigitCharacter = true accm += 10 } if !includesPunctuationCharacter && CharacterSet.punctuationCharacters.contains(c) { includesPunctuationCharacter = true accm += 20 } if !includesSymbolCharacter && CharacterSet.symbols.contains(c) { includesSymbolCharacter = true accm += 10 } if !includesWhitespaceCharacter && CharacterSet.whitespaces.contains(c) { includesWhitespaceCharacter = true accm += 1 } if !includesNonBaseCharacter && CharacterSet.nonBaseCharacters.contains(c) { includesNonBaseCharacter = true accm += 32 + 128 } return accm } let entropyPerCharacter = log2(CGFloat(base)) return entropyPerCharacter * CGFloat(string.unicodeScalars.count) } } public func <(lhs: Strength, rhs: Strength) -> Bool { return lhs.intValue < rhs.intValue }
mit
09341055dcf674e65091d9dae94c660a
26.523148
112
0.603869
5.059574
false
false
false
false
Adorkable/BingAPIiOS
BingAPI/BingSearchResult.swift
1
2672
// // BingSearchResult.swift // BingAPI // // Created by Ian on 4/3/15. // Copyright (c) 2015 Adorkable. All rights reserved. // import Foundation import AdorkableAPIBase /** * Bing Search Results */ public class BingSearchResult: RouteBase<Bing>, CustomDebugStringConvertible { /// id public let id : String /// description public let resultDescription : String /// title public let title : String /// Url string public let urlString : String /// Url as NSURL public var url : NSURL? { get { return NSURL(string: self.urlString) } } /// meta data public let metaData : NSDictionary init(resultDescription : String, id : String, title : String, urlString : String, metaData : NSDictionary) { self.resultDescription = resultDescription self.id = id self.title = title self.urlString = urlString self.metaData = metaData super.init() } init?(dictionary : NSDictionary) { var initFailed = false if let id = dictionary["ID"] as? String { self.id = id } else { self.id = "" initFailed = true } if let description = dictionary["Description"] as? String { self.resultDescription = description } else { self.resultDescription = "" initFailed = true } if let title = dictionary["Title"] as? String { self.title = title } else { self.title = "" initFailed = true } if let urlString = dictionary["Url"] as? String { self.urlString = urlString } else { self.urlString = "" initFailed = true } if let metaData = dictionary["__metadata"] as? NSDictionary { self.metaData = metaData } else { self.metaData = NSDictionary() initFailed = true } super.init() if initFailed { return nil } } /// debug description override public var debugDescription: String { get { var result = super.debugDescription + "\n" result += "ID: \(self.id)\n" result += "Title: \(self.title)\n" result += "Description: \(self.resultDescription)\n" result += "URL: \(self.url)\n" result += "Metadata: \(self.metaData)" return result } } }
mit
9db6cc605d4532d4d6fbbabd2e4d33b2
22.857143
112
0.507111
4.893773
false
false
false
false
fulldecent/FDTextFieldTableViewCell
Sources/FDTextFieldTableViewCell/FDTextFieldTableViewCell.swift
1
2383
// // FDTextFieldTableViewCell.swift // FDTextFieldTableViewCell // // Created by William Entriken on 2/2/16. // Copyright © 2016 William Entriken. All rights reserved. // import UIKit //@IBDesignable /// A UITableViewCell with a UITextField inside open class FDTextFieldTableViewCell: UITableViewCell { open var textField = UITextField() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override open func awakeFromNib() { super.awakeFromNib() self.setup() } private func setup() { self.detailTextLabel?.isHidden = true self.contentView.viewWithTag(3)?.removeFromSuperview() self.textField.tag = 3 self.textField.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.textField) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .leading, relatedBy: .equal, toItem: self.contentView, attribute: .leading, multiplier: 1, constant: 50 )) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1, constant: 8 )) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .bottom, relatedBy: .equal, toItem: self.contentView, attribute: .bottom, multiplier: 1, constant: -8 )) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: -16 )) self.textField.textAlignment = .right } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.textField.becomeFirstResponder() } }
mit
efaecfb48a09a19f42d57de514023b2a
29.151899
84
0.602435
5.133621
false
false
false
false
XLsn0w/XLsn0wKit_swift
XLsn0wKit/Components/XLsn0wSwiftLoop/XLsn0wSwiftLoop.swift
1
8051
/********************************************************************************************* * __ __ _ _________ _ _ _ _________ __ _ __ * * \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / * * \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / * * \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / * * /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / * * / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / * * /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ * * * ********************************************************************************************* ********************************************************************************************* *********************************************************************************************/ import UIKit let ScreenWidth = UIScreen.main.bounds.width class XLsn0wSwiftLoop: UIView { var timer:Timer? public var dataArray:NSArray? { didSet{ /** * 因为传进来的是Array类型的数组,没有exchangeObjectAtIndex方法,只能转换为NSMutableArray类型,笔者初学swfit只能这样遍历一下了 */ for object in dataArray!{ self.imageArray.add(object) } leftImageView.image = UIImage(named: self.imageArray[0] as! String) contentImageView.image = UIImage(named: self.imageArray[1] as! String ) rightImageView.image = UIImage(named: self.imageArray[2] as! String) pageView.numberOfPages = self.imageArray.count } } /// pageView当前点的颜色 var cuttentPageColor:UIColor = UIColor.blue { didSet{ pageView.currentPageIndicatorTintColor = cuttentPageColor } } /// pageView没有选中点的颜色 var pageIndicatorTintColor:UIColor = UIColor.yellow { didSet{ pageView.pageIndicatorTintColor = pageIndicatorTintColor; } } override init(frame: CGRect) { super.init(frame: frame) steUpUI() } private func steUpUI(){ addSubview(scrollView) scrollView.addSubview(leftImageView) scrollView.addSubview(contentImageView) scrollView.addSubview(rightImageView) addSubview(pageView) timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(XLsn0wSwiftLoop.guandong), userInfo: nil, repeats: true) RunLoop().add(timer!, forMode: RunLoopMode.commonModes) } // 定时器和button的点击的时间前面都不能使用private修饰,因为他们的时间是runloop循环式调用 // let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // let size = CGSize(width: 100, height: 100) // let point = CGPoint(x: 2.0, y: 0) func guandong() { let point = CGPoint(x: 2.0*width, y: 0) scrollView.setContentOffset(point, animated: true) } /// 懒加载scrollview private lazy var scrollView :UIScrollView = { let scrollViewRect = CGRect(x:0, y:0, width:UIScreen.main.bounds.width, height:self.frame.size.height) let scro = UIScrollView(frame: scrollViewRect) scro.showsHorizontalScrollIndicator = false; scro.showsVerticalScrollIndicator = false; scro.contentSize = CGSize(width:3.0*UIScreen.main.bounds.width, height: 0) scro.contentOffset = CGPoint(x:UIScreen.main.bounds.width, y:0) scro.delegate = self scro.bounces = false //设置弹簧效果关闭,有助于滚动的时候显示后面的白框 scro.isPagingEnabled = true // 设置分页效果,有助于手动拖动一页 return scro }() /// 懒加载左视图 public lazy var leftImageView:UIImageView = { let left = UIImageView(frame: CGRect(x:0, y:0, width:ScreenWidth, height:self.frame.size.height)) return left }() /// 懒加载当前视图 public lazy var contentImageView:UIImageView = { let content = UIImageView(frame: CGRect(x:ScreenWidth, y:0, width:ScreenWidth, height:self.frame.size.height)) return content }() /// 懒加载右视图 public lazy var rightImageView:UIImageView = { let right = UIImageView(frame: CGRect(x:2*ScreenWidth, y:0, width:ScreenWidth, height:self.frame.size.height)) return right }() /// 懒加载数据 /* * :NSMutableArray使用可变数组类型为NSMutableArray,因为下面用到NSMutableArray里面的交换元素位置的方法 */ public lazy var imageArray :NSMutableArray = NSMutableArray() /// 懒加载pageView public lazy var pageView:UIPageControl = { let page = UIPageControl(frame: CGRect(x:(ScreenWidth - 200.0)*0.5, y:self.frame.size.height-20, width:200, height:20)) page.currentPage = 0; page.currentPageIndicatorTintColor = self.cuttentPageColor page.pageIndicatorTintColor = self.pageIndicatorTintColor return page }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - XLsn0wSwiftLoop的代理方法 extension XLsn0wSwiftLoop : UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { /** * scrollview滚动到右视图的时候 */ if scrollView.contentOffset.x/width == 2.0 { if self.pageView.currentPage == self.imageArray.count-1{ pageView.currentPage = 0 }else{ pageView.currentPage = pageView.currentPage+1 } for i in 0..<imageArray.count-1 { // 交换数组里面元素的位置 每个都后移一个位置 imageArray .exchangeObject(at: i, withObjectAt: i+1) } leftImageView.image = UIImage(named: imageArray[0] as! String) contentImageView.image = UIImage(named: imageArray[1]as! String ) rightImageView.image = UIImage(named: imageArray[2] as! String) // 滚动到了右视图后,让它不带动画再悄悄滚动到中间的视图 scrollView.setContentOffset(CGPoint(x:ScreenWidth, y:0), animated: false) } // 向左滚动一个位置 if scrollView.contentOffset.x/width == 0.0{ if pageView.currentPage == 0{ pageView.currentPage = imageArray.count-1 }else{ pageView.currentPage = pageView.currentPage-1 } for i in 0..<imageArray.count-1 { // 将每个元素和最后一个元素进行交换 imageArray.exchangeObject(at: i, withObjectAt: imageArray.count-1) } leftImageView.image = UIImage(named: imageArray[0] as! String) contentImageView.image = UIImage(named: imageArray[1] as! String) rightImageView.image = UIImage(named: imageArray[2] as! String) // 还是一样的悄悄的滚到中间的位置 scrollView.setContentOffset(CGPoint(x:ScreenWidth, y:0), animated: false) } } /** 将要拖动的时候调用 */ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { timer?.invalidate() timer = nil } /** 拖动完成之后调用 */ func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(XLsn0wSwiftLoop.guandong), userInfo: nil, repeats: true) RunLoop().add(timer!, forMode: RunLoopMode.commonModes) } }
mit
5471678eb48d18fb9f8b68590d3b9bb4
40.165746
144
0.530935
4.209605
false
false
false
false
emilstahl/swift
test/DebugInfo/argument.swift
10
2478
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | FileCheck %s func markUsed<T>(t: T) {} // CHECK-DAG: !DILocalVariable(name: "arg", arg: 1,{{.*}} line: [[@LINE+1]] func a(arg : Int64) { // CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]] var local = arg } // CHECK-DAG: !DILocalVariable(name: "a", arg: 1,{{.*}} line: [[@LINE+3]] // CHECK-DAG: !DILocalVariable(name: "b", arg: 2,{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "c", arg: 3,{{.*}} line: [[@LINE+1]] func many(a: Int64, b: (Int64, Int64), c: Int64) -> Int64 { // CHECK-DAG: !DILocalVariable(name: "i1",{{.*}} line: [[@LINE+1]] var i1 = a // CHECK-DAG: !DILocalVariable(name: "i2",{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "i3",{{.*}} line: [[@LINE+1]] var (i2, i3) : (Int64, Int64) = b // CHECK-DAG: !DILocalVariable(name: "i4",{{.*}} line: [[@LINE+1]] var i4 = c return i1+i2+i3+i4 } class A { var member : Int64 // CHECK-DAG: !DILocalVariable(name: "a", arg: 1,{{.*}} line: [[@LINE+1]] init(a: Int64) { member = a } // CHECK-DAG: !DILocalVariable(name: "offset", arg: 1,{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "self", arg: 2,{{.*}} line: [[@LINE+1]] func getValuePlus(offset: Int64) -> Int64 { // CHECK-DAG: !DILocalVariable(name: "a",{{.*}} line: [[@LINE+1]] var a = member return a+offset } // CHECK-DAG: !DILocalVariable(name: "factor", arg: 1,{{.*}} line: [[@LINE+3]] // CHECK-DAG: !DILocalVariable(name: "offset", arg: 2,{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "self", arg: 3,{{.*}} line: [[@LINE+1]] func getValueTimesPlus(factor: Int64, offset: Int64) -> Int64 { // CHECK-DAG: !DILocalVariable(name: "a",{{.*}} line: [[@LINE+1]] var a = member // CHECK-DAG: !DILocalVariable(name: "f",{{.*}} line: [[@LINE+1]] var f = factor return a*f+offset } // CHECK: !DILocalVariable(name: "self", arg: 1,{{.*}} line: [[@LINE+1]] deinit { markUsed(member) } } // Curried functions have their arguments backwards. // CHECK: !DILocalVariable(name: "b", arg: 1,{{.*}} line: [[@LINE+2]] // CHECK: !DILocalVariable(name: "a", arg: 2,{{.*}} line: [[@LINE+1]] func uncurry (a: Int64) (b: Int64) -> (Int64, Int64) { return (a, b) } // CHECK: !DILocalVariable(name: "x", arg: 1,{{.*}} line: [[@LINE+2]] // CHECK: !DILocalVariable(name: "y", arg: 2,{{.*}} line: [[@LINE+1]] func tuple(x: Int64, y: (Int64, Float, String)) -> Int64 { return x+y.0; }
apache-2.0
2046e238b6a65629e71b9cde78cdfc7a
35.441176
79
0.575061
2.901639
false
false
false
false
nebojsamihajlovic/SecondAssignment
GuessGame/RandomStringExtension.swift
1
750
// // RandomStringExtension.swift // GuessGame // // Created by Nebojsa Mihajlovic on 2/16/17. // Copyright © 2017 course. All rights reserved. // import Foundation extension String { static func randomizeAnimalString(randomizeString forAnimal: String) -> String { let letters: NSString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let len = UInt32(letters.length) var randomized = forAnimal for _ in 0 ..< 12 - forAnimal.characters.count { let rand = arc4random_uniform(len) var nextChar = letters.character(at: Int(rand)) randomized += NSString(characters: &nextChar, length: 1) as String } return randomized } }
gpl-3.0
8e42f2e0ad54ddf38c4ebc0120781b9d
23.966667
84
0.607477
4.32948
false
false
false
false
Henryforce/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorAnimationBallZigZag.swift
1
3723
// // KRActivityIndicatorAnimationBallZigZag.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // 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 Cocoa import QuartzCore class KRActivityIndicatorAnimationBallZigZag: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let circleSize: CGFloat = size.width / 5 let duration: CFTimeInterval = 0.7 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) // Circle 1 animation let animation = CAKeyframeAnimation(keyPath:"transform") animation.keyTimes = [0.0, 0.33, 0.66, 1.0] animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle 1 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) // Circle 2 animation animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] // Draw circle 2 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) } func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: NSColor, animation: CAAnimation) { let circle = KRActivityIndicatorShape.circle.layerWith(size: size, color: color) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
72401e2e59bd4b09584922b79b4695c6
48.64
160
0.686275
4.828794
false
false
false
false
webim/webim-client-sdk-ios
WebimClientLibrary/Implementation/WMKeychainWrapper.swift
1
8304
// // WMKeychainWrapper.swift // WebimClientLibrary // // Created by EVGENII Loshchenko on 05.07.2021. // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import Security import Foundation public class WMKeychainWrapper: NSObject { public static let dbFilePrefix = "webim_" public static let fileGuidURLDictionaryKey = "fileGuidURLDictionaryKey" public static let deviceTokenKey = "device-token" public static let webimKeyPrefix = "ru.webim." let webimUserDefaultsFirstRunKey = "ru.webim.userDefaultsFirstRunKey" override init() { super.init() cleanUserDefaults() } private var inited = false private func cleanUserDefaults() { if inited { return } inited = true UserDefaults.standard.removeObject(forKey: "fileGuidURLDictionaryKey") UserDefaults.standard.removeObject(forKey: "ru.webim.WebimClientSDKiOS.guid") UserDefaults.standard.removeObject(forKey: "settings") UserDefaults.standard.removeObject(forKey: "previous_account") UserDefaults.standard.removeObject(forKey: "device-token") for key in UserDefaults.standard.dictionaryRepresentation().keys { if key.starts(with: "ru.webim.WebimClientSDKiOS") { UserDefaults.standard.removeObject(forKey: key) } } let userDefaults = UserDefaults.standard if !userDefaults.bool(forKey: webimUserDefaultsFirstRunKey) { userDefaults.set(true, forKey: webimUserDefaultsFirstRunKey) for key in getAllKeychainItems() { if let key = key { if key.starts(with: WMKeychainWrapper.webimKeyPrefix) { _ = WMKeychainWrapper.removeObject(key: key) } } } } // remove old db files for file in FileManager.default.urls(for: .libraryDirectory) ?? [] { if fileIsWebimDb(url: file) { if !DBFileIsActual(url: file) { do { print("delete old db file: \(file)") try FileManager.default.removeItem(at: file) } catch { print("Could not delete old db file: \(error) \(file)") } } } } } static func actualDBPrefix() -> String { return WMKeychainWrapper.dbFilePrefix + "\(SQLiteHistoryStorage.getMajorVersion())_" } func fileIsWebimDb(url: URL) -> Bool { let fileName = url.lastPathComponent return fileName.hasPrefix(WMKeychainWrapper.dbFilePrefix) && fileName.hasSuffix(".db") } func DBFileIsActual(url: URL) -> Bool { let fileName = url.lastPathComponent return fileName.hasPrefix(WMKeychainWrapper.actualDBPrefix()) } public static var standard: WMKeychainWrapper = WMKeychainWrapper() open func dictionary(forKey defaultName: String) -> [String : Any]? { return WMKeychainWrapper.load(key: defaultName)?.dataToDictionary() } open func setDictionary(_ value: [String : Any]?, forKey defaultName: String) { _ = WMKeychainWrapper.save(key: defaultName, data: Data.dataFromDictionary(value)) } public func setString(_ value: String, forKey key: String) { WMKeychainWrapper.saveString(key: key, value: value) } open func string(forKey defaultName: String) -> String? { return WMKeychainWrapper.readString(key: defaultName) } static func removeObject(key: String) -> OSStatus{ let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: key] return SecItemDelete(query as CFDictionary) } class func saveString(key: String, value: String) { let data = Data(value.utf8) _ = WMKeychainWrapper.save(key: key, data: data) } class func readString(key: String) -> String? { if let receivedData = WMKeychainWrapper.load(key: key) { return String(decoding: receivedData, as: UTF8.self) } return nil } class func save(key: String, data: Data?) -> OSStatus { let secureStringKey = webimKeyPrefix + key let query = [ kSecClass as String : kSecClassGenericPassword as String, kSecAttrAccount as String : secureStringKey, kSecValueData as String : data as Any] as [String : Any] SecItemDelete(query as CFDictionary) return SecItemAdd(query as CFDictionary, nil) } class func load(key: String) -> Data? { let secureStringKey = webimKeyPrefix + key let query = [ kSecClass as String : kSecClassGenericPassword, kSecAttrAccount as String : secureStringKey, kSecReturnData as String : kCFBooleanTrue!, kSecMatchLimit as String : kSecMatchLimitOne ] as [String : Any] var dataTypeRef: AnyObject? = nil let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef) if status == noErr { return dataTypeRef as! Data? } else { return nil } } open func getAllKeychainItems() -> [String?] { let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecMatchLimit as String: kSecMatchLimitAll, kSecReturnAttributes as String: true, kSecReturnRef as String: true] var items_ref: CFTypeRef? _ = SecItemCopyMatching(query as CFDictionary, &items_ref) let items = items_ref as? Array<Dictionary<String, Any>> ?? [] return items.map({$0[kSecAttrAccount as String] as? String}) } } extension Data { static func dataFromDictionary(_ dict: [String: Any]?) -> Data? { if dict == nil { return nil } var data: Data? = nil do { data = try PropertyListSerialization.data(fromPropertyList: dict as Any, format: PropertyListSerialization.PropertyListFormat.binary, options: 0) } catch { print(error) } return data } func dataToDictionary() -> [String: Any]? { var dict: [String: Any]? do { let dicFromData = try PropertyListSerialization.propertyList(from: self, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil) dict = dicFromData as? [String: Any] } catch{ print(error) } return dict } } extension FileManager { func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? { let documentsURL = urls(for: directory, in: .userDomainMask)[0] let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] ) return fileURLs } }
mit
2ce57e1ec40c7910ca841f7089d8df70
37.091743
163
0.618979
4.960573
false
false
false
false
nayzak/Swift-MVVM
Swift MVVM/Framework/MVVM/SimpleTableViewHelper.swift
1
3735
// // TableViewHelper.swift // // Created by NayZaK on 24.02.15. // Copyright (c) 2015 Amur.net. All rights reserved. // import UIKit class SimpleTableViewHelper: NSObject, UITableViewDataSource, UITableViewDelegate { private weak var tableView: UITableView? private weak var data: Dynamic<[ViewModel]>? private weak var command: Command<Int>? private let cellId: String private var offscreenCell: BindableTableCell? init<C: BindableTableCell>(tableView tv: UITableView, data d: Dynamic<[ViewModel]>, cellType: C.Type, command c: Command<Int>? = nil) { tableView = tv data = d command = c cellId = className(cellType) super.init() let nib = UINib(nibName: cellId, bundle: nil) tableView!.registerNib(nib, forCellReuseIdentifier: cellId) tableView!.estimatedRowHeight = tableView!.rowHeight tableView!.delegate = self tableView!.dataSource = self data! >> { [weak self] v in if let tableView = self?.tableView { Async.main { tableView.reloadData() } } } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data != nil ? data!.value.count : 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? BindableTableCell { if let vm = data?.value[indexPath.row] { cell.bindViewModel(vm) if DeviceHelper.version < 8.0 { cell.setNeedsUpdateConstraints() cell.updateConstraintsIfNeeded() } return cell } } return UITableViewCell() } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { command?.execute(indexPath.row) } private var estimatedRowHeightCache = [NSIndexPath:CGFloat]() func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height = tableView.estimatedRowHeight if DeviceHelper.version >= 8.0 { height = UITableViewAutomaticDimension estimatedRowHeightCache[indexPath] = height } else { if let h = estimatedRowHeightCache[indexPath] { height = h } else if let h = cellHeight(tableView, indexPath: indexPath) { height = h estimatedRowHeightCache[indexPath] = height } } return height } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height = tableView.estimatedRowHeight if DeviceHelper.version >= 8.0 { height = estimatedRowHeightCache[indexPath] ?? height } else { if let h = estimatedRowHeightCache[indexPath] { height = h } else if let h = cellHeight(tableView, indexPath: indexPath) { height = h estimatedRowHeightCache[indexPath] = height } } return height } private func cellHeight(tableView: UITableView, indexPath: NSIndexPath) -> CGFloat? { var height: CGFloat? = nil if offscreenCell == nil { offscreenCell = tableView.dequeueReusableCellWithIdentifier(cellId) as? BindableTableCell } if let vm = data?.value[indexPath.row] { if let cell = offscreenCell { cell.bounds = CGRect(x: 0.0, y: 0.0, width: tableView.bounds.width, height: tableView.estimatedRowHeight) cell.bindViewModel(vm) cell.setNeedsUpdateConstraints() cell.updateConstraintsIfNeeded() cell.setNeedsLayout() cell.layoutIfNeeded() height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height if tableView.separatorStyle != .None { height! += 1.0 } } } return height } }
mit
2d50d27505e73702175190b87c578d6f
32.061947
137
0.688889
4.831824
false
false
false
false
aqeelb/BobaCam
BobaCam/ViewController.swift
1
2688
// // CameraViewController.swift // BobaCam // // Created by Aqeel Bhat on 27/10/16. // Copyright © 2016 PIXERF PTE LTD. All rights reserved. // import UIKit import AVFoundation class CameraViewController: UIViewController { /* To-do List: 1 - Show a preview of camera on screen 2 - Remove deprecated API's 3 - Save photo 4 - Save photo with exif 5 - Save photo with exif to custom album 6 - Pick photo from Library 7 - Get lat, long 8 - Write lat, long to exif 9 - Save photo with exif, tiff, gps to custom album */ @IBOutlet weak var previewView: UIView! @IBOutlet weak var capturedImage: UIView! // MARK: Declarations var captureSession: AVCaptureSession? var stillImageOutput: AVCaptureStillImageOutput? var previewLayer: AVCaptureVideoPreviewLayer? // MARK: - view lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // @info: prepare capture session captureSession = AVCaptureSession() captureSession!.sessionPreset = AVCaptureSessionPresetPhoto let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { let input = try AVCaptureDeviceInput(device: backCamera) captureSession!.addInput(input) stillImageOutput = AVCaptureStillImageOutput() stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] if captureSession!.canAddOutput(stillImageOutput) { captureSession!.addOutput(stillImageOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.portrait previewView.layer.addSublayer(previewLayer!) captureSession!.startRunning() } } catch let error { print(error.localizedDescription) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) previewLayer!.frame = previewView.bounds } // MARK: - UIViewController override public var prefersStatusBarHidden: Bool { return true } // MARK: Actions @IBAction func didPressCapture(_ sender: UIButton) { print("didPressCapture Button") } }
mit
63a72ec2d401e93e216bf3194efb335d
28.206522
95
0.624488
5.971111
false
false
false
false
gintsmurans/SwiftCollection
Sources/Extensions/eDictionary.swift
2
3011
// // EDictionary.swift // // Created by Gints Murans on 03.11.14. // Copyright © 2014 Gints Murans. All rights reserved. // import Foundation public extension NSDictionary { // Returns json string constructed from this dictionary or nil in case of an error func jsonString(_ pretty: Bool = false) -> (String?, String?) { if JSONSerialization.isValidJSONObject(self) == false { return (nil, "Not valid JSON object") } var jsonData: Data? do { let options = (pretty == true ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()) try jsonData = JSONSerialization.data(withJSONObject: self, options: options) } catch let error as NSError { return (nil, error.localizedDescription) } if let tmp = String(data: jsonData!, encoding: String.Encoding.utf8) { return (tmp, nil) } else { return ("{}", nil) } } convenience init?(jsonString: String) { guard let data = jsonString.data(using: String.Encoding.utf8) else { return nil } var newObject: NSDictionary? do { newObject = try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.mutableLeaves, JSONSerialization.ReadingOptions.mutableContainers]) as? NSDictionary } catch { return nil } self.init(dictionary: newObject!) } } public extension Dictionary { // Returns json string constructed from this dictionary or nil in case of an error func jsonString(_ pretty: Bool = false) -> (String?, String?) { if JSONSerialization.isValidJSONObject(self) == false { return (nil, "Not valid JSON object") } var jsonData: Data? do { let options = (pretty == true ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()) try jsonData = JSONSerialization.data(withJSONObject: self, options: options) } catch let error as NSError { return (nil, error.localizedDescription) } if let tmp = String(data: jsonData!, encoding: String.Encoding.utf8) { return (tmp, nil) } else { return ("{}", nil) } } } extension Dictionary where Key == String, Value == Any? { public func replaceNull(with newItem: Any, doRecursive recursive: Bool = true) -> [String: Any?] { var dict: [String: Any?] = self.mapValues { $0 is NSNull || $0 == nil ? newItem : $0 } if recursive == true { for (key, item) in dict { if let tmpItem = item as? [String: Any?] { dict[key] = tmpItem.replaceNull(with: newItem) } else if let tmpItem = item as? [[String: Any?]] { dict[key] = tmpItem.replaceNull(with: newItem) } } } return dict } }
mit
a38abf7f457d3d8817b98f5716d18738
33.204545
196
0.592359
4.666667
false
false
false
false
honishi/Hakumai
Hakumai/Managers/CommentCopier/CommentCopier.swift
1
4488
// // CommentCopier.swift // Hakumai // // Created by Hiroyuki Onishi on 2022/06/18. // Copyright © 2022 Hiroyuki Onishi. All rights reserved. // import Foundation final class CommentCopier: CommentCopierType { let live: Live let messageContainer: MessageContainer let nicoManager: NicoManagerType let handleNameManager: HandleNameManager init(live: Live, messageContainer: MessageContainer, nicoManager: NicoManagerType, handleNameManager: HandleNameManager) { self.live = live self.messageContainer = messageContainer self.nicoManager = nicoManager self.handleNameManager = handleNameManager } } extension CommentCopier { static func make(live: Live, messageContainer: MessageContainer, nicoManager: NicoManagerType, handleNameManager: HandleNameManager) -> CommentCopierType { let copier = CommentCopier( live: live, messageContainer: messageContainer, nicoManager: nicoManager, handleNameManager: handleNameManager) return copier } func copy(completion: (() -> Void)?) { preCacheUserIds { self.copyMessages() completion?() } } } private extension CommentCopier { func preCacheUserIds(completion: @escaping () -> Void) { let userIds = messageContainer .filteredMessages .toRawUserIds() log.debug(userIds) resolveUserIds(userIds) { completion() } } func resolveUserIds(_ userIds: [String], completion: @escaping () -> Void) { guard let userId = userIds.first else { completion() return } let resolveOnceCompleted = { var _userIds = userIds _userIds.removeFirst() DispatchQueue.global(qos: .default).async { self.resolveUserIds(_userIds, completion: completion) } } if let cached = nicoManager.cachedUserName(for: userId) { log.debug("Already cached: \(cached)") resolveOnceCompleted() return } nicoManager.resolveUsername(for: userId) { log.debug("Pre-cached: \($0 ?? "")") resolveOnceCompleted() } } func copyMessages() { let comments = messageContainer .filteredMessages .map { $0.toComment(live: live, nicoManager: nicoManager, handleNameManager: handleNameManager) } .reduce("") { $0 + "\($1)\n" } comments.copyToPasteBoard() } } private extension Array where Element == Message { func toRawUserIds() -> [String] { let userIds = map { message -> String? in switch message.content { case .system, .debug: return nil case .chat(let chat): return chat.userId } } .compactMap { $0 } .filter { $0.isRawUserId } return [String](Set(userIds)) } } private extension Message { func toComment(live: Live, nicoManager: NicoManagerType, handleNameManager: HandleNameManager) -> String { var number = "" var comment = "" var user = "" var premium = "" switch content { case .system(let message): comment = message.message case .chat(let message): number = String(message.no) comment = message.comment user = message.toResolvedUserId( live: live, nicoManager: nicoManager, handleNameManager: handleNameManager) premium = message.premium.label() case .debug(let message): comment = message.message } comment = comment.trimEnter() return "\(number)\t\(comment)\t\(user)\t\(premium)" } } private extension ChatMessage { func toResolvedUserId(live: Live, nicoManager: NicoManagerType, handleNameManager: HandleNameManager) -> String { var resolved = userId if let handleName = handleNameManager.handleName(for: userId, in: live.communityId) { resolved = "\(handleName) (\(userId))" } else if userId.isRawUserId, let accountName = nicoManager.cachedUserName(for: userId) { resolved = "\(accountName) (\(userId))" } return resolved } } private extension String { func trimEnter() -> String { return stringByRemovingRegexp(pattern: "\n") } }
mit
eeee320759eecf00529ea9cc87072d69
30.822695
159
0.598172
4.425049
false
false
false
false
theScud/Lunch
lunchPlanner/das-Quadart/Result.swift
1
5292
// // Result.swift // Quadrat // // Created by Constantine Fry on 16/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public let QuadratResponseErrorDomain = "QuadratOauthErrorDomain" public let QuadratResponseErrorTypeKey = "errorType" public let QuadratResponseErrorDetailKey = "errorDetail" /** A response from Foursquare server. Read `Responses & Errors`: https://developer.foursquare.com/overview/responses */ open class Result: CustomStringConvertible { /** HTTP response status code. */ open var HTTPSTatusCode: Int? /** HTTP response headers. Can contain `RateLimit-Remaining` and `X-RateLimit-Limit`. Read about `Rate Limits` <https://developer.foursquare.com/overview/ratelimits>. */ open var HTTPHeaders: [AnyHashable: Any]? /** The URL which has been requested. */ open var URL: Foundation.URL? /* Can contain error with following error domains: QuadratResponseErrorDomain - in case of error in `meta` parameter of Foursquare response. Error doesn't have localized description, but has `QuadratResponseErrorTypeKey` and `QuadratResponseErrorDetailKey` parameters in `userUnfo`. NSURLErrorDomain - in case of some networking problem. NSCocoaErrorDomain - in case of error during JSON parsing. */ open var error: NSError? /** A response. Extracted from JSON `response` field. Can be empty in case of error or `multi` request. If you are doung `multi` request use `subresponses` property */ open var response: [String:AnyObject]? /** Responses returned from `multi` endpoint. Subresponses never have HTTP headers and status code. Extracted from JSON `responses` field. */ open var results: [Result]? /** A notifications. Extracted from JSON `notifications` field. */ open var notifications: [[String:AnyObject]]? init() { } open var description: String { return "Status code: \(HTTPSTatusCode)\nResponse: \(response)\nError: \(error)" } } /** Response creation from HTTP response. */ extension Result { class func createResult(_ HTTPResponse: HTTPURLResponse?, JSON: [String:AnyObject]?, error: NSError? ) -> Result { let result = Result() if let error = error { result.error = error return result } if let HTTPResponse = HTTPResponse { result.HTTPHeaders = HTTPResponse.allHeaderFields result.HTTPSTatusCode = HTTPResponse.statusCode result.URL = HTTPResponse.url } if let JSON = JSON { if let meta = JSON["meta"] as? [String:AnyObject], let code = meta["code"] as? Int, code < 200 || code > 299 { result.error = NSError(domain: QuadratResponseErrorDomain, code: code, userInfo: meta) } result.notifications = JSON["notifications"] as? [[String:AnyObject]] result.response = JSON["response"] as? [String:AnyObject] if let response = result.response, let responses = response["responses"] as? [[String:AnyObject]] { var subResults = [Result]() for aJSONResponse in responses { let quatratResponse = Result.createResult(nil, JSON: aJSONResponse, error: nil) subResults.append(quatratResponse) } result.results = subResults result.response = nil } } return result } class func resultFromURLSessionResponse(_ response: URLResponse?, data: Data?, error: NSError?) -> Result { let HTTPResponse = response as? HTTPURLResponse var JSONResult: [String: AnyObject]? var JSONError = error if let data = data, JSONError == nil && HTTPResponse?.mimeType == "application/json" { do { JSONResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String: AnyObject] } catch let error as NSError { JSONError = error } } let result = Result.createResult(HTTPResponse, JSON: JSONResult, error: JSONError) return result } } /** Some helpers methods. */ extension Result { /** Returns `RateLimit-Remaining` parameter, if there is one in `HTTPHeaders`. */ public func rateLimitRemaining() -> Int? { return self.HTTPHeaders?["RateLimit-Remaining"] as? Int } /** Returns `X-RateLimit-Limit` parameter, if there is one in `HTTPHeaders`. */ public func rateLimit() -> Int? { return self.HTTPHeaders?["X-RateLimit-Limit"] as? Int } /** Whether task has been cancelled or not. */ public func isCancelled() -> Bool { if let error = self.error { return (error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled) } return false } }
apache-2.0
fd833a9ac3058e70c83c259284ed70d1
32.923077
118
0.601096
4.9
false
false
false
false
TakuSemba/DribbbleSwiftApp
Carthage/Checkouts/RxSwift/Rx.playground/Pages/Debugging_Operators.xcplaygroundpage/Contents.swift
1
2233
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxSwift-OSX** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator**. 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). ---- [Previous](@previous) - [Table of Contents](Table_of_Contents) */ import RxSwift /*: # Debugging Operators Operators to help debug Rx code. ## `debug` Prints out all subscriptions, events, and disposals. */ example("debug") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<String>.create { observer in observer.onNext("🍎") observer.onNext("🍐") observer.onNext("🍊") if count < 5 { observer.onError(Error.Test) print("Error encountered") count += 1 } observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐭") observer.onCompleted() return NopDisposable.instance } sequenceThatErrors .retry(3) .debug() .subscribeNext { print($0) } .addDisposableTo(disposeBag) } /*: ---- ## `RxSwift.resourceCount` Provides a count of all Rx resource allocations, which is useful for detecting leaks during development. */ #if NOT_IN_PLAYGROUND #else example("RxSwift.resourceCount") { print(RxSwift.resourceCount) let disposeBag = DisposeBag() print(RxSwift.resourceCount) let variable = Variable("🍎") let subscription1 = variable.asObservable().subscribeNext { print($0) } print(RxSwift.resourceCount) let subscription2 = variable.asObservable().subscribeNext { print($0) } print(RxSwift.resourceCount) subscription1.dispose() print(RxSwift.resourceCount) subscription2.dispose() print(RxSwift.resourceCount) } print(RxSwift.resourceCount) #endif //: > `RxSwift.resourceCount` is not enabled by default, and should generally not be enabled in Release builds. [Click here](Enable_RxSwift.resourceCount) for instructions on how to enable it. //: [Table of Contents](Table_of_Contents)
apache-2.0
71b74d42fecd3c52464072ff6b96a086
25.578313
192
0.625567
4.576763
false
false
false
false
shohei/firefox-ios
ClientTests/ClientTests.swift
17
3273
/* 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 XCTest import Storage import WebKit class ClientTests: XCTestCase { func testArrayCursor() { let data = ["One", "Two", "Three"]; let t = ArrayCursor<String>(data: data); // Test subscript access XCTAssertNil(t[-1], "Subscript -1 returns nil"); XCTAssertEqual(t[0]!, "One", "Subscript zero returns the correct data"); XCTAssertEqual(t[1]!, "Two", "Subscript one returns the correct data"); XCTAssertEqual(t[2]!, "Three", "Subscript two returns the correct data"); XCTAssertNil(t[3], "Subscript three returns nil"); // Test status data with default initializer XCTAssertEqual(t.status, CursorStatus.Success, "Cursor as correct status"); XCTAssertEqual(t.statusMessage, "Success", "Cursor as correct status message"); XCTAssertEqual(t.count, 3, "Cursor as correct size"); // Test generator access var i = 0; for s in t { XCTAssertEqual(s!, data[i], "Subscript zero returns the correct data"); i++; } // Test creating a failed cursor let t2 = ArrayCursor<String>(data: data, status: CursorStatus.Failure, statusMessage: "Custom status message"); XCTAssertEqual(t2.status, CursorStatus.Failure, "Cursor as correct status"); XCTAssertEqual(t2.statusMessage, "Custom status message", "Cursor as correct status message"); XCTAssertEqual(t2.count, 0, "Cursor as correct size"); // Test subscript access return nil for a failed cursor XCTAssertNil(t2[0], "Subscript zero returns nil if failure"); XCTAssertNil(t2[1], "Subscript one returns nil if failure"); XCTAssertNil(t2[2], "Subscript two returns nil if failure"); XCTAssertNil(t2[3], "Subscript three returns nil if failure"); // Test that generator doesn't work with failed cursors var ran = false; for s in t2 { println("Got \(s)") ran = true; } XCTAssertFalse(ran, "for...in didn't run for failed cursor"); } // Simple test to make sure the WKWebView UA matches the expected FxiOS pattern. func testUserAgent() { let expectation = expectationWithDescription("Found Firefox user agent") let webView = WKWebView() webView.evaluateJavaScript("navigator.userAgent") { result, error in let userAgent = result as! String let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let range = userAgent.rangeOfString("^Mozilla/5\\.0 \\(.+\\) AppleWebKit/[0-9\\.]+ \\(KHTML, like Gecko\\) FxiOS/\(appVersion) Mobile/[A-Z0-9]+ Safari/[0-9\\.]+$", options: NSStringCompareOptions.RegularExpressionSearch) if range != nil { expectation.fulfill() } else { XCTFail("User agent did not match expected pattern! \(userAgent)") } } waitForExpectationsWithTimeout(5, handler: nil) } }
mpl-2.0
0ebd8fd9552ed2463885811e67b740f4
42.64
232
0.634892
4.757267
false
true
false
false
sugar2010/arcgis-runtime-samples-ios
ClosestFacilitySample/swift/ClosestFacility/Controllers/SettingsViewController.swift
4
1925
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var facilityCountLabel:UILabel! @IBOutlet weak var cutoffTimeLabel:UILabel! @IBOutlet weak var facilityCountSlider:UISlider! @IBOutlet weak var cutOffTimeSlider:UISlider! var parameters:Parameters! override func viewDidLoad() { super.viewDidLoad() //reflect default values in sliders self.facilityCountSlider.value = Float(self.parameters.facilityCount) self.facilityCountLabel.text = "\(Int(self.parameters.facilityCount))" self.cutOffTimeSlider.value = Float(self.parameters.cutoffTime) self.cutoffTimeLabel.text = "\(Int(self.parameters.cutoffTime))" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Action Methods @IBAction func facilityCountChanged(facilityCountSlider:UISlider) { self.parameters.facilityCount = Int(facilityCountSlider.value) self.facilityCountLabel.text = "\(self.parameters.facilityCount)" } @IBAction func cutoffTimeChanged(cutoffTimeSlider:UISlider) { self.parameters.cutoffTime = Double(cutoffTimeSlider.value) self.cutoffTimeLabel.text = "\(Int(self.parameters.cutoffTime))" } @IBAction func done(sender:AnyObject) { self.dismissViewControllerAnimated(true, completion:nil) } }
apache-2.0
8e84dd952ec91286169c8ffcc55185b5
31.627119
87
0.70961
4.540094
false
false
false
false
LesCoureurs/Courir
Courir/Courir/PauseMenuNode.swift
1
2748
// // PauseMenuNode.swift // Courir // // Created by Ian Ngiaw on 4/2/16. // Copyright © 2016 NUS CS3217. All rights reserved. // import SpriteKit protocol PauseMenuDelegate: class { func pauseMenuDismissed() func leaveGameSelected() } class PauseMenuNode: SKNode { weak var delegate: PauseMenuDelegate? var overlayNode: SKShapeNode! let resumeNode = SKLabelNode(text: "resume") let leaveNode = SKLabelNode(text: "leave") override init() { super.init() initBackground() initResumeNode() initLeaveNode() } required init?(coder aDecoder: NSCoder) { overlayNode = aDecoder.decodeObjectForKey("overlayKey") as! SKShapeNode super.init(coder: aDecoder) } override func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(overlayNode, forKey: "overlayKey") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! let position = touch.locationInNode(self) let touchedNode = nodeAtPoint(position) if let name = touchedNode.name { switch name { case "resume": removeFromParent() delegate?.pauseMenuDismissed() case "leave": delegate?.leaveGameSelected() default: break } } } private func initBackground() { let mainScreenBounds = UIScreen.mainScreen().bounds overlayNode = SKShapeNode(rect: mainScreenBounds) overlayNode.fillColor = SKColor.whiteColor() overlayNode.alpha = 0.85 overlayNode.position = CGPoint(x: -CGRectGetMidX(mainScreenBounds), y: -CGRectGetMidY(mainScreenBounds)) overlayNode.zPosition = 998 overlayNode.userInteractionEnabled = false addChild(overlayNode) } private func initResumeNode() { resumeNode.fontName = "Baron Neue Bold 60" resumeNode.fontColor = blue resumeNode.fontSize = 40 resumeNode.name = "resume" resumeNode.position = CGPoint(x: 0, y: resumeNode.frame.height) resumeNode.zPosition = 999 resumeNode.userInteractionEnabled = false addChild(resumeNode) } private func initLeaveNode() { leaveNode.fontName = "Baron Neue Bold 60" leaveNode.fontColor = blue leaveNode.fontSize = 40 leaveNode.name = "leave" leaveNode.position = CGPoint(x: 0, y: -leaveNode.frame.height) leaveNode.zPosition = 999 leaveNode.userInteractionEnabled = false addChild(leaveNode) } }
mit
d0cd7b8c5474930c7012d4a0dc48908a
29.876404
82
0.610848
4.760832
false
false
false
false
rherndon47/TIYAssignments
Swift playground folder/Protocols.playground/section-1.swift
1
1174
import Foundation @objc protocol Speaker { func Speak() optional func TellJoke() } class Sterling: Speaker { func Speak() { println("Danger Zone!") } func TellJoke() { println("It's like Meowshwitz in there") } } class Lana: Speaker { func Speak() { println("Watch It!") } } class Pam: Speaker { func Speak() { println("Bear Claws!") } } class Animal { } class Dog: Animal, Speaker { func Speak() { println("Boof") } } //var speaker:Speaker //speaker = Sterling() //speaker.Speak() //speaker.TellJoke!() //(speaker as Sterling).TellJoke() //speaker = Lana() //speaker.Speak() //speaker.TellJoke?() //speaker = Dog() //speaker.Speak() class DateSimulator { let a:Speaker let b:Speaker init(a:Speaker, b:Speaker) { self.a = a self.b = b } func simulate() { println("Off to dinner...") a.Speak() b.Speak() println("Walking back home") a.TellJoke?() b.TellJoke?() } } let sim = DateSimulator(a: Lana(), b:Sterling()) sim.simulate()
cc0-1.0
2718013ca21d5b7ed81720d5125e741c
11.103093
48
0.53322
3.383285
false
false
false
false
github/Quick
Quick/Hooks/SuiteHooks.swift
1
873
/** A container for closures to be executed before and after all examples. */ internal class SuiteHooks { internal var befores: [BeforeSuiteClosure] = [] internal var beforesAlreadyExecuted = false internal var afters: [AfterSuiteClosure] = [] internal var aftersAlreadyExecuted = false internal func appendBefore(closure: BeforeSuiteClosure) { befores.append(closure) } internal func appendAfter(closure: AfterSuiteClosure) { afters.append(closure) } internal func executeBefores() { assert(!beforesAlreadyExecuted) for before in befores { before() } beforesAlreadyExecuted = true } internal func executeAfters() { assert(!aftersAlreadyExecuted) for after in afters { after() } aftersAlreadyExecuted = true } }
apache-2.0
db82d1ff8e4f904a85557094c282ae81
24.676471
74
0.644903
4.960227
false
false
false
false
narner/AudioKit
Examples/iOS/SongProcessor/SongProcessor/View Controllers/iTunes Library Access/SongsViewController.swift
1
3174
// // SongsViewController.swift // SongProcessor // // Created by Aurelius Prochazka on 6/22/16. // Copyright © 2016 AudioKit. All rights reserved. // import AVFoundation import MediaPlayer import UIKit class SongsViewController: UITableViewController { var albumName: String! var artistName: String! var songsList = [MPMediaItem]() override func viewDidLoad() { super.viewDidLoad() let albumPredicate = MPMediaPropertyPredicate(value: albumName, forProperty: MPMediaItemPropertyAlbumTitle, comparisonType: .contains) let artistPredicate = MPMediaPropertyPredicate(value: artistName, forProperty: MPMediaItemPropertyArtist, comparisonType: .contains) let songsQuery = MPMediaQuery.songs() songsQuery.addFilterPredicate(albumPredicate) songsQuery.addFilterPredicate(artistPredicate) songsQuery.addFilterPredicate(MPMediaPropertyPredicate( value: NSNumber(value: false as Bool), forProperty: MPMediaItemPropertyIsCloudItem)) if let items = songsQuery.items { songsList = items tableView.reloadData() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return songsList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "SongCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) ?? UITableViewCell(style: .default, reuseIdentifier: cellIdentifier) let song: MPMediaItem = songsList[(indexPath as NSIndexPath).row] let songTitle = song.value(forProperty: MPMediaItemPropertyTitle) as? String ?? "" let minutes = (song.value(forProperty: MPMediaItemPropertyPlaybackDuration)! as AnyObject).floatValue / 60 let seconds = ((song.value( forProperty: MPMediaItemPropertyPlaybackDuration)! as AnyObject).floatValue).truncatingRemainder( dividingBy: 60) cell.textLabel?.text = songTitle cell.detailTextLabel?.text = String(format: "%.0f:%02.0f", minutes, seconds) return cell } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SongSegue" { if let indexPath = tableView.indexPathForSelectedRow { if let songVC = segue.destination as? SongViewController { songVC.song = songsList[(indexPath as NSIndexPath).row] songVC.title = songVC.song!.value(forProperty: MPMediaItemPropertyTitle) as? String } } } } }
mit
674a0d9bc97dc5dd88f4e18b6cccee80
34.651685
114
0.612669
5.666071
false
false
false
false
pvzig/SlackKit
SKCore/Sources/Team.swift
2
1992
// // Team.swift // // Copyright © 2017 Peter Zignego. 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. public struct Team { public let id: String? public var name: String? public var domain: String? public var emailDomain: String? public var messageEditWindowMinutes: Int? public var overStorageLimit: Bool? public var prefs: [String: Any]? public var plan: String? public var icon: TeamIcon? public init(team: [String: Any]?) { id = team?["id"] as? String name = team?["name"] as? String domain = team?["domain"] as? String emailDomain = team?["email_domain"] as? String messageEditWindowMinutes = team?["msg_edit_window_mins"] as? Int overStorageLimit = team?["over_storage_limit"] as? Bool prefs = team?["prefs"] as? [String: Any] plan = team?["plan"] as? String icon = TeamIcon(icon: team?["icon"] as? [String: Any]) } }
mit
a028fb6912392f7332ff7d5c1e3a6d8f
42.282609
80
0.699648
4.290948
false
false
false
false
macostea/SpotifyWrapper
SpotifyWrapper/ViewController.swift
1
3414
// // ViewController.swift // SpotifyWrapper // // Created by Mihai Costea on 10/04/15. // Copyright (c) 2015 Skobbler. All rights reserved. // import Cocoa import WebKit class ViewController: NSViewController { @IBOutlet weak var webView: WebView! var mediaKeyTap: SPMediaKeyTap? override func viewDidLoad() { super.viewDidLoad() let userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17" let url = "http://play.spotify.com" self.webView.preferences.javaScriptEnabled = true self.webView.preferences.javaScriptCanOpenWindowsAutomatically = true self.webView.customUserAgent = userAgent self.webView.mainFrameURL = url self.addMediaKeyesTap() } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } // MARK:- Private func playPause() { self.webView.stringByEvaluatingJavaScriptFromString("var iframe = document.getElementById('app-player');" + "var key = iframe.contentDocument.getElementById('play-pause');" + "key.click();" ) } func forward() { self.webView.stringByEvaluatingJavaScriptFromString("var iframe = document.getElementById('app-player');" + "var key = iframe.contentDocument.getElementById('next');" + "key.click();" ) } func back() { self.webView.stringByEvaluatingJavaScriptFromString("var iframe = document.getElementById('app-player');" + "var key = iframe.contentDocument.getElementById('previous');" + "key.click();" ) } // MARK:- SPMediaKeyTapDelegate override func mediaKeyTap(keyTap: SPMediaKeyTap!, receivedMediaKeyEvent event: NSEvent!) { let keyCode = ((event.data1 & 0xFFFF0000) >> 16); let keyFlags = (event.data1 & 0x0000FFFF); let keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA; let keyRepeat = (keyFlags & 0x1); if (keyState == true) { switch (keyCode) { case Int(NX_KEYTYPE_PLAY): // Play things println("Play pressed") self.playPause() case Int(NX_KEYTYPE_FAST): // Next println("Next pressed") self.forward() case Int(NX_KEYTYPE_REWIND): // Back println("Back pressed") self.back() default: // Other keyes println("Other key pressed") } } } // MARK:- Private func addMediaKeyesTap() { self.mediaKeyTap = SPMediaKeyTap(delegate: self) if (SPMediaKeyTap.usesGlobalMediaKeyTap()) { self.mediaKeyTap?.startWatchingMediaKeys() } else { println("Media key monitoring disabled") } } }
mit
01090a72b43045b4904b613397872656
29.756757
144
0.509666
5.027982
false
false
false
false
MarceloOscarJose/DynamicSkeleton
Example/DynamicSkeleton/Views/RowView.swift
1
2646
// // RowView.swift // DynamicSkeleton // // Created by Marcelo Oscar José on 7/31/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import DynamicSkeleton import PureLayout class RowView: UIView { let activityImage: UIView = { let view = UIView() view.backgroundColor = UIColor(red: 236 / 255, green: 236 / 255, blue: 236 / 255, alpha: 1) view.layer.cornerRadius = 25 view.layer.borderWidth = 0 return view }() let title: SkeletonElementView = { let view = SkeletonElementView() view.backgroundColor = UIColor(red: 236 / 255, green: 236 / 255, blue: 236 / 255, alpha: 1) return view }() let amount: SkeletonElementView = { let view = SkeletonElementView() view.backgroundColor = UIColor(red: 236 / 255, green: 236 / 255, blue: 236 / 255, alpha: 1) return view }() let date: SkeletonElementView = { let view = SkeletonElementView() view.backgroundColor = UIColor(red: 236 / 255, green: 236 / 255, blue: 236 / 255, alpha: 1) return view }() init() { super.init(frame: .zero) self.setupElements() self.setupConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupElements() { self.addSubview(activityImage) self.addSubview(title) self.addSubview(amount) self.addSubview(date) } func setupConstraints() { self.backgroundColor = UIColor.white self.autoSetDimension(.height, toSize: 74) activityImage.autoSetDimension(.height, toSize: 50) activityImage.autoSetDimension(.width, toSize: 50) activityImage.autoPinEdge(.top, to: .top, of: self, withOffset: 12) activityImage.autoPinEdge(.left, to: .left, of: self, withOffset: 16) title.autoSetDimension(.height, toSize: 10) title.autoPinEdge(.left, to: .right, of: activityImage, withOffset: 14) title.autoPinEdge(.top, to: .top, of: self, withOffset: 24) title.autoSetDimension(.width, toSize: 150) amount.autoSetDimension(.height, toSize: 10) amount.autoSetDimension(.width, toSize: 60) amount.autoPinEdge(.top, to: .top, of: self, withOffset: 24) amount.autoPinEdge(.right, to: .right, of: self, withOffset: -16) date.autoSetDimension(.height, toSize: 10) date.autoSetDimension(.width, toSize: 40) date.autoPinEdge(.top, to: .bottom, of: amount, withOffset: 10) date.autoPinEdge(.right, to: .right, of: self, withOffset: -16) } }
mit
417e5afd9c3a6f8ec6915b4425912ec2
32.05
99
0.628215
4.10559
false
false
false
false
stevethemaker/WoodpeckerPole-ControlPanel-iOS
PoleControlPanel/RobotControllerModel.swift
1
8131
// // RobotControllerModel.swift // PoleControlPanel // // Created by Steven Knodl on 4/12/17. // Copyright © 2017 Steve Knodl. All rights reserved. // import Foundation import CoreBluetooth let robotDisconnectedNotification = Notification.Name("robot.bluetooth.disconnected") let robotConnectedNotification = Notification.Name("robot.bluetooth.connected") enum RobotControllerError : Error { case nonConnected } typealias FindDevicesClosure = (Result<[CBPeripheral]>) -> () typealias ConnectDeviceClosure = (Result<CBPeripheral>) -> () typealias DisconnectDeviceClosure = (Result<UUID>) -> () class RobotControllerModel { let robotServiceIdentifer = RobotDevice.ControlService.identifier static let shared = RobotControllerModel() let centralManager = CentralManagerWrapper.shared var connectedPeripheral: CBPeripheral? = nil var connectedPeripheralManager: RobotPeripheralManager? = nil init() { NotificationCenter.default.addObserver(self, selector: #selector(RobotControllerModel.centralManagerNotificationReceived), name: centralManagerNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func centralManagerNotificationReceived(notification: Notification) { if let userInfo = notification.userInfo, let centralNotification = userInfo["type"] as? CentralNotification { switch centralNotification { case .peripherialDisconnect(let peripheral): if peripheral == self.connectedPeripheral { self.connectedPeripheral = nil NotificationCenter.default.post(name: robotDisconnectedNotification, object: nil) } case .stateChange(_): break } } } //MARK: - Selection/Connection func scanForRobots(completion: @escaping FindDevicesClosure) { centralManager.scanForPeripherals(withServices: [robotServiceIdentifer]) { result in completion(result) } } func connect(toPeripheral peripheral: CBPeripheral, completion: @escaping ConnectDeviceClosure) { centralManager.connect(toPeripheral: peripheral) { result in switch result { case .success(let peripheral): self.connectedPeripheral = peripheral self.connectedPeripheralManager = RobotPeripheralManager(peripheral: peripheral) NotificationCenter.default.post(name: robotConnectedNotification, object: nil) case .failure: break } completion(result) } } func disconnect(fromPeripheral peripheral: CBPeripheral, completion: @escaping DisconnectDeviceClosure) { centralManager.disconnect(peripheral: peripheral) { result in switch result { case .success(_): self.connectedPeripheral = nil completion(Result.success(peripheral.identifier)) case .failure(let error): completion(Result.failure(error)) } } } //MARK: - Get (read) commands func getBatteryVoltage(completion: @escaping ((Result<Battery>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.batteryVoltage, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<Battery> in return Result { try Battery(rawData: rawData) } }) )} )} func getRobotPosition(completion: @escaping ((Result<RobotPosition>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.robotPosition, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<RobotPosition> in return Result { try RobotPosition(rawData: rawData) } }) )} )} func getLatchPosition(completion: @escaping ((Result<ServoPosition>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.latchPosition, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<ServoPosition> in return Result { try ServoPosition(rawData: rawData) } }) )} )} func getLauncherPosition(completion: @escaping ((Result<ServoPosition>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.launcherPosition, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<ServoPosition> in return Result { try ServoPosition(rawData: rawData) } }) )} )} func getMotorControlSetting(completion: @escaping ((Result<MotorControl>) -> ())) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readCharacteristicValue(forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.motorControl, completion: { result in completion(result.flatMap({ (rawData:Data) -> Result<MotorControl> in return Result { try MotorControl(rawData: rawData) } }) )} )} //MARK: - Set (Write) commands func setMotorControlSetting(data: Data, confirmWrite: Bool, completion: @escaping WriteOperationClosure) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.writeCharacteristicValue(data: data, confirmWrite: confirmWrite, forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.motorControl, completion: { result in completion(result) }) } func setLatchPosition(data: Data, confirmWrite: Bool, completion: @escaping WriteOperationClosure) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.writeCharacteristicValue(data: data, confirmWrite: confirmWrite, forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.latchPosition, completion: { result in completion(result) }) } func setLauncherPosition(data: Data, confirmWrite: Bool, completion: @escaping WriteOperationClosure) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.writeCharacteristicValue(data: data, confirmWrite: confirmWrite, forIdentifier: RobotDevice.ControlService.CharacteristicIdentifiers.launcherPosition, completion: { result in completion(result) }) } func readRSSIValue(completion: @escaping (Result<Data>) -> ()) { guard let connectedPeripheralManager = connectedPeripheralManager else { completion(Result.failure(RobotControllerError.nonConnected)); return } connectedPeripheralManager.readRSSIValue(completion: { result in completion(result) }) } }
mit
1009a1309d453fa6b843cf4b79230328
47.106509
209
0.702706
5.423616
false
false
false
false
gb-6k-house/YsSwift
Sources/Peacock/Extenstion/UIImage+Extension.swift
1
3002
/****************************************************************************** ** auth: liukai ** date: 2017/7 ** ver : 1.0 ** desc: 说明 ** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved ******************************************************************************/ import UIKit extension UIImage { /// iOS截图,使用WKWebView截图会有问题 /// /// - Parameter view: 显示图片View /// - Returns: 截取图片 open static func screenShot(_ view: UIView) -> UIImage? { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } view.layer.render(in: context) let capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return capturedImage } /// 截取图片到指定大小 open static func removeImageBorder(_ image: UIImage) -> UIImage? { let rectWidth = (image.size.width - 2) * image.scale let rectHeight = (image.size.height - 8) * image.scale guard let imageRef = image.cgImage?.cropping(to: CGRect(x: 1 * image.scale, y: 1 * image.scale, width: rectWidth, height: rectHeight)) else { return nil } let newImage = UIImage(cgImage: imageRef) return newImage } // 压缩图片到指定尺寸 open class func resizeImage(image: UIImage, size: CGSize) -> UIImage { // 图片尺寸 1:2 let imageScale: CGFloat = image.size.width / image.size.height let scaleHeight: CGFloat = size.height let scaleWidth = scaleHeight * imageScale // 指定图片高度,宽度按照图片的比例缩放,不然图片会变形 // 图片高度大于指定高度才压缩 guard image.size.height > scaleHeight else { return image } UIGraphicsBeginImageContext(CGSize(width: scaleWidth, height: scaleHeight)) image.draw(in: CGRect(x: 0, y: 0, width: scaleWidth, height: scaleHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // 获取失败,返回原图 guard let myNewImage = newImage else { return image } return myNewImage } /// 压缩图片到指定大小,如100K /// /// - Parameters: /// - img: 原始图片 /// - length: 压缩到指定大小 /// - Returns: 返回的data open class func compressImageDataLength(img: UIImage, length: Int) -> Data? { var data: Data var dep: CGFloat = 1.0 repeat { guard let mydata = UIImageJPEGRepresentation(img, dep) else { return nil } data = mydata dep = dep - 0.1 } while(dep > 0 && data.count >= length) return data } }
mit
9dbbe23c6182181c1498d7ccd0f94f76
31.05814
149
0.557127
4.641414
false
false
false
false
rokridi/GiphyHub
GiphyHub/Source/GiphyHub.swift
1
6963
// // GiphyHub.swift // GiphyHub // // Created by Mohamed Aymen Landolsi on 26/07/2017. // Copyright © 2017 Roridi. All rights reserved. // import Foundation import Alamofire import ObjectMapper import AlamofireObjectMapper public class GiphyHub { let apiKey: String private let sessionManager: SessionManager private var timeout = 10 init(apiKey: String, sessionConfiguration: URLSessionConfiguration, timeout:Int = 10) { sessionManager = Alamofire.SessionManager(configuration: sessionConfiguration) self.apiKey = apiKey self.timeout = timeout } convenience init(apiKey key: String) { self.init(apiKey: key, sessionConfiguration: URLSessionConfiguration.default) } //MARK: GIF func searchGifs(query: String, limit: UInt?, offset:UInt?, rating:Gif.GifRating?, language: String?, queue: DispatchQueue?, completionHandler: @escaping ([Gif]?, GifPagination?, Error?) -> Void) -> DataRequest { let urlRequest = GifsRouter.search(query: query, limit: limit, offset: offset, rating: rating, language: language, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifsResponse completionHandler(response?.gifs, response?.pagination, error) }) } func trendingGifs(limit: UInt?, offset:UInt?, rating:Gif.GifRating?, language: String?, queue: DispatchQueue?, completionHandler: @escaping ([Gif]?, GifPagination?, Error?) -> Void) -> DataRequest { let urlRequest = GifsRouter.trending(limit: limit, rating: rating, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifsResponse completionHandler(response?.gifs, response?.pagination, error) }) } func translateGif(_ term: String, queue: DispatchQueue?, completionHandler: @escaping (Gif?, Error?) -> Void) -> DataRequest { let urlRequest = GifsRouter.translate(term, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifResponse completionHandler(response?.gif, error) }) } func randomGif(_ tag: String?, rating:Gif.GifRating?, queue: DispatchQueue?, completionHandler: @escaping (Gif?, Error?) -> Void) -> DataRequest { let urlRequest = GifsRouter.random(tag: tag, rating: rating, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifResponse completionHandler(response?.gif, error) }) } func gifs(identifiers: [String], offset:UInt?, rating:Gif.GifRating?, language: String?, queue: DispatchQueue?, completionHandler: @escaping ([Gif]?, GifPagination?, Error?) -> Void) -> DataRequest { let urlRequest = GifsRouter.gifs(identifiers: identifiers, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifsResponse completionHandler(response?.gifs, response?.pagination, error) }) } func gif(identifier: String, language: String?, queue: DispatchQueue?, completionHandler: @escaping (Gif?, Error?) -> Void) -> DataRequest { let urlRequest = GifsRouter.gif(identifier: identifier, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifResponse completionHandler(response?.gif, error) }) } //MARK: Stickers func searchStickers(query: String, limit: UInt?, offset:UInt?, rating:Gif.GifRating?, language: String?, queue: DispatchQueue?, completionHandler: @escaping ([Gif]?, GifPagination?, Error?) -> Void) -> DataRequest { let urlRequest = StickersRouter.search(query: query, limit: limit, offset: offset, rating: rating, language: language, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifsResponse completionHandler(response?.gifs, response?.pagination, error) }) } func trendingStickers(limit: UInt?, offset:UInt?, rating:Gif.GifRating?, language: String?, queue: DispatchQueue?, completionHandler: @escaping ([Gif]?, GifPagination?, Error?) -> Void) -> DataRequest { let urlRequest = StickersRouter.trending(limit: limit, rating: rating, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifsResponse completionHandler(response?.gifs, response?.pagination, error) }) } func translateSticker(_ term: String, queue: DispatchQueue?, completionHandler: @escaping (Gif?, Error?) -> Void) -> DataRequest { let urlRequest = StickersRouter.translate(term, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifResponse completionHandler(response?.gif, error) }) } func randomSticker(_ tag: String?, rating:Gif.GifRating?, queue: DispatchQueue?, completionHandler: @escaping (Gif?, Error?) -> Void) -> DataRequest { let urlRequest = StickersRouter.random(tag: tag, rating: rating, apiKey: apiKey) return self.launchRequest(urlRequest, queue: queue, completionHandler: { (response, error) in let response = response as? GifResponse completionHandler(response?.gif, error) }) } //MARK: Private private func launchRequest(_ urlRequest: URLRequestConvertible, queue: DispatchQueue?, completionHandler: @escaping (GiphyResponse?, Error?) -> Void) -> DataRequest { return sessionManager.request(urlRequest).validate().responseObject(queue: queue, keyPath: nil, mapToObject: nil, context: nil, completionHandler: { (response:DataResponse<GiphyResponse>) in let gifResponse = response.result.value (queue ?? DispatchQueue.main).async { completionHandler(gifResponse, response.error) } }) } }
mit
3f9f1967c58a3745cd17f3bb9b83c87c
40.939759
219
0.631428
5.100366
false
false
false
false
ngageoint/mage-ios
Mage/MageSideBarController.swift
1
9787
// // MageTabBarController.m // MAGE // // import Foundation import Kingfisher import PureLayout class SidebarUIButton: UIButton { public enum SidebarType: String { case observations, locations, feed } var feed: Feed? var sidebarType: SidebarType? var viewController: UIViewController? var title: String? } @objc class MageSideBarController : UIViewController { var activeButton: SidebarUIButton?; var scheme: MDCContainerScheming?; typealias Delegate = AttachmentSelectionDelegate & ObservationSelectionDelegate & UserActionsDelegate & UserSelectionDelegate & FeedItemSelectionDelegate & ObservationActionsDelegate weak public var delegate: Delegate?; private lazy var railScroll : UIScrollView = { let scroll : UIScrollView = UIScrollView(forAutoLayout: ()); scroll.addSubview(navigationRail); navigationRail.autoPinEdge(toSuperviewEdge: .left); navigationRail.autoPinEdge(toSuperviewEdge: .right); return scroll; }() private lazy var border : UIView = { let border : UIView = UIView(forAutoLayout: ()); border.autoSetDimension(.width, toSize: 1.0); border.backgroundColor = UIColor(white: 0.0, alpha: 0.2); return border; }() private lazy var dataContainer : UIView = { let container : UIView = UIView(forAutoLayout: ()); return container; }() private lazy var navigationRail : UIStackView = { let rail : UIStackView = UIStackView(forAutoLayout: ()); rail.axis = .vertical rail.alignment = .fill rail.spacing = 0 rail.distribution = .fill rail.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0) rail.isLayoutMarginsRelativeArrangement = true; rail.translatesAutoresizingMaskIntoConstraints = false; return rail; }() func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) { guard let containerScheme = containerScheme else { return } self.scheme = containerScheme; navigationRail.backgroundColor = containerScheme.colorScheme.surfaceColor; view.backgroundColor = containerScheme.colorScheme.backgroundColor; railScroll.backgroundColor = containerScheme.colorScheme.surfaceColor; } init(frame: CGRect) { super.init(nibName: nil, bundle: nil); } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } @objc convenience public init(containerScheme: MDCContainerScheming) { self.init(frame: CGRect.zero); self.scheme = containerScheme; } override func viewDidLoad() { super.viewDidLoad(); view.addSubview(railScroll); railScroll.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), excludingEdge: .right); railScroll.layoutMargins = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0); railScroll.autoSetDimension(.height, toSize: view.frame.size.height); railScroll.autoSetDimension(.width, toSize: 56); railScroll.contentSize = navigationRail.frame.size; railScroll.autoresizingMask = UIView.AutoresizingMask.flexibleHeight; view.addSubview(border); border.autoPinEdge(.leading, to: .trailing, of: railScroll); border.autoPinEdge(.top, to: .top, of: railScroll); border.autoMatch(.height, to: .height, of: railScroll); view.addSubview(dataContainer); dataContainer.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), excludingEdge: .left); dataContainer.autoPinEdge(.left, to: .right, of: border); createRailItems(); applyTheme(withContainerScheme: self.scheme); } func activateSidebarDataController(viewController: UIViewController?, title: String?) { guard let controller = viewController else { return; } self.title = title; addChild(controller) controller.view.translatesAutoresizingMaskIntoConstraints = false if (dataContainer.subviews.count != 0) { dataContainer.subviews[0].removeFromSuperview(); } dataContainer.addSubview(controller.view) controller.view.autoPinEdgesToSuperviewEdges(); controller.didMove(toParent: self) } func createRailItem(sidebarType: SidebarUIButton.SidebarType, title: String?, iconUrl: URL? = nil, imageName: String? = nil, systemImageName: String? = nil) -> SidebarUIButton { let size = 24; let button : SidebarUIButton = SidebarUIButton(forAutoLayout: ()); button.autoSetDimensions(to: CGSize(width: 56, height: 56)); button.tintColor = self.scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.6); button.sidebarType = sidebarType; button.title = title; if let iconUrl: URL = iconUrl { let processor = DownsamplingImageProcessor(size: CGSize(width: size, height: size)); button.kf.setImage( with: iconUrl, for: .normal, placeholder: UIImage(named: "rss"), options: [ .processor(processor), .scaleFactor(UIScreen.main.scale), .transition(.fade(1)), .cacheOriginalImage ], completionHandler: { result in switch result { case .success(let value): var image: UIImage = value.image.aspectResize(to: CGSize(width: size, height: size)); image = image.withRenderingMode(.alwaysTemplate); button.setImage(image, for: .normal) case .failure(let error): print(error); } }) } else if let imageName: String = imageName { button.setImage(UIImage(named: imageName), for: .normal); } else if let systemImageName = systemImageName { button.setImage(UIImage(systemName: systemImageName), for: .normal) } return button; } func createRailItems() { let observationButton: SidebarUIButton = createObservationsRailView(); let locationButton: SidebarUIButton = createLocationsRailView(); var allRailItems: [SidebarUIButton] = [observationButton, locationButton]; for feed in Feed.mr_findAll()! as! [Feed] { let feedButton: SidebarUIButton = createFeedRailView(feed: feed); feedButton.feed = feed; allRailItems.append(feedButton); } for view in allRailItems { navigationRail.addArrangedSubview(view); } activateButton(button: allRailItems[0]) } func createLocationsRailView() -> SidebarUIButton { let locationButton: SidebarUIButton = createRailItem(sidebarType: SidebarUIButton.SidebarType.locations, title: "People", systemImageName: "person.2.fill"); locationButton.addTarget(self, action: #selector(activateButton(button:)), for: .touchUpInside); let locationViewController : LocationsTableViewController = LocationsTableViewController(scheme: self.scheme); // locationViewController.actionsDelegate = delegate; locationButton.viewController = locationViewController; return locationButton; } func createObservationsRailView() -> SidebarUIButton { let observationButton: SidebarUIButton = createRailItem(sidebarType: SidebarUIButton.SidebarType.observations, title: "Observations", imageName: "observations"); observationButton.addTarget(self, action: #selector(activateButton(button:)), for: .touchUpInside); // let observationViewController : ObservationTableViewController = ObservationTableViewController(attachmentDelegate: delegate, observationActionsDelegate: delegate, scheme: self.scheme); let observationViewController : ObservationTableViewController = ObservationTableViewController(scheme: self.scheme); observationButton.viewController = observationViewController; return observationButton; } func createFeedRailView(feed: Feed) -> SidebarUIButton { let feedButton: SidebarUIButton = createRailItem(sidebarType: SidebarUIButton.SidebarType.feed, title: feed.title, iconUrl: feed.iconURL, imageName: "rss"); feedButton.feed = feed; feedButton.addTarget(self, action: #selector(activateButton(button:)), for: .touchUpInside); let feedItemsViewController: FeedItemsViewController = FeedItemsViewController(feed: feed, selectionDelegate: delegate, scheme: self.scheme); feedButton.viewController = feedItemsViewController; return feedButton; } @objc func activateButton(button: SidebarUIButton) { if let activeButton = activeButton { activeButton.tintColor = self.scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.6); } button.tintColor = self.scheme?.colorScheme.onSurfaceColor; activeButton = button; activateSidebarDataController(viewController: button.viewController, title: button.title); } @objc func observationButtonTapped(sender: SidebarUIButton) { activateButton(button: sender); } @objc func locationButtonTapped(sender: SidebarUIButton) { activateButton(button: sender); } @objc func feedButtonTapped(sender: SidebarUIButton) { activateButton(button: sender); } }
apache-2.0
e0d2b89b53d42b673c042136fd24970d
41.367965
195
0.661592
5.256176
false
false
false
false
EstebanVallejo/EVDevelopmentKit
EVDevelopmentKit/Classes/Extensions/UIViewControllers+Extensions.swift
1
1164
import UIKit public extension UIViewController { public var isFirstInStack : Bool { get { guard let indexInStack = indexInNavigationStack else { return false } return indexInStack == 0 } } public var isPresented : Bool { get { return presentingViewController != nil } } public func backViewController() { let _ = navigationController?.popViewController(animated: true) } public func backToRootViewController() { let _ = navigationController?.popToRootViewController(animated: true) } public func dismissViewController() { navigationController?.dismiss(animated: true, completion: nil) } public func removeBackButtonText() { navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) } } public extension UIViewController { public func hasNavigationController() -> Bool { return navigationController != nil } vpublic ar indexInNavigationStack: Int? { guard hasNavigationController() else { return nil } return navigationController!.viewControllers.index(of: self) } }
mit
80d331aa96c5cf48e9d6ce937fb68575
21.823529
107
0.683849
5.082969
false
false
false
false
nibty/skate-retro-tvos
RetroSkate/Movable.swift
1
1007
// // Movable.swift // Game // // Created by Nicholas Pettas on 11/10/15. // Copyright © 2015 Nicholas Pettas. All rights reserved. // import SpriteKit class Movable: SKSpriteNode { var resetPosition:CGFloat = -900 var startPosition:CGFloat = 1800 var movingSpeed = GameManager.sharedInstance.movingSpeed var moveAction: SKAction! var moveForeverAction: SKAction! var yPos:CGFloat = 0 func startMoving() { self.position = CGPointMake(startPosition, yPos) moveAction = SKAction.moveByX(movingSpeed, y: 0, duration: 0.02) moveForeverAction = SKAction.repeatActionForever(moveAction) self.runAction(moveForeverAction) } override func update() { if self.position.x <= self.resetPosition { didExceedBounds() } } func didExceedBounds() { self.position = CGPointMake(self.startPosition, self.position.y) GameManager.sharedInstance.levelLoop++ } }
mit
aa2a70063b5ab87a0d16dcffcd79ac61
24.820513
72
0.652087
4.412281
false
false
false
false
snakajima/vs-metal
vs-metal/vs-metal/SampleViewController2.swift
1
1769
// // SampleViewController2.swift // vs-metal // // Created by SATOSHI NAKAJIMA on 6/20/17. // Copyright © 2017 SATOSHI NAKAJIMA. All rights reserved. // import UIKit import MetalKit class SampleViewController2: UIViewController { @IBOutlet var mtkView:MTKView! let context = VSContext(device: MTLCreateSystemDefaultDevice()!) var runtime:VSRuntime? lazy var session:VSCaptureSession = VSCaptureSession(device: self.context.device, pixelFormat: self.context.pixelFormat, delegate: self.context) lazy var renderer:VSRenderer = VSRenderer(device:self.context.device, pixelFormat:self.context.pixelFormat) override func viewDidLoad() { super.viewDidLoad() mtkView.device = context.device mtkView.delegate = self context.pixelFormat = mtkView.colorPixelFormat // This is an alternative way to create a script object (Beta) let script = VSScript() .gaussian_blur(sigma: 2.0) .fork() .gaussian_blur(sigma: 2.0) .toone() .swap() .sobel() .canny_edge(threshhold: 0.19, thin: 0.5) .anti_alias() .alpha(ratio: 1.0) runtime = script.compile(context: context) session.start() } } extension SampleViewController2 : MTKViewDelegate { public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} public func draw(in view: MTKView) { if context.hasUpdate { runtime?.encode(commandBuffer:context.makeCommandBuffer(), context:context).commit() renderer.encode(commandBuffer:context.makeCommandBuffer(), view:view, texture: context.pop()?.texture)?.commit() context.flush() } } }
mit
99d3e0acd7e339a6fd7ca44335a1f497
30.571429
148
0.64819
4.150235
false
false
false
false
evanhughes3/reddit-news-swift
reddit-news-swift/Domain/Models/NetworkResponse.swift
1
431
import Foundation enum NetworkResponse : Equatable { case Success(Data) case Error(NetworkError) static func ==(lhs: NetworkResponse, rhs: NetworkResponse) -> Bool { switch (lhs, rhs) { case (let .Success(lhsData), let .Success(rhsData)): return lhsData == rhsData case (let .Error(lhsError), let .Error(rhsError)): return lhsError == rhsError default: return false } } }
mit
318de563aa998ad1fef066c7456edba4
24.411765
70
0.640371
4.144231
false
false
false
false
rjstelling/HTTPFormRequest
Projects/HTTPFormEncoder/HTTPFormEncoder/HTTPFormSingleValueEncodingContainer.swift
1
3360
// // HTTPFormSingleValueEncodingContainer.swift // HTTPFormEncoder // // Created by Richard Stelling on 18/07/2018. // Copyright © 2018 Lionheart Applications Ltd. All rights reserved. // import Foundation struct HTTPFormSingleValueEncodingContainer: SingleValueEncodingContainer { var codingPath: [CodingKey] let encoder: HTTPFormEncoder let containerName: String internal init(referencing encoder: HTTPFormEncoder, codingPath: [CodingKey], name: String) { self.encoder = encoder self.codingPath = codingPath self.containerName = name } mutating func encodeNil() throws { print("nil… skipping!)") } mutating func encode(_ value: Bool) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: String) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Double) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Float) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int8) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int16) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int32) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int64) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt8) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt16) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt32) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt64) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode<T>(_ value: T) throws where T : Encodable { //self.encoder.parameters[self.containerName] = try encoder.box( value ) //print("VLAUE: \(value)") //fatalError("NOT IMP") self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) //self.encoder.parameters[self.containerName] = try encoder.box_( value ) } }
mit
4c284142b33814fc6c00b5a919fbefd2
26.743802
96
0.617814
4.331613
false
false
false
false
toshiapp/toshi-ios-client
Toshi/Controllers/Chats/NewChatViewController.swift
1
8227
// Copyright (c) 2018 Token Browser, Inc // // 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 UIKit final class NewChatViewController: UIViewController { enum NewChatItem { case startGroup case inviteFriend var title: String { switch self { case .startGroup: return Localized.start_a_new_group case .inviteFriend: return Localized.recent_invite_a_friend } } var icon: UIImage { switch self { case .startGroup: return ImageAsset.group_icon case .inviteFriend: return ImageAsset.invite_friend } } } var scrollViewBottomInset: CGFloat = 0.0 var scrollView: UIScrollView { return searchTableView } private let defaultTableViewBottomInset: CGFloat = -21 private let newChatItems: [NewChatItem] = [.startGroup, .inviteFriend] private var dataSource: SearchProfilesDataSource? private lazy var tableView: UITableView = { let view = UITableView(frame: CGRect.zero, style: .plain) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.viewBackgroundColor BasicTableViewCell.register(in: view) view.delegate = self view.dataSource = self view.sectionFooterHeight = 0.0 view.contentInset.bottom = defaultTableViewBottomInset view.scrollIndicatorInsets.bottom = defaultTableViewBottomInset view.estimatedRowHeight = 98 view.alwaysBounceVertical = true view.separatorStyle = .none BasicTableViewCell.register(in: view) return view }() private lazy var searchHeaderView: PushedSearchHeaderView = { let view = PushedSearchHeaderView() view.searchPlaceholder = Localized.search_for_name_or_username view.rightButtonTitle = Localized.cancel_action_title view.delegate = self return view }() private lazy var searchTableView: SearchProfilesTableView = { let searchTableView = SearchProfilesTableView() searchTableView.profileTypeSelectionDelegate = self searchTableView.isHidden = true return searchTableView }() override func viewDidLoad() { super.viewDidLoad() registerForKeyboardNotifications() dataSource = SearchProfilesDataSource(tableView: searchTableView) dataSource?.delegate = self addSubviewsAndConstraints() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) preferLargeTitleIfPossible(false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } private func addSubviewsAndConstraints() { view.addSubview(tableView) view.addSubview(searchHeaderView) view.addSubview(searchTableView) edgesForExtendedLayout = [] automaticallyAdjustsScrollViewInsets = false definesPresentationContext = true searchHeaderView.top(to: view) searchHeaderView.left(to: layoutGuide()) searchHeaderView.right(to: layoutGuide()) searchHeaderView.bottomAnchor.constraint(equalTo: layoutGuide().topAnchor, constant: PushedSearchHeaderView.headerHeight).isActive = true tableView.topToBottom(of: searchHeaderView) tableView.left(to: view) tableView.right(to: view) tableView.bottom(to: layoutGuide()) searchTableView.edges(to: tableView) } } extension NewChatViewController: ProfileTypeSelectionDelegate { func searchProfilesTableViewDidChangeProfileType(_ tableView: SearchProfilesTableView) { dataSource?.search(type: searchTableView.selectedProfileType.typeString, text: searchHeaderView.searchTextField.text, searchDelay: SearchProfilesDataSource.defaultSearchRequestDelay) } } extension NewChatViewController: PushedSearchHeaderDelegate { func searchHeaderViewDidUpdateSearchText(_ headerView: PushedSearchHeaderView, _ searchText: String) { dataSource?.search(type: searchTableView.selectedProfileType.typeString, text: searchHeaderView.searchTextField.text) } func searchHeaderWillBeginEditing(_ headerView: PushedSearchHeaderView) { searchTableView.isHidden = false } func searchHeaderWillEndEditing(_ headerView: PushedSearchHeaderView) { searchTableView.isHidden = true } func searchHeaderDidReceiveRightButtonEvent(_ headerView: PushedSearchHeaderView) { // TODO: Cancel might be used later when search is being implemented, otherwise will be removed } func searchHeaderViewDidReceiveBackEvent(_ headerView: PushedSearchHeaderView) { navigationController?.popViewController(animated: true) } } extension NewChatViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newChatItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard indexPath.row < newChatItems.count else { return UITableViewCell() } let item = newChatItems[indexPath.row] let cellData = TableCellData(title: item.title, leftImage: item.icon) let configurator = CellConfigurator() guard let cell = tableView.dequeueReusableCell(withIdentifier: configurator.cellIdentifier(for: cellData.components), for: indexPath) as? BasicTableViewCell else { return UITableViewCell() } configurator.configureCell(cell, with: cellData) cell.titleTextField.textColor = Theme.tintColor switch item { case .startGroup: cell.showSeparator(leftInset: 80) case .inviteFriend: cell.showSeparator() } return cell } } extension NewChatViewController: ProfilesDataSourceDelegate { func didSelectProfile(_ profile: Profile) { let profileController = ProfileViewController(profile: profile) navigationController?.pushViewController(profileController, animated: true) } } // MARK: - Mix-in extensions extension NewChatViewController: SystemSharing { /* mix-in */ } extension NewChatViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.row < newChatItems.count else { return } let item = newChatItems[indexPath.row] switch item { case .inviteFriend: shareWithSystemSheet(item: Localized.sharing_action_item) case .startGroup: let groupChatSelection = ProfilesViewController(type: .newGroupChat) navigationController?.pushViewController(groupChatSelection, animated: true) } } } // MARK: - Keyboard Adjustable extension NewChatViewController: KeyboardAdjustable { var keyboardWillShowSelector: Selector { return #selector(keyboardShownNotificationReceived(_:)) } var keyboardWillHideSelector: Selector { return #selector(keyboardHiddenNotificationReceived(_:)) } @objc private func keyboardShownNotificationReceived(_ notification: NSNotification) { keyboardWillShow(notification) } @objc private func keyboardHiddenNotificationReceived(_ notification: NSNotification) { keyboardWillHide(notification) } }
gpl-3.0
d436fba4a83e94690f84cb86dba1cb5d
33.279167
198
0.706819
5.373612
false
false
false
false
huonw/swift
stdlib/public/SDK/Foundation/TimeZone.swift
19
12564
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims /** `TimeZone` defines the behavior of a time zone. Time zone values represent geopolitical regions. Consequently, these values have names for these regions. Time zone values also represent a temporal offset, either plus or minus, from Greenwich Mean Time (GMT) and an abbreviation (such as PST for Pacific Standard Time). `TimeZone` provides two static functions to get time zone values: `current` and `autoupdatingCurrent`. The `autoupdatingCurrent` time zone automatically tracks updates made by the user. Note that time zone database entries such as "America/Los_Angeles" are IDs, not names. An example of a time zone name is "Pacific Daylight Time". Although many `TimeZone` functions include the word "name", they refer to IDs. Cocoa does not provide any API to change the time zone of the computer, or of other applications. */ public struct TimeZone : Hashable, Equatable, ReferenceConvertible { public typealias ReferenceType = NSTimeZone fileprivate var _wrapped : NSTimeZone private var _autoupdating : Bool /// The time zone currently used by the system. public static var current : TimeZone { return TimeZone(adoptingReference: __NSTimeZoneCurrent() as! NSTimeZone, autoupdating: false) } /// The time zone currently used by the system, automatically updating to the user's current preference. /// /// If this time zone is mutated, then it no longer tracks the system time zone. /// /// The autoupdating time zone only compares equal to itself. public static var autoupdatingCurrent : TimeZone { return TimeZone(adoptingReference: __NSTimeZoneAutoupdating() as! NSTimeZone, autoupdating: true) } // MARK: - // /// Returns a time zone initialized with a given identifier. /// /// An example identifier is "America/Los_Angeles". /// /// If `identifier` is an unknown identifier, then returns `nil`. public init?(identifier: String) { if let r = NSTimeZone(name: identifier) { _wrapped = r _autoupdating = false } else { return nil } } @available(*, unavailable, renamed: "init(secondsFromGMT:)") public init(forSecondsFromGMT seconds: Int) { fatalError() } /// Returns a time zone initialized with a specific number of seconds from GMT. /// /// Time zones created with this never have daylight savings and the offset is constant no matter the date. The identifier and abbreviation do NOT follow the POSIX convention (of minutes-west). /// /// - parameter seconds: The number of seconds from GMT. /// - returns: A time zone, or `nil` if a valid time zone could not be created from `seconds`. public init?(secondsFromGMT seconds: Int) { if let r = NSTimeZone(forSecondsFromGMT: seconds) as NSTimeZone? { _wrapped = r _autoupdating = false } else { return nil } } /// Returns a time zone identified by a given abbreviation. /// /// In general, you are discouraged from using abbreviations except for unique instances such as "GMT". Time Zone abbreviations are not standardized and so a given abbreviation may have multiple meanings--for example, "EST" refers to Eastern Time in both the United States and Australia /// /// - parameter abbreviation: The abbreviation for the time zone. /// - returns: A time zone identified by abbreviation determined by resolving the abbreviation to an identifier using the abbreviation dictionary and then returning the time zone for that identifier. Returns `nil` if there is no match for abbreviation. public init?(abbreviation: String) { if let r = NSTimeZone(abbreviation: abbreviation) { _wrapped = r _autoupdating = false } else { return nil } } fileprivate init(reference: NSTimeZone) { if __NSTimeZoneIsAutoupdating(reference) { // we can't copy this or we lose its auto-ness (27048257) // fortunately it's immutable _autoupdating = true _wrapped = reference } else { _autoupdating = false _wrapped = reference.copy() as! NSTimeZone } } private init(adoptingReference reference: NSTimeZone, autoupdating: Bool) { // this path is only used for types we do not need to copy (we are adopting the ref) _wrapped = reference _autoupdating = autoupdating } // MARK: - // @available(*, unavailable, renamed: "identifier") public var name: String { fatalError() } /// The geopolitical region identifier that identifies the time zone. public var identifier: String { return _wrapped.name } @available(*, unavailable, message: "use the identifier instead") public var data: Data { fatalError() } /// The current difference in seconds between the time zone and Greenwich Mean Time. /// /// - parameter date: The date to use for the calculation. The default value is the current date. public func secondsFromGMT(for date: Date = Date()) -> Int { return _wrapped.secondsFromGMT(for: date) } /// Returns the abbreviation for the time zone at a given date. /// /// Note that the abbreviation may be different at different dates. For example, during daylight saving time the US/Eastern time zone has an abbreviation of "EDT." At other times, its abbreviation is "EST." /// - parameter date: The date to use for the calculation. The default value is the current date. public func abbreviation(for date: Date = Date()) -> String? { return _wrapped.abbreviation(for: date) } /// Returns a Boolean value that indicates whether the receiver uses daylight saving time at a given date. /// /// - parameter date: The date to use for the calculation. The default value is the current date. public func isDaylightSavingTime(for date: Date = Date()) -> Bool { return _wrapped.isDaylightSavingTime(for: date) } /// Returns the daylight saving time offset for a given date. /// /// - parameter date: The date to use for the calculation. The default value is the current date. public func daylightSavingTimeOffset(for date: Date = Date()) -> TimeInterval { return _wrapped.daylightSavingTimeOffset(for: date) } /// Returns the next daylight saving time transition after a given date. /// /// - parameter date: A date. /// - returns: The next daylight saving time transition after `date`. Depending on the time zone, this function may return a change of the time zone's offset from GMT. Returns `nil` if the time zone of the receiver does not observe daylight savings time as of `date`. public func nextDaylightSavingTimeTransition(after date: Date) -> Date? { return _wrapped.nextDaylightSavingTimeTransition(after: date) } /// Returns an array of strings listing the identifier of all the time zones known to the system. public static var knownTimeZoneIdentifiers : [String] { return NSTimeZone.knownTimeZoneNames } /// Returns the mapping of abbreviations to time zone identifiers. public static var abbreviationDictionary : [String : String] { get { return NSTimeZone.abbreviationDictionary } set { NSTimeZone.abbreviationDictionary = newValue } } /// Returns the time zone data version. public static var timeZoneDataVersion : String { return NSTimeZone.timeZoneDataVersion } /// Returns the date of the next (after the current instant) daylight saving time transition for the time zone. Depending on the time zone, the value of this property may represent a change of the time zone's offset from GMT. Returns `nil` if the time zone does not currently observe daylight saving time. public var nextDaylightSavingTimeTransition: Date? { return _wrapped.nextDaylightSavingTimeTransition } @available(*, unavailable, renamed: "localizedName(for:locale:)") public func localizedName(_ style: NSTimeZone.NameStyle, locale: Locale?) -> String? { fatalError() } /// Returns the name of the receiver localized for a given locale. public func localizedName(for style: NSTimeZone.NameStyle, locale: Locale?) -> String? { return _wrapped.localizedName(style, locale: locale) } // MARK: - public var hashValue : Int { if _autoupdating { return 1 } else { return _wrapped.hash } } public static func ==(lhs: TimeZone, rhs: TimeZone) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { return lhs._wrapped.isEqual(rhs._wrapped) } } } extension TimeZone : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { private var _kindDescription : String { if self == TimeZone.autoupdatingCurrent { return "autoupdatingCurrent" } else if self == TimeZone.current { return "current" } else { return "fixed" } } public var customMirror : Mirror { let c: [(label: String?, value: Any)] = [ ("identifier", identifier), ("kind", _kindDescription), ("abbreviation", abbreviation() as Any), ("secondsFromGMT", secondsFromGMT()), ("isDaylightSavingTime", isDaylightSavingTime()), ] return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } public var description: String { return "\(identifier) (\(_kindDescription))" } public var debugDescription : String { return "\(identifier) (\(_kindDescription))" } } extension TimeZone : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSTimeZone { // _wrapped is immutable return _wrapped } public static func _forceBridgeFromObjectiveC(_ input: NSTimeZone, result: inout TimeZone?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSTimeZone, result: inout TimeZone?) -> Bool { result = TimeZone(reference: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSTimeZone?) -> TimeZone { var result: TimeZone? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSTimeZone : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as TimeZone) } } extension TimeZone : Codable { private enum CodingKeys : Int, CodingKey { case identifier } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let identifier = try container.decode(String.self, forKey: .identifier) guard let timeZone = TimeZone(identifier: identifier) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Invalid TimeZone identifier.")) } self = timeZone } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.identifier, forKey: .identifier) } }
apache-2.0
bc582f3423ad1031867d03bc97e7f1f3
40.740864
319
0.655444
5.14918
false
false
false
false
7ulipa/VideoCache
VideoCache/Classes/CacheManager.swift
1
2928
// // CacheManager.swift // Pods // // Created by DirGoTii on 02/07/2017. // // import Foundation import ReactiveSwift public class CacheManager { public static let shared = CacheManager() init() { NotificationCenter.default.reactive.notifications(forName: .UIApplicationWillTerminate).observeValues { [weak self] (noti) in self?.deleteOldFiles() } NotificationCenter.default.reactive.notifications(forName: .UIApplicationDidEnterBackground).observeValues { [weak self] (noti) in self?.backgroundDeleteOldFiles() } } private func deleteOldFiles() { deleteOldFiles(with: nil) } private var backgroundTask: UIBackgroundTaskIdentifier! private func backgroundDeleteOldFiles() { func endBackgroundTask() { UIApplication.shared.endBackgroundTask(self.backgroundTask) backgroundTask = UIBackgroundTaskInvalid } backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "DeleteOldFiles", expirationHandler: { endBackgroundTask() }) deleteOldFiles { endBackgroundTask() } } private func deleteOldFiles(with complete: (() -> Void)?) { workQueue.async { do { try FileManager.default.contentsOfDirectory(atPath: VideoCacheSettings.kCachePath as String).forEach({ (dirname) in let dirPath = VideoCacheSettings.kCachePath.appendingPathComponent(dirname) if let record = CacheRecord(path: dirPath), record.isExpired() { try FileManager.default.removeItem(atPath: dirPath) } }) complete?() } catch { NSLog((error as NSError).localizedDescription) } } } public func startPlay(url: URL) { workQueue.async { self.cache(for: url.fakeTransform).playing.value = true } } public func stopPlay(url: URL) { workQueue.async { self.cache(for: url.fakeTransform).playing.value = false } } public func startPrefetch(url: URL) { workQueue.async { self.cache(for: url.fakeTransform).prefetching.value = true } } public func stopPrefetch(url: URL) { workQueue.async { self.cache(for: url.fakeTransform).prefetching.value = false } } let workQueue = DispatchQueue(label: "com.\(CacheManager.self).workQueue") let caches = Atomic<[URL: CacheRecord]>([:]) func cache(for URL: URL) -> CacheRecord { return caches.modify { if let result = $0[URL] { return result } let result = CacheRecord(url: URL) $0[URL] = result return result } } }
mit
0de7678885ea1e2487c033e4ed2280c5
29.185567
138
0.584358
5.013699
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/ToneGenerator/ConductorSoundType.swift
1
2092
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /// A tone generator sound type that plays a note only when the value change is above 5%. class ConductorSoundType: PitchedSoundType { /// The value percent change that will create a sound. let valuePercentChange = 0.05 /// The minimum value so far. var currentMinimumValue: Double = .greatestFiniteMagnitude /// The maximum value so far. var currentMaximumValue: Double = .leastNormalMagnitude init() { let name = String.conductor super.init(name: name) frequencyMin = 261.63 frequencyMax = 440.0 shouldAnimateToNextFrequency = false } override func frequency(from value: Double, valueMin: Double, valueMax: Double, timestamp: Int64) -> Double? { if value < currentMinimumValue { currentMinimumValue = value } if value > currentMaximumValue { currentMaximumValue = value } // If value < min + 5%, map to silence let valueThreshhold = currentMinimumValue + (currentMaximumValue - currentMinimumValue) * valuePercentChange guard value > valueThreshhold else { return nil } let numerator = floor(value - valueThreshhold) let denominator = currentMaximumValue - valueThreshhold if let index = Int(exactly: numerator / denominator * Double(pitches.count - 1)) { return frequency(from: Double(pitches[index])) } else { return nil } } }
apache-2.0
ba11778c1938a8abd8a3ea66057bb9ba
31.184615
94
0.679732
4.557734
false
false
false
false
Fitbit/RxBluetoothKit
Source/Descriptor.swift
1
5756
import Foundation import CoreBluetooth import RxSwift /// Descriptor is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with /// [CBDescriptor](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBDescriptor_Class/) /// Descriptors provide more information about a characteristic’s value. public class Descriptor { /// Intance of CoreBluetooth descriptor class public let descriptor: CBDescriptor /// Characteristic to which this descriptor belongs. public let characteristic: Characteristic /// The Bluetooth UUID of the `Descriptor` instance. public var uuid: CBUUID { return descriptor.uuid } /// The value of the descriptor. It can be written and read through functions on `Descriptor` instance. public var value: Any? { return descriptor.value } init(descriptor: CBDescriptor, characteristic: Characteristic) { self.descriptor = descriptor self.characteristic = characteristic } convenience init(descriptor: CBDescriptor, peripheral: Peripheral) throws { let cbCharacteristic = try descriptor.unwrapCharacteristic() let cbService = try cbCharacteristic.unwrapService() let service = Service(peripheral: peripheral, service: cbService) let characteristic = Characteristic(characteristic: cbCharacteristic, service: service) self.init(descriptor: descriptor, characteristic: characteristic) } /// Function that allow to observe writes that happened for descriptor. /// - Returns: Observable that emits `next` with `Descriptor` instance every time when write has happened. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `BluetoothError.descriptorWriteFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func observeWrite() -> Observable<Descriptor> { return characteristic.service.peripheral.observeWrite(for: self) } /// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made. /// - Parameter data: `Data` that'll be written to `Descriptor` instance /// - Returns: `Single` that emits `Next` with `Descriptor` instance, once value is written successfully. /// /// Observable can ends with following errors: /// * `BluetoothError.descriptorWriteFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func writeValue(_ data: Data) -> Single<Descriptor> { return characteristic.service.peripheral.writeValue(data, for: self) } /// Function that allow to observe value updates for `Descriptor` instance. /// - Returns: Observable that emits `next` with `Descriptor` instance every time when value has changed. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `BluetoothError.descriptorReadFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func observeValueUpdate() -> Observable<Descriptor> { return characteristic.service.peripheral.observeValueUpdate(for: self) } /// Function that triggers read of current value of the `Descriptor` instance. /// Read is called after subscription to `Observable` is made. /// - Returns: `Single` which emits `next` with given descriptor when value is ready to read. /// /// Observable can ends with following errors: /// * `BluetoothError.descriptorReadFailed` /// * `BluetoothError.peripheralDisconnected` /// * `BluetoothError.destroyed` /// * `BluetoothError.bluetoothUnsupported` /// * `BluetoothError.bluetoothUnauthorized` /// * `BluetoothError.bluetoothPoweredOff` /// * `BluetoothError.bluetoothInUnknownState` /// * `BluetoothError.bluetoothResetting` public func readValue() -> Single<Descriptor> { return characteristic.service.peripheral.readValue(for: self) } } extension Descriptor: CustomStringConvertible { public var description: String { return "\(type(of: self)) \(uuid)" } } extension Descriptor: Equatable {} /// Compare two descriptors. Descriptors are the same when their UUIDs are the same. /// /// - parameter lhs: First descriptor to compare /// - parameter rhs: Second descriptor to compare /// - returns: True if both descriptor are the same. public func == (lhs: Descriptor, rhs: Descriptor) -> Bool { return lhs.descriptor == rhs.descriptor } extension CBDescriptor { /// Unwrap the parent characteristic or throw if the characteristic is nil func unwrapCharacteristic() throws -> CBCharacteristic { guard let cbCharacteristic = characteristic as CBCharacteristic? else { throw BluetoothError.characteristicDeallocated } return cbCharacteristic } }
apache-2.0
c6c7fa2219492692aa67f18a6ac58e86
41.622222
119
0.710115
5.27406
false
false
false
false
EurekaCommunity/GooglePlacesRow
Sources/GooglePlacesRow.swift
1
3528
// // iOS.swift // GooglePlacesRow // // Copyright © 2016 Xmartlabs SRL. All rights reserved. // import Foundation import Eureka import GooglePlaces import GoogleMapsBase protocol GooglePlacesRowProtocol { func autoComplete(_ text: String) } /** The value of the Google Places rows - UserInput: The value will be of this type when the user inputs a string and does not select a place suggestion - Prediction: The value will be of this type if the user selects an option suggested by requesting autocomplete of the Google Places API. */ public enum GooglePlace { case userInput(value: String) case prediction(prediction: GMSAutocompletePrediction) } extension GooglePlace: Equatable, InputTypeInitiable { public init?(string stringValue: String) { self = .userInput(value: stringValue) } } public func == (lhs: GooglePlace, rhs: GooglePlace) -> Bool { switch (lhs, rhs) { case (let .userInput( val), let .userInput( val2)): return val == val2 case (let .prediction( pred), let .prediction( pred2)): if pred.placeID != nil { return pred.placeID == pred2.placeID } return pred2.placeID == nil && pred.attributedFullText == pred2.attributedFullText default: return false } } /// Generic GooglePlaces rows superclass open class _GooglePlacesRow<Cell: GooglePlacesCell>: FieldRow<Cell>, GooglePlacesRowProtocol { /// client that connects with Google Places fileprivate let placesClient = GMSPlacesClient() /// Google Places filter. Change this to search for cities, addresses, country, etc public var placeFilter: GMSAutocompleteFilter? /// Google Places bounds. Ratio for the results of the filter. Read the official documentation for more public var placeBounds: GMSCoordinateBounds? /// Will be called when Google Places request returns an error. public var onNetworkingError: ((Error?) -> Void)? required public init(tag: String?) { super.init(tag: tag) placeFilter = GMSAutocompleteFilter() placeFilter?.type = .city displayValueFor = { place in guard let place = place else { return nil } switch place { case let GooglePlace.userInput(val): return val case let GooglePlace.prediction(pred): return pred.attributedFullText.string } } } func autoComplete(_ text: String) { placesClient.autocompleteQuery(text, bounds: placeBounds, filter: placeFilter, callback: { [weak self] (results, error: Error?) -> Void in guard let results = results else { self?.onNetworkingError?(error) return } self?.cell.predictions = results self?.cell.reload() }) } } /// Row that lets the user choose an option from Google Places using Autocomplete. Options are shown in the inputAccessoryView public final class GooglePlacesAccessoryRow: _GooglePlacesRow<GooglePlacesCollectionCell<GPCollectionViewCell>>, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// Row that lets the user choose an option from Google Places using Autocomplete. Options are shown in a table below the cell public final class GooglePlacesTableRow: _GooglePlacesRow<GooglePlacesTableCell<GPTableViewCell>>, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
28c8e0f1a8f6ceec7db6b576c681a775
33.242718
146
0.671392
4.696405
false
false
false
false
carabina/DDMathParser
MathParser/HexNumberExtractor.swift
2
1615
// // HexNumberExtractor.swift // DDMathParser // // Created by Dave DeLong on 8/6/15. // // import Foundation internal struct HexNumberExtractor: TokenExtractor { func matchesPreconditions(buffer: TokenCharacterBuffer) -> Bool { return buffer.peekNext() == "0" && buffer.peekNext(1, lowercase: true) == "x" } func extract(buffer: TokenCharacterBuffer) -> TokenGenerator.Element { let start = buffer.currentIndex guard buffer.peekNext() == "0" && buffer.peekNext(1, lowercase: true) == "x" else { let error = TokenizerError(kind: .CannotParseHexNumber, sourceRange: start ..< start) return .Error(error) } buffer.consume(2) // 0x let indexBeforeHexNumbers = buffer.currentIndex while buffer.peekNext()?.isHexDigit == true { buffer.consume() } if buffer.currentIndex == indexBeforeHexNumbers { // there wasn't anything after 0[xX] buffer.resetTo(start) } let result: TokenGenerator.Element if start.distanceTo(buffer.currentIndex) > 0 { let range = indexBeforeHexNumbers ..< buffer.currentIndex let raw = buffer[range] result = .Value(RawToken(kind: .HexNumber, string: raw, range: range)) } else { let range = start ..< buffer.currentIndex let error = TokenizerError(kind: .CannotParseHexNumber, sourceRange: range) result = .Error(error) } return result } }
mit
608053c6b78778d01aee07f207e8ca18
29.471698
97
0.582663
4.627507
false
false
false
false
manavgabhawala/UberSDK
Shared/UberManager.swift
1
43485
// // UberManager.swift // UberSDK // // Created by Manav Gabhawala on 24/07/15. // // import Foundation import CoreLocation /// You must implement this protocol to communicate with the UberManager and return information as and when requested. This information can all be found in the Uber app dashboard at `https://developer.uber.com/apps/`. @objc public protocol UberManagerDelegate : NSObjectProtocol { /// The application name with which you setup the Uber app. @objc var applicationName: String { get } /// The client ID for the application setup in Uber @objc var clientID : String { get } /// The client secret for the application setup in Uber @objc var clientSecret: String { get } /// The server token for the application setup in Uber @objc var serverToken : String { get } /// The redirect URI/URL for the application setup in Uber @objc var redirectURI : String { get } /// This is an enumeration that allows you to choose between using the SandboxAPI or the ProductionAPI. You should use the Sandbox while testing and change this to Production before releasing the app. See `UberBaseURL` enumeration. @objc var baseURL : UberBaseURL { get } /// Return an array of raw values of the scopes enum that you would like to request from the user if you are using OAuth2.0. If you don't require user authentication, return an empty array. This must be an array of UberScopes. See the enum type. @objc var scopes : [Int] { get } /// The redirect URI/URL where surge confirmation should be returned to. In swift if not specified, this defaults to the `redirectURI` @objc var surgeConfirmationRedirectURI : String { get } } extension UberManagerDelegate { var surgeConfirmationRedirectURI : String { return redirectURI } } /// This is the main class to which you make calls to access the UberAPI. In general it is best practice to only make one instance of this class and share it across all threads and classes using weak referencing. @objc public class UberManager : NSObject { //MARK: - General Initializers and Properties internal let delegate : UberManagerDelegate internal let userAuthenticator : UberUserAuthenticator internal var surgeCode : String? internal let surgeLock = NSLock() /// Set this property to define the language that the Uber SDK should respond in. The default value of this property is English. public var language : Language = .English /// Dedicated default constructor for an UberManager. /// /// - parameter delegate: The delegate which implements the UberManagerDelegate protocol and returns all the important details required for the Manager to perform API operations on your application's behalf. /// /// - returns: An initialized `UberManager`. @objc public init(delegate: UberManagerDelegate) { self.delegate = delegate self.userAuthenticator = UberUserAuthenticator(clientID: delegate.clientID, clientSecret: delegate.clientSecret, redirectURI: delegate.redirectURI, scopes: delegate.scopes.map { UberScopes(rawValue: $0)! } ) super.init() } /// Use this constructor if you do not wish to create a delegate around one of your classes and just wish to pass in the data once. /// /// - parameter applicationName: The application name with which you setup the Uber app. /// - parameter clientID: The client ID for the application setup in Uber /// - parameter clientSecret: The client secret for the application setup in Uber /// - parameter serverToken: The server token for the application setup in Uber /// - parameter redirectURI: The redirect URI/URL for the application setup in Uber /// - parameter surgeConfirmationRedirectURI: The redirect URI/URL where surge confirmation should be returned to. /// - parameter baseURL: This is an enumeration that allows you to choose between using the SandboxAPI or the ProductionAPI. You should use the Sandbox while testing and change this to Production before releasing the app. See `UberBaseURL` enumeration. /// - parameter scopes: An array of scopes that you would like to request from the user if you are using OAuth2.0. If you don't require user authentication, pass an empty array. This must be an array of `UberScopes`. See the enum type. /// /// - returns: An initialized `UberManager`. public convenience init(applicationName: String, clientID: String, clientSecret: String, serverToken: String, redirectURI: String, surgeConfirmationRedirectURI: String, baseURL: UberBaseURL, scopes: [UberScopes]) { self.init(delegate: PrivateUberDelegate(applicationName: applicationName, clientID: clientID, clientSecret: clientSecret, serverToken: serverToken, redirectURI: redirectURI, baseURL: baseURL, scopes: scopes,surgeConfirmationRedirectURI: surgeConfirmationRedirectURI)) } /// Use this constructor if you do not wish to create a delegate around one of your classes and just wish to pass in the data once. Only use this method if you are using Objective C. Otherwise use the other initializer to ensure for type safety. /// /// - parameter applicationName: The application name with which you setup the Uber app. /// - parameter clientID: The client ID for the application setup in Uber /// - parameter clientSecret: The client secret for the application setup in Uber /// - parameter serverToken: The server token for the application setup in Uber /// - parameter redirectURI: The redirect URI/URL for the application setup in Uber /// - parameter surgeConfirmationRedirectURI: The redirect URI/URL where surge confirmation should be returned to. /// - parameter baseURL: This is an enumeration that allows you to choose between using the SandboxAPI or the ProductionAPI. You should use the Sandbox while testing and change this to Production before releasing the app. See `UberBaseURL` enumeration. /// - parameter scopes: An array of raw values of scopes that you would like to request from the user if you are using OAuth2.0. If you don't require user authentication, pass an empty array. This must be an array of Int's formed using the raw values of the enum `UberScopes` /// /// - returns: An initialized `UberManager`. @objc public convenience init(applicationName: String, clientID: String, clientSecret: String, serverToken: String, redirectURI: String, surgeConfirmationRedirectURI: String, baseURL: UberBaseURL, scopes: [Int]) { self.init(delegate: PrivateUberDelegate(applicationName: applicationName, clientID: clientID, clientSecret: clientSecret, serverToken: serverToken, redirectURI: redirectURI, baseURL: baseURL, scopes: scopes.map { UberScopes(rawValue: $0)!}, surgeConfirmationRedirectURI: surgeConfirmationRedirectURI)) } /// Use this function to log an Uber user out of the system and remove all associated cached files about the user. /// /// - parameter success: The block of code to execute once we have successfully logged a user out. /// - parameter failure: An error occurred while logging the user out. Handle the error in this block. @objc public func logUberUserOut(completionBlock success: UberSuccessBlock?, errorHandler failure: UberErrorHandler?) { userAuthenticator.logout(completionBlock: success, errorHandler: failure) } } //MARK: - Product Fetching extension UberManager { /// Use this function to fetch uber products for a particular latitude and longitude `asynchronously`. /// /// - parameter latitude: The latitude for which you want to find Uber products. /// - parameter longitude: The longitude for which you want to find Uber products. /// - parameter success: The block to be executed if the request was successful and we were able to parse the products. This block takes one parameter, an array of UberProducts. See the `UberProduct` class for more details on how this is returned. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. @objc public func fetchProductsForLocation(latitude latitude: Double, longitude: Double, completionBlock success: UberProductSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchObjects("/v1/products", withPathParameters: ["latitude": latitude, "longitude": longitude], arrayKey: "products", completionHandler: { success($0.0) }, errorHandler: failure) } /// Use this function to fetch uber products for a particular location `asynchronously`. If you are using CoreLocation use this function to pass in the location. Otherwise use the actual latitude and longitude. /// /// - parameter location: The location for which you want to find Uber products. /// - parameter success: The block to be executed if the request was successful and we were able to parse the products. This block takes one parameter, an array of `UberProducts`. See the `UberProduct` class for more details on how this is returned. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. @objc public func fetchProductsForLocation(location: CLLocation, completionBlock success: UberProductSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchProductsForLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, completionBlock: success, errorHandler: failure) } /// Use this function to communicate with the Uber Product Endpoint. You can create an `UberProduct` wrapper using just the productID. /// /// - parameter productID: The productID with which to create a new `UberProduct` /// - parameter success: The block of code to execute if we successfully create the `UberProduct` /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: Product IDs are different for different regions. Fetch all products for a location using the `UberManager` instance. @objc public func createProduct(productID: String, completionBlock success: UberSingleProductSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchObject("/v1/products/\(productID)", completionHandler: success, errorHandler: failure) } } //MARK: - Price Estimates extension UberManager { /// Use this function to fetch price estimates for a particular trip between two points as defined by you `asynchronously`. /// /// - parameter startLatitude: The starting latitude for the trip. /// - parameter startLongitude: The starting longitude for the trip. /// - parameter endLatitude: The ending latitude for the trip. /// - parameter endLongitude: The ending longitude for the trip. /// - parameter success: The block to be executed if the request was successful and we were able to parse the price estimates. This block takes one parameter, an array of `UberPriceEstimates`. See the `UberPriceEstimate` class for more details on how this is returned. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: This function will report errors for points further away than 100 miles. Please make sure that you are asserting that the two locations are closer than that for best results. @objc public func fetchPriceEstimateForTrip(startLatitude startLatitude: Double, startLongitude: Double, endLatitude: Double, endLongitude: Double, completionBlock success: UberPriceEstimateSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchObjects("/v1/estimates/price", withPathParameters: ["start_latitude" : startLatitude, "start_longitude" : startLongitude, "end_latitude" : endLatitude, "end_longitude" : endLongitude], arrayKey: "prices", completionHandler: { success($0.0) }, errorHandler: failure) } /// Use this function to fetch price estimates for a particular trip between two points `asynchronously`. If you are using CoreLocation use this function to pass in the location. Otherwise use the actual latitudes and longitudes. /// /// - parameter startLocation: The starting location for the trip /// - parameter endLocation: The ending location for the trip /// - parameter success: The block to be executed if the request was successful and we were able to parse the price estimates. This block takes one parameter, an array of UberPriceEstimates. See the `UberPriceEstimate` class for more details on how this is returned. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: This function will report errors for points further away than 100 miles. Please make sure that you are asserting that the two locations are closer than that for best results. @objc public func fetchPriceEstimateForTrip(startLocation startLocation: CLLocation, endLocation: CLLocation, completionBlock success: UberPriceEstimateSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchPriceEstimateForTrip(startLatitude: startLocation.coordinate.latitude, startLongitude: startLocation.coordinate.longitude, endLatitude: endLocation.coordinate.latitude, endLongitude: endLocation.coordinate.longitude, completionBlock: success, errorHandler: failure) } } //MARK: - Time Estimates extension UberManager { /// Use this function to fetch time estimates for a particular latitude and longitude `asynchronously`. Optionally, add a productID and/or a userID to narrow down the search results. /// /// - parameter startLatitude: The starting latitude of the user. /// - parameter startLongitude: The starting longitude of the user. /// - parameter userID: An optional parameter: the user's unique ID which allows you to improve search results as defined in the Uber API endpoints. /// - parameter productID: An optional parameter: a specific product ID which allows you to narrow down searches to a particular product. /// - parameter success: The block to be executed if the request was successful and we were able to parse the time estimates. This block takes one parameter, an array of `UberTimeEstimate`s. See the `UberTimeEstimate` class for more details on how this is returned. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. @objc public func fetchTimeEstimateForLocation(startLatitude startLatitude: Double, startLongitude: Double, userID: String? = nil, productID: String? = nil, completionBlock success: UberTimeEstimateSuccessBlock, errorHandler failure: UberErrorHandler?) { var pathParameters : [NSObject: AnyObject] = ["start_latitude": startLatitude, "start_longitude" : startLongitude] if let user = userID { pathParameters["customer_uuid"] = user } if let product = productID { pathParameters["product_id"] = product } fetchObjects("/v1/estimates/time", withPathParameters: pathParameters, arrayKey: "times", completionHandler: { success($0.0) }, errorHandler: failure) } /// Use this function to fetch time estimates for a particular latitude and longitude `synchronously`. Optionally, add a productID and/or a userID to narrow down the search results. If you are using CoreLocation use this function to pass in the location. Otherwise use the actual latitude and longitude. /// /// - parameter location: The location of the user. /// - parameter userID: An optional parameter: the user's unique ID which allows you to improve search results as defined in the Uber API endpoints. /// - parameter productID: An optional parameter: a specific product ID which allows you to narrow down searches to a particular product. /// - parameter success: The block to be executed if the request was successful and we were able to parse the time estimates. This block takes one parameter, an array of `UberTimeEstimate`s. See the `UberTimeEstimate` class for more details on how this is returned. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. @objc public func fetchTimeEstimateForLocation(location: CLLocation, userID : String? = nil, productID: String? = nil, completionBlock success: UberTimeEstimateSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchTimeEstimateForLocation(startLatitude: location.coordinate.latitude, startLongitude: location.coordinate.longitude, userID: userID, productID: productID, completionBlock: success, errorHandler: failure) } } //MARK: - Promotions extension UberManager { /// Use this function to fetch promotions for new users for a particular start and end locations `asynchronously`. /// /// - parameter startLatitude: The starting latitude of the user. /// - parameter startLongitude: The starting longitude of the user. /// - parameter endLatitude: The ending latitude for the travel. /// - parameter endLongitude: The ending longitude for the travel. /// - parameter success: The block of code to execute if an `UberPromotion` was successfully created. This block takes one parameter the `UberPromotion` object. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. @objc public func fetchPromotionsForLocations(startLatitude startLatitude: Double, startLongitude: Double, endLatitude: Double, endLongitude: Double, completionBlock success: UberPromotionSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchObject("/v1/promotions", withPathParameters: ["start_latitude": startLatitude, "start_longitude" : startLongitude, "end_latitude" : endLatitude, "end_longitude" : endLongitude], completionHandler: success, errorHandler: failure) } /// Use this function to fetch promotions for new users for a particular start and end locations `asynchronously`. If you are using CoreLocation use this function to pass in the location. Otherwise use the actual latitude and longitude. /// /// - parameter startLocation: The starting location of the user. /// - parameter endLocation: The ending location for the travel. /// - parameter success: The block of code to execute if an `UberPromotion` was successfully created. This block takes one parameter the `UberPromotion` object. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. @objc public func fetchPromotionsForLocations(startLocation startLocation: CLLocation, endLocation: CLLocation, completionBlock success: UberPromotionSuccessBlock, errorHandler failure: UberErrorHandler?) { fetchPromotionsForLocations(startLatitude: startLocation.coordinate.latitude, startLongitude: startLocation.coordinate.longitude, endLatitude: endLocation.coordinate.latitude, endLongitude: endLocation.coordinate.longitude, completionBlock: success, errorHandler: failure) } } //MARK: - Profile extension UberManager { /// Use this function to `asynchronously` create an `UberUser`. The uber user gives you access to the logged in user's profile. /// /// - parameter success: The block of code to execute if the user has successfully been created. This block takes one parameter an `UberUser` object. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @objc public func createUserProfile(completionBlock success: UberUserSuccess, errorHandler failure: UberErrorHandler?) { assert(userAuthenticator.authenticated(), "You must authenticate the user before calling this end point") fetchObject("/v1/me", requireUserAccessToken: true, completionHandler: success, errorHandler: failure) } } //MARK: - Activity extension UberManager { /// Use this function to fetch a user's activity data `asynchronously`. This interacts with the v1.1 of the History endpoint and requires the HistoryLite scope. /// /// - parameter offset: Offset the list of returned results by this amount. Default is zero. /// - parameter limit: Number of items to retrieve. Default is 5, maximum is 50. /// - parameter success: The block of code to execute on success. The parameters to this block is an array of `UberActivity`, the offset that is passed in, the limit passed in, the count which is the total number of items available. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @available(*, deprecated=1.1, message="Use instead `fetchUserActivity offset:limit:completionBlock:errorHandler` to use the v1.2 endpoint.") @objc public func fetchActivityForUser(offset offset: Int = 0, limit: Int = 5, completionBlock success: UberActivitySuccessCallback, errorHandler failure: UberErrorHandler?) { assert(limit <= UberActivity.maximumActivitiesRetrievable, "The maximum limit size supported by this endpoint is \(UberActivity.maximumActivitiesRetrievable). Please pass in a value smaller than this.") assert(delegate.scopes.contains(UberScopes.HistoryLite.rawValue), "The HistoryLite scope is required for access to the v1.1 History endpoint. Please make sure you pass this in through the delegate.") assert(userAuthenticator.authenticated(), "You must authenticate the user before calling this end point") fetchObjects("/v1.1/history", withPathParameters: ["offset" : offset, "limit" : limit], requireUserAccessToken: true, arrayKey: "history", completionHandler: {(activities: [UberActivity], JSON) in if let count = JSON["count"] as? Int, let offset = JSON["offset"] as? Int, let limit = JSON["limit"] as? Int { success(activities, offset: offset, limit: limit, count: count) return } failure?(UberError(JSON: JSON) ?? unknownError) }, errorHandler: failure) } /// Use this function to fetch a user's activity data `asynchronously` for v 1.2. It requires the History scope. /// - Note: See the `fetchAllUserActivity` function for retrieving all the user's activity at one go. /// /// - parameter offset: Offset the list of returned results by this amount. Default is zero. /// - parameter limit: Number of items to retrieve. Default is 5, maximum is 50. /// - parameter success: The block of code to execute on success. The parameters to this block is an array of `UberActivity`, the offset that is passed in, the limit passed in, the count which is the total number of items available. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @objc public func fetchUserActivity(offset offset: Int = 0, limit: Int = 5, completionBlock success: UberActivitySuccessCallback, errorHandler failure: UberErrorHandler?) { assert(limit <= UberActivity.maximumActivitiesRetrievable, "The maximum limit size supported by this endpoint is \(UberActivity.maximumActivitiesRetrievable). Please pass in a value smaller than this.") assert(delegate.scopes.contains(UberScopes.History.rawValue), "The History scope is required for access to the v1.2 History endpoint. Please make sure you pass this in through the delegate.") assert(userAuthenticator.authenticated(), "You must authenticate the user before calling this end point") fetchObjects("/v1.2/history", withPathParameters: ["offset" : offset, "limit" : limit], requireUserAccessToken: true, arrayKey: "history", completionHandler: {(activities: [UberActivity], JSON) in if let count = JSON["count"] as? Int, let offset = JSON["offset"] as? Int, let limit = JSON["limit"] as? Int { success(activities, offset: offset, limit: limit, count: count) return } failure?(UberError(JSON: JSON) ?? unknownError) }, errorHandler: failure) } /// Use this function to fetch a user's activity data `asynchronously` for v 1.2. It requires the History scope. This function will return all the user's activity after retrieving all of it without any limits however may take longer to run. If you want tor retrieve a smaller number of results and limit and offset the results use the `fetchUserActivity:offset:limit:` function. /// /// - parameter success: The block of code to execute on success. The parameters to this block is an array of `UberActivity` /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @objc public func fetchAllUserActivity(completionBlock success: UberAllActivitySuccessCallback, errorHandler failure: UberErrorHandler?) { assert(delegate.scopes.contains(UberScopes.History.rawValue), "The History scope is required for access to the v1.2 History endpoint. Please make sure you pass this in through the delegate.") assert(userAuthenticator.authenticated(), "You must authenticate the user before calling this end point") var userActivity = [UberActivity]() var count = -1 let lock = NSLock() while count < userActivity.count { lock.lock() fetchUserActivity(offset: userActivity.count, limit: UberActivity.maximumActivitiesRetrievable, completionBlock: { (activities, offset, limit, theCount) -> Void in count = theCount activities.map { userActivity.append($0) } lock.unlock() }, errorHandler: failure) lock.lock() } success(userActivity) } } // MARK: - Request extension UberManager { func createRequest(startLatitude startLatitude: Double, startLongitude: Double, endLatitude: Double, endLongitude: Double, productID: String, surgeConfirmation: String?, completionBlock success: UberRequestSuccessBlock, errorHandler failure: UberErrorHandler?) { assert(userAuthenticator.authenticated(), "You must authenticate the user before attempting to use this endpoint.") assert(delegate.scopes.contains(UberScopes.Request.rawValue), "You must use the Request scope on your delegate or during initialization to access this endpoint.") var queryParameters : [NSObject: AnyObject] = ["start_latitude": startLatitude, "start_longitude": startLongitude, "end_latitude": endLatitude, "end_longitude": endLongitude, "product_id": productID] if let surge = surgeConfirmation { queryParameters["surge_confirmation_id"] = surge } surgeCode = nil fetchObject("/v1/requests", withQueryParameters: queryParameters, requireUserAccessToken: true, usingHTTPMethod: HTTPMethod.Post, completionHandler: success, errorHandler: failure) } /// Use this function to communicate with the Uber Request Endpoint. You can create an `UberRequest` wrapper using just the requestID. You must have authenticated the user with the Request scope before you can use this endpoint. /// /// - parameter requestID: The requestID with which to create a new `UberRequest` /// - parameter success: The block of code to execute if we successfully create the `UberRequest` /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @objc public func createRequest(requestID: String, completionBlock success: UberRequestSuccessBlock, errorHandler failure: UberErrorHandler?) { assert(userAuthenticator.authenticated(), "You must authenticate the user before attempting to use this endpoint.") assert(delegate.scopes.contains(UberScopes.Request.rawValue), "You must use the Request scope on your delegate or during initialization to access this endpoint.") fetchObject("/v1/products/\(requestID)", requireUserAccessToken: true, completionHandler: success, errorHandler: failure) } /// Use this function to cancel an Uber Request whose request ID you have but do not have the wrapper `UberRequest` object. If you have an `UberRequest` which you want to cancel call the function `cancelRequest:` by passing its id. /// /// - parameter requestID: The request ID for the request you want to cancel. /// - parameter success: The block of code to execute on a successful cancellation. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @objc public func cancelRequest(requestID: String, completionBlock success: UberSuccessBlock?, errorHandler failure: UberErrorHandler?) { assert(userAuthenticator.authenticated(), "You must authenticate the user before using this endpoint.") assert(delegate.scopes.contains(UberScopes.Request.rawValue), "You must use the Request scope on your delegate or during initialization to access this endpoint.") let request = createRequestForURL("/v1/requests/\(requestID)", requireUserAccessToken: true, usingHTTPMethod: .Delete) let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in guard error != nil && (response as! NSHTTPURLResponse).statusCode == 204 else { failure?((error == nil ? UberError(JSONData: data, response: response) : UberError(error: error, response: response)) ?? unknownError) return } success?() }) task.resume() } /// Use this function to get the map for an Uber Request whose request ID you have. /// /// - parameter requestID: The request ID for the request whose map you want. /// - parameter success: The block of code to execute on a successful fetching of the map. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @objc public func mapForRequest(requestID: String, completionBlock success: UberMapSuccessBlock, errorHandler failure: UberErrorHandler?) { assert(userAuthenticator.authenticated(), "You must authenticate the user before using this endpoint.") assert(delegate.scopes.contains(UberScopes.Request.rawValue), "You must use the Request scope on your delegate or during initialization to access this endpoint.") fetchObject("/v1/requests/\(requestID)/map", requireUserAccessToken: true, completionHandler: success, errorHandler: failure) } /// Use this function to get a receipt for an Uber Request whose request ID you have. /// /// - parameter requestID: The request ID for the request whose receipt you want. /// - parameter success: The block of code to execute on a successful fetching of the receipt. /// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information. /// - Warning: User authentication must be completed before calling this function. @objc public func receiptForRequest(requestID: String, completionBlock success: UberRequestReceiptSuccessBlock, errorHandler failure: UberErrorHandler?) { assert(userAuthenticator.authenticated(), "You must authenticate the user before using this endpoint.") assert(delegate.scopes.contains(UberScopes.RequestReceipt.rawValue), "You must use the Request Receipt scope on your delegate or during initialization to access this endpoint.") fetchObject("/v1/requests/\(requestID)/receipt", requireUserAccessToken: true, completionHandler: success, errorHandler: failure) } } // MARK: - Private Helpers extension UberManager { @objc private class PrivateUberDelegate : NSObject, UberManagerDelegate { @objc let applicationName : String @objc let clientID : String @objc let clientSecret: String @objc let serverToken : String @objc let redirectURI : String @objc let baseURL : UberBaseURL @objc let scopes : [Int] @objc let surgeConfirmationRedirectURI : String init(applicationName: String, clientID: String, clientSecret: String, serverToken: String, redirectURI: String, baseURL: UberBaseURL, scopes: [UberScopes], surgeConfirmationRedirectURI: String) { self.applicationName = applicationName self.clientID = clientID self.clientSecret = clientSecret self.serverToken = serverToken self.redirectURI = redirectURI self.baseURL = baseURL self.scopes = scopes.map { $0.rawValue } self.surgeConfirmationRedirectURI = surgeConfirmationRedirectURI } } /// Creates a NSURLRequest using the parameters to set it up. /// /// - parameter URL: The URL that the request should point to. /// - parameter queries: These are query parameters that are encoded into the HTTP body. /// - parameter paths: These are path parameters that get encoded into the URL. /// - parameter accessTokenRequired: This is a boolean that indicates whether the caller requires user authentication or not. If the caller requires user authentication and it hasn't been finished this method fails. /// - parameter method: The HTTP method to use, by default this is a GET request. /// /// - returns: The initialized and fully setup NSURLRequest. private func createRequestForURL(var URL: String, withQueryParameters queries: [NSObject: AnyObject]? = nil, withPathParameters paths: [NSObject: AnyObject]? = nil, requireUserAccessToken accessTokenRequired: Bool = false, usingHTTPMethod method: HTTPMethod = .Get) -> NSURLRequest { URL = "\(delegate.baseURL.URL)\(URL)" if let pathParameters = paths { URL += "?" for pathParameter in pathParameters { URL += "\(pathParameter.0)=\(pathParameter.1)&" } URL = URL.substringToIndex(URL.endIndex.predecessor()) } let mutableRequest = NSMutableURLRequest(URL: NSURL(string: URL)!) mutableRequest.HTTPMethod = method.rawValue mutableRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") // If we couldn't add the user access header if !userAuthenticator.addBearerAccessHeader(mutableRequest) { if accessTokenRequired { fatalError("You must call the performUserAuthorization in the Uber Manager class to ensure that the user has been authorized before using this end point because it requires an OAuth2 access token.") } else { mutableRequest.addValue("Token \(delegate.serverToken)", forHTTPHeaderField: "Authorization") } } mutableRequest.addValue(language.description, forHTTPHeaderField: "Accept-Language") if let queryParameters = queries { do { mutableRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(queryParameters, options: []) } catch { mutableRequest.HTTPBody = nil } } return mutableRequest.copy() as! NSURLRequest } /// Performs a network call to the request and calls the success block or failure block depending on what happens on the network call. It parses the JSON and returns it to the success block as a `Dictionary`. /// /// - parameter request: The request on which to perform the network call. /// - parameter success: The block of code to exeucte on an error. /// - parameter failure: The block of code to execute on an error. private func performRequest(request: NSURLRequest, success: ([NSObject: AnyObject], NSURLResponse?) -> Void, failure: UberErrorHandler?) { let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in guard error == nil else { failure?(UberError(JSONData: data, response: response) ?? UberError(error: error!, response: response)); return } do { guard let JSONData = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject: AnyObject] else { failure?(UberError(JSONData: data, response: response) ?? UberError(error: error!, response: response)); return } success(JSONData, response) } catch let error as NSError { failure?(UberError(error: error, response: response)) } catch { failure?(UberError(JSONData: data, response: response) ?? unknownError) } }) task.resume() } /// When multiple objects exist, at the JSON request use this generic function to parse the objects created. The success block must be of the form `([T], [NSObject: AnyObject]) -> Void` where T conforms to JSON createable. See `fetchObject` for only fetching a single object. /// /// - parameter URL: The URL on which to perform the request. /// - parameter queries: The queries to use on the request. /// - parameter paths: The path parameters to pass to the request. /// - parameter accessTokenRequired: Whether the user access token is required or not. /// - parameter method: The HTTP method to use to perform the request. /// - parameter key: The key that has the array object. /// - parameter success: The code to exeucte on success. /// - parameter failure: The code to execute on an error. private func fetchObjects<T: JSONCreateable>(URL: String, withQueryParameters queries: [NSObject: AnyObject]? = nil, withPathParameters paths: [NSObject: AnyObject]? = nil, requireUserAccessToken accessTokenRequired: Bool = false, usingHTTPMethod method: HTTPMethod = .Get, arrayKey key: String, completionHandler success: ([T], [NSObject: AnyObject]) -> Void, errorHandler failure: UberErrorHandler?) { let request = createRequestForURL(URL, withQueryParameters: queries, withPathParameters: paths, requireUserAccessToken: accessTokenRequired, usingHTTPMethod: method) performRequest(request, success: {(JSON, response) in if let arrayJSON = JSON[key] as? [[NSObject : AnyObject]] { let objects = arrayJSON.map { T(JSON: $0) }.filter { $0 != nil }.map { $0! } success(objects, JSON) } else { failure?(UberError(JSON: JSON, response: response) ?? unknownError) } }, failure: failure) } /// When only one object exists in the JSON use this generic function instead of the `fetchObjects` function. /// /// - parameter URL: The URL on which to perform the request. /// - parameter queries: The queries to use on the request. /// - parameter paths: The path parameters to pass to the request. /// - parameter accessTokenRequired: Whether the user access token is required or not. /// - parameter method: The HTTP method to use to perform the request. /// - parameter success: The code to exeucte on success. /// - parameter failure: The code to execute on an error. private func fetchObject<T: JSONCreateable>(URL: String, withQueryParameters queries: [NSObject: AnyObject]? = nil, withPathParameters paths: [NSObject: AnyObject]? = nil, requireUserAccessToken accessTokenRequired: Bool = false, usingHTTPMethod method: HTTPMethod = .Get, completionHandler success: (T) -> Void, errorHandler failure: UberErrorHandler?) { let request = createRequestForURL(URL, withQueryParameters: queries, withPathParameters: paths, requireUserAccessToken: accessTokenRequired, usingHTTPMethod: method) performRequest(request, success: {(JSON, response) in if let object = T(JSON: JSON) { success(object) } else { if let error = UberError(JSON: JSON, response: response) { failure?(error) return } let errors = UberError.createErrorsWithJSON(JSON, response: response) for error in errors { failure?(error) } if errors.count == 0 { failure?(unknownError) } } }, failure: failure) } }
apache-2.0
aa7b5b3a7d071f72db69862b5f322e28
74.233564
402
0.755341
4.464579
false
false
false
false
wuhduhren/Mr-Ride-iOS
Mr-Ride-iOS/Model/RootViewManager.swift
1
2005
// // RootViewManager.swift // Mr-Ride-iOS // // Created by Eph on 2016/6/21. // Copyright © 2016年 AppWorks School WuDuhRen. All rights reserved. // import Foundation class RootViewManager { static let sharedManager = RootViewManager() typealias ChangeRootViewControllerSuccess = () -> Void typealias ChangeRootViewControllerFailure = (error: ErrorType) -> Void enum ChangeRootViewControllerError: ErrorType { case NoWindow } func changeRootViewController(viewController viewController: UIViewController, animated: Bool, success: ChangeRootViewControllerSuccess?, failure: ChangeRootViewControllerFailure?) { if let window = UIApplication.sharedApplication().delegate?.window { if animated { if let currentRootViewController = window?.rootViewController { let snapshotView = currentRootViewController.view.snapshotViewAfterScreenUpdates(true) viewController.view.addSubview(snapshotView) window?.rootViewController = viewController UIView.animateWithDuration( 1.0, animations: { snapshotView.layer.opacity = 0.0 }, completion: { _ in snapshotView.removeFromSuperview() success?() } ) } else { window?.rootViewController = viewController success?() } } else { window?.rootViewController = viewController success?() } } else { let error: ChangeRootViewControllerError = .NoWindow failure?(error: error) } } }
mit
bcc4aed2d5f5d02b2dc439e06a6fdae0
31.290323
186
0.521479
6.856164
false
false
false
false
silence0201/Swift-Study
SimpleProject/ContactDemo/ContactDemo/DetailTableVc.swift
1
1172
// // DetailTableVc.swift // ContactDemo // // Created by 杨晴贺 on 2017/3/5. // Copyright © 2017年 Silence. All rights reserved. // import UIKit class DetailTableVc: UITableViewController { var person: Person? // 闭包是可选的 var completionCallBack: (() -> Void)? @IBOutlet weak var nameText: UITextField! @IBOutlet weak var phoneText: UITextField! @IBOutlet weak var titleText: UITextField! override func viewDidLoad() { super.viewDidLoad() // 判断person是否有值 if person != nil{ nameText.text = person?.name phoneText.text = person?.phone titleText.text = person?.title } } @IBAction func savePerson(_ sender: Any) { // 判断Person是否为空 if person == nil{ person = Person() } person?.name = nameText.text person?.phone = phoneText.text person?.title = titleText.text // ? 可选解包 completionCallBack?() // 返回 _ = navigationController?.popViewController(animated: true) } }
mit
70a9a60d344ecb492f384d5113e56b08
21.755102
67
0.563229
4.569672
false
false
false
false
priyax/TextToSpeech
textToTableViewController/textToTableViewController/LoginViewController.swift
1
3804
// // LoginViewController.swift // textToTableViewController // // Created by Priya Xavier on 10/6/16. // Copyright © 2016 Guild/SA. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var signInBtn: UIButton! @IBAction func cancelBtn(_ sender: UIButton) { dismiss(animated: true, completion: nil) } @IBAction func signIn(_ sender: UIButton) { if !Utility.isValidEmail(emailAddress: emailField.text!) { Utility.showAlert(viewController: self, title: "Login Error", message: "Please enter a valid email address.") return } // spinner.startAnimating() let email = emailField.text! let password = passwordField.text! BackendlessManager.sharedInstance.loginUser(email: email, password: password, completion: { // self.spinner.stopAnimating() self.performSegue(withIdentifier: "gotoSavedRecipesFromLogin", sender: sender) }, error: { message in // self.spinner.stopAnimating() Utility.showAlert(viewController: self, title: "Login Error", message: message) }) } override func viewDidLoad() { super.viewDidLoad() signInBtn.isEnabled = false emailField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: UIControlEvents.editingChanged) passwordField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: UIControlEvents.editingChanged) self.emailField.delegate = self self.passwordField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //facebook and twitter login @IBAction func loginViaFacebook(_ sender: UIButton) { BackendlessManager.sharedInstance.loginViaFacebook(completion: { }, error: { message in Utility.showAlert(viewController: self, title: "Login Error", message: message) }) } @IBAction func loginViaTwitter(_ sender: UIButton) { BackendlessManager.sharedInstance.loginViaTwitter(completion: { }, error: { message in Utility.showAlert(viewController: self, title: "Login Error", message: message) }) } //Hide Keyboard when user touches outside keyboard override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } //Presses return key to exit keyboard func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return (true) } func textFieldChanged(textField: UITextField) { if emailField.text == "" || passwordField.text == "" { signInBtn.isEnabled = false } else { signInBtn.isEnabled = true } } // UITextFieldDelegate, called when editing session begins, or when keyboard displayed func textFieldDidBeginEditing(_ textField: UITextField) { // Create padding for textFields let paddingView = UIView(frame:CGRect(x: 0, y: 0, width: 20, height: 20)) textField.leftView = paddingView textField.leftViewMode = UITextFieldViewMode.always if textField == emailField { emailField.placeholder = "Email" } else { passwordField.placeholder = "Password" } } }
mit
dcd0789e204825d77688faff431a502e
30.691667
124
0.62214
5.311453
false
false
false
false
GraphKit/MaterialKit
Sources/iOS/CollectionView.swift
3
4416
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit open class CollectionView: UICollectionView { /// A preset wrapper around contentEdgeInsets. open var contentEdgeInsetsPreset: EdgeInsetsPreset { get { return (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsetsPreset } set(value) { (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsetsPreset = value } } open var contentEdgeInsets: EdgeInsets { get { return (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsets } set(value) { (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsets = value } } /// Scroll direction. open var scrollDirection: UICollectionViewScrollDirection { get { return (collectionViewLayout as? CollectionViewLayout)!.scrollDirection } set(value) { (collectionViewLayout as? CollectionViewLayout)!.scrollDirection = value } } /// A preset wrapper around interimSpace. open var interimSpacePreset: InterimSpacePreset { get { return (collectionViewLayout as? CollectionViewLayout)!.interimSpacePreset } set(value) { (collectionViewLayout as? CollectionViewLayout)!.interimSpacePreset = value } } /// Spacing between items. @IBInspectable open var interimSpace: InterimSpace { get { return (collectionViewLayout as? CollectionViewLayout)!.interimSpace } set(value) { (collectionViewLayout as? CollectionViewLayout)!.interimSpace = value } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object. - Parameter frame: A CGRect defining the view's frame. - Parameter collectionViewLayout: A UICollectionViewLayout reference. */ public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) prepare() } /** An initializer that initializes the object. - Parameter frame: A CGRect defining the view's frame. */ public init(frame: CGRect) { super.init(frame: frame, collectionViewLayout: CollectionViewLayout()) prepare() } /// A convenience initializer that initializes the object. public convenience init() { self.init(frame: .zero) } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { contentScaleFactor = Screen.scale backgroundColor = .white } }
agpl-3.0
e3de33015d970daac4583e93ca30427f
33.5
91
0.737998
4.748387
false
false
false
false
PatrickSCLin/PLMenuBar
PLMenuBar/PLMenuDetailComboView.swift
1
3591
// // PLMenuDetailComboView.swift // PLMenuBar // // Created by Patrick Lin on 4/13/16. // Copyright © 2016 Patrick Lin. All rights reserved. // @objc public protocol PLMenuDetailComboViewDelegate: NSObjectProtocol { func combo(_ combo: PLMenuDetailComboView, didChangeValueAtSection section: Int, Row row: Int) } open class PLMenuDetailComboView: PLMenuDetailView, PLMenuDetailComboSectionViewDelegate { var items: [PLMenuComboSection] = [PLMenuComboSection]() open var delegate: PLMenuDetailComboViewDelegate? // MARK: Combo Section Delegate Methods func section(_ section: PLMenuDetailComboSectionView, didChangeValueAtRow row: Int) { for (indexOfSection, sectionView) in self.contentViews.enumerated() { if sectionView == section { self.delegate?.combo(self, didChangeValueAtSection: indexOfSection, Row: row) break } } } // MARK: Public Methods override open func layoutSubviews() { super.layoutSubviews() let contentWidth = self.bounds.size.width / CGFloat(self.items.count) let contentHeight = self.bounds.size.height for (index, content) in self.contentViews.enumerated() { content.frame = CGRect(x: contentWidth * CGFloat(index), y: 0, width: contentWidth, height: contentHeight) } } override open func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { if context.nextFocusedView != nil { for (_, contentView) in self.contentViews.enumerated() { let sectionView = contentView as! PLMenuDetailComboSectionView for (_, rowView) in sectionView.rowViews.enumerated() { if rowView.contentBtn === context.nextFocusedView! { rowView.isHighLighted = true } } } } if context.previouslyFocusedView != nil { for (_, contentView) in self.contentViews.enumerated() { let sectionView = contentView as! PLMenuDetailComboSectionView for (_, rowView) in sectionView.rowViews.enumerated() { if rowView.contentBtn === context.previouslyFocusedView! { rowView.isHighLighted = false } } } } } // MARK: Init Methods func commonInit() { for (_, item) in self.items.enumerated() { let content = PLMenuDetailComboSectionView(item: item) content.delegate = self self.addSubview(content) self.contentViews.append(content) } } convenience init(items: [PLMenuComboSection]) { self.init(frame: CGRect.zero) self.items.append(contentsOf: items) self.commonInit() } }
mit
59e827f5ec3d4cfdbdfd49742ffd4c79
26.829457
120
0.498607
6.105442
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Dealers/WhenToldToOpenDealersWebsite.swift
1
1008
import EurofurenceModel import XCTest import XCTEurofurenceModel class WhenToldToOpenDealersWebsite: XCTestCase { func testTellTheApplicationToOpenTheURL() { var dealer = DealerCharacteristics.random dealer.links = [ LinkCharacteristics(name: .random, fragmentType: .WebExternal, target: "https://www.eurofurence.org") ] var syncResponse = ModelCharacteristics.randomWithoutDeletions syncResponse.dealers.changed = [dealer] let expected = URL(string: "https://www.eurofurence.org").unsafelyUnwrapped let urlOpener = CapturingURLOpener() let context = EurofurenceSessionTestBuilder().with(urlOpener).build() context.performSuccessfulSync(response: syncResponse) let dealerIdentifier = DealerIdentifier(dealer.identifier) let entity = context.dealersService.fetchDealer(for: dealerIdentifier) entity?.openWebsite() XCTAssertEqual(expected, urlOpener.capturedURLToOpen) } }
mit
f7807977ce155373dfba225d4ed06cfc
37.769231
113
0.720238
5.333333
false
true
false
false
sauravexodus/RxFacebook
Carthage/Checkouts/facebook-sdk-swift/Samples/Catalog/Sources/LoginManagerViewController.swift
2
2681
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FacebookCore import FacebookLogin class LoginManagerViewController: UIViewController { func loginManagerDidComplete(_ result: LoginResult) { let alertController: UIAlertController switch result { case .cancelled: alertController = UIAlertController(title: "Login Cancelled", message: "User cancelled login.") case .failed(let error): alertController = UIAlertController(title: "Login Fail", message: "Login failed with error \(error)") case .success(let grantedPermissions, _, _): alertController = UIAlertController(title: "Login Success", message: "Login succeeded with granted permissions: \(grantedPermissions)") } self.present(alertController, animated: true, completion: nil) } } extension LoginManagerViewController { @IBAction func loginWithReadPermissions() { let loginManager = LoginManager() loginManager.logIn(readPermissions: [.publicProfile, .userFriends], viewController: self) { result in self.loginManagerDidComplete(result) } } @IBAction func loginWithPublishPermissions() { let loginManager = LoginManager() loginManager.logIn(publishPermissions: [.publishActions], viewController: self) { result in self.loginManagerDidComplete(result) } } @IBAction func logOut() { let loginManager = LoginManager() loginManager.logOut() let alertController = UIAlertController(title: "Logout", message: "Logged out.") present(alertController, animated: true, completion: nil) } }
mit
8348288e64da31770d8f4fbe44b1f453
40.246154
117
0.738903
4.910256
false
false
false
false
nkirby/Humber
Humber/_src/Table View Cells/EditOverviewItemTitleCell.swift
1
2506
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore import HMGithub internal protocol EditOverviewTitleDelegate: class { var tapGestureView: UIView { get } func didUpdateTitle(title title: String) } // ======================================================= class EditOverviewItemTitleCell: UITableViewCell, UITextFieldDelegate { @IBOutlet var textField: UITextField! private var tapGesture: UITapGestureRecognizer? private weak var delegate: EditOverviewTitleDelegate? override func awakeFromNib() { super.awakeFromNib() self.textField.attributedPlaceholder = NSAttributedString(string: "Name", attributes: [ NSFontAttributeName: Theme.font(type: .Regular(12.0)), NSForegroundColorAttributeName: Theme.color(type: .DisabledTextColor) ]) self.textField.font = Theme.font(type: .Regular(12.0)) self.textField.delegate = self self.textField.rac_textSignal().subscribeNext {[weak self] obj in if let text = obj as? String { self?.delegate?.didUpdateTitle(title: text) } } } override func prepareForReuse() { super.prepareForReuse() if let tapGesture = self.tapGesture { tapGesture.view?.removeGestureRecognizer(tapGesture) self.tapGesture = nil } self.delegate = nil self.textField.text = "" } // ======================================================= internal func render(model model: GithubOverviewItemModel, delegate: EditOverviewTitleDelegate) { self.backgroundColor = Theme.color(type: .CellBackgroundColor) self.delegate = delegate let tapGesture = UITapGestureRecognizer(target: self, action: #selector(EditOverviewItemTitleCell.didTapView)) delegate.tapGestureView.addGestureRecognizer(tapGesture) tapGesture.cancelsTouchesInView = false self.tapGesture = tapGesture self.textField.text = model.title } @objc private func didTapView() { self.textField.resignFirstResponder() } // ======================================================= // MARK: - Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
5b8da7b40d25c631059df50ba8fc5247
30.721519
118
0.579808
5.774194
false
false
false
false
alitan2014/swift
Heath/Heath/Controllers/TreatViewController.swift
1
26221
// // TreatViewController.swift // Heath // // Created by TCL on 15/8/19. // Copyright (c) 2015年 Mac. All rights reserved. // import UIKit class TreatViewController: UIViewController { var IPHONE_WIDTH:CGFloat=UIScreen.mainScreen().bounds.width var IPHONE_HEIGHT:CGFloat=UIScreen.mainScreen().bounds.height @IBOutlet weak var woManButton: UIButton! @IBOutlet weak var manButton: UIButton! @IBOutlet weak var faceButton: UIButton! @IBOutlet weak var otherButton: UIButton! @IBOutlet weak var bodyImgView: UIImageView! @IBOutlet weak var footImgView: UIImageView!//足部 @IBOutlet weak var legImgView: UIImageView!//腿部 @IBOutlet weak var reproductionImgView: UIImageView!//生殖部位 @IBOutlet weak var abdominalImgView: UIImageView!//腹部 @IBOutlet weak var chestImgView: UIImageView!//胸部 @IBOutlet weak var handImgView: UIImageView!//手部 @IBOutlet weak var limbImgView: UIImageView!//上肢 @IBOutlet weak var neckImageView: UIImageView!//脖子 var treatmentView:TreatmentView!//男性头部图 var womenHeadView:WomenHeadView!//女性头部图 var womenBodyView:WomenBodyView!//女性全图 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. createUI() clickImage() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.hidden=false self.treatmentView.createUI() self.womenBodyView.createUI() self.womenHeadView.createUI() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?){ super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience init() { var nibNameOrNil = String?("TreatViewController") //考虑到xib文件可能不存在或被删,故加入判断 if NSBundle.mainBundle().pathForResource(nibNameOrNil, ofType: "xib") == nil { nibNameOrNil = nil } self.init(nibName: nibNameOrNil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createUI() { var normalImage=UIImage(named: "gray_1") var selectedImage=UIImage(named: "gray_2") otherButton.setTitleColor(UIColor(red: 64/255.0, green: 193/255.0, blue: 218/255.0, alpha: 1), forState: UIControlState.Normal) manButton.setTitle("男性", forState: UIControlState.Normal) manButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) //manButton.frame=CGRectMake(manButton.frame.origin.x, manButton.frame.origin.y, 40, 40) manButton.selected=true manButton.titleLabel?.font=UIFont(name: "heiti SC", size: 15) //manButton.setTitleColor(UIColor(red: 64/255.0, green: 193/255.0, blue: 218/255.0, alpha: 1), forState: UIControlState.Normal) manButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) manButton.setBackgroundImage(selectedImage, forState: UIControlState.Selected) manButton.setBackgroundImage(normalImage, forState: UIControlState.Normal) if IPHONE_HEIGHT==480 { manButton.clipsToBounds=true } woManButton.setTitle("女性", forState: UIControlState.Normal) woManButton.titleLabel?.font=UIFont(name: "heiti SC", size: 15) //woManButton.setTitleColor(UIColor(red: 64/255.0, green: 193/255.0, blue: 218/255.0, alpha: 1), forState: UIControlState.Normal) woManButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) woManButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) woManButton.setBackgroundImage(selectedImage, forState: UIControlState.Selected) woManButton.setBackgroundImage(normalImage, forState: UIControlState.Normal) woManButton.layer.cornerRadius=CGRectGetWidth(woManButton.frame)/2 //woManButton.clipsToBounds=true //创建点击男性头部跳转页面 treatmentView=NSBundle.mainBundle().loadNibNamed("TreatmentView", owner: self, options: nil).first as!TreatmentView treatmentView.createUI() treatmentView.frame=CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-100) treatmentView.sendTouchBlock={ (touch:UITouch,state:String)->() in if state == "began" { self.imgViewBeganTouch(touch) }else if state == "ended" { self.imgViewEndedTouch(touch) } } self.treatmentView.sendButtonBlock={ (sender:UIButton)->() in self.btbClick(sender) } //创建选择女性跳转页面 womenBodyView=NSBundle.mainBundle().loadNibNamed("WomenBodyView", owner: self, options: nil).first as!WomenBodyView self.womenBodyView.frame=CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-113) womenBodyView.createUI() self.womenBodyView.sendTouch={ (touch:UITouch,state:String)->() in if state=="began" { self.imgViewBeganTouch(touch) }else if state=="ended" { self.imgViewEndedTouch(touch) } } self.womenBodyView.sendButton={ (sender:UIButton)->() in self.btbClick(sender) } //创建跳转女性头部图 self.womenHeadView=NSBundle.mainBundle().loadNibNamed("WomenHeadView", owner: self, options: nil).first as! WomenHeadView self.womenHeadView.frame=CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-113) self.womenHeadView.sendTouchBlock={ (touch:UITouch,state:String)->() in if state=="began" { self.imgViewBeganTouch(touch) }else if state == "ended" { self.imgViewEndedTouch(touch) } } self.womenHeadView.sendButtonBlock={ (sender:UIButton)->() in self.btbClick(sender) } } func clickImage() { self.bodyImgView.userInteractionEnabled=true self.footImgView.image=nil self.footImgView.userInteractionEnabled=true self.legImgView.image=nil self.legImgView.userInteractionEnabled=true self.reproductionImgView.image=nil self.reproductionImgView.userInteractionEnabled=true self.abdominalImgView.image=nil self.abdominalImgView.userInteractionEnabled=true self.chestImgView.image=nil self.chestImgView.userInteractionEnabled=true self.handImgView.image=nil self.handImgView.userInteractionEnabled=true self.limbImgView.image=nil self.limbImgView.userInteractionEnabled=true self.neckImageView.image=nil self.neckImageView.userInteractionEnabled=true } //开始触摸图片 func imgViewBeganTouch(touch:UITouch) { var view=touch.view let tag=view.tag if faceButton.selected==true || self.womenBodyView.faceButton.selected==true { switch tag { case 120://点击了屁股 self.reproductionImgView.image=UIImage(named: "intelligence_highlight_0314") case 130://点击了腰部 self.abdominalImgView.image=UIImage(named: "intelligence_highlight_0312") case 140://点击了腰部 self.chestImgView.image=UIImage(named: "intelligence_highlight_0312") case 230://女性生殖部位 self.womenBodyView.reproductionImgView.image=UIImage(named: "intelligence_highlight_0214") case 250://女性腹部 self.womenBodyView.abdominalImgView.image=UIImage(named: "intelligence_highlight_0212") case 270://女性胸部 self.womenBodyView.chestImgView.image=UIImage(named: "intelligence_highlight_0210") default: println() } }else { switch tag { case 10://点击了嘴巴 self.treatmentView.mouthImageView.image=UIImage(named: "intelligence_highlight_0304.png") case 20://点击了眼睛 self.treatmentView.eyesImageView.image=UIImage(named: "intelligence_highlight_0102") case 30://点击了耳朵 self.treatmentView.earsImageView.image=UIImage(named: "intelligence_highlight_0105") case 40://点击了面部 self.treatmentView.faceImageView.image=UIImage(named: "intelligence_highlight_0306") case 50://点击了耳朵 self.treatmentView.noseImageView.image=UIImage(named: "intelligence_highlight_0103") case 60://点击了头部 self.treatmentView.headImageView.image=UIImage(named: "intelligence_highlight_0301") case 100://点击了足部 self.footImgView.image=UIImage(named: "intelligence_highlight_0317") case 110://腿部 self.legImgView.image=UIImage(named: "intelligence_highlight_0116") case 120://点击了生殖部位 self.reproductionImgView.image=UIImage(named: "intelligence_highlight_0315") case 130://点击了腹部 self.abdominalImgView.image=UIImage(named: "intelligence_highlight_0311") case 140://点击了胸部 self.chestImgView.image=UIImage(named: "intelligence_highlight_0310") case 150://点击了手 self.handImgView.image=UIImage(named: "intelligence_highlight_0109") case 160://点击了上肢 self.limbImgView.image=UIImage(named: "intelligence_highlight_0108") case 170://点击了脖子 self.neckImageView.image=UIImage(named: "intelligence_highlight_0307") case 180://点击 跳转男性头部大图 println("跳转头部界面") var views=self.view.subviews for view in views { (view as! UIView).hidden=true } self.view.addSubview(treatmentView) case 210://女性足部 self.womenBodyView.footImgView.image=UIImage(named: "intelligence_highlight_0217") case 220://女性腿部 self.womenBodyView.legImgView.image=UIImage(named: "intelligence_highlight_0216") case 230://女性生殖部位 self.womenBodyView.reproductionImgView.image=UIImage(named: "intelligence_highlight_0215") case 240://女性手部 self.womenBodyView.handImgView.image=UIImage(named: "intelligence_highlight_0209") case 250://女性腹部 self.womenBodyView.abdominalImgView.image=UIImage(named: "intelligence_highlight_0211") case 260://女性上肢 self.womenBodyView.limbImgView.image=UIImage(named: "intelligence_highlight_0208") case 270://女性胸部 self.womenBodyView.chestImgView.image=UIImage(named: "intelligence_highlight_0210") case 280://女性脖子 self.womenBodyView.neckImageView.image=UIImage(named: "intelligence_highlight_0207") case 290://点击跳转女子头部图 self.womenBodyView.hidden=true self.view.addSubview(self.womenHeadView) println("点击了女性头部") case 410://点击了女性 嘴巴 self.womenHeadView.mouthImageView.image=UIImage(named: "intelligence_highlight_0206") case 420://点击了女性 鼻子 self.womenHeadView.noseImageView.image=UIImage(named: "intelligence_highlight_0203") case 430://点击了女性 面部 self.womenHeadView.faceImageView.image=UIImage(named: "intelligence_highlight_0206") case 440://点击了女性眼睛 self.womenHeadView.eyesImageView.image=UIImage(named: "intelligence_highlight_0202") case 450://点击了女性耳朵 self.womenHeadView.earsImageView.image=UIImage(named: "intelligence_highlight_0205") case 460://点击了女性头部 self.womenHeadView.headImageView.image=UIImage(named: "intelligence_highlight_0201") default: println() } } } //结束触摸图片 func imgViewEndedTouch(touch:UITouch) { var view=touch.view let tag=view.tag var symptom=SymptomViewController() if faceButton.selected==true || self.womenBodyView.faceButton.selected==true { if manButton.hidden==false { symptom.personType="男性" symptom.typeNum=1 }else { symptom.personType="女性" symptom.typeNum=2 } switch tag { case 120://点击了屁股 self.reproductionImgView.image=nil symptom.position="臀部" self.navigationController?.pushViewController(symptom, animated: true) case 130://点击了腰部 self.abdominalImgView.image=nil symptom.position="腰部" self.navigationController?.pushViewController(symptom, animated: true) case 140://点击了背部 self.chestImgView.image=nil symptom.position="背部" self.navigationController?.pushViewController(symptom, animated: true) case 230://女性臀部 self.womenBodyView.reproductionImgView.image=nil symptom.position="臀部" self.navigationController?.pushViewController(symptom, animated: true) case 250://女性腰部 self.womenBodyView.abdominalImgView.image=nil symptom.position="腰部" self.navigationController?.pushViewController(symptom, animated: true) case 270://女性背部部 self.womenBodyView.chestImgView.image=nil symptom.position="背部" self.navigationController?.pushViewController(symptom, animated: true) default: println() } }else { if manButton.hidden==false { symptom.personType="男性" symptom.typeNum=1 }else { symptom.personType="女性" symptom.typeNum=2 } switch tag { case 10://嘴巴 self.treatmentView.mouthImageView.image=nil symptom.position="口腔" self.navigationController?.pushViewController(symptom, animated: true) case 20://眼睛 self.treatmentView.eyesImageView.image=nil symptom.position="眼部" self.navigationController?.pushViewController(symptom, animated: true) case 30://耳朵 self.treatmentView.earsImageView.image=nil symptom.position="耳部" self.navigationController?.pushViewController(symptom, animated: true) case 40://面部 self.treatmentView.faceImageView.image=nil symptom.position="面部" self.navigationController?.pushViewController(symptom, animated: true) case 50://鼻子 self.treatmentView.noseImageView.image=nil symptom.position="鼻部" self.navigationController?.pushViewController(symptom, animated: true) case 60://头部 self.treatmentView.headImageView.image=nil symptom.position="头部" self.navigationController?.pushViewController(symptom, animated: true) case 100://足部 self.footImgView.image=nil symptom.position="足部" self.navigationController?.pushViewController(symptom, animated: true) case 110://腿部 self.legImgView.image=nil symptom.position="腿部" self.navigationController?.pushViewController(symptom, animated: true) case 120://生殖部位 self.reproductionImgView.image=nil symptom.position="生殖部位" self.navigationController?.pushViewController(symptom, animated: true) case 130://腹部 self.abdominalImgView.image=nil symptom.position="腹部" self.navigationController?.pushViewController(symptom, animated: true) case 140://胸部 self.chestImgView.image=nil symptom.position="胸部" self.navigationController?.pushViewController(symptom, animated: true) case 150://手部 self.handImgView.image=nil symptom.position="手部" self.navigationController?.pushViewController(symptom, animated: true) case 160://上肢 self.limbImgView.image=nil symptom.position="上肢" self.navigationController?.pushViewController(symptom, animated: true) case 170: self.neckImageView.image=nil symptom.position="颈部" self.navigationController?.pushViewController(symptom, animated: true) case 210://女性足部 self.womenBodyView.footImgView.image=nil symptom.position="足部" self.navigationController?.pushViewController(symptom, animated: true) case 220://女性腿部 self.womenBodyView.legImgView.image=nil symptom.position="腿部" self.navigationController?.pushViewController(symptom, animated: true) case 230://女性生殖部位 self.womenBodyView.reproductionImgView.image=nil symptom.position="生殖部位" self.navigationController?.pushViewController(symptom, animated: true) case 240://女性手部 self.womenBodyView.handImgView.image=nil symptom.position="手部" self.navigationController?.pushViewController(symptom, animated: true) case 250://女性腹部 self.womenBodyView.abdominalImgView.image=nil symptom.position="腹部" self.navigationController?.pushViewController(symptom, animated: true) case 260://女性上肢 self.womenBodyView.limbImgView.image=nil symptom.position="上肢" self.navigationController?.pushViewController(symptom, animated: true) case 270://女性胸部 self.womenBodyView.chestImgView.image=nil symptom.position="胸部" self.navigationController?.pushViewController(symptom, animated: true) case 280://女性脖子 self.womenBodyView.neckImageView.image=nil symptom.position="颈部" self.navigationController?.pushViewController(symptom, animated: true) case 410://点击了女性 嘴巴 self.womenHeadView.mouthImageView.image=nil symptom.position="口腔" self.navigationController?.pushViewController(symptom, animated: true) case 420://点击了女性 鼻子 self.womenHeadView.noseImageView.image=nil symptom.position="鼻部" self.navigationController?.pushViewController(symptom, animated: true) case 430://点击了女性 面部 self.womenHeadView.faceImageView.image=nil symptom.position="面部" self.navigationController?.pushViewController(symptom, animated: true) case 440://点击了女性眼睛 self.womenHeadView.eyesImageView.image=nil symptom.position="眼部" self.navigationController?.pushViewController(symptom, animated: true) case 450://点击了女性耳朵 self.womenHeadView.earsImageView.image=nil symptom.position="耳部" self.navigationController?.pushViewController(symptom, animated: true) case 460://点击了女性头部 self.womenHeadView.headImageView.image=nil symptom.position="头部" self.navigationController?.pushViewController(symptom, animated: true) default: println() } } } //开始触摸 override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { var set=touches as NSSet let touch:UITouch=set.anyObject() as! UITouch imgViewBeganTouch(touch) } //结束触摸 override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { var set=touches as NSSet let touch:UITouch=set.anyObject() as! UITouch imgViewEndedTouch(touch) } @IBAction func btbClick(sender: AnyObject) { var tag=sender.tag var symptom=SymptomViewController() switch tag { case 10://点击了男性按钮 manButton.selected = true woManButton.selected=false if faceButton.selected==false { bodyImgView.image=UIImage(named: "man_front") }else { bodyImgView.image=UIImage(named: "man_back_view") } case 20://点击了女性按钮 var views=self.view.subviews for view in views { (view as!UIView).hidden=true } self.view.addSubview(self.womenBodyView) case 30://点击了正反面按钮 faceButton.selected = !faceButton.selected self.womenBodyView.faceButton.selected=faceButton.selected changeImage() if faceButton.selected==false { if manButton.selected==true { bodyImgView.image=UIImage(named: "man_front") }else { bodyImgView.image=UIImage(named: "woman_front") } }else { if manButton.selected==true { bodyImgView.image=UIImage(named: "man_back_view") }else { bodyImgView.image=UIImage(named: "woman_back_view") } } case 40: sender.setTitleColor(UIColor(red: 64/255.0, green: 193/255.0, blue: 218/255.0, alpha: 1), forState: UIControlState.Normal) symptom.personType="男性" symptom.typeNum=1 self.navigationController?.pushViewController(symptom, animated: true) case 300://点击了女性图 男性按钮 var views=self.view.subviews for view in views { (view as!UIView).hidden=false } self.womenBodyView.removeFromSuperview() case 310://点击了女性图 女性按钮 self.womenBodyView.woManButton.selected=true case 320://点击了女性图 正反面按钮 self.womenBodyView.faceButton.selected = !self.womenBodyView.faceButton.selected faceButton.selected=self.womenBodyView.faceButton.selected changeImage() if faceButton.selected==false { bodyImgView.image=UIImage(named: "man_front") }else { bodyImgView.image=UIImage(named: "man_back_view") } case 330://点击了女性图 身体其他症状 symptom.personType="女性" symptom.typeNum=2 self.navigationController?.pushViewController(symptom, animated: true) case 470://点击了女性头像返回按钮 self.womenHeadView.removeFromSuperview() self.womenBodyView.hidden=false case 1000://男头像点击了返回 self.treatmentView.removeFromSuperview() var views=self.view.subviews for view in views { (view as! UIView).hidden=false } default: println() } } func changeImage() { if self.womenBodyView.faceButton.selected==false { self.womenBodyView.bodyImgView.image=UIImage(named: "woman_front") }else { self.womenBodyView.bodyImgView.image=UIImage(named: "woman_back_view") } } 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 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
12fffbe062a44a2bc5a178aca4badbd5
40.113487
137
0.588991
4.535015
false
false
false
false
williamFalcon/Bolt_Swift
Source/UIWindow/UIWindow.swift
2
1757
// // UIWindow.swift // Testee // // Created by William Falcon on 7/15/15. // Copyright (c) 2015 William Falcon. All rights reserved. // import Foundation import UIKit //extension UIWindow { // // ///Finds current view controller on window // func _currentViewController() -> UIViewController? { // let current = _currentVC() // let top = _topViewController(current) // return top // } // // private func _currentVC() -> UIViewController? { // var currentVC : UIViewController? // // //Find current view controller // if let root = rootViewController { // if root is UITabBarController { // let tab = root as! UITabBarController // currentVC = tab.selectedViewController // // if currentVC is UINavigationController { // let nav = currentVC as! UINavigationController // currentVC = nav.topViewController // } // } // } // // return currentVC // } // // private func _topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window!.rootViewController) -> UIViewController? { // if let nav = base as? UINavigationController { // return _topViewController(nav.visibleViewController) // } // if let tab = base as? UITabBarController { // if let selected = tab.selectedViewController { // return _topViewController(selected) // } // } // if let presented = base?.presentedViewController { // return _topViewController(presented) // } // return base // } //}
mit
54fa6839e377a97764efcba7d51ff8db
31.555556
175
0.568583
4.761518
false
false
false
false
congncif/PagingDataController
Example/Pods/SiFUtilities/Core/UIView+Utils.swift
1
2094
// // UIView+Utils.swift // SiFUtilities // // Created by FOLY on 1/11/17. // Copyright © 2017 [iF] Solution. All rights reserved. // import Foundation import UIKit // MARK: - Methods inspired by S.w.i.f.t.e.r.S.w.i.f.t extension UIView { public var screenshot: UIImage? { UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { return nil } layer.render(in: context) return UIGraphicsGetImageFromCurrentImageContext() } public var parentViewController: UIViewController? { weak var parentResponder: UIResponder? = self while let parent = parentResponder { parentResponder = parent.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } } extension UIView { public func firstResponder() -> UIView? { var views = [UIView](arrayLiteral: self) var i = 0 repeat { let view = views[i] if view.isFirstResponder { return view } views.append(contentsOf: view.subviews) i += 1 } while i < views.count return nil } public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { let maskPath = UIBezierPath( roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius) ) let shape = CAShapeLayer() shape.path = maskPath.cgPath layer.mask = shape } public func addShadow(ofColor color: UIColor = UIColor(red: 0.07, green: 0.47, blue: 0.57, alpha: 1.0), radius: CGFloat = 3, offset: CGSize = .zero, opacity: Float = 0.5) { layer.shadowColor = color.cgColor layer.shadowOffset = offset layer.shadowRadius = radius layer.shadowOpacity = opacity layer.masksToBounds = false } }
mit
d9713f767d39a53846342ef4a85290ec
28.478873
176
0.602484
4.692825
false
false
false
false
hsavit1/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_003_Longest_Substring_Without_Repeating_Characters.swift
1
1479
/* https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ #3 Longest Substring Without Repeating Characters Level: medium Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. Inspired by @heiyanbin at https://oj.leetcode.com/discuss/6168/my-o-n-solution */ private extension String { subscript (index: Int) -> Character { let i: Index = advance(self.startIndex, index) return self[i] } } class Medium_003_Longest_Substring_Without_Repeating_Characters { // O (N) class func longest(s: String) -> Int { let len: Int = s.characters.count if len < 2 { return len } else { var d: Int = 1, maxLen: Int = 1 var map: Dictionary = Dictionary<Character, Int>() map[s[0]] = 0 for i in 1..<len { if let v = map[s[i]] { if v < i - d { d++ } else { d = i - v //redundant? } } else { d++ } map[s[i]] = i if d > maxLen { maxLen = d } } return maxLen } } }
mit
7de978077427d8567113ab70571cf261
28.6
259
0.509128
4.237822
false
false
false
false
tardieu/swift
test/Interpreter/bitvector.swift
14
1952
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test import Swift struct BitVector64 { var bits : Int64 subscript (bit : Int) -> Bool { get { if (bits & (1 << Int64(bit))) != 0 { return true } return false } set { var mask = 1 << Int64(bit) if newValue { bits = bits | mask } else { bits = bits & ~mask } } } } // Create an empty bitvector var vec = BitVector64(bits: 0) // Set even elements to 'true'. for i in 0..<64 { if i % 2 == 0 { vec[i] = true } } // Print all elements for i in 0..<64 { print("\(vec[i])") } // CHECK: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false // CHECK-NEXT: true // CHECK-NEXT: false
apache-2.0
ceccf2adc95a9230902eb88280179bd1
17.769231
48
0.610656
3.007704
false
false
false
false
coderwjq/swiftweibo
SwiftWeibo/SwiftWeibo/Classes/Compose/ComposeTextView.swift
1
1066
// // ComposeTextView.swift // SwiftWeibo // // Created by mzzdxt on 2016/11/7. // Copyright © 2016年 wjq. All rights reserved. // import UIKit class ComposeTextView: UITextView { // MARK:- 懒加载属性 lazy var placeHolderLabel: UILabel = UILabel() // MARK:- 构造函数 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } } // MARK:- 设置UI界面 extension ComposeTextView { fileprivate func setupUI() { // 添加子控件 addSubview(placeHolderLabel) // 设置frame placeHolderLabel.snp.makeConstraints { (make) in make.top.equalTo(8) make.left.equalTo(10) } // 设置placeHolderLabel的属性 placeHolderLabel.textColor = UIColor.lightGray placeHolderLabel.font = font placeHolderLabel.text = "分享新鲜事..." // 设置内容的内边距 textContainerInset = UIEdgeInsets(top: 8, left: 7, bottom: 0, right: 7) } }
apache-2.0
cf6db79634dbb51256a0994a1b87d9bd
20.933333
79
0.588652
4.445946
false
false
false
false
SwiftGen/templates
Pods/StencilSwiftKit/Sources/Parameters.swift
2
3991
// // StencilSwiftKit // Copyright (c) 2017 SwiftGen // MIT Licence // import Foundation /// Namespace to handle extra context parameters passed as a list of `foo=bar` strings. /// Typically used when parsing command-line arguments one by one /// (like `foo=bar pt.x=1 pt.y=2 values=1 values=2 values=3 flag`) /// to turn them into a dictionary structure public enum Parameters { public enum Error: Swift.Error { case invalidSyntax(value: Any) case invalidKey(key: String, value: Any) case invalidStructure(key: String, oldValue: Any, newValue: Any) } typealias Parameter = (key: String, value: Any) public typealias StringDict = [String: Any] /// Transforms a list of strings representing structured-key/value pairs, like /// `["pt.x=1", "pt.y=2", "values=1", "values=2", "values=3", "flag"]` /// into a structured dictionary. /// /// - Parameter items: The list of `k=v`-style Strings, each string /// representing either a `key=value` pair or a /// single `flag` key with no `=` (which will then /// be interpreted as a `true` value) /// - Returns: A structured dictionary matching the list of keys /// - Throws: `Parameters.Error` public static func parse(items: [String]) throws -> StringDict { let parameters: [Parameter] = try items.map { item in let parts = item.components(separatedBy: "=") if parts.count >= 2 { return (key: parts[0], value: parts.dropFirst().joined(separator: "=")) } else if let part = parts.first, parts.count == 1 && validate(key: part) { return (key: part, value: true) } else { throw Error.invalidSyntax(value: item) } } return try parameters.reduce(StringDict()) { try parse(parameter: $1, result: $0) } } // MARK: - Private methods /// Parse a single `key=value` (or `key`) string and inserts it into /// an existing StringDict dictionary being built. /// /// - Parameters: /// - parameter: The parameter/string (key/value pair) to parse /// - result: The dictionary currently being built and to which to add the value /// - Returns: The new content of the dictionary being built after inserting the new parsed value /// - Throws: `Parameters.Error` private static func parse(parameter: Parameter, result: StringDict) throws -> StringDict { let parts = parameter.key.components(separatedBy: ".") let key = parts.first ?? "" var result = result // validate key guard validate(key: key) else { throw Error.invalidKey(key: parameter.key, value: parameter.value) } // no sub keys, may need to convert to array if repeat key if possible if parts.count == 1 { if let current = result[key] as? [Any] { result[key] = current + [parameter.value] } else if let current = result[key] as? String { result[key] = [current, parameter.value] } else if let current = result[key] { throw Error.invalidStructure(key: key, oldValue: current, newValue: parameter.value) } else { result[key] = parameter.value } } else if parts.count > 1 { guard result[key] is StringDict || result[key] == nil else { throw Error.invalidStructure(key: key, oldValue: result[key] ?? "", newValue: parameter.value) } // recurse into sub keys let current = result[key] as? StringDict ?? StringDict() let sub = (key: parts.suffix(from: 1).joined(separator: "."), value: parameter.value) result[key] = try parse(parameter: sub, result: current) } return result } // a valid key is not empty and only alphanumerical or dot private static func validate(key: String) -> Bool { return !key.isEmpty && key.rangeOfCharacter(from: notAlphanumericsAndDot) == nil } private static let notAlphanumericsAndDot: CharacterSet = { var result = CharacterSet.alphanumerics result.insert(".") return result.inverted }() }
mit
afc9fe521edb22a6c661cbea373ea1ad
37.375
104
0.646455
4.031313
false
false
false
false
zhangjk4859/MyWeiBoProject
sinaWeibo/sinaWeibo/Classes/Home/JKStatusPictureView.swift
1
6152
// // JKStatusPictureView.swift // sinaWeibo // // Created by 张俊凯 on 16/7/16. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit import SDWebImage class JKStatusPictureView: UICollectionView { //设置数据源 属性的set方法 var status: JKStatus? { didSet { // 1. 刷新表格 reloadData() } } //collectionView 初始化布局 init() { super.init(frame: CGRectZero, collectionViewLayout: pictureLayout) //注册cell registerClass(PictureViewCell.self, forCellWithReuseIdentifier: JKPictureViewCellReuseIdentifier) //设置数据源 dataSource = self delegate = self //设置cell之间的间隙 pictureLayout.minimumInteritemSpacing = 10 pictureLayout.minimumLineSpacing = 10 //设置配图的背景颜色 backgroundColor = UIColor.darkGrayColor() } //计算图片尺寸 func calculateImageSize() -> CGSize { //取出配图个数 let count = status?.storedPicURLS?.count //如果没有配图zero if count == 0 || count == nil { return CGSizeZero } //如果只有一张配图, 返回图片的实际大小 if count == 1 { // 取出缓存的图片 let key = status?.storedPicURLS!.first?.absoluteString let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key!) pictureLayout.itemSize = image.size // 返回缓存图片的尺寸 return image.size } // 如果有4张配图, 计算田字格的大小 let width = 90 let margin = 10 pictureLayout.itemSize = CGSize(width: width, height: width) if count == 4 { let viewWidth = width * 2 + margin return CGSize(width: viewWidth, height: viewWidth) } // 如果是其它(多张), 计算九宫格的大小 // 计算列数 let colNumber = 3 // 计算行数 let rowNumber = (count! - 1) / 3 + 1 // 宽度 = 列数 * 图片的宽度 + (列数 - 1) * 间隙 let viewWidth = colNumber * width + (colNumber - 1) * margin // 高度 = 行数 * 图片的高度 + (行数 - 1) * 间隙 let viewHeight = rowNumber * width + (rowNumber - 1) * margin return CGSize(width: viewWidth, height: viewHeight) } //MARK -- 懒加载 //布局方法 private var pictureLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() //必须无用代码 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //内部使用的cell,一个独立的类,可以放出去 private class PictureViewCell: UICollectionViewCell { // 定义属性接收外界传入的数据 var imageURL: NSURL? { didSet{ // 1.设置图片 iconImageView.sd_setImageWithURL(imageURL!) // 2.判断是否需要显示gif图标 // GIF if (imageURL!.absoluteString as NSString).pathExtension.lowercaseString == "gif" { gifImageView.hidden = false } } } override init(frame: CGRect) { super.init(frame: frame) // 初始化UI setupUI() } //添加子控件 private func setupUI() { // 1.添加子控件 contentView.addSubview(iconImageView) iconImageView.addSubview(gifImageView) // 2.布局子控件 iconImageView.jk_Fill(contentView) gifImageView.jk_AlignInner(type: JK_AlignType.BottomRight, referView: iconImageView, size: nil) } // MARK: - 懒加载 两个控件 private lazy var iconImageView:UIImageView = UIImageView() private lazy var gifImageView: UIImageView = { let iv = UIImageView(image: UIImage(named: "avatar_vgirl")) iv.hidden = true return iv }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } //选中图片的通知名称 let JKStatusPictureViewSelected = "JKStatusPictureViewSelected" //当前选中图片的索引对应的key let JKStatusPictureViewIndexKey = "JKStatusPictureViewIndexKey" //需要展示的所有图片对应的key let JKStatusPictureViewURLsKey = "JKStatusPictureViewURLsKey" //数据源代理方法 extension JKStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return status?.storedPicURLS?.count ?? 0 } //collectionView返回cell func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 1.取出cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(JKPictureViewCellReuseIdentifier, forIndexPath: indexPath) as! PictureViewCell // 2.设置数据 cell.imageURL = status?.storedPicURLS![indexPath.item] // 3.返回cell return cell } //图片点击事件 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { print(status?.storedLargePicURLS![indexPath.item]) //选中就发送通知给主页控制器 let info = [JKStatusPictureViewIndexKey : indexPath, JKStatusPictureViewURLsKey : status!.storedLargePicURLS!] NSNotificationCenter.defaultCenter().postNotificationName(JKStatusPictureViewSelected, object: self, userInfo: info) } }
mit
0c53c7d8b256bdfe645f70754d585c70
26.743719
151
0.584133
5.055861
false
false
false
false
bamurph/FeedKit
Sources/Model/RSS/RSSFeed.swift
2
11372
// // RSSFeed.swift // // Copyright (c) 2016 Nuno Manuel Dias // // 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 /** Data model for the XML DOM of the RSS 2.0 Specification See http://cyber.law.harvard.edu/rss/rss.html At the top level, a RSS document is a <rss> element, with a mandatory attribute called version, that specifies the version of RSS that the document conforms to. If it conforms to this specification, the version attribute must be 2.0. Subordinate to the <rss> element is a single <channel> element, which contains information about the channel (metadata) and its contents. */ open class RSSFeed { /** The name of the channel. It's how people refer to your service. If you have an HTML website that contains the same information as your RSS file, the title of your channel should be the same as the title of your website. Example: GoUpstate.com News Headlines */ open var title: String? /** The URL to the HTML website corresponding to the channel. Example: http://www.goupstate.com/ */ open var link: String? /** Phrase or sentence describing the channel. Example: The latest news from GoUpstate.com, a Spartanburg Herald-Journal Web site. */ open var description: String? /** The language the channel is written in. This allows aggregators to group all Italian language sites, for example, on a single page. A list of allowable values for this element, as provided by Netscape, is here: http://cyber.law.harvard.edu/rss/languages.html You may also use values defined by the W3C: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes Example: en-us */ open var language: String? /** Copyright notice for content in the channel. Example: Copyright 2002, Spartanburg Herald-Journal */ open var copyright: String? /** Email address for person responsible for editorial content. Example: [email protected] (George Matesky) */ open var managingEditor: String? /** Email address for person responsible for technical issues relating to channel. Example: [email protected] (Betty Guernsey) */ open var webMaster: String? /** The publication date for the content in the channel. For example, the New York Times publishes on a daily basis, the publication date flips once every 24 hours. That's when the pubDate of the channel changes. All date-times in RSS conform to the Date and Time Specification of RFC 822, with the exception that the year may be expressed with two characters or four characters (four preferred). Example: Sat, 07 Sep 2002 00:00:01 GMT */ open var pubDate: Date? /** The last time the content of the channel changed. Example: Sat, 07 Sep 2002 09:42:31 GMT */ open var lastBuildDate: Date? /** Specify one or more categories that the channel belongs to. Follows the same rules as the <item>-level category element. Example: Newspapers */ open var categories: [RSSFeedCategory]? /** A string indicating the program used to generate the channel. Example: MightyInHouse Content System v2.3 */ open var generator: String? /** A URL that points to the documentation for the format used in the RSS file. It's probably a pointer to this page. It's for people who might stumble across an RSS file on a Web server 25 years from now and wonder what it is. Example: http://blogs.law.harvard.edu/tech/rss */ open var docs: String? /** Allows processes to register with a cloud to be notified of updates to the channel, implementing a lightweight publish-subscribe protocol for RSS feeds. Example: <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/> <cloud> is an optional sub-element of <channel>. It specifies a web service that supports the rssCloud interface which can be implemented in HTTP-POST, XML-RPC or SOAP 1.1. Its purpose is to allow processes to register with a cloud to be notified of updates to the channel, implementing a lightweight publish-subscribe protocol for RSS feeds. <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="myCloud.rssPleaseNotify" protocol="xml-rpc" /> In this example, to request notification on the channel it appears in, you would send an XML-RPC message to rpc.sys.com on port 80, with a path of /RPC2. The procedure to call is myCloud.rssPleaseNotify. A full explanation of this element and the rssCloud interface is here: http://cyber.law.harvard.edu/rss/soapMeetsRss.html#rsscloudInterface */ open var cloud: RSSFeedCloud? /** The PICS rating for the channel. */ open var rating: String? /** ttl stands for time to live. It's a number of minutes that indicates how long a channel can be cached before refreshing from the source. Example: 60 <ttl> is an optional sub-element of <channel>. ttl stands for time to live. It's a number of minutes that indicates how long a channel can be cached before refreshing from the source. This makes it possible for RSS sources to be managed by a file-sharing network such as Gnutella. */ open var ttl: Int? /** Specifies a GIF, JPEG or PNG image that can be displayed with the channel. <image> is an optional sub-element of <channel>, which contains three required and three optional sub-elements. <url> is the URL of a GIF, JPEG or PNG image that represents the channel. <title> describes the image, it's used in the ALT attribute of the HTML <img> tag when the channel is rendered in HTML. <link> is the URL of the site, when the channel is rendered, the image is a link to the site. (Note, in practice the image <title> and <link> should have the same value as the channel's <title> and <link>. Optional elements include <width> and <height>, numbers, indicating the width and height of the image in pixels. <description> contains text that is included in the TITLE attribute of the link formed around the image in the HTML rendering. Maximum value for width is 144, default value is 88. Maximum value for height is 400, default value is 31. */ open var image: RSSFeedImage? /** Specifies a text input box that can be displayed with the channel. A channel may optionally contain a <textInput> sub-element, which contains four required sub-elements. <title> -- The label of the Submit button in the text input area. <description> -- Explains the text input area. <name> -- The name of the text object in the text input area. <link> -- The URL of the CGI script that processes text input requests. The purpose of the <textInput> element is something of a mystery. You can use it to specify a search engine box. Or to allow a reader to provide feedback. Most aggregators ignore it. */ open var textInput: RSSFeedTextInput? /** A hint for aggregators telling them which hours they can skip. An XML element that contains up to 24 <hour> sub-elements whose value is a number between 0 and 23, representing a time in GMT, when aggregators, if they support the feature, may not read the channel on hours listed in the skipHours element. The hour beginning at midnight is hour zero. */ open var skipHours: [RSSFeedSkipHour]? /** A hint for aggregators telling them which days they can skip. An XML element that contains up to seven <day> sub-elements whose value is Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday. Aggregators may not read the channel during days listed in the skipDays element. */ open var skipDays: [RSSFeedSkipDay]? /** A channel may contain any number of <item>s. An item may represent a "story" -- much like a story in a newspaper or magazine; if so its description is a synopsis of the story, and the link points to the full story. An item may also be complete in itself, if so, the description contains the text (entity-encoded HTML is allowed; see examples: http://cyber.law.harvard.edu/rss/encodingDescriptions.html), and the link and title may be omitted. All elements of an item are optional, however at least one of title or description must be present. */ open var items: [RSSFeedItem]? // MARK: - Namespaces /** The Dublin Core Metadata Element Set is a standard for cross-domain resource description. See https://tools.ietf.org/html/rfc5013 */ open var dublinCore: DublinCoreNamespace? /** Provides syndication hints to aggregators and others picking up this RDF Site Summary (RSS) feed regarding how often it is updated. For example, if you updated your file twice an hour, updatePeriod would be "hourly" and updateFrequency would be "2". The syndication module borrows from Ian Davis's Open Content Syndication (OCS) directory format. It supercedes the RSS 0.91 skipDay and skipHour elements. See http://web.resource.org/rss/1.0/modules/syndication/ */ open var syndication: SyndicationNamespace? /** iTunes Podcasting Tags are de facto standard for podcast syndication. For more information see https://help.apple.com/itc/podcasts_connect/#/itcb54353390 */ open var iTunes: ITunesNamespace? }
mit
edaf5b760da602cf269cf5f9b9e85502
31.678161
158
0.662768
4.5488
false
false
false
false
damianesteban/Github-Swift
Github/Login/Login.swift
1
3129
// // Login.swift // Github // // Created by Austin Cherry on 6/3/14. // Copyright (c) 2014 Vluxe. All rights reserved. // import SwiftHTTP import JSONJoy struct App: JSONJoy { var url: String? var name: String? var clientId: String? init(_ decoder: JSONDecoder) { url = decoder["url"].string name = decoder["name"].string clientId = decoder["client_id"].string } } struct Authorization: JSONJoy { var id: Int? var url: String? //var scopes: Array<String>? var app: App? var token: String? var note: String? var noteUrl: String? //var updatedAt: String? //var createdAt: String? init(_ decoder: JSONDecoder) { id = decoder["id"].integer url = decoder["url"].string //decoder["scopes"].array(&scopes) app = App(decoder["app"]) token = decoder["token"].string note = decoder["note"].string noteUrl = decoder["note_url"].string //updatedAt = decoder["updated_at"].string //createdAt = decoder["created_at"].string } } struct Login { let clientId = "80b1798b0b410dd723ee" let clientSecret = "58b7abd90008cb39626802d4bb9444c53d9d79ad" var basicAuth = "" init(username: String, password: String) { let optData = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding) if let data = optData { basicAuth = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) } } func auth(completionHandler: (Bool -> Void)) -> Void { var request = HTTPTask() request.requestSerializer = JSONRequestSerializer() request.responseSerializer = JSONResponseSerializer() request.requestSerializer.headers = ["Authorization": "Basic \(basicAuth)"] let params = ["scopes":"repo", "note": "dev", "client_id": clientId, "client_secret": clientSecret] request.POST("https://api.github.com/authorizations", parameters: params, completionHandler: {(response: HTTPResponse) -> Void in if let err = response.error { println("error: \(err.localizedDescription)") dispatch_async(dispatch_get_main_queue(),{ completionHandler(false) }) return //also notify app of failure as needed } if let obj: AnyObject = response.responseObject { let auth = Authorization(JSONDecoder(obj)) if let token = auth.token { println("token: \(token)") let defaults = NSUserDefaults() defaults.setObject(token, forKey: "token") defaults.synchronize() dispatch_async(dispatch_get_main_queue(),{ completionHandler(true) }) } else { dispatch_async(dispatch_get_main_queue(),{ completionHandler(false) }) } } }) } }
mit
7c9176ef8914eb8e2c5a0b87e03c3c10
32.655914
137
0.568552
4.698198
false
false
false
false
LeoMobileDeveloper/PullToRefreshKit
Demo/Demo/DefaultTableViewController.swift
1
2448
// // WebviewController.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/13. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit import PullToRefreshKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } class DefaultTableViewController:UITableViewController{ let originalModes = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] var models = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView(frame: CGRect.zero) self.tableView.configRefreshHeader(container:self) { [weak self] in delay(1.5, closure: { guard let vc = self else{ return; } vc.models = vc.originalModes.map{_ in random100()} vc.tableView.switchRefreshHeader(to: .normal(.success, 0.5)) vc.tableView.reloadData() }) } self.tableView.configRefreshFooter(container:self) { [weak self] in delay(1.5, closure: { guard let vc = self else{ return; } vc.models.append(random100()) vc.tableView.reloadData() if vc.models.count < 18 { vc.tableView.switchRefreshFooter(to: .normal) }else{ vc.tableView.switchRefreshFooter(to: .noMoreData) } }) }; self.tableView.switchRefreshHeader(to: .refreshing) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell?.textLabel?.text = "\(models[(indexPath as NSIndexPath).row])" return cell! } deinit{ print("Deinit of DefaultTableViewController") } }
mit
e4fa003c8db403f826395e6ad655165f
32.958333
109
0.582413
4.297012
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/SafeWalk/model/SafeWalkClient.swift
1
2467
// // SafeWalkClient.swift // byuSuite // // Created by Erik Brady on 8/3/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import MapKit private let BASE_URL = "https://api.byu.edu/domains/safewalk/v1" class SafeWalkClient: ByuClient2 { static func createSession(destination: SafeWalkCoordinateInfo, callback: @escaping (Int?, ByuError?) -> Void) { makeRequest(method: .POST, body: destination.toDict()) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any], let responseInt = data["id"] as? Int { callback(responseInt, nil) } else { callback(nil, response.error) } } } static func updateLocation(sessionId: Int, coordinate: SafeWalkCoordinateInfo, callback: @escaping(ByuError?) -> Void) { makeRequest(method: .PUT, pathParams: ["\(sessionId)"], body: coordinate.toDict()) { (response) in if response.failed { callback(response.error) } else { callback(nil) } } } static func reportEmergency(sessionId: Int, location: SafeWalkCoordinateInfo, callback: @escaping (ByuError?) -> Void) { makeRequest(method: .POST, pathParams: ["\(sessionId)", "emergency"], body: location.toDict()) { (response) in if response.failed { callback(response.error) } else { callback(nil) } } } static func finishSession(sessionId: Int, callback: @escaping (ByuError?) -> Void) { makeRequest(method: .DELETE, pathParams: ["\(sessionId)"]) { (response) in if response.failed { callback(response.error) } else { callback(nil) } } } private static func makeRequest(method: ByuRequest2.RequestMethod, pathParams: [String]? = nil, body: [String: Any]? = nil, callback: @escaping (ByuResponse2) -> Void) { var data: Data? if let body = body { data = try? JSONSerialization.data(withJSONObject: body, options: []) } let request = ByuRequest2(requestMethod: method, url: super.url(base: BASE_URL, pathParams: pathParams), contentType: .JSON, body: data, pathToReadableError: "Message") makeRequest(request, callback: callback) } }
apache-2.0
ae820233c7a631a40e2817dc78b5798e
35.80597
176
0.582725
4.403571
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Aztec/Processors/VideoUploadProcessor.swift
2
1506
import Foundation import Aztec import WordPressEditor class VideoUploadProcessor: Processor { let mediaUploadID: String let remoteURLString: String let videoPressID: String? init(mediaUploadID: String, remoteURLString: String, videoPressID: String?) { self.mediaUploadID = mediaUploadID self.remoteURLString = remoteURLString self.videoPressID = videoPressID } lazy var videoPostMediaUploadProcessor = ShortcodeProcessor(tag: "video", replacer: { (shortcode) in guard let uploadValue = shortcode.attributes[MediaAttachment.uploadKey]?.value, case let .string(uploadID) = uploadValue, self.mediaUploadID == uploadID else { return nil } var html = "" if let videoPressGUID = self.videoPressID { html = "[wpvideo " html += videoPressGUID html += " ]" } else { html = "[video " var updatedAttributes = shortcode.attributes updatedAttributes.set(.string(self.remoteURLString), forKey: "src") //remove the uploadKey updatedAttributes.remove(key: MediaAttachment.uploadKey) let attributeSerializer = ShortcodeAttributeSerializer() html += attributeSerializer.serialize(updatedAttributes) html += "]" } return html }) func process(_ text: String) -> String { return videoPostMediaUploadProcessor.process(text) } }
gpl-2.0
77780e9eca8c88e272ae17ff056bf405
31.042553
104
0.634794
4.905537
false
false
false
false
raginmari/RAGTextField
Sources/RAGTextField/Classes/Views/UnderlineView.swift
1
11633
// // Copyright (c) 2019 Reimar Twelker // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit /// Draws two colored lines at the bottom on top of one another that extend from the left to the right edge. /// /// The foreground line is initially not visible. It can be expanded to fully cover the background line. /// The expansion can be animated in different ways. /// /// - Note /// The view is meant to be used with `RAGTextField`. Set it as the `textBackgroundView` to approximate the look and feel of a /// Material text field. The expansion of the line has to be controlled manually, for example from the text field delegate. open class UnderlineView: UIView { /// The different ways in which the expanding line is animated. public enum Mode { /// The line equally expands from the center of the view to its left and right edges. case expandsFromCenter /// The line expands from the right edge of the view to the left. case expandsFromRight /// The line expands from the left edge of the view to the right. case expandsFromLeft /// The line expands from the leading edge of the view to the trailing one. case expandsInUserInterfaceDirection /// The line is not animated. case notAnimated } /// The width of both the foreground line in points. @IBInspectable open var foregroundLineWidth: CGFloat = 1.0 { didSet { heightConstraint?.constant = foregroundLineWidth } } /// The color of the background line. @IBInspectable open var backgroundLineColor: UIColor = .clear { didSet { underlineBackgroundView.backgroundColor = backgroundLineColor } } /// The color of the foreground line. @IBInspectable open var foregroundLineColor: UIColor = .black { didSet { underlineView.backgroundColor = foregroundLineColor } } /// The way the foreground line is expanded. open var expandMode: Mode = .expandsFromCenter { didSet { setNeedsUpdateConstraints() } } /// The duration of the animation of the foreground line. open var expandDuration: TimeInterval = 0.2 private let underlineView = UIView() private let underlineBackgroundView = UIView() /// Used to pin the foreground line to the leading edge of the view. /// /// Enabled and disabled depending on the `expandMode` value. private var leadingConstraint: NSLayoutConstraint? /// Used to pin the foreground line to the trailing edge of the view. /// /// Enabled and disabled depending on the `expandMode` value. private var trailingConstraint: NSLayoutConstraint? /// Used to animate the foreground line. private var widthConstraint: NSLayoutConstraint? /// Updated when `lineWidth` is changed. private var heightConstraint: NSLayoutConstraint? /// If `true`, the foreground line is currently expanded. private var isExpanded = false /// Whether the underline is animated when the associated text field begins editing. /// /// If `false`, the underline is updated but not animated. The default value is `true`. /// /// - Note /// For this property to take effect, the `textField` property must be set. open var animatesWhenEditingBegins = true /// Whether the underline is animated when the associated text field ends editing. /// /// If `false`, the underline is updated but not animated. The default value is `true`. /// /// - Note /// For this property to take effect, the `textField` property must be set. open var animatesWhenEditingEnds = true /// Refers to the text field whose editing state is used to update the appearance of the underline automatically. /// /// If `nil`, the appearance of the underline must be updated manually, for example from a view controller or text field delegate. open weak var textField: UITextField? { didSet { if let oldTextField = oldValue { stopObserving(oldTextField) } if let newTextField = textField { startObserving(newTextField) } } } /// The tint color of the `UIView` overwrites the current `expandedLineColor`. open override var tintColor: UIColor! { didSet { foregroundLineColor = tintColor } } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { addSubview(underlineBackgroundView) addSubview(underlineView) setUpUnderlineBackground() setUpUnderline() } /// Sets up the underline background view. Sets properties and configures constraints. private func setUpUnderlineBackground() { underlineBackgroundView.backgroundColor = backgroundLineColor underlineBackgroundView.translatesAutoresizingMaskIntoConstraints = false let views = ["v": underlineBackgroundView] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v]|", options: [], metrics: nil, views: views)) // Cling to the bottom of the view underlineBackgroundView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true // Always be as high as the underline let onePixel = 1.0 / UIScreen.main.scale underlineBackgroundView.heightAnchor.constraint(equalToConstant: onePixel).isActive = true } /// Sets up the underline view. Sets properties and configures constraints. private func setUpUnderline() { underlineView.backgroundColor = foregroundLineColor underlineView.translatesAutoresizingMaskIntoConstraints = false // Cling to the bottom of the view underlineView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true heightConstraint = underlineView.heightAnchor.constraint(equalToConstant: foregroundLineWidth) heightConstraint?.isActive = true // (De)activating the higher priority width constraint animates the underline widthConstraint = underlineView.widthAnchor.constraint(equalTo: widthAnchor) widthConstraint?.priority = .defaultHigh let zeroWidthConstraint = underlineView.widthAnchor.constraint(equalToConstant: 0.0) zeroWidthConstraint.priority = .defaultHigh - 1 zeroWidthConstraint.isActive = true leadingConstraint = underlineView.leadingAnchor.constraint(equalTo: leadingAnchor) // Do not activate just yet trailingConstraint = underlineView.trailingAnchor.constraint(equalTo: trailingAnchor) // Do not activate just yet // Center with low priority let centerConstraint = underlineView.centerXAnchor.constraint(equalTo: centerXAnchor) centerConstraint.priority = .defaultLow centerConstraint.isActive = true setNeedsUpdateConstraints() } private func stopObserving(_ textField: UITextField) { NotificationCenter.default.removeObserver(self, name: UITextField.textDidBeginEditingNotification, object: textField) NotificationCenter.default.removeObserver(self, name: UITextField.textDidEndEditingNotification, object: textField) } private func startObserving(_ textField: UITextField) { NotificationCenter.default.addObserver(self, selector: #selector(onDidBeginEditing(_:)), name: UITextField.textDidBeginEditingNotification, object: textField) NotificationCenter.default.addObserver(self, selector: #selector(onDidEndEditing(_:)), name: UITextField.textDidEndEditingNotification, object: textField) } @objc private func onDidBeginEditing(_ notification: Notification) { setExpanded(true, animated: animatesWhenEditingBegins) } @objc private func onDidEndEditing(_ notification: Notification) { setExpanded(false, animated: animatesWhenEditingEnds) } open override func updateConstraints() { // Enable the leading and trailing constraints depending on the `expandMode`. switch expandMode { case .expandsFromCenter, .notAnimated: leadingConstraint?.isActive = false trailingConstraint?.isActive = false case .expandsFromRight where UIApplication.shared.userInterfaceLayoutDirection == .leftToRight: leadingConstraint?.isActive = false trailingConstraint?.isActive = true case .expandsFromRight: leadingConstraint?.isActive = true trailingConstraint?.isActive = false case .expandsFromLeft where UIApplication.shared.userInterfaceLayoutDirection == .leftToRight: leadingConstraint?.isActive = true trailingConstraint?.isActive = false case .expandsFromLeft: leadingConstraint?.isActive = false trailingConstraint?.isActive = true case .expandsInUserInterfaceDirection: leadingConstraint?.isActive = true trailingConstraint?.isActive = false } super.updateConstraints() } /// Sets the foreground line to its expanded or contracted state depending on the given parameter. Optionally, the change is animated. /// /// - Parameters: /// - expanded: If `true`, the line is expanded. /// - animated: If `true`, the change is animated. open func setExpanded(_ expanded: Bool, animated: Bool) { guard expanded != isExpanded else { return } widthConstraint?.isActive = expanded if animated && expandMode != .notAnimated { UIView.animate(withDuration: expandDuration) { [unowned self] in self.layoutIfNeeded() } } isExpanded = expanded } }
mit
21858508e30d42f4ee1a18af6ac9043a
39.113793
138
0.654517
5.767476
false
false
false
false
PatrickChow/Swift-Awsome
News/Modules/Profile/Setting/View/SettingsCell.swift
1
3779
// // Created by Patrick Chow on 2017/5/26. // Copyright (c) 2017 Jiemian Technology. All rights reserved. import UIKit import SnapKit import RxSwift import RxCocoa class SettingsCell: UITableViewCell { var viewModel = PublishSubject<SettingsOption>() fileprivate var disposeBag = DisposeBag() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) accessoryType = .none backgroundColor = .clear textLabel?.font = UIFont.systemFont(ofSize: (15, 16, 17)) textLabel?.nv.textColor(UIColor(hexNumber: 0x666666), night: UIColor(hexNumber: 0xd7d7d7)) detailTextLabel?.font = UIFont.systemFont(ofSize: 13) detailTextLabel?.nv.textColor(UIColor(hexNumber: 0x666666), night: UIColor(hexNumber: 0xd7d7d7)) viewModel.map { $0.description }.bind(to: textLabel!.rx.text).disposed(by: disposeBag) viewModel.map { $0.detail }.bind(to: detailTextLabel!.rx.text).disposed(by: disposeBag) viewModel.map { feature -> UITableViewCellSelectionStyle in if feature == .version || feature == .notification || feature == .cellularData { return .none } return .gray } .bind(to: self.rx.selectionStyle) .disposed(by: disposeBag) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setViewModel(_ viewModel: SettingsOption) { self.viewModel.onNext(viewModel) } } class SettingsIconCell: SettingsCell { var iconImageView = UIImageView(image: UIImage(named: .icon(.about))) public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) accessoryView = iconImageView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SettingsSwitchCell: SettingsCell { public var preparingForReuse: Observable<Void> { return _preparingForReuse.asObserver() } public var isOn: Observable<Bool> { return _isOn.asObserver() } fileprivate var _preparingForReuse = PublishSubject<Void>() fileprivate var _isOn = PublishSubject<Bool>() fileprivate var switchView = UISwitch() override func prepareForReuse() { super.prepareForReuse() _preparingForReuse.onNext(()) setupSubscription() } public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) switchView.onTintColor = UIColor(hexNumber: 0x3bc1e9) switchView.tintColor = UIColor(hexNumber: 0xe5e7ea) accessoryView = switchView setupSubscription() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupSubscription() { disposeBag = DisposeBag() switchView.rx .isOn.subscribe(onNext: { [weak self] in self?._isOn.onNext($0) }) .disposed(by: disposeBag) // 由于初始的 `disposeBag` 被释放了,所以这里要重新绑定 `text` viewModel.map { $0.description } .bind(to: textLabel!.rx.text) .disposed(by: disposeBag) viewModel.map { $0.detail } .bind(to: detailTextLabel!.rx.text) .disposed(by: disposeBag) } }
mit
fb0a4a87af098f5effe96baffb2b69c6
30.436975
104
0.619086
4.753494
false
false
false
false
azizuysal/NetKit
NetKitExample/NetKitExample/ServiceController.swift
1
6099
// // ServiceController.swift // NetKitExample // // Created by Aziz Uysal on 2/17/16. // Copyright © 2016 Aziz Uysal. All rights reserved. // import Foundation import NetKit struct ServiceResult { static let success = "success" static let error = "error" } class ServiceController { private static let jsonService = JsonService() private static let serviceWithDelegate = ServiceWithDelegate() private static let weatherService = GlobalWeatherService() private static let downloadService = DownloadService() private static let networkQueueSerial = DispatchQueue(label: "networkQueueSerial", attributes: []) private static let networkQueueParallel = DispatchQueue(label: "networkQueueParallel", attributes: DispatchQueue.Attributes.concurrent) private static let downloadQueue = DispatchQueue(label: "downloadQueue", attributes: []) // MARK: ExampleService class func getPostsSync() -> Any { var result: Any = [] jsonService.getPosts() // .respondOnCurrentQueue(true) .responseJSON { json in result = json notifyUser(.postsDownloaded) return .success } .responseError { error in print(error) notifyUser(.postsDownloaded, error: error) } .resumeAndWait(1) return result } class func getPosts() { _ = networkQueueSerial.sync { jsonService.getPosts() .setURLParameters(["dummy":"domain\\+dummy"]) .responseJSON { json in print(json) notifyUser(.postsDownloaded) return .success } .responseError { error in print(error) notifyUser(.postsDownloaded, error: error) } .resumeAndWait() } } class func addPost(_ post: Post) { networkQueueParallel.async { jsonService.addPost() .setJSON(post.toJson()) .responseJSON { json in print(json) notifyUser(.postsCreated) return .success } .responseError { error in print(error) notifyUser(.postsCreated, error: error) } .resume() } } class func updatePost(_ post: Post) { networkQueueParallel.async { jsonService.updatePost() .setPath(String(post.id)) .setJSON(post.toJson()) .responseJSON { json in print(json) notifyUser(.postsUpdated) return .success } .responseError { error in print(error) notifyUser(.postsUpdated, error: error) } .resume() } } // MARK: ServiceWithDelegate class func getComments() { _ = networkQueueSerial.sync { serviceWithDelegate.getComments() .responseJSON { json in print(json) notifyUser(.commentsDownloaded) return .success } .responseError { error in print(error) notifyUser(.commentsDownloaded, error: error) } .resume() } } // MARK: GlobalWeatherService class func getCities(_ country: String) { _ = networkQueueSerial.sync { weatherService.getCitiesByCountry() .setURLParameters(["op":"GetCitiesByCountry"]) .setSOAP("<GetCitiesByCountry xmlns=\"http://www.webserviceX.NET\"><CountryName>\(country)</CountryName></GetCitiesByCountry>") .response { data, url, response in // print(String(data: data!, encoding: NSUTF8StringEncoding)) notifyUser(.receivedCities) return .success } .responseError { error in print(error) notifyUser(.receivedCities, error: error) } .resume() } } class func downloadFile(_ filename: String) { downloadQueue.async { downloadService.getFile() .setCachePolicy(.reloadIgnoringLocalAndRemoteCacheData) .setPath(filename) .responseFile { (url, response) in let path = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first?.appendingPathComponent("Documents") do { try FileManager.default.createDirectory(at: path!, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print(error.localizedDescription) return .failure(error) } if let url = url, let response = response, let filename = response.suggestedFilename, let path = path?.appendingPathComponent(filename) { do { if FileManager.default.fileExists(atPath: path.path) { try FileManager.default.removeItem(at: path) } try FileManager.default.copyItem(at: url, to: path) } catch let error as NSError { print(error.localizedDescription) return .failure(error) } } else { return .failure(WebServiceError.badData("File parameter is nil")) } notifyUser(.fileDownloaded, filename: response?.suggestedFilename) return .success } .responseError { error in print(error) notifyUser(.fileDownloaded, error: error) } .resumeAndWait() } } // MARK: Private methods private class func notifyUser(_ event: Notification.Name, error: Error? = nil, filename: String? = nil) { var userInfo = [String:AnyObject]() userInfo = [ServiceResult.success:true as AnyObject] if let error = error { userInfo[ServiceResult.success] = false as AnyObject? userInfo[ServiceResult.error] = error as NSError } if let filename = filename { userInfo[DownloadService.fileName] = filename as AnyObject? } NotificationCenter.default.post(name: event, object: nil, userInfo: userInfo) } } // MARK: Errors enum WebServiceError: Error, CustomStringConvertible { case badResponse(String) case badData(String) var description: String { switch self { case let .badResponse(info): return info case let .badData(info): return info } } }
mit
163a31e8f681f344271d60c737a1224b
28.458937
147
0.619055
4.752923
false
false
false
false
anirudh24seven/wikipedia-ios
Wikipedia/Code/WMFAlertManager.swift
1
7265
import UIKit import MessageUI import TSMessages extension NSError { public func alertMessage() -> String { if(self.wmf_isNetworkConnectionError()){ return localizedStringForKeyFallingBackOnEnglish("alert-no-internet") }else{ return self.localizedDescription } } public func alertType() -> TSMessageNotificationType { if(self.wmf_isNetworkConnectionError()){ return .Warning }else{ return .Error } } } public class WMFAlertManager: NSObject, TSMessageViewProtocol, MFMailComposeViewControllerDelegate { public static let sharedInstance = WMFAlertManager() override init() { super.init() TSMessage.addCustomDesignFromFileWithName("AlertDesign.json") TSMessage.sharedMessage().delegate = self } public func showInTheNewsAlert(message: String, sticky:Bool, dismissPreviousAlerts:Bool, tapCallBack: dispatch_block_t?) { if (message ?? "").isEmpty { return } self.showAlert(dismissPreviousAlerts, alertBlock: { () -> Void in TSMessage.showNotificationInViewController(nil, title: localizedStringForKeyFallingBackOnEnglish("in-the-news-title"), subtitle: message, image: UIImage(named:"trending-notification-icon"), type: .Message, duration: sticky ? -1 : 2, callback: tapCallBack, buttonTitle: nil, buttonCallback: {}, atPosition: .Top, canBeDismissedByUser: true) }) } public func showAlert(message: String, sticky:Bool, dismissPreviousAlerts:Bool, tapCallBack: dispatch_block_t?) { if (message ?? "").isEmpty { return } self.showAlert(dismissPreviousAlerts, alertBlock: { () -> Void in TSMessage.showNotificationInViewController(nil, title: message, subtitle: nil, image: nil, type: .Message, duration: sticky ? -1 : 2, callback: tapCallBack, buttonTitle: nil, buttonCallback: {}, atPosition: .Top, canBeDismissedByUser: true) }) } public func showSuccessAlert(message: String, sticky:Bool,dismissPreviousAlerts:Bool, tapCallBack: dispatch_block_t?) { self.showAlert(dismissPreviousAlerts, alertBlock: { () -> Void in TSMessage.showNotificationInViewController(nil, title: message, subtitle: nil, image: nil, type: .Success, duration: sticky ? -1 : 2, callback: tapCallBack, buttonTitle: nil, buttonCallback: {}, atPosition: .Top, canBeDismissedByUser: true) }) } public func showWarningAlert(message: String, sticky:Bool,dismissPreviousAlerts:Bool, tapCallBack: dispatch_block_t?) { self.showAlert(dismissPreviousAlerts, alertBlock: { () -> Void in TSMessage.showNotificationInViewController(nil, title: message, subtitle: nil, image: nil, type: .Warning, duration: sticky ? -1 : 2, callback: tapCallBack, buttonTitle: nil, buttonCallback: {}, atPosition: .Top, canBeDismissedByUser: true) }) } public func showErrorAlert(error: NSError, sticky:Bool,dismissPreviousAlerts:Bool, tapCallBack: dispatch_block_t?) { self.showAlert(dismissPreviousAlerts, alertBlock: { () -> Void in TSMessage.showNotificationInViewController(nil, title: error.alertMessage(), subtitle: nil, image: nil, type: error.alertType(), duration: sticky ? -1 : 2, callback: tapCallBack, buttonTitle: nil, buttonCallback: {}, atPosition: .Top, canBeDismissedByUser: true) }) } public func showErrorAlertWithMessage(message: String, sticky:Bool,dismissPreviousAlerts:Bool, tapCallBack: dispatch_block_t?) { self.showAlert(dismissPreviousAlerts, alertBlock: { () -> Void in TSMessage.showNotificationInViewController(nil, title: message, subtitle: nil, image: nil, type: .Error, duration: sticky ? -1 : 2, callback: tapCallBack, buttonTitle: nil, buttonCallback: {}, atPosition: .Top, canBeDismissedByUser: true) }) } func showAlert(dismissPreviousAlerts:Bool, alertBlock: dispatch_block_t){ if(dismissPreviousAlerts){ TSMessage.dismissAllNotificationsWithCompletion({ () -> Void in alertBlock() }) }else{ alertBlock() } } public func dismissAlert() { TSMessage.dismissActiveNotification() } public func dismissAllAlerts() { TSMessage.dismissAllNotifications() } public func customizeMessageView(messageView: TSMessageView!) { if(messageView.notificationType == .Message){ messageView.contentFont = UIFont.systemFontOfSize(14, weight: UIFontWeightSemibold) messageView.titleFont = UIFont.systemFontOfSize(12) } } public func showEmailFeedbackAlertViewWithError(error: NSError) { let message = localizedStringForKeyFallingBackOnEnglish("request-feedback-on-error") showErrorAlertWithMessage(message, sticky: true, dismissPreviousAlerts: true) { self.dismissAllAlerts() if MFMailComposeViewController.canSendMail() { guard let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController else { return } let vc = MFMailComposeViewController() vc.setSubject("Bug:\(WikipediaAppUtils.versionedUserAgent())") vc.setToRecipients(["[email protected]"]) vc.mailComposeDelegate = self vc.setMessageBody("Domain:\t\(error.domain)\nCode:\t\(error.code)\nDescription:\t\(error.localizedDescription)\n\n\n\nVersion:\t\(WikipediaAppUtils.versionedUserAgent())", isHTML: false) rootVC.presentViewController(vc, animated: true, completion: nil) } else { self.showErrorAlertWithMessage(localizedStringForKeyFallingBackOnEnglish("no-email-account-alert"), sticky: false, dismissPreviousAlerts: false, tapCallBack: nil) } } } public func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } }
mit
8728f87800f49255baba74ae092afb72
35.507538
202
0.580179
5.644911
false
false
false
false
thefuntasty/TagView
Pod/Classes/TagView.swift
1
12634
// // TagView.swift // TagView // // Created by Martin Pinka on 24.02.16. // Copyright © 2016 Martin Pinka. All rights reserved. // import UIKit public class TagView: UIView, UIScrollViewDelegate { public enum Align { case Center case Left case Right } var tapRecognizer : UITapGestureRecognizer? public var selectionEnabled : Bool = false { didSet { if selectionEnabled { self.addGestureRecognizer(tapRecognizer!) } else { self.removeGestureRecognizer(tapRecognizer!) } } } public var dataSource : TagViewDataSource? public var delegate : TagViewDelegate? public var align : Align = .Center public var cellInsets : UIEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5) var contentHeight : CGFloat = 0.0 var tagViews : [TagViewCell] = [] var contentView = UIScrollView() var contentViewToBottomConstraint: NSLayoutConstraint! public var enabledScrolling : Bool = true { didSet { self.contentView.scrollEnabled = enabledScrolling } } /// UIPageControl is added to superview on-demand in `showPageControl:` method private(set) public var pageControl = UIPageControl() private let kPageControlHeight: CGFloat = 15.0 /// Set a value for max allowed height of contentView or nil for unlimited height public var maxAllowedHeight: Float? { willSet { if newValue <= 0 { fatalError("Value for 'maxAllowedHeight' must be greater than zero.") } } } /// Set a value for max allowed number of rows of contentView or nil for unlimited rows public var maxAllowedRows: UInt? /// current number of pages private(set) var numberOfPages = 1 // MARK: - UIView life cycle required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } override public init(frame: CGRect) { super.init(frame: frame) configure() } override public func layoutSubviews() { super.layoutSubviews() reloadData() invalidateIntrinsicContentSize() } func configure() { tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TagView.tapSelect(_:))) selectionEnabled = false contentView.pagingEnabled = true contentView.showsHorizontalScrollIndicator = false contentView.delegate = self addSubview(contentView) contentView.translatesAutoresizingMaskIntoConstraints = false let bindings = ["contentView": contentView] self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings) self.addConstraints(verticalConstraints) self.contentViewToBottomConstraint = verticalConstraints.last! } public func selectTagAtIndex(index:Int) { tagViews[index].selected = true } public func deselectTagAtIndex(index:Int) { tagViews[index].selected = false } func tapSelect (sender : UITapGestureRecognizer) { if (sender.state != .Ended) { return } let loc = sender.locationInView(self) if let tagView = self.hitTest(loc, withEvent: nil) as? TagViewCell { tagView.selected = !tagView.selected if tagView.selected { delegate?.tagView(self, didSelectTagAtIndex: tagView.index) } else { delegate?.tagView(self, didDeselectTagAtIndex: tagView.index) } } } // MARK: - Layout public func reloadData() { contentHeight = 0 var y : CGFloat = 0 var line = 0 for subview in tagViews { subview.removeFromSuperview() } tagViews = [] guard let dataSource = dataSource else { self.contentView.contentSize = CGSizeZero invalidateIntrinsicContentSize() return } let selfWidth = intrinsicContentSize().width var currentPageIndex: Int = 0 var pages: [[[TagViewCell]]] = [[]] // [page][row][item] var rowsWidth : [[CGFloat]] = [[]] // [page][row] = width var currentLine : [TagViewCell] = [] var currentLineWidth : CGFloat = 0 let numberOfTags = dataSource.numberOfTags(self) if numberOfTags == 0 { self.contentView.contentSize = CGSizeZero invalidateIntrinsicContentSize() return } func isNewPageRequired() -> Bool { let newRowCount = pages[currentPageIndex].count + 1 let newPageHeight = (dataSource.heightOfTag(self) + self.cellInsets.top + cellInsets.bottom) * (CGFloat(newRowCount) ) if let maxAllowedRows = self.maxAllowedRows where newRowCount > Int(maxAllowedRows) { return true } else if let maxAllowedHeight = self.maxAllowedHeight where Float(newPageHeight) > maxAllowedHeight { return true } else { return false } } func addNewPage() { currentPageIndex += 1 pages.append([]) rowsWidth.append([]) y = 0 } for i in 0..<numberOfTags { let cell = dataSource.tagCellForTagView(self, index: i) tagViews.append(cell) let size = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) cell.frame = CGRectMake(0, 0, size.width, dataSource.heightOfTag(self)) cell.height.constant = dataSource.heightOfTag(self) cell.index = i var tagWidth = cell.frame.size.width tagWidth += cellInsets.left + cellInsets.right var fullLine = false if currentLineWidth + tagWidth < selfWidth { currentLineWidth += tagWidth currentLine.append(cell) } else { fullLine = true } if i == numberOfTags - 1 || fullLine { // put the line on the next page if needed if isNewPageRequired() { addNewPage() } pages[currentPageIndex].append(currentLine) rowsWidth[currentPageIndex].append(currentLineWidth) currentLine = [] currentLineWidth = 0 line += 1 } if fullLine { currentLineWidth = tagWidth currentLine = [cell] y += cellInsets.top + dataSource.heightOfTag(self) } } if currentLine.count > 0 { if isNewPageRequired() { addNewPage() } // we're done, finish off by adding the last row pages[currentPageIndex].append(currentLine) rowsWidth[currentPageIndex].append(currentLineWidth) } // Add all pages of rows of cell views to this view // and update contentHeight for pageIndex in 0..<pages.count { let currentPageHeight = (dataSource.heightOfTag(self) + self.cellInsets.top + cellInsets.bottom) * CGFloat(pages[pageIndex].count) contentHeight = max(contentHeight, currentPageHeight) for lineIndex in 0..<pages[pageIndex].count { self.addLine(lineIndex, ofTagViewCells: pages[pageIndex][lineIndex], currentLineWidth: rowsWidth[pageIndex][lineIndex], toPage: pageIndex) } } numberOfPages = pages.count if numberOfPages > 1 { showPageControl(withPageCount: numberOfPages) } else { hidePageControl() } self.contentView.contentSize = CGSizeMake(self.bounds.width * CGFloat(numberOfPages), contentHeight) self.invalidateIntrinsicContentSize() } func addLine(line : Int, ofTagViewCells cells : [TagViewCell], currentLineWidth : CGFloat, toPage pageIndex: Int) { let selfWidth = intrinsicContentSize().width let freeSpace = selfWidth - currentLineWidth let line = CGFloat(line) let y = line * self.dataSource!.heightOfTag(self) + (line + 1.0) * self.cellInsets.top + line * self.cellInsets.bottom var offset : CGFloat = 0.0 switch align { case .Center: offset = freeSpace / 2 case .Right: offset = freeSpace case .Left: offset = 0 } offset += (CGFloat(pageIndex) * self.bounds.width) var lastFrame = CGRectMake(offset, y, 0, 0) for addCell in cells { addCell.frame = CGRectOffset(addCell.frame, lastFrame.size.width + lastFrame.origin.x + cellInsets.left, y) contentView.addSubview(addCell) lastFrame = CGRectOffset(addCell.frame, cellInsets.right, 0) } } // MARK: - UIScrollViewDelegate var previousPage = 0 public func scrollViewDidScroll(scrollView: UIScrollView) { if !(numberOfPages > 1) { return } let pageWidth = scrollView.bounds.size.width let fractionalPage = Double(scrollView.contentOffset.x / pageWidth) let currentPage = lround(fractionalPage) if (previousPage != currentPage) { previousPage = currentPage pageControl.currentPage = currentPage } } // MARK: - IBAction @IBAction func changePage(sender: UIPageControl) { contentView.setContentOffset(CGPointMake(self.bounds.size.width * CGFloat(sender.currentPage), 0), animated: true) } // MARK: - Autolayout override public func invalidateIntrinsicContentSize() { super.invalidateIntrinsicContentSize() } override public func intrinsicContentSize() -> CGSize { var height: CGFloat = contentHeight // Add extra space for page control if /*let pcHeight = pageControl.frame.height where*/ pageControl.hidden == false { height += pageControl.frame.height //pcHeight } let size = CGSizeMake(frame.width, height) return size } // MARK: - Helpers private func showPageControl(withPageCount pageCount: Int) { if pageControl.superview == nil { pageControl.addTarget(self, action: #selector(TagView.changePage(_:)), forControlEvents: UIControlEvents.ValueChanged) self.addSubview(pageControl) // Autolayout pageControl.translatesAutoresizingMaskIntoConstraints = false let bindings = ["pageControl": pageControl] self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[pageControl]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[pageControl(\(kPageControlHeight))]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) } contentViewToBottomConstraint.constant = kPageControlHeight pageControl.numberOfPages = pageCount pageControl.hidden = false } private func hidePageControl() { contentViewToBottomConstraint.constant = 0 pageControl.hidden = true } private func findBottomMost() -> CGRect { var bottomMost = CGRectZero for cell in tagViews { if CGRectGetMaxY(cell.frame) > CGRectGetMaxY(bottomMost) { bottomMost = cell.frame } } return bottomMost } }
mit
358b4633639c13803d6a2f59c9ec222d
31.559278
196
0.576585
5.627171
false
false
false
false
aschwaighofer/swift
test/Driver/macabi-environment.swift
2
8122
// Tests to check that the driver finds standard library in the macabi environment. // UNSUPPORTED: windows // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios13.0-macabi -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS13-MACABI %s // IOS13-MACABI: bin/swift // IOS13-MACABI: -target x86_64-apple-ios13.0-macabi // IOS13-MACABI: bin/ld // IOS13-MACABI-DAG: -L [[MACCATALYST_STDLIB_PATH:[^ ]+/lib/swift/maccatalyst]] // IOS13-MACABI-DAG: -L [[MACOSX_STDLIB_PATH:[^ ]+/lib/swift/macosx]] // IOS13-MACABI-DAG: -L [[MACCATALYST_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/System/iOSSupport/usr/lib/swift]] // IOS13-MACABI-DAG: -L [[MACOSX_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/usr/lib/swift]] // IOS13-MACABI-DAG: -rpath [[MACCATALYST_STDLIB_PATH]] // IOS13-MACABI-DAG: -rpath [[MACOSX_STDLIB_PATH]] // IOS13-MACABI-DAG: -rpath [[MACCATALYST_SDK_STDLIB_PATH]] // IOS13-MACABI-DAG: -rpath [[MACOSX_SDK_STDLIB_PATH]] // IOS13-MACABI-DAG: -platform_version mac-catalyst 13.0.0 0.0.0 // Adjust iOS versions < 13.0 to 13.0 for the linker's sake. // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios12.0-macabi -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS12-MACABI %s // IOS12-MACABI: bin/swift // IOS12-MACABI: -target x86_64-apple-ios12.0-macabi // IOS12-MACABI: bin/ld // IOS12-MACABI-DAG: -L [[MACCATALYST_STDLIB_PATH:[^ ]+/lib/swift/maccatalyst]] // IOS12-MACABI-DAG: -L [[MACOSX_STDLIB_PATH:[^ ]+/lib/swift/macosx]] // IOS12-MACABI-DAG: -L [[MACCATALYST_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/System/iOSSupport/usr/lib/swift]] // IOS12-MACABI-DAG: -L [[MACOSX_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/usr/lib/swift]] // IOS12-MACABI-DAG: -rpath [[MACCATALYST_STDLIB_PATH]] // IOS12-MACABI-DAG: -rpath [[MACOSX_STDLIB_PATH]] // IOS12-MACABI-DAG: -rpath [[MACCATALYST_SDK_STDLIB_PATH]] // IOS12-MACABI-DAG: -rpath [[MACOSX_SDK_STDLIB_PATH]] // IOS12-MACABI-DAG: -platform_version mac-catalyst 13.0.0 0.0.0 // Test using target-variant to build zippered outputs // RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-OBJECT %s // ZIPPERED-VARIANT-OBJECT: bin/swift // ZIPPERED-VARIANT-OBJECT: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -module-name foo %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-LIBRARY %s // ZIPPERED-VARIANT-LIBRARY: bin/swift // ZIPPERED-VARIANT-LIBRARY: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // ZIPPERED-VARIANT-LIBRARY: bin/ld // ZIPPERED-VARIANT-LIBRARY: -platform_version macos 10.14.0 0.0.0 -platform_version mac-catalyst 13.0.0 0.0.0 // Make sure we pass the -target-variant when creating the pre-compiled header. // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -enable-bridging-pch -import-objc-header %S/Inputs/bridging-header.h %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-PCH %s // ZIPPERED-VARIANT-PCH: bin/swift // ZIPPERED-VARIANT-PCH: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // ZIPPERED_VARIANT-PCH -emit-pch // ZIPPERED-VARIANT-PCH: bin/swift // ZIPPERED-VARIANT-PCH: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi // ZIPPERED-VARIANT-PCH: bin/ld // ZIPPERED-VARIANT-PCH: -platform_version macos 10.14.0 0.0.0 -platform_version mac-catalyst 13.0.0 0.0.0 // Test using 'reverse' target-variant to build zippered outputs when the primary // target is ios-macabi // RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-OBJECT %s // REVERSE-ZIPPERED-VARIANT-OBJECT: bin/swift // REVERSE-ZIPPERED-VARIANT-OBJECT: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 -module-name foo %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-LIBRARY %s // REVERSE-ZIPPERED-VARIANT-LIBRARY: bin/swift // REVERSE-ZIPPERED-VARIANT-LIBRARY: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // REVERSE-ZIPPERED-VARIANT-LIBRARY: bin/ld // REVERSE-ZIPPERED-VARIANT-LIBRARY: -platform_version mac-catalyst 13.0.0 0.0.0 -platform_version macos 10.14.0 // Make sure we pass the -target-variant when creating the pre-compiled header. // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 -enable-bridging-pch -import-objc-header %S/Inputs/bridging-header.h %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-PCH %s // REVERSE-ZIPPERED-VARIANT-PCH: bin/swift // REVERSE-ZIPPERED-VARIANT-PCH: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // REVERSE-ZIPPERED_VARIANT-PCH -emit-pch // REVERSE-ZIPPERED-VARIANT-PCH: bin/swift // REVERSE-ZIPPERED-VARIANT-PCH: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 // REVERSE-ZIPPERED-VARIANT-PCH: bin/ld // REVERSE-ZIPPERED-VARIANT-PCH: -platform_version mac-catalyst 13.0.0 0.0.0 -platform_version macos 10.14.0 0.0.0 // RUN: not %swiftc_driver -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0 %s 2>&1 | %FileCheck --check-prefix=UNSUPPORTED-TARGET-VARIANT %s // RUN: not %swiftc_driver -target x86_64-apple-ios13.0 -target-variant x86_64-apple-macosx10.14 %s 2>&1 | %FileCheck --check-prefix=UNSUPPORTED-TARGET %s // UNSUPPORTED-TARGET-VARIANT: error: unsupported '-target-variant' value {{.*}}; use 'ios-macabi' instead // UNSUPPORTED-TARGET: error: unsupported '-target' value {{.*}}; use 'ios-macabi' instead // When compiling for iOS, pass iphoneos_version_min to the linker, not maccatalyst_version_min. // RUN: %swiftc_driver -driver-print-jobs -target arm64-apple-ios13.0 -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS13-NO-MACABI -implicit-check-not=mac-catalyst %s // IOS13-NO-MACABI: bin/swift // IOS13-NO-MACABI: -target arm64-apple-ios13.0 // IOS13-NO-MACABI: bin/ld // IOS13-NO-MACABI-DAG: -L {{[^ ]+/lib/swift/iphoneos}} // IOS13-NO-MACABI-DAG: -L {{[^ ]+/clang-importer-sdk/usr/lib/swift}} // IOS13-NO-MACABI-DAG: -platform_version ios 13.0.0 // Check reading the SDKSettings.json from an SDK and using it to map Catalyst // SDK version information. // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_ZIPPERED %s // MACOS_10_15_ZIPPERED: -target-sdk-version 10.15 // MACOS_10_15_ZIPPERED: -target-variant-sdk-version 13.1 // MACOS_10_15_ZIPPERED: -platform_version macos 10.14.0 10.15.0 // MACOS_10_15_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.1.0 // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.4.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_4_ZIPPERED %s // MACOS_10_15_4_ZIPPERED: -target-sdk-version 10.15.4 // MACOS_10_15_4_ZIPPERED: -target-variant-sdk-version 13.4 // MACOS_10_15_4_ZIPPERED: -platform_version macos 10.14.0 10.15.4 // MACOS_10_15_4_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.4.0 // RUN: %swiftc_driver -driver-print-jobs -target-variant x86_64-apple-macosx10.14 -target x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.4.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_4_REVERSE_ZIPPERED %s // MACOS_10_15_4_REVERSE_ZIPPERED: -target-sdk-version 13.4 // MACOS_10_15_4_REVERSE_ZIPPERED: -target-variant-sdk-version 10.15.4 // MACOS_10_15_4_REVERSE_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.4.0 // MACOS_10_15_4_REVERSE_ZIPPERED: -platform_version macos 10.14.0 10.15.4
apache-2.0
20d40b123105e93cb2d3c4fbf6ec3978
66.123967
249
0.738734
2.657723
false
false
false
false
odinasoftware/MockWebServer
Example/Tests/TestMockServer.swift
1
3449
// // TestMockServer.swift // MockWebServer // // Created by Jae Han on 12/10/16. // Copyright © 2016 jaehan. All rights reserved. // import XCTest import MockWebServer class TestMockServer: XCTestCase { var mockWebServer: MockWebServer = MockWebServer() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. mockWebServer.start(9000) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() mockWebServer.stop() } func testResponse() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let dispatchMap: DispatchMap = DispatchMap() let dispatch: Dispatch = Dispatch() dispatch.requestContain("test") .setResponseCode(200) .responseString("test") .responseHeaders(["Accept-encoding": "*.*"]) dispatchMap.add(dispatch) mockWebServer.setDispatch(dispatchMap) let url = NSURL(string: "http://127.0.0.1:9000/test") let testCondition: TestConditionWait = TestConditionWait() let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in debugPrint("response data=", data ?? "response null", "\n") debugPrint("response headers=", response ?? "no response header", "\n") testCondition.wakeup() } task.resume() testCondition.wait(for: 1) } func testMultipleResponse() { let dispatchMap: DispatchMap = DispatchMap() let dispatch: Dispatch = Dispatch() dispatch.requestContain("test1") .setResponseCode(200) .responseString("test") .responseHeaders(["Accept-encoding": "*.*"]) dispatchMap.add(dispatch) let dispatch1: Dispatch = Dispatch() dispatch1.requestContain("test2") .setResponseCode(200) .responseBody(for: Bundle(for: object_getClass(self)), fromFile: "response.json") .responseHeaders(["Accept-encoding": "*.*"]) dispatchMap.add(dispatch1) mockWebServer.setDispatch(dispatchMap) let url = NSURL(string: "http://127.0.0.1:9000/test1") let url2 = NSURL(string: "http://127.0.0.1:9000/test2") let testCondition: TestConditionWait = TestConditionWait.instance() let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in debugPrint("response data=", data ?? "response null") debugPrint("response headers=", response ?? "no response header") testCondition.wakeup() } task.resume() let task2 = URLSession.shared.dataTask(with: url2! as URL) { (data, response, error) in debugPrint("response data=", data ?? "response null", "\n") debugPrint("response headers=", response ?? "no response header", "\n") testCondition.wakeup() } task2.resume() testCondition.wait(for: 2) } }
mit
aea986d0f18a8b2a2074bffa6668bf6a
32.803922
111
0.582947
4.628188
false
true
false
false
suifengqjn/CatLive
CatLive/CatLive/Classes/Home/CLPageView/CLTitleView.swift
1
11419
// // CLTitleView.swift // CatLive // // Created by qianjn on 2017/6/11. // Copyright © 2017年 SF. All rights reserved. // import UIKit // MARK:- 定义协议 protocol CLTitleViewDelegate : class { func titleView(_ titleView : CLTitleView, selectedIndex index : Int) } class CLTitleView: UIView { // MARK: 对外属性 weak var delegate : CLTitleViewDelegate? // MARK: 定义属性 fileprivate var titles : [String]! fileprivate var style : CLTitleStyle! fileprivate var currentIndex : Int = 0 // MARK: 存储属性 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() // MARK: 控件属性 fileprivate lazy var scrollView : UIScrollView = { let scrollV = UIScrollView() scrollV.frame = self.bounds scrollV.showsHorizontalScrollIndicator = false scrollV.scrollsToTop = false return scrollV }() fileprivate lazy var splitLineView : UIView = { let splitView = UIView() splitView.backgroundColor = UIColor.lightGray let h : CGFloat = 0.5 splitView.frame = CGRect(x: 0, y: self.frame.height - h, width: self.frame.width, height: h) return splitView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor return bottomLine }() fileprivate lazy var coverView : UIView = { let coverView = UIView() coverView.backgroundColor = self.style.coverBgColor coverView.alpha = 0.7 return coverView }() // MARK: 计算属性 fileprivate lazy var normalColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.normalColor) fileprivate lazy var selectedColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.selectedColor) // MARK: 自定义构造函数 init(frame: CGRect, titles : [String], style : CLTitleStyle) { super.init(frame: frame) self.titles = titles self.style = style setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面内容 extension CLTitleView { fileprivate func setupUI() { // 1.添加Scrollview addSubview(scrollView) // 2.添加底部分割线 addSubview(splitLineView) // 3.设置所有的标题Label setupTitleLabels() // 4.设置Label的位置 setupTitleLabelsPosition() // 5.设置底部的滚动条 if style.isShowBottomLine { setupBottomLine() } // 6.设置遮盖的View if style.isShowCover { setupCoverView() } } fileprivate func setupTitleLabels() { for (index, title) in titles.enumerated() { let label = UILabel() label.tag = index label.text = title label.textColor = index == 0 ? style.selectedColor : style.normalColor label.font = style.font label.textAlignment = .center label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_ :))) label.addGestureRecognizer(tapGes) titleLabels.append(label) scrollView.addSubview(label) } } fileprivate func setupTitleLabelsPosition() { var titleX: CGFloat = 0.0 var titleW: CGFloat = 0.0 let titleY: CGFloat = 0.0 let titleH : CGFloat = frame.height let count = titles.count for (index, label) in titleLabels.enumerated() { if style.isScrollEnable { let rect = (label.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0.0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : style.font], context: nil) titleW = rect.width if index == 0 { titleX = style.titleMargin * 0.5 } else { let preLabel = titleLabels[index - 1] titleX = preLabel.frame.maxX + style.titleMargin } } else { titleW = frame.width / CGFloat(count) titleX = titleW * CGFloat(index) } label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) // 放大的代码 if index == 0 { let scale = style.isNeedScale ? style.scaleRange : 1.0 label.transform = CGAffineTransform(scaleX: scale, y: scale) } } if style.isScrollEnable { scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleMargin * 0.5, height: 0) } } fileprivate func setupBottomLine() { scrollView.addSubview(bottomLine) bottomLine.frame = titleLabels.first!.frame bottomLine.frame.size.height = style.bottomLineH bottomLine.frame.origin.y = bounds.height - style.bottomLineH } fileprivate func setupCoverView() { scrollView.insertSubview(coverView, at: 0) let firstLabel = titleLabels[0] var coverW = firstLabel.frame.width let coverH = style.coverH var coverX = firstLabel.frame.origin.x let coverY = (bounds.height - coverH) * 0.5 if style.isScrollEnable { coverX -= style.coverMargin coverW += style.coverMargin * 2 } coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) coverView.layer.cornerRadius = style.coverRadius coverView.layer.masksToBounds = true } } // MARK:- 事件处理 extension CLTitleView { @objc fileprivate func titleLabelClick(_ tap : UITapGestureRecognizer) { // 0.获取当前Label guard let currentLabel = tap.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = style.selectedColor oldLabel.textColor = style.normalColor // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.通知代理 delegate?.titleView(self, selectedIndex: currentIndex) // 6.居中显示 contentViewDidEndScroll() // 7.调整bottomLine if style.isShowBottomLine { UIView.animate(withDuration: 0.15, animations: { self.bottomLine.frame.origin.x = currentLabel.frame.origin.x self.bottomLine.frame.size.width = currentLabel.frame.size.width }) } // 8.调整比例 if style.isNeedScale { oldLabel.transform = CGAffineTransform.identity currentLabel.transform = CGAffineTransform(scaleX: style.scaleRange, y: style.scaleRange) } // 9.遮盖移动 if style.isShowCover { let coverX = style.isScrollEnable ? (currentLabel.frame.origin.x - style.coverMargin) : currentLabel.frame.origin.x let coverW = style.isScrollEnable ? (currentLabel.frame.width + style.coverMargin * 2) : currentLabel.frame.width UIView.animate(withDuration: 0.15, animations: { self.coverView.frame.origin.x = coverX self.coverView.frame.size.width = coverW }) } } } // MARK:- 获取RGB的值 extension CLTitleView { fileprivate func getRGBWithColor(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) { guard let components = color.cgColor.components else { fatalError("请使用RGB方式给Title赋值颜色") } return (components[0] * 255, components[1] * 255, components[2] * 255) } } // MARK:- 对外暴露的方法 extension CLTitleView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (selectedColorRGB.0 - normalColorRGB.0, selectedColorRGB.1 - normalColorRGB.1, selectedColorRGB.2 - normalColorRGB.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: selectedColorRGB.0 - colorDelta.0 * progress, g: selectedColorRGB.1 - colorDelta.1 * progress, b: selectedColorRGB.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: normalColorRGB.0 + colorDelta.0 * progress, g: normalColorRGB.1 + colorDelta.1 * progress, b: normalColorRGB.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width // 5.计算滚动的范围差值 if style.isShowBottomLine { bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress } // 6.放大的比例 if style.isNeedScale { let scaleDelta = (style.scaleRange - 1.0) * progress sourceLabel.transform = CGAffineTransform(scaleX: style.scaleRange - scaleDelta, y: style.scaleRange - scaleDelta) targetLabel.transform = CGAffineTransform(scaleX: 1.0 + scaleDelta, y: 1.0 + scaleDelta) } // 7.计算cover的滚动 if style.isShowCover { coverView.frame.size.width = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverMargin + moveTotalW * progress) : (sourceLabel.frame.width + moveTotalW * progress) coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverMargin + moveTotalX * progress) : (sourceLabel.frame.origin.x + moveTotalX * progress) } } func contentViewDidEndScroll() { // 0.如果是不需要滚动,则不需要调整中间位置 guard style.isScrollEnable else { return } // 1.获取获取目标的Label let targetLabel = titleLabels[currentIndex] // 2.计算和中间位置的偏移量 var offSetX = targetLabel.center.x - bounds.width * 0.5 if offSetX < 0 { offSetX = 0 } let maxOffset = scrollView.contentSize.width - bounds.width if offSetX > maxOffset { offSetX = maxOffset } // 3.滚动UIScrollView scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true) } }
apache-2.0
65648f8f7e0b518c46edcbea981637e2
33.16875
214
0.593561
4.783027
false
false
false
false
kdawgwilk/vapor
Tests/Vapor/ConsoleTests.swift
1
4456
import XCTest @testable import Vapor class ConsoleTests: XCTestCase { static let allTests = [ ("testCommandRun", testCommandRun), ("testCommandInsufficientArgs", testCommandInsufficientArgs), ("testCommandFetchArgs", testCommandFetchArgs), ("testCommandFetchOptions", testCommandFetchOptions), ("testDefaultServe", testDefaultServe), ] func testCommandRun() { let console = TestConsoleDriver() let drop = Droplet(console: console, arguments: ["/path/to/exe", "test-1"]) drop.commands = [ TestOneCommand(console: console) ] do { try drop.runCommands() XCTAssertEqual(console.input(), "Test 1 Ran", "Command 1 did not run") } catch { XCTFail("Command 1 failed: \(error)") } } func testCommandInsufficientArgs() { let console = TestConsoleDriver() let drop = Droplet(console: console, arguments: ["/path/to/exe", "test-2"]) let command = TestTwoCommand(console: console) drop.commands = [ command ] do { try drop.runCommands() XCTFail("Command 2 did not fail") } catch { XCTAssert(console.input().contains("Usage: /path/to/exe test-2 <arg-1> [--opt-1] [--opt-2]"), "Did not print signature") } } func testCommandFetchArgs() { let console = TestConsoleDriver() let drop = Droplet(console: console, arguments: ["/path/to/ext", "test-2", "123"]) let command = TestTwoCommand(console: console) drop.commands = [ command ] do { try drop.runCommands() XCTAssertEqual(console.input(), "123", "Did not print 123") } catch { XCTFail("Command 2 failed to run: \(error)") } } func testCommandFetchOptions() { let console = TestConsoleDriver() let drop = Droplet(console: console, arguments: ["/path/to/ext", "test-2", "123", "--opt-1=abc"]) let command = TestTwoCommand(console: console) drop.commands = [ command ] do { try drop.runCommands() XCTAssert(console.input() == "123abc", "Did not print 123abc") } catch { XCTFail("Command 2 failed to run: \(error)") } } func testDefaultServe() { final class TestServe: Command { let id: String = "serve" let console: Console static var ran = false init(console: Console) { self.console = console } func run(arguments: [String]) { TestServe.ran = true } } let drop = Droplet(arguments: ["/path/to/exec"]) drop.commands = [TestServe(console: drop.console)] do { try drop.runCommands() XCTAssert(TestServe.ran, "Serve did not default") } catch { XCTFail("Serve did not default: \(error)") } } } final class TestOneCommand: Command { let id: String = "test-1" let console: Console var counter = 0 init(console: Console) { self.console = console } func run(arguments: [String]) throws { console.print("Test 1 Ran") } } final class TestTwoCommand: Command { let id: String = "test-2" let console: Console let signature: [Argument] = [ ArgValue(name: "arg-1"), Option(name: "opt-1"), Option(name: "opt-2") ] init(console: Console) { self.console = console } func run(arguments: [String]) throws { let arg1 = try value("arg-1", from: arguments).string ?? "" console.print(arg1) let opt1 = arguments.option("opt-1").string ?? "" console.print(opt1) } } class TestConsoleDriver: Console { var buffer: Bytes init() { buffer = [] } func output(_ string: String, style: ConsoleStyle, newLine: Bool) { buffer += string.data.bytes } func input() -> String { let string = buffer.string buffer = [] return string } func clear(_ clear: ConsoleClear) { } func execute(_ command: String) throws { } func subexecute(_ command: String, input: String) throws -> String { return "" } let size: (width: Int, height: Int) = (0,0) }
mit
9e5b53a8d460174b8e4a6b23f400a5d7
24.318182
132
0.549147
4.247855
false
true
false
false
overtake/TelegramSwift
Telegram-Mac/DateSelectorModalController.swift
1
15009
// // DateSelectorModalController.swift // Telegram // // Created by Mikhail Filimonov on 07/08/2019. // Copyright © 2019 Telegram. All rights reserved. // import TGUIKit import TelegramCore import SwiftSignalKit import CalendarUtils import Postbox final class DateSelectorModalView : View { fileprivate let dayPicker: DatePicker<Date> private let atView = TextView() fileprivate let timePicker: TimePicker private let containerView = View() fileprivate let sendOn = TitleButton() fileprivate let sendWhenOnline = TitleButton() required init(frame frameRect: NSRect) { self.dayPicker = DatePicker<Date>(selected: DatePickerOption<Date>(name: DateSelectorUtil.formatDay(Date()), value: Date())) self.timePicker = TimePicker(selected: TimePickerOption(hours: 0, minutes: 0, seconds: 0)) super.init(frame: frameRect) containerView.addSubview(self.dayPicker) containerView.addSubview(self.atView) containerView.addSubview(self.timePicker) self.addSubview(self.containerView) self.addSubview(sendOn) self.atView.userInteractionEnabled = false self.atView.isSelectable = false self.sendOn.layer?.cornerRadius = .cornerRadius self.sendOn.disableActions() self.addSubview(self.sendWhenOnline) self.updateLocalizationAndTheme(theme: theme) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) self.sendOn.set(font: .medium(.text), for: .Normal) self.sendOn.set(color: .white, for: .Normal) self.sendOn.set(background: theme.colors.accent, for: .Normal) self.sendOn.set(background: theme.colors.accent.highlighted, for: .Highlight) self.sendWhenOnline.set(font: .normal(.text), for: .Normal) self.sendWhenOnline.set(color: theme.colors.accent, for: .Normal) self.sendWhenOnline.set(text: strings().scheduleSendWhenOnline, for: .Normal) _ = self.sendWhenOnline.sizeToFit() let atLayout = TextViewLayout(.initialize(string: strings().scheduleControllerAt, color: theme.colors.text, font: .normal(.title)), alwaysStaticItems: true) atLayout.measure(width: .greatestFiniteMagnitude) atView.update(atLayout) needsLayout = true } private var mode: DateSelectorModalController.Mode? func updateWithMode(_ mode: DateSelectorModalController.Mode, sendWhenOnline: Bool) { self.mode = mode self.sendWhenOnline.isHidden = !sendWhenOnline switch mode { case .date: self.atView.isHidden = true self.sendOn.isHidden = true self.sendWhenOnline.isHidden = true case .schedule: self.atView.isHidden = false self.sendOn.isHidden = false self.sendWhenOnline.isHidden = !sendWhenOnline } needsLayout = true } override func layout() { super.layout() if let mode = mode { switch mode { case .date: self.dayPicker.setFrameSize(NSMakeSize(130, 30)) self.timePicker.setFrameSize(NSMakeSize(130, 30)) let fullWidth = dayPicker.frame.width + 15 + timePicker.frame.width self.containerView.setFrameSize(NSMakeSize(fullWidth, max(dayPicker.frame.height, timePicker.frame.height))) self.dayPicker.centerY(x: 0) self.timePicker.centerY(x: dayPicker.frame.maxX + 15) self.containerView.centerX(y: 30) case .schedule: self.dayPicker.setFrameSize(NSMakeSize(115, 30)) self.timePicker.setFrameSize(NSMakeSize(115, 30)) let fullWidth = dayPicker.frame.width + 15 + atView.frame.width + 15 + timePicker.frame.width self.containerView.setFrameSize(NSMakeSize(fullWidth, max(dayPicker.frame.height, timePicker.frame.height))) self.dayPicker.centerY(x: 0) self.atView.centerY(x: self.dayPicker.frame.maxX + 15) self.timePicker.centerY(x: self.atView.frame.maxX + 15) self.containerView.centerX(y: 30) _ = self.sendOn.sizeToFit(NSZeroSize, NSMakeSize(fullWidth, 30), thatFit: true) self.sendOn.centerX(y: containerView.frame.maxY + 30) self.sendWhenOnline.centerX(y: self.sendOn.frame.maxY + 15) } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TimePickerOption { var interval: TimeInterval { let hours = Double(self.hours) * 60.0 * 60 let minutes = Double(self.minutes) * 60.0 let seconds = Double(self.seconds) return hours + minutes + seconds } } class DateSelectorModalController: ModalViewController { enum Mode { case schedule(PeerId) case date(title: String, doneTitle: String) } private let context: AccountContext private let selectedAt: (Date)->Void private let defaultDate: Date? private var sendWhenOnline: Bool = false fileprivate let mode: Mode private let disposable = MetaDisposable() init(context: AccountContext, defaultDate: Date? = nil, mode: Mode, selectedAt:@escaping(Date)->Void) { self.context = context self.defaultDate = defaultDate self.selectedAt = selectedAt self.mode = mode switch mode { case .schedule: super.init(frame: NSMakeRect(0, 0, 350, 200)) case .date: super.init(frame: NSMakeRect(0, 0, 350, 90)) } self.bar = .init(height: 0) } override func viewClass() -> AnyClass { return DateSelectorModalView.self } override var modalHeader: (left: ModalHeaderData?, center: ModalHeaderData?, right: ModalHeaderData?)? { let title: String switch mode { case .schedule: title = strings().scheduleControllerTitle case let .date(value, _): title = value } return (left: ModalHeaderData(title: nil, image: theme.icons.modalClose, handler: { [weak self] in self?.close() }), center: ModalHeaderData(title: title, handler: { }), right: nil) } override open func measure(size: NSSize) { var height: CGFloat = 0 switch mode { case .date: height = 90 case .schedule: height = sendWhenOnline ? 170 : 150 } self.modal?.resize(with:NSMakeSize(frame.width, height), animated: false) } override var dynamicSize: Bool { return true } var genericView: DateSelectorModalView { return self.view as! DateSelectorModalView } private func applyDay(_ date: Date) { genericView.dayPicker.selected = DatePickerOption(name: DateSelectorUtil.formatDay(date), value: date) let current = date.addingTimeInterval(self.genericView.timePicker.selected.interval) if CalendarUtils.isSameDate(Date(), date: date, checkDay: true) { if current < Date() { for interval in DateSelectorUtil.timeIntervals.compactMap ({$0}) { let new = date.startOfDay.addingTimeInterval(interval) if new > Date() { applyTime(new) break } } } else { if date != current { applyTime(date.addingTimeInterval(current.timeIntervalSince1970 - current.startOfDay.timeIntervalSince1970)) } else { applyTime(date) } } } else { if date != current { applyTime(date.addingTimeInterval(current.timeIntervalSince1970 - current.startOfDay.timeIntervalSince1970)) } else { applyTime(date) } } } private func applyTime(_ date: Date) { var t: time_t = time_t(date.timeIntervalSince1970) var timeinfo: tm = tm() localtime_r(&t, &timeinfo) genericView.timePicker.selected = TimePickerOption(hours: timeinfo.tm_hour, minutes: timeinfo.tm_min, seconds: timeinfo.tm_sec) if CalendarUtils.isSameDate(Date(), date: date, checkDay: true) { genericView.sendOn.set(text: strings().scheduleSendToday(DateSelectorUtil.formatTime(date)), for: .Normal) } else { genericView.sendOn.set(text: strings().scheduleSendDate(DateSelectorUtil.formatDay(date), DateSelectorUtil.formatTime(date)), for: .Normal) } } override var handleAllEvents: Bool { return true } private func select() { let day = self.genericView.dayPicker.selected.value let date = day.startOfDay.addingTimeInterval(self.genericView.timePicker.selected.interval) if CalendarUtils.isSameDate(Date(), date: day, checkDay: true) { if Date() > date { genericView.timePicker.shake() return } } self.selectedAt(date) self.close() } override func returnKeyAction() -> KeyHandlerResult { self.select() return .invoked } override func firstResponder() -> NSResponder? { return genericView.timePicker.firstResponder } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) window?.set(handler: { _ -> KeyHandlerResult in return .invokeNext }, with: self, for: .Tab, priority: .modal) window?.set(handler: { _ -> KeyHandlerResult in return .invokeNext }, with: self, for: .LeftArrow, priority: .modal) window?.set(handler: { _ -> KeyHandlerResult in return .invokeNext }, with: self, for: .RightArrow, priority: .modal) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) window?.removeAllHandlers(for: self) } override func viewDidLoad() { super.viewDidLoad() let context = self.context switch mode { case let .schedule(peerId): let presence = context.account.postbox.transaction { $0.getPeerPresence(peerId: peerId) as? TelegramUserPresence } |> deliverOnMainQueue disposable.set(presence.start(next: { [weak self] presence in var sendWhenOnline: Bool = false if let presence = presence { switch presence.status { case .present: sendWhenOnline = peerId != context.peerId default: break } } self?.sendWhenOnline = sendWhenOnline self?.initialize() })) case .date: initialize() } } override var modalInteractions: ModalInteractions? { switch mode { case .schedule: return nil case let .date(_, doneTitle): return ModalInteractions(acceptTitle: doneTitle, accept: { [weak self] in self?.select() }, drawBorder: true, height: 50, singleButton: true) } } private func initialize() { let date = self.defaultDate ?? Date() var t: time_t = time_t(date.timeIntervalSince1970) var timeinfo: tm = tm() localtime_r(&t, &timeinfo) self.genericView.dayPicker.selected = DatePickerOption<Date>(name: DateSelectorUtil.formatDay(date), value: date) self.genericView.timePicker.selected = TimePickerOption(hours: 0, minutes: 0, seconds: 0) self.genericView.updateWithMode(self.mode, sendWhenOnline: self.sendWhenOnline) self.applyDay(date) self.genericView.timePicker.update = { [weak self] updated in guard let `self` = self else { return false } let day = self.genericView.dayPicker.selected.value let date = day.startOfDay.addingTimeInterval(updated.interval) self.applyTime(date) return true } self.genericView.sendOn.set(handler: { [weak self] _ in self?.select() }, for: .Click) self.genericView.sendWhenOnline.set(handler: { [weak self] _ in self?.selectedAt(Date(timeIntervalSince1970: TimeInterval(scheduleWhenOnlineTimestamp))) self?.close() }, for: .Click) self.readyOnce() self.genericView.dayPicker.set(handler: { [weak self] control in if let control = control as? DatePicker<Date>, let window = self?.window, !hasPopover(window) { let calendar = CalendarController(NSMakeRect(0, 0, 300, 300), window, current: control.selected.value, onlyFuture: true, selectHandler: { [weak self] date in self?.applyDay(date) }) showPopover(for: control, with: calendar, edge: .maxY, inset: NSMakePoint(-8, -60)) } }, for: .Down) self.genericView.timePicker.set(handler: { [weak self] control in if let control = control as? DatePicker<Date>, let `self` = self, let window = self.window, !hasPopover(window) { var items:[SPopoverItem] = [] let day = self.genericView.dayPicker.selected.value for interval in DateSelectorUtil.timeIntervals { if let interval = interval { let date = day.startOfDay.addingTimeInterval(interval) if CalendarUtils.isSameDate(Date(), date: day, checkDay: true) { if Date() > date { continue } } items.append(SPopoverItem(DateSelectorUtil.formatTime(date), { [weak self] in self?.applyTime(date) }, height: 30)) } else if !items.isEmpty { items.append(SPopoverItem()) } } showPopover(for: control, with: SPopoverViewController(items: items, visibility: 6), edge: .maxY, inset: NSMakePoint(0, -50)) } }, for: .Down) } deinit { disposable.dispose() } }
gpl-2.0
f5334d853d69e10720a9c32780e05e12
36.240695
173
0.579957
4.752375
false
false
false
false
Bunn/firefox-ios
SyncTests/MockSyncServer.swift
9
17608
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import GCDWebServers import SwiftyJSON @testable import Sync import XCTest private let log = Logger.syncLogger private func optTimestamp(x: AnyObject?) -> Timestamp? { guard let str = x as? String else { return nil } return decimalSecondsStringToTimestamp(str) } private func optStringArray(x: AnyObject?) -> [String]? { guard let str = x as? String else { return nil } return str.components(separatedBy: ",").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } } private struct SyncRequestSpec { let collection: String let id: String? let ids: [String]? let limit: Int? let offset: String? let sort: SortOption? let newer: Timestamp? let full: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncRequestSpec? { // Input is "/1.5/user/storage/collection", possibly with "/id" at the end. // That means we get five or six path components here, the first being empty. let parts = request.path.components(separatedBy: "/").filter { !$0.isEmpty } let id: String? let query = request.query! let ids = optStringArray(x: query["ids"] as AnyObject?) let newer = optTimestamp(x: query["newer"] as AnyObject?) let full: Bool = query["full"] != nil let limit: Int? if let lim = query["limit"] { limit = Int(lim) } else { limit = nil } let offset = query["offset"] let sort: SortOption? switch query["sort"] ?? "" { case "oldest": sort = SortOption.OldestFirst case "newest": sort = SortOption.NewestFirst case "index": sort = SortOption.Index default: sort = nil } if parts.count < 4 { return nil } if parts[2] != "storage" { return nil } // Use dropFirst, you say! It's buggy. switch parts.count { case 4: id = nil case 5: id = parts[4] default: // Uh oh. return nil } return SyncRequestSpec(collection: parts[3], id: id, ids: ids, limit: limit, offset: offset, sort: sort, newer: newer, full: full) } } struct SyncDeleteRequestSpec { let collection: String? let id: GUID? let ids: [GUID]? let wholeCollection: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncDeleteRequestSpec? { // Input is "/1.5/user{/storage{/collection{/id}}}". // That means we get four, five, or six path components here, the first being empty. return SyncDeleteRequestSpec.fromPath(path: request.path, withQuery: request.query! as [NSString : AnyObject]) } static func fromPath(path: String, withQuery query: [NSString: AnyObject]) -> SyncDeleteRequestSpec? { let parts = path.components(separatedBy: "/").filter { !$0.isEmpty } let queryIDs: [GUID]? = (query["ids"] as? String)?.components(separatedBy: ",") guard [2, 4, 5].contains(parts.count) else { return nil } if parts.count == 2 { return SyncDeleteRequestSpec(collection: nil, id: nil, ids: queryIDs, wholeCollection: true) } if parts[2] != "storage" { return nil } if parts.count == 4 { let hasIDs = queryIDs != nil return SyncDeleteRequestSpec(collection: parts[3], id: nil, ids: queryIDs, wholeCollection: !hasIDs) } return SyncDeleteRequestSpec(collection: parts[3], id: parts[4], ids: queryIDs, wholeCollection: false) } } private struct SyncPutRequestSpec { let collection: String let id: String static func fromRequest(request: GCDWebServerRequest) -> SyncPutRequestSpec? { // Input is "/1.5/user/storage/collection/id}}}". // That means we get six path components here, the first being empty. let parts = request.path.components(separatedBy: "/").filter { !$0.isEmpty } guard parts.count == 5 else { return nil } if parts[2] != "storage" { return nil } return SyncPutRequestSpec(collection: parts[3], id: parts[4]) } } class MockSyncServer { let server = GCDWebServer() let username: String var offsets: Int = 0 var continuations: [String: [EnvelopeJSON]] = [:] var collections: [String: (modified: Timestamp, records: [String: EnvelopeJSON])] = [:] var baseURL: String! init(username: String) { self.username = username } class func makeValidEnvelope(guid: GUID, modified: Timestamp) -> EnvelopeJSON { let clientBody: [String: Any] = [ "id": guid, "name": "Foobar", "commands": [], "type": "mobile", ] let clientBodyString = JSON(clientBody).stringify()! let clientRecord: [String : Any] = [ "id": guid, "collection": "clients", "payload": clientBodyString, "modified": Double(modified) / 1000, ] return EnvelopeJSON(JSON(clientRecord).stringify()!) } class func withHeaders(response: GCDWebServerResponse, lastModified: Timestamp? = nil, records: Int? = nil, timestamp: Timestamp? = nil) -> GCDWebServerResponse { let timestamp = timestamp ?? Date.now() let xWeaveTimestamp = millisecondsToDecimalSeconds(timestamp) response.setValue("\(xWeaveTimestamp)", forAdditionalHeader: "X-Weave-Timestamp") if let lastModified = lastModified { let xLastModified = millisecondsToDecimalSeconds(lastModified) response.setValue("\(xLastModified)", forAdditionalHeader: "X-Last-Modified") } if let records = records { response.setValue("\(records)", forAdditionalHeader: "X-Weave-Records") } return response } func storeRecords(records: [EnvelopeJSON], inCollection collection: String, now: Timestamp? = nil) { let now = now ?? Date.now() let coll = self.collections[collection] var out = coll?.records ?? [:] records.forEach { out[$0.id] = $0.withModified(now) } let newModified = max(now, coll?.modified ?? 0) self.collections[collection] = (modified: newModified, records: out) } private func splitArray<T>(items: [T], at: Int) -> ([T], [T]) { return (Array(items.dropLast(items.count - at)), Array(items.dropFirst(at))) } private func recordsMatchingSpec(spec: SyncRequestSpec) -> (records: [EnvelopeJSON], offsetID: String?)? { // If we have a provided offset, handle that directly. if let offset = spec.offset { log.debug("Got provided offset \(offset).") guard let remainder = self.continuations[offset] else { log.error("Unknown offset.") return nil } // Remove the old one. self.continuations.removeValue(forKey: offset) // Handle the smaller-than-limit or no-provided-limit cases. guard let limit = spec.limit, limit < remainder.count else { log.debug("Returning all remaining items.") return (remainder, nil) } // Record the next continuation and return the first slice of records. let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items: remainder, at: limit) self.continuations[next] = remaining log.debug("Returning \(limit) items; next continuation is \(next).") return (returned, next) } guard let records = self.collections[spec.collection]?.records.values else { // No matching records. return ([], nil) } var items = Array(records) log.debug("Got \(items.count) candidate records.") if spec.newer ?? 0 > 0 { items = items.filter { $0.modified > spec.newer! } } if let ids = spec.ids { let ids = Set(ids) items = items.filter { ids.contains($0.id) } } if let sort = spec.sort { switch sort { case SortOption.NewestFirst: items = items.sorted { $0.modified > $1.modified } log.debug("Sorted items newest first: \(items.map { $0.modified })") case SortOption.OldestFirst: items = items.sorted { $0.modified < $1.modified } log.debug("Sorted items oldest first: \(items.map { $0.modified })") case SortOption.Index: log.warning("Index sorting not yet supported.") } } if let limit = spec.limit, items.count > limit { let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items: items, at: limit) self.continuations[next] = remaining return (returned, next) } return (items, nil) } private func recordResponse(record: EnvelopeJSON) -> GCDWebServerResponse { let body = record.asJSON().stringify()! let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response: response, lastModified: record.modified) } private func modifiedResponse(timestamp: Timestamp) -> GCDWebServerResponse { let body = JSON(["modified": timestamp]).stringify() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData!, contentType: "application/json") return MockSyncServer.withHeaders(response: response) } func modifiedTimeForCollection(collection: String) -> Timestamp? { return self.collections[collection]?.modified } func removeAllItemsFromCollection(collection: String, atTime: Timestamp) { if self.collections[collection] != nil { self.collections[collection] = (atTime, [:]) } } func start() { let basePath = "/1.5/\(self.username)" let storagePath = "\(basePath)/storage/" let infoCollectionsPath = "\(basePath)/info/collections" server.addHandler(forMethod: "GET", path: infoCollectionsPath, request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse in var ic = [String: Any]() var lastModified: Timestamp = 0 for collection in self.collections.keys { if let timestamp = self.modifiedTimeForCollection(collection: collection) { ic[collection] = Double(timestamp) / 1000 lastModified = max(lastModified, timestamp) } } let body = JSON(ic).stringify() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData!, contentType: "application/json") return MockSyncServer.withHeaders(response: response, lastModified: lastModified, records: ic.count) } let matchPut: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest? in if method != "PUT" || !path.hasPrefix(basePath) { return nil } return GCDWebServerDataRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandler(match: matchPut) { (request) -> GCDWebServerResponse in guard let request = request as? GCDWebServerDataRequest else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } guard let spec = SyncPutRequestSpec.fromRequest(request: request) else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } var body = JSON(request.jsonObject!) body["modified"] = JSON(stringLiteral: millisecondsToDecimalSeconds(Date.now())) let record = EnvelopeJSON(body) self.storeRecords(records: [record], inCollection: spec.collection) let timestamp = self.modifiedTimeForCollection(collection: spec.collection)! let response = GCDWebServerDataResponse(data: millisecondsToDecimalSeconds(timestamp).utf8EncodedData, contentType: "application/json") return MockSyncServer.withHeaders(response: response) } let matchDelete: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest? in if method != "DELETE" || !path.hasPrefix(basePath) { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandler(match: matchDelete) { (request) -> GCDWebServerResponse in guard let spec = SyncDeleteRequestSpec.fromRequest(request: request) else { return GCDWebServerDataResponse(statusCode: 400) } if let collection = spec.collection, let id = spec.id { guard var items = self.collections[collection]?.records else { // Unable to find the requested collection. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } guard let item = items[id] else { // Unable to find the requested id. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } items.removeValue(forKey: id) return self.modifiedResponse(timestamp: item.modified) } if let collection = spec.collection { if spec.wholeCollection { self.collections.removeValue(forKey: collection) } else { if let ids = spec.ids, var map = self.collections[collection]?.records { for id in ids { map.removeValue(forKey: id) } self.collections[collection] = (Date.now(), records: map) } } return self.modifiedResponse(timestamp: Date.now()) } self.collections = [:] return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(data: "{}".utf8EncodedData, contentType: "application/json")) } let match: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest? in if method != "GET" || !path.hasPrefix(storagePath) { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandler(match: match) { (request) -> GCDWebServerResponse in // 1. Decide what the URL is asking for. It might be a collection fetch or // an individual record, and it might have query parameters. guard let spec = SyncRequestSpec.fromRequest(request: request) else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } // 2. Grab the matching set of records. Prune based on TTL, exclude with X-I-U-S, etc. if let id = spec.id { guard let collection = self.collections[spec.collection], let record = collection.records[id] else { // Unable to find the requested collection/id. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } return self.recordResponse(record: record) } guard let (items, offset) = self.recordsMatchingSpec(spec: spec) else { // Unable to find the provided offset. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } // TODO: TTL // TODO: X-I-U-S let body = JSON(items.map { $0.asJSON() }).stringify() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData!, contentType: "application/json") // 3. Compute the correct set of headers: timestamps, X-Weave-Records, etc. if let offset = offset { response.setValue(offset, forAdditionalHeader: "X-Weave-Next-Offset") } let timestamp = self.modifiedTimeForCollection(collection: spec.collection)! log.debug("Returning GET response with X-Last-Modified for \(items.count) records: \(timestamp).") return MockSyncServer.withHeaders(response: response, lastModified: timestamp, records: items.count) } if server.start(withPort: 0, bonjourName: nil) == false { XCTFail("Can't start the GCDWebServer.") } baseURL = "http://localhost:\(server.port)\(basePath)" } }
mpl-2.0
7d4a89284a7193f562af539f7a095019
37.955752
166
0.595866
4.914318
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestTask.swift
1
2340
// // QuestTask.swift // AwesomeCore // // Created by Evandro Harrison Hoffmann on 11/3/17. // import Foundation public class QuestTask: Codable, Equatable { public var completed: Bool public let completionDetails: String? public let description: String? public let id: String? public let imageUrl: String? public let coverAsset: QuestTaskCoverAsset? public let name: String? public let position: Int public let required: Bool public let type: String? public let pageId: String? // FK to the CDPage init(completed: Bool, completionDetails: String?, description: String?, id: String?, imageUrl: String?, coverAsset: QuestTaskCoverAsset?, name: String?, position: Int, required: Bool, type: String?, pageId: String? = nil) { self.completed = completed self.completionDetails = completionDetails self.description = description self.id = id self.imageUrl = imageUrl self.coverAsset = coverAsset self.name = name self.position = position self.required = required self.type = type self.pageId = pageId } } // MARK: - JSON Key public struct QuestTasks: Codable { public let tasks: [QuestTask] } // MARK: - Equatable extension QuestTask { public static func ==(lhs: QuestTask, rhs: QuestTask) -> Bool { if lhs.completed != rhs.completed { return false } if lhs.completionDetails != rhs.completionDetails { return false } if lhs.description != rhs.description { return false } if lhs.id != rhs.id { return false } if lhs.imageUrl != rhs.imageUrl { return false } if lhs.coverAsset != rhs.coverAsset { return false } if lhs.name != rhs.name { return false } if lhs.position != rhs.position { return false } if lhs.required != rhs.required { return false } if lhs.type != rhs.type { return false } if lhs.pageId != rhs.pageId { return false } return true } }
mit
07b2d65ad5a288a68d1f38421be2fc13
23.123711
67
0.55641
4.59725
false
false
false
false
avaidyam/Parrot
MochaUI/ViewAttachmentCell.swift
1
2882
import AppKit import Mocha public class ViewAttachmentCell: NSTextAttachmentCell { /// The view to be embed in the NSTextView this attachment is contained within. public private(set) var view: NSView /// The textView being tracked (the container of this attachment). /// Note: we track the NSTextDidChange notification to see if we should remove /// or migrate the view from/to the textView as needed. private weak var textView: NSTextView? = nil { didSet { let n = NotificationCenter.default if oldValue != nil { n.removeObserver(self, name: NSText.didChangeNotification, object: oldValue!) self.view.removeFromSuperview() } if self.textView != nil { n.addObserver(self, selector: #selector(ViewAttachmentCell.verifyAttached(_:)), name: NSText.didChangeNotification, object: self.textView!) self.textView!.addSubview(self.view) } } } public init(for view: NSView) { self.view = view super.init() } public required init(coder: NSCoder) { self.view = NSView() super.init(coder: coder) } /// We forget the tracking and remove the view from any container on deinit. deinit { NotificationCenter.default.removeObserver(self) self.view.removeFromSuperview() } public override func cellSize() -> NSSize { return self.view.intrinsicContentSize } public override func draw(withFrame cellFrame: NSRect, in controlView: NSView!) { if let control = controlView as? NSTextView, control != self.textView { self.textView = control } self.view.frame = cellFrame } @objc dynamic private func verifyAttached(_ note: Notification) { let str = (note.object as? NSTextView)?.attributedString() var attached = false // Enumerate all possible attributes to ensure we are attached still. str?.enumerateAttributes(in: NSMakeRange(0, str?.length ?? 0), options: []) { if let a = $0[.attachment] as? NSTextAttachment, let cell = a.attachmentCell, cell === self { attached = true; $2.pointee = true } } // If we're not attached, make sure to remove the view from the textView. if !attached { self.view.removeFromSuperview() } } } public extension NSTextAttachment { public convenience init(attachmentCell cell: NSTextAttachmentCell) { self.init() self.attachmentCell = cell } } public extension NSAttributedString { public convenience init(attachmentCell cell: NSTextAttachmentCell) { self.init(attachment: NSTextAttachment(attachmentCell: cell)) } }
mpl-2.0
c88b5d5a8794aaa343345826a21c9fe6
33.722892
105
0.619362
5.05614
false
false
false
false
orta/RxSwift
RxSwift/RxSwift/Disposables/AnonymousDisposable.swift
3
767
// // AnonymousDisposable.swift // Rx // // Created by Krunoslav Zaher on 2/15/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation public class AnonymousDisposable : DisposeBase, Disposable { public typealias DisposeAction = () -> Void var lock = Lock() var disposeAction: DisposeAction? public init(_ disposeAction: DisposeAction) { self.disposeAction = disposeAction super.init() } public func dispose() { let toDispose: DisposeAction? = lock.calculateLocked { var action = self.disposeAction self.disposeAction = nil return action } if let toDispose = toDispose { toDispose() } } }
mit
145fb8f45156796c65eeaf97f95b3661
22.272727
62
0.607562
4.79375
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/AttributeDetailView.swift
1
5649
// // AttributeDetailView.swift // RealmModelGenerator // // Created by Zhaolong Zhong on 3/29/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Cocoa protocol AttributeDetailViewDelegate: AnyObject { func attributeDetailView(attributeDetailView:AttributeDetailView, shouldChangeAttributeTextField newValue:String, control:NSControl) -> Bool func attributeDetailView(attributeDetailView:AttributeDetailView, shouldChangeAttributeCheckBoxFor sender:NSButton, state:Bool) -> Bool func attributeDetailView(attributeDetailView:AttributeDetailView, selectedTypeDidChange selectedIndex:Int) -> Bool } // --MARK-- assuming push buttons have two states @IBDesignable class AttributeDetailView: NibDesignableView, NSTextFieldDelegate { static let TAG = NSStringFromClass(AttributeDetailView.self) private var previousSelectedIndex = 0; @IBOutlet var nameTextField:NSTextField! @IBOutlet weak var defaultValueTextField: NSTextField! @IBOutlet weak var attributeTypePopUpButton: NSPopUpButton! @IBOutlet weak var ignoredCheckBox: NSButton! @IBOutlet weak var indexedCheckBox: NSButton! @IBOutlet weak var primaryCheckBox: NSButton! @IBOutlet weak var requiredCheckBox: NSButton! @IBOutlet weak var defaultCheckBox: NSButton! weak var delegate:AttributeDetailViewDelegate? override func nibDidLoad() { super.nibDidLoad() self.attributeTypePopUpButton.removeAllItems() self.attributeTypePopUpButton.addItems(withTitles: AttributeType.values.flatMap({$0.rawValue})) } @IBInspectable var name:String { set { self.nameTextField.stringValue = newValue } get { return self.nameTextField.stringValue } } @IBInspectable var isIgnored:Bool { set { self.ignoredCheckBox.state = newValue ? .on : .off } get { return self.ignoredCheckBox.state == .on ? true : false } } @IBInspectable var isIndexed:Bool { set { self.indexedCheckBox.state = newValue ? .on : .off } get { return self.indexedCheckBox.state == .on ? true : false } } @IBInspectable var isPrimary:Bool { set { self.primaryCheckBox.state = newValue ? .on : .off } get { return self.primaryCheckBox.state == .on ? true : false } } @IBInspectable var isRequired:Bool { set { self.requiredCheckBox.state = newValue ? .on : .off } get { return self.requiredCheckBox.state == .on ? true : false } } @IBInspectable var hasDefault:Bool { set { self.defaultCheckBox.state = newValue ? .on : .off } get { return self.defaultCheckBox.state == .on ? true : false } } @IBInspectable var attributeTypeNames:[String] { set { self.attributeTypePopUpButton.removeAllItems() self.attributeTypePopUpButton.addItems(withTitles: newValue) } get { return self.attributeTypePopUpButton.itemTitles } } @IBInspectable var selectedIndex:Int { set { self.attributeTypePopUpButton.selectItem(at: newValue) if self.previousSelectedIndex != newValue { self.previousSelectedIndex = newValue } if ((AttributeType.values[newValue] == .Unknown) || (AttributeType.values[newValue] == .Blob)) { self.defaultValueTextField.isEnabled = false self.defaultCheckBox.isEnabled = false } else { self.defaultValueTextField.isEnabled = true self.defaultCheckBox.isEnabled = true } } get { return self.attributeTypePopUpButton.indexOfSelectedItem } } @IBInspectable var defaultValue:String { set { self.defaultValueTextField.stringValue = newValue } get { return self.defaultValueTextField.stringValue } } func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { if let shouldEnd = self.delegate?.attributeDetailView(attributeDetailView: self, shouldChangeAttributeTextField: fieldEditor.string, control: control) { return shouldEnd } return true } @IBAction func checkBoxStateChanged(_ sender: NSButton) { if let shouldChangeState = self.delegate?.attributeDetailView(attributeDetailView: self, shouldChangeAttributeCheckBoxFor: sender, state: sender.state == .on) { if shouldChangeState == false { switch sender { case self.ignoredCheckBox: ignoredCheckBox.state = .off break; case self.indexedCheckBox: indexedCheckBox.state = .off break; case self.primaryCheckBox: primaryCheckBox.state = .off break; case self.requiredCheckBox: requiredCheckBox.state = .off break; case self.defaultCheckBox: defaultCheckBox.state = .off break; default: break } } } } @IBAction func attributeTypeChanged(_ sender: NSPopUpButton) { if let shouldSelect = self.delegate?.attributeDetailView(attributeDetailView: self, selectedTypeDidChange: selectedIndex) { if !shouldSelect { self.selectedIndex = self.previousSelectedIndex } } } }
mit
d801c688b525c8f5d057ea566142c629
36.157895
168
0.629072
5.399618
false
false
false
false