repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
STShenZhaoliang/STKitSwift
|
STKitSwift/STHUD.swift
|
1
|
4847
|
//
// STHUD.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2019 沈天
//
// 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 SnapKit
public class STHUD: UIView{
// MARK: 1.lift cycle
@discardableResult
public class func show(_ title:String, completion:((Bool) -> Void)? = nil) -> STHUD{
let noticeView = STHUD.init(frame: UIScreen.main.bounds)
noticeView.setupUI()
noticeView.labelTitle.text = title
noticeView.show()
noticeView.completion = completion
return noticeView
}
@discardableResult
public class func show(_ title:String, image:UIImage?, completion:((Bool) -> Void)? = nil) -> STHUD{
let noticeView = STHUD.init(frame: UIScreen.main.bounds)
noticeView.setupImageUI()
noticeView.labelTitle.text = title
noticeView.imageView.image = image
noticeView.show()
noticeView.completion = completion
return noticeView
}
// MARK: 2.private methods
private func show() {
let window = UIApplication.shared.keyWindow!
window.addSubview(self)
self.snp.makeConstraints { (maker) in
maker.edges.equalToSuperview()
}
UIView.animate(withDuration: 0.3, animations: {
self.contentView.layer.opacity = 1.0
}) { (finished) in
self.perform(#selector(self.remove), with: nil, afterDelay: 1)
}
}
@objc private func remove(){
UIView.animate(withDuration: 0.3, animations: {
self.contentView.layer.opacity = 0
}) { (finished) in
self.removeFromSuperview()
self.completion?(true)
}
}
// MARK: 3.event response
private func setupUI(){
contentView.snp.makeConstraints { (maker) in
maker.left.greaterThanOrEqualTo(50)
maker.right.lessThanOrEqualTo(-50)
maker.center.equalToSuperview()
}
labelTitle.snp.makeConstraints { (maker) in
maker.left.equalTo(28)
maker.right.equalTo(-28)
maker.top.equalTo(14)
maker.bottom.equalTo(-14)
}
}
private func setupImageUI(){
contentView.snp.makeConstraints { (maker) in
maker.left.greaterThanOrEqualTo(50)
maker.right.lessThanOrEqualTo(-50)
maker.center.equalToSuperview()
}
imageView.snp.makeConstraints { (maker) in
maker.centerX.equalToSuperview()
maker.top.equalTo(16)
}
labelTitle.snp.makeConstraints { (maker) in
maker.left.equalTo(28)
maker.right.equalTo(-28)
maker.top.equalTo(imageView.snp.bottom).offset(14)
maker.bottom.equalTo(-14)
}
}
// MARK: 4.interface
var completion: ((Bool) -> Void)? = nil
// MARK: 5.getter
private lazy var labelTitle: UILabel = {
let labelTitle = UILabel()
labelTitle.textColor = .white
labelTitle.font = UIFont.systemFont(ofSize: 16)
labelTitle.numberOfLines = 0
labelTitle.textAlignment = .center
contentView.addSubview(labelTitle)
return labelTitle
}()
private lazy var contentView: UIView = {
let contentView = UIView()
contentView.layer.cornerRadius = 5
contentView.backgroundColor = UIColor.init(white: 0, alpha: 0.7)
contentView.layer.masksToBounds = true
addSubview(contentView)
return contentView
}()
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = UIView.ContentMode.scaleAspectFit
contentView.addSubview(imageView)
return imageView
}()
}
|
mit
|
469d2419e1178d4edfd5b5426c597547
| 34.350365 | 104 | 0.633905 | 4.568868 | false | false | false | false |
twittemb/Weavy
|
WeavyDemo/WeavyDemo/Weaving/WishlistWarp.swift
|
1
|
3763
|
//
// WishlistWarp.swift
// WeavyDemo
//
// Created by Thibault Wittemberg on 17-09-05.
// Copyright © 2017 Warp Factor. All rights reserved.
//
import Weavy
import RxSwift
import UIKit
class WishlistWarp: Warp {
var head: UIViewController {
return self.rootViewController
}
private let rootViewController = UINavigationController()
private let wishlistWeftable: WishlistWeftable
private let service: MoviesService
init(withService service: MoviesService, andWeftable weftable: WishlistWeftable) {
self.service = service
self.wishlistWeftable = weftable
}
func knit(withWeft weft: Weft) -> [Stitch] {
guard let weft = weft as? DemoWeft else { return Stitch.emptyStitches }
switch weft {
case .movieList:
return navigateToMovieListScreen()
case .moviePicked(let movieId):
return navigateToMovieDetailScreen(with: movieId)
case .castPicked(let castId):
return navigateToCastDetailScreen(with: castId)
case .settings:
return navigateToSettings()
default:
return Stitch.emptyStitches
}
}
private func navigateToMovieListScreen () -> [Stitch] {
let viewModel = WishlistViewModel(with: self.service)
let viewController = WishlistViewController.instantiate(with: viewModel)
viewController.title = "Wishlist"
self.rootViewController.pushViewController(viewController, animated: true)
if let navigationBarItem = self.rootViewController.navigationBar.items?[0] {
navigationBarItem.setRightBarButton(UIBarButtonItem(image: UIImage(named: "settings"),
style: UIBarButtonItemStyle.plain,
target: self.wishlistWeftable,
action: #selector(WishlistWeftable.settings)),
animated: false)
}
return [Stitch(nextPresentable: viewController, nextWeftable: viewController.viewModel)]
}
private func navigateToMovieDetailScreen (with movieId: Int) -> [Stitch] {
let viewModel = MovieDetailViewModel(withService: self.service, andMovieId: movieId)
let viewController = MovieDetailViewController.instantiate(with: viewModel)
viewController.title = viewModel.title
self.rootViewController.pushViewController(viewController, animated: true)
return [Stitch(nextPresentable: viewController, nextWeftable: viewModel)]
}
private func navigateToCastDetailScreen (with castId: Int) -> [Stitch] {
let viewModel = CastDetailViewModel(withService: self.service, andCastId: castId)
let viewController = CastDetailViewController.instantiate(with: viewModel)
viewController.title = viewModel.name
self.rootViewController.pushViewController(viewController, animated: true)
return Stitch.emptyStitches
}
private func navigateToSettings () -> [Stitch] {
let settingsWeftable = SettingsWeftable()
let settingsWarp = SettingsWarp(withService: self.service, andWeftable: settingsWeftable)
Warps.whenReady(warp: settingsWarp, block: { [unowned self] (head: UISplitViewController) in
self.rootViewController.present(head, animated: true)
})
return [Stitch(nextPresentable: settingsWarp, nextWeftable: settingsWeftable)]
}
}
class WishlistWeftable: Weftable, HasDisposeBag {
init() {
self.weftSubject.onNext(DemoWeft.movieList)
}
@objc func settings () {
self.weftSubject.onNext(DemoWeft.settings)
}
}
|
mit
|
e0f0cb047376773152a57a1c6d488c67
| 37.387755 | 110 | 0.660553 | 4.774112 | false | false | false | false |
urbn/URBNSwiftyConvenience
|
Example/Tests/Tests.swift
|
1
|
1343
|
import UIKit
import XCTest
import URBNSwiftyConvenience
class Tests: XCTestCase {
func testColors() {
XCTAssertEqual(UIColor(rgb: 0xFF0000), UIColor.red)
XCTAssertEqual(UIColor(rgb: 0x00FF00), UIColor.green)
XCTAssertEqual(UIColor(rgb: 0x0000FF), UIColor.blue)
XCTAssertEqual(UIColor(rgb: 0x00FFFF), UIColor.cyan)
XCTAssertEqual(UIColor(rgb: 0xFFFF00), UIColor.yellow)
XCTAssertEqual(UIColor(hexString: "FF0000"), UIColor.red)
XCTAssertEqual(UIColor(hexString: "#00FF00"), UIColor.green)
XCTAssertEqual(UIColor(hexString: "0000FF"), UIColor.blue)
XCTAssertEqual(UIColor(hexString: "#00FFFF"), UIColor.cyan)
XCTAssertEqual(UIColor(hexString: "FFFF00"), UIColor.yellow)
XCTAssertEqual(UIColor(hexString: "FFFF0"), UIColor(rgb: 0))
XCTAssertEqual(UIColor(hexString: "#FFFF0"), UIColor(rgb: 0))
XCTAssertEqual(UIColor(hexString: "Jerkface"), UIColor(rgb: 0))
}
func testConditionalAssignment() {
var myDictionary = [String: String]()
let missing: String? = nil
let exists: String? = "baz"
myDictionary["foo"] ?= missing
myDictionary["bar"] ?= exists
XCTAssertNil(myDictionary["foo"])
XCTAssertEqual(myDictionary["bar"], "baz")
}
}
|
mit
|
02402a875040affd435c7311da17aee8
| 35.297297 | 71 | 0.650782 | 4.374593 | false | true | false | false |
uias/Pageboy
|
Sources/Pageboy/PageboyViewController+ScrollCalculations.swift
|
1
|
10232
|
//
// PageboyViewController+ScrollCalculations.swift
// Pageboy iOS
//
// Created by Merrick Sapsford on 18/10/2018.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
// MARK: - Calculations
internal extension PageboyViewController {
/// Calculate the new page position for a scroll view at its current offset.
///
/// - Parameters:
/// - scrollView: Scroll view.
/// - currentIndex: Known current page index.
/// - Returns: New page position & previous page position.
func calculateNewPagePosition(in scrollView: UIScrollView, currentIndex: PageIndex) -> (CGFloat, CGFloat)? {
let (pageSize, contentOffset) = calculateRelativePageSizeAndContentOffset(for: scrollView)
guard let scrollIndexDiff = pageScrollIndexDiff(forCurrentIndex: currentIndex,
expectedIndex: expectedTransitionIndex,
currentContentOffset: contentOffset,
pageSize: pageSize) else {
return nil
}
guard let position = calculatePagePosition(for: contentOffset,
pageSize: pageSize,
indexDiff: scrollIndexDiff) else {
return nil
}
// Return nil if previous position equals current
let previousPosition = previousPagePosition ?? 0.0
guard position != previousPosition else {
return nil
}
return (position, previousPosition)
}
/// Calculate the relative page size and content offset for a scroll view at its current position.
///
/// - Parameter scrollView: Scroll View
/// - Returns: Relative page size and content offset.
func calculateRelativePageSizeAndContentOffset(for scrollView: UIScrollView) -> (CGFloat, CGFloat) {
var pageSize: CGFloat
var contentOffset: CGFloat
let orientation = navigationOrientation
switch orientation {
case .horizontal:
pageSize = scrollView.frame.size.width
if scrollView.layoutIsRightToLeft {
contentOffset = pageSize + (pageSize - scrollView.contentOffset.x)
} else {
contentOffset = scrollView.contentOffset.x
}
case .vertical:
pageSize = scrollView.frame.size.height
contentOffset = scrollView.contentOffset.y
@unknown default:
fatalError("unsupported orientation \(orientation.rawValue)")
}
return (pageSize, contentOffset)
}
/// Detect whether the scroll view is overscrolling while infinite scroll is enabled
///
/// - Parameter pagePosition: the current page position.
/// - Returns: The updated page position (if needed).
func adjustedPagePositionForInfiniteOverscroll(from pagePosition: CGFloat) -> CGFloat? {
guard isInfinitelyScrolling(forPosition: pagePosition) else {
return nil
}
let maxPagePosition = CGFloat((viewControllerCount ?? 1) - 1)
var integral: Double = 0.0
var progress = CGFloat(modf(fabs(Double(pagePosition)), &integral))
var maxInfinitePosition: CGFloat!
if pagePosition > 0.0 {
progress = 1.0 - progress
maxInfinitePosition = 0.0
} else {
maxInfinitePosition = maxPagePosition
}
var infinitePagePosition = maxPagePosition * progress
if fmod(progress, 1.0) == 0.0 {
infinitePagePosition = maxInfinitePosition
}
return infinitePagePosition
}
/// Whether a position is infinitely scrolling between end ranges
///
/// - Parameter pagePosition: The position.
/// - Returns: Whether the position is infinitely scrolling.
func isInfinitelyScrolling(forPosition pagePosition: CGFloat) -> Bool {
let maxPagePosition = CGFloat((viewControllerCount ?? 1) - 1)
let isOverscrolling = pagePosition < 0.0 || pagePosition > maxPagePosition
guard isInfiniteScrollEnabled && isOverscrolling else {
return false
}
return true
}
/// Detects whether a page boundary has been passed.
/// As pageViewController:didFinishAnimating is not reliable.
///
/// - Parameters:
/// - pageOffset: The current page scroll offset
/// - scrollView: The scroll view that is being scrolled.
/// - Returns: Whether a page transition has been detected.
func detectNewPageIndexIfNeeded(pagePosition: CGFloat, scrollView: UIScrollView) -> Bool {
guard var currentIndex = currentIndex else {
return false
}
// Handle scenario where user continues to pan past a single page range.
let isPagingForward = pagePosition > previousPagePosition ?? 0.0
if scrollView.isTracking {
if isPagingForward && pagePosition >= CGFloat(currentIndex + 1) {
updateCurrentPageIndexIfNeeded(currentIndex + 1)
return true
} else if !isPagingForward && pagePosition <= CGFloat(currentIndex - 1) {
updateCurrentPageIndexIfNeeded(currentIndex - 1)
return true
}
}
let isOnPage = pagePosition.truncatingRemainder(dividingBy: 1) == 0
if isOnPage {
// Special case where scroll view might be decelerating but on a new index,
// and UIPageViewController didFinishAnimating is not called
if scrollView.isDecelerating {
currentIndex = Int(pagePosition)
}
return updateCurrentPageIndexIfNeeded(currentIndex)
}
return false
}
/// Safely update the current page index.
///
/// - Parameter index: the proposed index.
/// - Returns: Whether the page index was updated.
@discardableResult
func updateCurrentPageIndexIfNeeded(_ index: Int) -> Bool {
guard currentIndex != index, index >= 0 && index < viewControllerCount ?? 0 else {
return false
}
currentIndex = index
return true
}
/// Calculate the expected index diff for a page scroll.
///
/// - Parameters:
/// - index: The current index.
/// - expectedIndex: The target page index.
/// - currentContentOffset: The current content offset.
/// - pageSize: The size of each page.
/// - Returns: The expected index diff.
func pageScrollIndexDiff(forCurrentIndex index: Int?,
expectedIndex: Int?,
currentContentOffset: CGFloat,
pageSize: CGFloat) -> CGFloat? {
guard let index = index else {
return nil
}
let expectedIndex = expectedIndex ?? index
let expectedDiff = CGFloat(max(1, abs(expectedIndex - index)))
let expectedPosition = calculatePagePosition(for: currentContentOffset,
pageSize: pageSize,
indexDiff: expectedDiff) ?? CGFloat(index)
guard !isInfinitelyScrolling(forPosition: expectedPosition) else {
return 1
}
return expectedDiff
}
/// Calculate the relative page position.
///
/// - Parameters:
/// - contentOffset: The current contentOffset.
/// - pageSize: The current page size.
/// - indexDiff: The expected difference between current / target page indexes.
/// - Returns: The relative page position.
func calculatePagePosition(for contentOffset: CGFloat,
pageSize: CGFloat,
indexDiff: CGFloat) -> CGFloat? {
guard let currentIndex = currentIndex else {
return nil
}
let scrollOffset = contentOffset - pageSize
let pageOffset = (CGFloat(currentIndex) * pageSize) + (scrollOffset * indexDiff)
let position = pageOffset / pageSize
return position.isFinite ? position : 0
}
/// Update the scroll view contentOffset for bouncing preference if required.
///
/// - Parameter scrollView: The scroll view.
/// - Returns: Whether the contentOffset was manipulated to achieve bouncing preference.
@discardableResult
func updateContentOffsetForBounceIfNeeded(scrollView: UIScrollView) -> Bool {
guard bounces == false else {
return false
}
let previousContentOffset = scrollView.contentOffset
if currentIndex == 0 && scrollView.contentOffset.x < scrollView.bounds.size.width {
scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0.0)
}
if currentIndex == (viewControllerCount ?? 1) - 1 && scrollView.contentOffset.x > scrollView.bounds.size.width {
scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0.0)
}
return previousContentOffset != scrollView.contentOffset
}
// MARK: Utilities
/// Check that a scroll view is the actual page view controller managed instance.
///
/// - Parameter scrollView: The scroll view to check.
/// - Returns: Whether it is the actual managed instance.
func scrollViewIsActual(_ scrollView: UIScrollView) -> Bool {
return scrollView === pageViewController?.scrollView
}
/// Check that a UIPageViewController is the actual managed instance.
///
/// - Parameter pageViewController: The page view controller to check.
/// - Returns: Whether it is the actual managed instance.
func pageViewControllerIsActual(_ pageViewController: UIPageViewController) -> Bool {
return pageViewController === self.pageViewController
}
}
|
mit
|
8e300f67656bae4c5b70eccab35f4d24
| 39.599206 | 120 | 0.598182 | 5.856325 | false | false | false | false |
zjjzmw1/robot
|
robot/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift
|
11
|
109406
|
//
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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 CoreGraphics
import UIKit
///---------------------
/// MARK: IQToolbar tags
///---------------------
/**
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
open class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
/**
Default tag for toolbar with Done button -1002.
*/
fileprivate static let kIQDoneButtonToolbarTag = -1002
/**
Default tag for toolbar with Previous/Next buttons -1005.
*/
fileprivate static let kIQPreviousNextButtonToolbarTag = -1005
///---------------------------
/// MARK: UIKeyboard handling
///---------------------------
/**
Registered classes list with library.
*/
fileprivate var registeredClasses = [UIView.Type]()
/**
Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
*/
open var enable = false {
didSet {
//If not enable, enable it.
if enable == true &&
oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if _kbShowNotification != nil {
keyboardWillShow(_kbShowNotification)
}
showLog("enabled")
} else if enable == false &&
oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
showLog("disabled")
}
}
}
fileprivate func privateIsEnabled()-> Bool {
var isEnabled = enable
if let textFieldViewController = _textFieldView?.viewController() {
if isEnabled == false {
//If viewController is kind of enable viewController class, then assuming it's enabled.
for enabledClass in enabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: enabledClass) {
isEnabled = true
break
}
}
}
if isEnabled == true {
//If viewController is kind of disabled viewController class, then assuming it's disabled.
for disabledClass in disabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: disabledClass) {
isEnabled = false
break
}
}
}
}
return isEnabled
}
/**
To set keyboard distance from textField. can't be less than zero. Default is 10.0.
*/
open var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/**
Boolean to know if keyboard is showing.
*/
open var keyboardShowing: Bool {
get {
return _privateIsKeyboardShowing
}
}
/**
moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
*/
open var movedDistance: CGFloat {
get {
return _privateMovedDistance
}
}
/**
Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES.
*/
open var preventShowingBottomBlankSpace = true
/**
Returns the default singleton instance.
*/
open class func sharedManager() -> IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
///-------------------------
/// MARK: IQToolbar handling
///-------------------------
/**
Automatic add the IQToolbar functionality. Default is YES.
*/
open var enableAutoToolbar = true {
didSet {
privateIsEnableAutoToolbar() ?addToolbarIfRequired():removeToolbarIfRequired()
let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
showLog("enableAutoToolbar: \(enableToolbar)")
}
}
fileprivate func privateIsEnableAutoToolbar() -> Bool {
var enableToolbar = enableAutoToolbar
if let textFieldViewController = _textFieldView?.viewController() {
if enableToolbar == false {
//If found any toolbar enabled classes then return.
for enabledClass in enabledToolbarClasses {
if textFieldViewController.isKind(of: enabledClass) {
enableToolbar = true
break
}
}
}
if enableToolbar == true {
//If found any toolbar disabled classes then return.
for disabledClass in disabledToolbarClasses {
if textFieldViewController.isKind(of: disabledClass) {
enableToolbar = false
break
}
}
}
}
return enableToolbar
}
/**
/**
IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view.
IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's.
IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate.
Default is IQAutoToolbarBySubviews.
*/
AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
*/
open var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews
/**
If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
*/
open var shouldToolbarUsesTextFieldTintColor = false
/**
This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
*/
open var toolbarTintColor : UIColor?
/**
If YES, then hide previous/next button. Default is NO.
*/
@available(*,deprecated, message: "Please use `previousNextDisplayMode` for better handling of previous/next button display. This property will be removed in future releases in favor of `previousNextDisplayMode`.")
open var shouldHidePreviousNext = false {
didSet {
previousNextDisplayMode = shouldHidePreviousNext ? .alwaysHide : .Default
}
}
/**
IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide.
IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case.
IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
*/
open var previousNextDisplayMode = IQPreviousNextDisplayMode.Default
/**
Toolbar done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
*/
open var toolbarDoneBarButtonItemImage : UIImage?
/**
Toolbar done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
*/
open var toolbarDoneBarButtonItemText : String?
/**
If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
*/
open var shouldShowTextFieldPlaceholder = true
/**
Placeholder Font. Default is nil.
*/
open var placeholderFont: UIFont?
///--------------------------
/// MARK: UITextView handling
///--------------------------
/** used to adjust contentInset of UITextView. */
fileprivate var startingTextViewContentInsets = UIEdgeInsets.zero
/** used to adjust scrollIndicatorInsets of UITextView. */
fileprivate var startingTextViewScrollIndicatorInsets = UIEdgeInsets.zero
/** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
fileprivate var isTextViewContentInsetChanged = false
///---------------------------------------
/// MARK: UIKeyboard appearance overriding
///---------------------------------------
/**
Override the keyboardAppearance for all textField/textView. Default is NO.
*/
open var overrideKeyboardAppearance = false
/**
If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
*/
open var keyboardAppearance = UIKeyboardAppearance.default
///-----------------------------------------------------------
/// MARK: UITextField/UITextView Next/Previous/Resign handling
///-----------------------------------------------------------
/**
Resigns Keyboard on touching outside of UITextField/View. Default is NO.
*/
open var shouldResignOnTouchOutside = false {
didSet {
_tapGesture.isEnabled = privateShouldResignOnTouchOutside()
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
showLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
fileprivate func privateShouldResignOnTouchOutside() -> Bool {
var shouldResign = shouldResignOnTouchOutside
if let textFieldViewController = _textFieldView?.viewController() {
if shouldResign == false {
//If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
for enabledClass in enabledTouchResignedClasses {
if textFieldViewController.isKind(of: enabledClass) {
shouldResign = true
break
}
}
}
if shouldResign == true {
//If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
for disabledClass in disabledTouchResignedClasses {
if textFieldViewController.isKind(of: disabledClass) {
shouldResign = false
break
}
}
}
}
return shouldResign
}
/**
Resigns currently first responder field.
*/
@discardableResult open func resignFirstResponder()-> Bool {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to resign first responder: \(_textFieldView?._IQDescription())")
}
return isResignFirstResponder
}
return false
}
/**
Returns YES if can navigate to previous responder textField/textView, otherwise NO.
*/
open var canGoPrevious: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index > 0 {
return true
}
}
}
}
return false
}
/**
Returns YES if can navigate to next responder textField/textView, otherwise NO.
*/
open var canGoNext: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index < textFields.count-1 {
return true
}
}
}
}
return false
}
/**
Navigate to previous responder textField/textView.
*/
@discardableResult open func goPrevious()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/**
Navigate to next responder textField/textView.
*/
@discardableResult open func goNext()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/** previousAction. */
internal func previousAction (_ barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoPrevious == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goPrevious()
if isAcceptAsFirstResponder &&
textFieldRetain.previousInvocation.target != nil &&
textFieldRetain.previousInvocation.action != nil {
UIApplication.shared.sendAction(textFieldRetain.previousInvocation.action!, to: textFieldRetain.previousInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** nextAction. */
internal func nextAction (_ barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoNext == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goNext()
if isAcceptAsFirstResponder &&
textFieldRetain.nextInvocation.target != nil &&
textFieldRetain.nextInvocation.action != nil {
UIApplication.shared.sendAction(textFieldRetain.nextInvocation.action!, to: textFieldRetain.nextInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** doneAction. Resigning current textField. */
internal func doneAction (_ barButton : IQBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if let textFieldRetain = _textFieldView {
//Resign textFieldView.
let isResignedFirstResponder = resignFirstResponder()
if isResignedFirstResponder &&
textFieldRetain.doneInvocation.target != nil &&
textFieldRetain.doneInvocation.action != nil{
UIApplication.shared.sendAction(textFieldRetain.doneInvocation.action!, to: textFieldRetain.doneInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
/** Resigning on tap gesture. (Enhancement ID: #14)*/
internal func tapRecognized(_ gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.ended {
//Resigning currently responder textField.
_ = resignFirstResponder()
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
return !(touch.view is UIControl ||
touch.view is UINavigationBar)
}
///-----------------------
/// MARK: UISound handling
///-----------------------
/**
If YES, then it plays inputClick sound on next/previous/done click.
*/
open var shouldPlayInputClicks = true
///---------------------------
/// MARK: UIAnimation handling
///---------------------------
/**
If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
*/
open var layoutIfNeededOnUpdate = false
///-----------------------------------------------
/// @name InteractivePopGestureRecognizer handling
///-----------------------------------------------
/**
If YES, then always consider UINavigationController.view begin point as {0,0}, this is a workaround to fix a bug #464 because there are no notification mechanism exist when UINavigationController.view.frame gets changed internally.
*/
open var shouldFixInteractivePopGestureRecognizer = true
///------------------------------------
/// MARK: Class Level disabling methods
///------------------------------------
/**
Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
*/
open var disabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored.
*/
open var enabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
*/
open var disabledToolbarClasses = [UIViewController.Type]()
/**
Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
*/
open var enabledToolbarClasses = [UIViewController.Type]()
/**
Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView.
*/
open var toolbarPreviousNextAllowedClasses = [UIView.Type]()
/**
Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController.
*/
open var disabledTouchResignedClasses = [UIViewController.Type]()
/**
Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
*/
open var enabledTouchResignedClasses = [UIViewController.Type]()
///-------------------------------------------
/// MARK: Third Party Library support
/// Add TextField/TextView Notifications customised NSNotifications. For example while using YYTextView https://github.com/ibireme/YYText
///-------------------------------------------
/**
Add customised Notification for third party customised TextField/TextView. Please be aware that the NSNotification object must be idential to UITextField/UITextView NSNotification objects and customised TextField/TextView support must be idential to UITextField/UITextView.
@param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification
@param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification
*/
open func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) {
registeredClasses.append(aClass)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
/**************************************************************************************/
///------------------------
/// MARK: Private variables
///------------------------
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
fileprivate weak var _textFieldView: UIView?
/** To save rootViewController.view.frame. */
fileprivate var _topViewBeginRect = CGRect.zero
/** To save rootViewController */
fileprivate weak var _rootViewController: UIViewController?
/** To save topBottomLayoutConstraint original constant */
fileprivate var _layoutGuideConstraintInitialConstant: CGFloat = 0
/** To save topBottomLayoutConstraint original constraint reference */
fileprivate weak var _layoutGuideConstraint: NSLayoutConstraint?
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
fileprivate weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
fileprivate var _startingContentOffset = CGPoint.zero
/** LastScrollView's initial scrollIndicatorInsets. */
fileprivate var _startingScrollIndicatorInsets = UIEdgeInsets.zero
/** LastScrollView's initial contentInsets. */
fileprivate var _startingContentInsets = UIEdgeInsets.zero
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
fileprivate var _kbShowNotification: Notification?
/** To save keyboard size. */
fileprivate var _kbSize = CGSize.zero
/** To save Status Bar size. */
fileprivate var _statusBarFrame = CGRect.zero
/** To save keyboard animation duration. */
fileprivate var _animationDuration = 0.25
/** To mimic the keyboard animation */
fileprivate var _animationCurve = UIViewAnimationOptions.curveEaseOut
/*******************************************/
/** TapGesture to resign keyboard on view's touch. */
fileprivate var _tapGesture: UITapGestureRecognizer!
/*******************************************/
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
fileprivate var _privateIsKeyboardShowing = false
fileprivate var _privateMovedDistance : CGFloat = 0.0
/** To use with keyboardDistanceFromTextField. */
fileprivate var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/**************************************************************************************/
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
/* Singleton Object Initialization. */
override init() {
super.init()
// Registering for keyboard notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
// Registering for UITextField notification.
registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue)
// Registering for UITextView notification.
registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue)
// Registering for orientation changes notification
NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
// Registering for status bar frame change notification
NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarFrame(_:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared)
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
_tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
_tapGesture.cancelsTouchesInView = false
_tapGesture.delegate = self
_tapGesture.isEnabled = shouldResignOnTouchOutside
//Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard apperance delay (Bug ID: #550)
let textField = UITextField()
textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:)))
textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)))
disabledDistanceHandlingClasses.append(UITableViewController.self)
disabledDistanceHandlingClasses.append(UIAlertController.self)
disabledToolbarClasses.append(UIAlertController.self)
disabledTouchResignedClasses.append(UIAlertController.self)
toolbarPreviousNextAllowedClasses.append(UITableView.self)
toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
//Special Controllers
struct InternalClass {
static var UIAlertControllerTextFieldViewController: UIViewController.Type? = NSClassFromString("_UIAlertControllerTextFieldViewController") as? UIViewController.Type //UIAlertView
}
if let aClass = InternalClass.UIAlertControllerTextFieldViewController {
disabledDistanceHandlingClasses.append(aClass.self)
disabledToolbarClasses.append(aClass.self)
disabledTouchResignedClasses.append(aClass.self)
}
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
/** It doesn't work from Swift 1.2 */
// override public class func load() {
// super.load()
//
// //Enabling IQKeyboardManager.
// IQKeyboardManager.sharedManager().enable = true
// }
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NotificationCenter.default.removeObserver(self)
}
/** Getting keyWindow. */
fileprivate func keyWindow() -> UIWindow? {
if let keyWindow = _textFieldView?.window {
return keyWindow
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static var keyWindow : UIWindow?
}
/* (Bug ID: #23, #25, #73) */
let originalKeyWindow = UIApplication.shared.keyWindow
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if originalKeyWindow != nil &&
(Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
///-----------------------
/// MARK: Helper Functions
///-----------------------
/* Helper function to manipulate RootViewController's frame with animation. */
fileprivate func setRootViewFrame(_ frame: CGRect) {
// Getting topMost ViewController.
var controller = _textFieldView?.topMostController()
if controller == nil {
controller = keyWindow()?.topMostController()
}
if let unwrappedController = controller {
var newFrame = frame
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
newFrame.size = unwrappedController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
// Setting it's new frame
unwrappedController.view.frame = newFrame
self.showLog("Set \(controller?._IQDescription()) frame to : \(newFrame)")
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
unwrappedController.view.setNeedsLayout()
unwrappedController.view.layoutIfNeeded()
}
}) { (animated:Bool) -> Void in}
} else { // If can't get rootViewController then printing warning to user.
showLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager")
}
}
/* Adjusting RootViewController's frame according to interface orientation. */
fileprivate func adjustFrame() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _textFieldView == nil {
return
}
let textFieldView = _textFieldView!
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting KeyWindow object.
let optionalWindow = keyWindow()
// Getting RootViewController. (Bug ID: #1, #4)
var optionalRootController = _textFieldView?.topMostController()
if optionalRootController == nil {
optionalRootController = keyWindow()?.topMostController()
}
// Converting Rectangle according to window bounds.
let optionalTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: optionalWindow)
if optionalRootController == nil ||
optionalWindow == nil ||
optionalTextFieldViewRect == nil {
return
}
let rootController = optionalRootController!
let window = optionalWindow!
let textFieldViewRect = optionalTextFieldViewRect!
// Getting RootViewRect.
var rootViewRect = rootController.view.frame
//Getting statusBarFrame
//Maintain keyboardDistanceFromTextField
var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField
if textFieldView.isSearchBarTextField() {
if let searchBar = textFieldView.superviewOfClassType(UISearchBar.self) {
specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField
}
}
let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField
var kbSize = _kbSize
kbSize.height += newKeyboardDistanceFromTextField
let statusBarFrame = UIApplication.shared.statusBarFrame
// (Bug ID: #250)
var layoutGuidePosition = IQLayoutGuidePosition.none
if let viewController = textFieldView.viewController() {
if let constraint = _layoutGuideConstraint {
var layoutGuide : UILayoutSupport?
if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
} else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
}
if let itemLayoutGuide : UILayoutSupport = layoutGuide {
if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint
{
layoutGuidePosition = .top
}
else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint
{
layoutGuidePosition = .bottom
}
}
}
}
let topLayoutGuide : CGFloat = statusBarFrame.height
var move : CGFloat = 0.0
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Checking if there is bottomLayoutGuide attached (Bug ID: #250)
if layoutGuidePosition == .bottom {
// Calculating move position.
move = textFieldViewRect.maxY-(window.frame.height-kbSize.height)
} else {
// Calculating move position. Common for both normal and special cases.
move = min(textFieldViewRect.minY-(topLayoutGuide+5), textFieldViewRect.maxY-(window.frame.height-kbSize.height))
}
showLog("Need to move: \(move)")
var superScrollView : UIScrollView? = nil
var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView
//Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
while let view = superView {
if (view.isScrollEnabled) {
superScrollView = view
break
}
else {
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_lastScrollView = superScrollView
_startingContentInsets = superScrollView!.contentInset
_startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets
_startingContentOffset = superScrollView!.contentOffset
showLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
_startingContentOffset = unwrappedSuperScrollView.contentOffset
showLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 {
var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
var nextScrollView : UIScrollView? = nil
while let view = tempScrollView {
if (view.isScrollEnabled) {
nextScrollView = view
break
} else {
tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
if textFieldView is UITextView == true &&
nextScrollView == nil &&
shouldOffsetY >= 0 {
var maintainTopLayout : CGFloat = 0
if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame {
maintainTopLayout = navigationBarFrame.maxY
}
maintainTopLayout += 10.0 //For good UI
// Converting Rectangle according to window bounds.
if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) {
//Calculating expected fix distance which needs to be managed from navigation bar
let expectedFixDistance = currentTextFieldViewRect.minY - maintainTopLayout
//Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
//Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
move = 0
}
else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
}
else
{
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.showLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset")
self.showLog("Remaining Move: \(move)")
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY)
}) { (animated:Bool) -> Void in }
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = nextScrollView
} else {
break
}
}
//Updating contentInset
if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) {
let bottom : CGFloat = kbSize.height-newKeyboardDistanceFromTextField-(window.frame.height-lastScrollViewRect.maxY)
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
showLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)")
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = movedInsets
var newInset = lastScrollView.scrollIndicatorInsets
newInset.bottom = movedInsets.bottom
lastScrollView.scrollIndicatorInsets = newInset
}) { (animated:Bool) -> Void in }
showLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)")
}
}
//Going ahead. No else if.
if layoutGuidePosition == .top {
if let constraint = _layoutGuideConstraint {
let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else if layoutGuidePosition == .bottom {
if let constraint = _layoutGuideConstraint {
let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else {
//Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
//_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
if let textView = textFieldView as? UITextView {
let textViewHeight = min(textView.frame.height, (window.frame.height-kbSize.height-(topLayoutGuide)))
if (textView.frame.size.height-textView.contentInset.bottom>textViewHeight)
{
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
//_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92)
if (self.isTextViewContentInsetChanged == false)
{
self.startingTextViewContentInsets = textView.contentInset
self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
}
var newContentInset = textView.contentInset
newContentInset.bottom = textView.frame.size.height-textViewHeight
textView.contentInset = newContentInset
textView.scrollIndicatorInsets = newContentInset
self.isTextViewContentInsetChanged = true
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
}, completion: { (finished) -> Void in })
}
}
// Special case for iPad modalPresentationStyle.
if rootController.modalPresentationStyle == UIModalPresentationStyle.formSheet ||
rootController.modalPresentationStyle == UIModalPresentationStyle.pageSheet {
showLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)")
// +Positive or zero.
if move >= 0 {
// We should only manipulate y.
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
let minimumY: CGFloat = (window.frame.height-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField)
rootViewRect.origin.y = max(rootViewRect.minY, minimumY)
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
// Calculating disturbed distance. Pull Request #3
let disturbDistance = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
// We should only manipulate y.
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
} else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
// +Positive or zero.
if move >= 0 {
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField))
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
let disturbDistance : CGFloat = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///---------------------
/// MARK: Public Methods
///---------------------
/* Refreshes textField/textView position if any external changes is explicitly made by user. */
open func reloadLayoutIfNeeded() -> Void {
if privateIsEnabled() == true {
if _textFieldView != nil &&
_privateIsKeyboardShowing == true &&
_topViewBeginRect.equalTo(CGRect.zero) == false &&
_textFieldView?.isAlertViewTextField() == false {
adjustFrame()
}
}
}
///-------------------------------
/// MARK: UIKeyboard Notifications
///-------------------------------
/* UIKeyboardWillShowNotification. */
internal func keyboardWillShow(_ notification : Notification?) -> Void {
_kbShowNotification = notification
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = true
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// (Bug ID: #5)
if _textFieldView != nil && _topViewBeginRect.equalTo(CGRect.zero) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
let oldKBSize = _kbSize
if let info = (notification as NSNotification?)?.userInfo {
// Getting keyboard animation.
if let curve = (info[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue {
_animationCurve = UIViewAnimationOptions(rawValue: curve)
} else {
_animationCurve = UIViewAnimationOptions.curveEaseOut
}
// Getting keyboard animation duration
if let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
} else {
_animationDuration = 0.25
}
// Getting UIKeyboardSize.
if let kbFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let screenSize = UIScreen.main.bounds
//Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
let intersectRect = kbFrame.intersection(screenSize)
if intersectRect.isNull {
_kbSize = CGSize(width: screenSize.size.width, height: 0)
} else {
_kbSize = intersectRect.size
}
showLog("UIKeyboard Size : \(_kbSize)")
}
}
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if _kbSize.equalTo(oldKBSize) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardDidShowNotification. */
internal func keyboardDidShow(_ notification : Notification?) -> Void {
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
if _textFieldView != nil &&
(topMostController?.modalPresentationStyle == UIModalPresentationStyle.formSheet || topMostController?.modalPresentationStyle == UIModalPresentationStyle.pageSheet) &&
_textFieldView?.isAlertViewTextField() == false {
//In case of form sheet or page sheet, we'll add adjustFrame call in main queue to perform it when UI thread will do all framing updation so adjustFrame will be executed after all internal operations.
OperationQueue.main.addOperation {
self.adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
internal func keyboardWillHide(_ notification : Notification?) -> Void {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = false
//If not enabled then do nothing.
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
let info : [AnyHashable: Any]? = (notification as NSNotification?)?.userInfo
// Getting keyboard animation duration
if let duration = (info?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.contentOffset = self._startingContentOffset
}
self.showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)")
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView : UIScrollView? = lastScrollView
while let scrollView = superScrollView {
let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
let minimumY = contentSize.height - scrollView.frame.height
if minimumY < scrollView.contentOffset.y {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
self.showLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)")
}
superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}) { (finished) -> Void in }
}
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if _topViewBeginRect.equalTo(CGRect.zero) == false {
if let rootViewController = _rootViewController {
//frame size needs to be adjusted on iOS8 due to orientation API changes.
_topViewBeginRect.size = rootViewController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
if let constraint = self._layoutGuideConstraint {
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
else {
self.showLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)")
// Setting it's new frame
rootViewController.view.frame = self._topViewBeginRect
self._privateMovedDistance = 0
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
}
}) { (finished) -> Void in }
_rootViewController = nil
}
} else if let constraint = self._layoutGuideConstraint {
if let rootViewController = _rootViewController {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}) { (finished) -> Void in }
}
}
//Reset all values
_lastScrollView = nil
_kbSize = CGSize.zero
_layoutGuideConstraint = nil
_layoutGuideConstraintInitialConstant = 0
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
// topViewBeginRect = CGRectZero //Commented due to #82
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
internal func keyboardDidHide(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
_topViewBeginRect = CGRect.zero
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///-------------------------------------------
/// MARK: UITextField/UITextView Notifications
///-------------------------------------------
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
internal func textFieldViewDidBeginEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if let textFieldView = _textFieldView as? UITextField {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
} else if let textFieldView = _textFieldView as? UITextView {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if privateIsEnableAutoToolbar() == true {
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if _textFieldView is UITextView == true &&
_textFieldView?.inputAccessoryView == nil {
UIView.animate(withDuration: 0.00001, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (finished) -> Void in
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
self._textFieldView?.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
} else {
removeToolbarIfRequired()
}
_tapGesture.isEnabled = privateShouldResignOnTouchOutside()
_textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14)
if privateIsEnabled() == true {
if _topViewBeginRect.equalTo(CGRect.zero) == true { // (Bug ID: #5)
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let rootViewController = _rootViewController {
_topViewBeginRect = rootViewController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
rootViewController is UINavigationController &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-rootViewController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)")
}
}
//If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
internal func textFieldViewDidEndEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Removing gesture recognizer (Enhancement ID: #14)
_textFieldView?.window?.removeGestureRecognizer(_tapGesture)
// We check if there's a change in original frame or not.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
//Setting object to nil
_textFieldView = nil
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------------------------------
/// MARK: UIStatusBar Notification methods
///------------------------------------------
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
internal func willChangeStatusBarOrientation(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//If textViewContentInsetChanged is saved then restore it.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UIApplicationDidChangeStatusBarFrameNotification. Need to refresh view position and update _topViewBeginRect. (Bug ID: #446)*/
internal func didChangeStatusBarFrame(_ notification : Notification?) -> Void {
let oldStatusBarFrame = _statusBarFrame;
// Getting keyboard animation duration
if let newFrame = ((notification as NSNotification?)?.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSNumber)?.cgRectValue {
_statusBarFrame = newFrame
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
if _rootViewController != nil &&
!_topViewBeginRect.equalTo(_rootViewController!.view.frame) == true {
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_statusBarFrame.size.equalTo(oldStatusBarFrame.size) == false &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------
/// MARK: AutoToolbar
///------------------
/** Get all UITextField/UITextView siblings of textFieldView. */
fileprivate func responderViews()-> [UIView]? {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView.
for disabledClass in toolbarPreviousNextAllowedClasses {
superConsideredView = _textFieldView?.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
//If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
if superConsideredView != nil {
return superConsideredView?.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.bySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
fileprivate func addToolbarIfRequired() {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
// If only one object is found, then adding only Done button.
if (siblings.count == 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysHide {
if let textField = _textFieldView {
var needReload = false;
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
//Supporting Custom Done button image (Enhancement ID: #366)
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
needReload = true
}
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
}
else if let toolbar = textField.inputAccessoryView as? IQToolbar {
if toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
if toolbar.doneTitle != doneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
} else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) ||
(toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
}
}
}
}
if textField.inputAccessoryView is IQToolbar &&
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
//Setting toolbar tintColor // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true &&
textField.shouldHidePlaceholderText == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.title == nil ||
toolbar.title != textField.drawingPlaceholderText {
toolbar.title = textField.drawingPlaceholderText
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
} else {
toolbar.title = nil
}
}
if needReload {
textField.reloadInputViews()
}
}
} else if (siblings.count > 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysShow {
// If more than 1 textField is found. then adding previous/next/done buttons on it.
for textField in siblings {
var needReload = false;
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
needReload = true
}
//Supporting Custom Done button image (Enhancement ID: #366)
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: doneBarButtonItemImage, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: doneBarButtonItemText, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
}
else if let toolbar = textField.inputAccessoryView as? IQToolbar {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: toolbarDoneBarButtonItemImage!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
if toolbar.doneTitle != doneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: toolbarDoneBarButtonItemText!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
} else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) ||
(toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
}
if textField.inputAccessoryView is IQToolbar &&
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true &&
textField.shouldHidePlaceholderText == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.title == nil ||
toolbar.title != textField.drawingPlaceholderText {
toolbar.title = textField.drawingPlaceholderText
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
}
else {
toolbar.title = nil
}
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings[0] == textField {
if (siblings.count == 1) {
textField.setEnablePrevious(false, isNextEnabled: false)
} else {
textField.setEnablePrevious(false, isNextEnabled: true)
}
} else if siblings.last == textField { // If lastTextField then next should not be enaled.
textField.setEnablePrevious(true, isNextEnabled: false)
} else {
textField.setEnablePrevious(true, isNextEnabled: true)
}
}
if needReload {
textField.reloadInputViews()
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** Remove any toolbar if it is IQToolbar. */
fileprivate func removeToolbarIfRequired() { // (Bug ID: #18)
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
for view in siblings {
if let toolbar = view.inputAccessoryView as? IQToolbar {
//setInputAccessoryView: check (Bug ID: #307)
if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
if let textField = view as? UITextField {
textField.inputAccessoryView = nil
} else if let textView = view as? UITextView {
textView.inputAccessoryView = nil
}
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
open func reloadInputViews() {
//If enabled then adding toolbar.
if privateIsEnableAutoToolbar() == true {
self.addToolbarIfRequired()
} else {
self.removeToolbarIfRequired()
}
}
open var enableDebugging = false
fileprivate func showLog(_ logString: String) {
if enableDebugging {
print("IQKeyboardManager: " + logString)
}
}
}
|
mit
|
146c1d4e46516c153de7a64ac9183c6b
| 47.711487 | 370 | 0.561112 | 7.179814 | false | false | false | false |
SoufianeLasri/Sisley
|
Sisley/NavigationButton.swift
|
1
|
2533
|
//
// NavigationButton.swift
// Sisley
//
// Created by Soufiane Lasri on 21/12/2015.
// Copyright © 2015 Soufiane Lasri. All rights reserved.
//
import UIKit
extension UIView {
func roundCorners(corners:UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.CGPath
self.layer.mask = mask
}
}
class NavigationButton: UIButton {
init( frame: CGRect, text: String, imageName: String ) {
super.init( frame: frame )
self.layer.cornerRadius = self.frame.width / 2
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor( red: 0.89, green: 0.81, blue: 0.47, alpha: 1.0 ).CGColor
self.alpha = 0
self.frame.origin.y += 5
let labelView = UIView( frame: CGRectMake( 25, 0, 200, self.frame.height ) )
labelView.backgroundColor = UIColor( red: 0.51, green: 0.54, blue: 0.68, alpha: 1 )
labelView.roundCorners( [ .TopRight, .BottomRight ], radius: 10.0 )
let label = UILabel( frame: labelView.frame )
label.frame.origin.x = 35.0
label.text = text
label.font = UIFont( name: "Bellota-Bold", size: 17.0 )
label.textColor = UIColor.whiteColor()
label.textAlignment = .Left
labelView.addSubview( label )
self.addSubview( labelView )
let circlePath = UIBezierPath( ovalInRect: CGRectMake( 0, 0, self.frame.width, self.frame.height ) )
let backgroundLayer = CAShapeLayer()
backgroundLayer.path = circlePath.CGPath
backgroundLayer.fillColor = UIColor.whiteColor().CGColor
self.layer.addSublayer( backgroundLayer )
let imageView = UIImageView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ) )
imageView.image = UIImage( named: imageName )
imageView.layer.cornerRadius = self.frame.width / 2
imageView.layer.masksToBounds = true
self.addSubview( imageView )
}
func toggleButton( openingState: Bool ) {
if openingState == true {
self.alpha = 1
self.frame.origin.y -= 5
} else {
self.alpha = 0
self.frame.origin.y += 5
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
f0aef93cf4aae79755c5801944f7737c
| 34.166667 | 137 | 0.610585 | 4.137255 | false | false | false | false |
Ryce/flickrpickr
|
Carthage/Checkouts/judokit/Source/SecurityInputField.swift
|
2
|
5132
|
//
// SecurityTextField.swift
// JudoKit
//
// Copyright (c) 2016 Alternative Payments Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
/**
The SecurityInputField is an input field configured to detect, validate and present security numbers of various types of credit cards.
*/
open class SecurityInputField: JudoPayInputField {
/// The card network for the security input field
open var cardNetwork: CardNetwork = .unknown
/// if it is a token payment, a different hint label text should appear
open var isTokenPayment: Bool = false
override func setupView() {
self.textField.isSecureTextEntry = true
super.setupView()
}
// MARK: UITextFieldDelegate Methods
/**
Delegate method implementation
- parameter textField: Text field
- parameter range: Range
- parameter string: String
- returns: Boolean to change characters in given range for a textfield
*/
open func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Only handle delegate calls for own text field
guard textField == self.textField else { return false }
if string.characters.count > 0 && self.textField.isSecureTextEntry {
self.textField.isSecureTextEntry = false
}
// Get old and new text
let oldString = textField.text!
let newString = (oldString as NSString).replacingCharacters(in: range, with: string)
if newString.characters.count == 0 {
return true
}
return newString.isNumeric() && newString.characters.count <= self.cardNetwork.securityCodeLength()
}
// MARK: Custom methods
/**
Check if this input field is valid
- returns: True if valid input
*/
open override func isValid() -> Bool {
return self.textField.text?.characters.count == self.cardNetwork.securityCodeLength()
}
/**
Subclassed method that is called when text field content was changed
- parameter textField: The text field of which the content has changed
*/
open override func textFieldDidChangeValue(_ textField: UITextField) {
super.textFieldDidChangeValue(textField)
self.didChangeInputText()
guard let text = textField.text else { return }
self.delegate?.judoPayInput(self, isValid: text.characters.count == self.cardNetwork.securityCodeLength())
}
/**
The placeholder string for the current input field
- returns: An Attributed String that is the placeholder of the receiver
*/
open override func placeholder() -> NSAttributedString? {
return NSAttributedString(string: self.title(), attributes: [NSForegroundColorAttributeName:self.theme.getPlaceholderTextColor()])
}
/**
Boolean indicating whether the receiver has to show a logo
- returns: True if input field shows a Logo
*/
open override func containsLogo() -> Bool {
return true
}
/**
If the receiving input field contains a logo, this method returns Some
- returns: An optional CardLogoView
*/
open override func logoView() -> CardLogoView? {
let type: CardLogoType = self.cardNetwork == .amex ? .cid : .cvc
return CardLogoView(type: type)
}
/**
Title of the receiver input field
- returns: A string that is the title of the receiver
*/
open override func title() -> String {
return self.cardNetwork.securityCodeTitle()
}
/**
Hint label text
- returns: String that is shown as a hint when user resides in a input field for more than 5 seconds
*/
open override func hintLabelText() -> String {
if isTokenPayment {
return "Re-enter security code"
}
return "Security code"
}
}
|
mit
|
0ea498196aecfef801ee8f0394072ded
| 31.481013 | 139 | 0.660171 | 5.076162 | false | false | false | false |
lyp1992/douyu-Swift
|
YPTV/Pods/Kingfisher/Sources/Indicator.swift
|
7
|
6709
|
//
// Indicator.swift
// Kingfisher
//
// Created by João D. Moreira on 30/08/16.
//
// Copyright (c) 2018 Wei Wang <[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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
#if os(macOS)
public typealias IndicatorView = NSView
#else
public typealias IndicatorView = UIView
#endif
public enum IndicatorType {
/// No indicator.
case none
/// Use system activity indicator.
case activity
/// Use an image as indicator. GIF is supported.
case image(imageData: Data)
/// Use a custom indicator, which conforms to the `Indicator` protocol.
case custom(indicator: Indicator)
}
// MARK: - Indicator Protocol
public protocol Indicator {
func startAnimatingView()
func stopAnimatingView()
var viewCenter: CGPoint { get set }
var view: IndicatorView { get }
}
extension Indicator {
#if os(macOS)
public var viewCenter: CGPoint {
get {
let frame = view.frame
return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 )
}
set {
let frame = view.frame
let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0,
y: newValue.y - frame.size.height / 2.0,
width: frame.size.width,
height: frame.size.height)
view.frame = newFrame
}
}
#else
public var viewCenter: CGPoint {
get {
return view.center
}
set {
view.center = newValue
}
}
#endif
}
// MARK: - ActivityIndicator
// Displays a NSProgressIndicator / UIActivityIndicatorView
final class ActivityIndicator: Indicator {
#if os(macOS)
private let activityIndicatorView: NSProgressIndicator
#else
private let activityIndicatorView: UIActivityIndicatorView
#endif
private var animatingCount = 0
var view: IndicatorView {
return activityIndicatorView
}
func startAnimatingView() {
animatingCount += 1
// Alrady animating
if animatingCount == 1 {
#if os(macOS)
activityIndicatorView.startAnimation(nil)
#else
activityIndicatorView.startAnimating()
#endif
activityIndicatorView.isHidden = false
}
}
func stopAnimatingView() {
animatingCount = max(animatingCount - 1, 0)
if animatingCount == 0 {
#if os(macOS)
activityIndicatorView.stopAnimation(nil)
#else
activityIndicatorView.stopAnimating()
#endif
activityIndicatorView.isHidden = true
}
}
init() {
#if os(macOS)
activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
activityIndicatorView.controlSize = .small
activityIndicatorView.style = .spinning
#else
#if os(tvOS)
let indicatorStyle = UIActivityIndicatorViewStyle.white
#else
let indicatorStyle = UIActivityIndicatorViewStyle.gray
#endif
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle)
activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin]
#endif
}
}
// MARK: - ImageIndicator
// Displays an ImageView. Supports gif
final class ImageIndicator: Indicator {
private let animatedImageIndicatorView: ImageView
var view: IndicatorView {
return animatedImageIndicatorView
}
init?(imageData data: Data, processor: ImageProcessor = DefaultImageProcessor.default, options: KingfisherOptionsInfo = KingfisherEmptyOptionsInfo) {
var options = options
// Use normal image view to show animations, so we need to preload all animation data.
if !options.preloadAllAnimationData {
options.append(.preloadAllAnimationData)
}
guard let image = processor.process(item: .data(data), options: options) else {
return nil
}
animatedImageIndicatorView = ImageView()
animatedImageIndicatorView.image = image
animatedImageIndicatorView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
#if os(macOS)
// Need for gif to animate on macOS
self.animatedImageIndicatorView.imageScaling = .scaleNone
self.animatedImageIndicatorView.canDrawSubviewsIntoLayer = true
#else
animatedImageIndicatorView.contentMode = .center
animatedImageIndicatorView.autoresizingMask = [.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleBottomMargin,
.flexibleTopMargin]
#endif
}
func startAnimatingView() {
#if os(macOS)
animatedImageIndicatorView.animates = true
#else
animatedImageIndicatorView.startAnimating()
#endif
animatedImageIndicatorView.isHidden = false
}
func stopAnimatingView() {
#if os(macOS)
animatedImageIndicatorView.animates = false
#else
animatedImageIndicatorView.stopAnimating()
#endif
animatedImageIndicatorView.isHidden = true
}
}
|
mit
|
fe0fea3b5c2d44aed86f45c77394d3fb
| 32.708543 | 153 | 0.629547 | 5.240625 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/SenderController.swift
|
1
|
34360
|
//
// SenderController.swift
// Telegram-Mac
//
// Created by keepcoder on 31/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TelegramCore
import ObjcUtils
import Postbox
import SwiftSignalKit
import AVFoundation
import QuickLook
import TGUIKit
import libwebp
import TGGifConverter
import InAppSettings
class MediaSenderContainer : Equatable {
let path:String
let caption:String
let isFile:Bool
public init(path:String, caption:String = "", isFile:Bool = false) {
self.path = path
self.caption = caption
self.isFile = isFile
}
static func ==(lhs: MediaSenderContainer, rhs: MediaSenderContainer) -> Bool {
return lhs.path == rhs.path && lhs.caption == rhs.caption && lhs.isFile == rhs.isFile
}
}
class ArchiverSenderContainer : MediaSenderContainer {
let files: [URL]
public init(path:String, caption:String = "", isFile:Bool = true, files: [URL] = []) {
self.files = files
super.init(path: path, caption: caption, isFile: isFile)
}
static func ==(lhs: ArchiverSenderContainer, rhs: ArchiverSenderContainer) -> Bool {
return lhs.path == rhs.path && lhs.caption == rhs.caption && lhs.isFile == rhs.isFile && lhs.files == rhs.files
}
}
class VoiceSenderContainer : MediaSenderContainer {
fileprivate let data:RecordedAudioData
fileprivate let id:Int64?
public init(data:RecordedAudioData, id: Int64?) {
self.data = data
self.id = id
let path: String = data.path
super.init(path: path)
}
}
class VideoMessageSenderContainer : MediaSenderContainer {
fileprivate let duration:Int
fileprivate let size: CGSize
fileprivate let id:Int64?
public init(path:String, duration: Int, size: CGSize, id: Int64?) {
self.duration = duration
self.size = size
self.id = id
super.init(path: path, caption: "", isFile: false)
}
}
class Sender: NSObject {
private static func previewForFile(_ path: String, isSecretRelated: Bool, account: Account) -> [TelegramMediaImageRepresentation] {
var preview:[TelegramMediaImageRepresentation] = []
// if isDirectory(path) {
// let image = NSWorkspace.shared.icon(forFile: path)
// image.lockFocus()
// let imageRep = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height))
// image.unlockFocus()
//
// let compressedData: Data? = imageRep?.representation(using: .jpeg, properties: [:])
// if let compressedData = compressedData {
// let resource = LocalFileMediaResource(fileId: arc4random64())
// account.postbox.mediaBox.storeResourceData(resource.id, data: compressedData)
// preview.append(TelegramMediaImageRepresentation(dimensions: image.size, resource: resource))
// }
// return preview
// }
let mimeType = MIMEType(path)
if mimeType.hasPrefix("video") {
let options = NSMutableDictionary()
options.setValue(320 as NSNumber, forKey: kCGImageDestinationImageMaxPixelSize as String)
options.setValue(true as NSNumber, forKey: kCGImageSourceCreateThumbnailWithTransform as String)
let colorQuality: Float = 0.3
options.setObject(colorQuality as NSNumber, forKey: kCGImageDestinationLossyCompressionQuality as NSString)
let asset = AVAsset(url: URL(fileURLWithPath: path))
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.maximumSize = CGSize(width: 320, height: 320)
imageGenerator.appliesPreferredTrackTransform = true
let fullSizeImage = try? imageGenerator.copyCGImage(at: CMTime(seconds: 0.0, preferredTimescale: asset.duration.timescale), actualTime: nil)
if let image = fullSizeImage {
let mutableData: CFMutableData = NSMutableData() as CFMutableData
if let colorDestination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, options) {
CGImageDestinationSetProperties(colorDestination, nil)
CGImageDestinationAddImage(colorDestination, image, options as CFDictionary)
if CGImageDestinationFinalize(colorDestination) {
let resource = LocalFileMediaResource(fileId: arc4random64(), isSecretRelated: isSecretRelated)
account.postbox.mediaBox.storeResourceData(resource.id, data: mutableData as Data)
preview.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(image.size), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false))
}
}
}
} else if (mimeType.hasPrefix("image") || mimeType.hasSuffix("pdf") && !mimeType.hasPrefix("image/webp")), let thumbData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let options = NSMutableDictionary()
options.setValue(320 as NSNumber, forKey: kCGImageDestinationImageMaxPixelSize as String)
let colorQuality: Float = 0.7
options.setObject(colorQuality as NSNumber, forKey: kCGImageDestinationLossyCompressionQuality as NSString)
options.setValue(true as NSNumber, forKey: kCGImageSourceCreateThumbnailWithTransform as String)
let sourceOptions = NSMutableDictionary()
sourceOptions.setValue(320 as NSNumber, forKey: kCGImageSourceThumbnailMaxPixelSize as String)
sourceOptions.setObject(true as NSNumber, forKey: kCGImageSourceCreateThumbnailFromImageAlways as NSString)
sourceOptions.setValue(true as NSNumber, forKey: kCGImageSourceCreateThumbnailWithTransform as String)
if let imageSource = CGImageSourceCreateWithData(thumbData as CFData, sourceOptions) {
let image = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, sourceOptions)
if let image = image {
let mutableData: CFMutableData = NSMutableData() as CFMutableData
if let colorDestination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, options) {
CGImageDestinationSetProperties(colorDestination, nil)
CGImageDestinationAddImage(colorDestination, image, options as CFDictionary)
if CGImageDestinationFinalize(colorDestination) {
let resource = LocalFileMediaResource(fileId: arc4random64(), isSecretRelated: isSecretRelated)
account.postbox.mediaBox.storeResourceData(resource.id, data: mutableData as Data)
preview.append(TelegramMediaImageRepresentation(dimensions: image.size.pixel, resource: resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false))
}
}
}
}
}
return preview
}
public static func enqueue( input:ChatTextInputState, context: AccountContext, peerId:PeerId, replyId:MessageId?, disablePreview:Bool = false, silent: Bool = false, atDate:Date? = nil, sendAsPeerId: PeerId? = nil, mediaPreview: TelegramMediaWebpage? = nil, emptyHandler:(()->Void)? = nil) ->Signal<[MessageId?],NoError> {
var inset:Int = 0
var input:ChatTextInputState = input
let emojis = Array(input.inputText.fixed.emojiString).map { String($0) }.compactMap {!$0.isEmpty ? $0 : nil}
if input.attributes.isEmpty {
input = ChatTextInputState(inputText: input.inputText.trimmed)
}
if FastSettings.isPossibleReplaceEmojies {
let text = input.attributedString.stringEmojiReplacements
if text != input.attributedString {
input = ChatTextInputState(inputText: text.string, selectionRange: 0 ..< text.string.length, attributes: chatTextAttributes(from: text))
}
}
var mediaReference: AnyMediaReference? = nil
let dices = InteractiveEmojiConfiguration.with(appConfiguration: context.appConfiguration)
if dices.emojis.contains(input.inputText), peerId.namespace != Namespaces.Peer.SecretChat {
mediaReference = AnyMediaReference.standalone(media: TelegramMediaDice(emoji: input.inputText, value: nil))
input = ChatTextInputState(inputText: "")
}
if let media = mediaPreview, !disablePreview {
mediaReference = AnyMediaReference.standalone(media: media)
}
let parsingUrlType: ParsingType
if peerId.namespace != Namespaces.Peer.SecretChat {
parsingUrlType = [.Hashtags]
} else {
parsingUrlType = [.Links, .Hashtags]
}
let mapped = cut_long_message( input.inputText, 4096).compactMap { message -> EnqueueMessage? in
let subState = input.subInputState(from: NSMakeRange(inset, message.length))
inset += message.length
var attributes:[MessageAttribute] = [TextEntitiesMessageAttribute(entities: subState.messageTextEntities(parsingUrlType))]
if let date = atDate {
attributes.append(OutgoingScheduleInfoMessageAttribute(scheduleTime: Int32(date.timeIntervalSince1970)))
}
if disablePreview {
attributes.append(OutgoingContentInfoMessageAttribute(flags: [.disableLinkPreviews]))
}
if FastSettings.isChannelMessagesMuted(peerId) || silent {
attributes.append(NotificationInfoMessageAttribute(flags: [.muted]))
}
if let sendAsPeerId = sendAsPeerId {
attributes.append(SendAsMessageAttribute(peerId: sendAsPeerId))
}
if !subState.inputText.isEmpty || mediaReference != nil {
return .message(text: subState.inputText, attributes: attributes, inlineStickers: subState.inlineMedia, mediaReference: mediaReference, replyToMessageId: replyId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: subState.upCollections)
} else {
return nil
}
}
if !mapped.isEmpty {
let inlineMedia = input.inlineMedia.map { $0.key }
return enqueueMessages(account: context.account, peerId: peerId, messages: mapped) |> mapToSignal { value in
if !emojis.isEmpty {
let es = saveUsedEmoji(emojis, postbox: context.account.postbox)
let aes = saveAnimatedUsedEmoji(inlineMedia, postbox: context.account.postbox)
return combineLatest(es, aes) |> map { _ in
return value
}
}
return .single(value)
} |> deliverOnMainQueue
} else {
DispatchQueue.main.async {
emptyHandler?()
}
return .complete()
}
}
public static func enqueue(message:EnqueueMessage, context: AccountContext, peerId:PeerId) ->Signal<[MessageId?],NoError> {
return enqueueMessages(account: context.account, peerId: peerId, messages: [message])
|> deliverOnMainQueue
}
static func generateMedia(for container:MediaSenderContainer, account: Account, isSecretRelated: Bool, isCollage: Bool = false) -> Signal<(Media,String), NoError> {
return Signal { (subscriber) in
let path = container.path
var media:Media!
var randomId: Int64 = 0
arc4random_buf(&randomId, 8)
func makeFileMedia(_ isMedia: Bool) {
let mimeType = MIMEType(path)
let attrs:[TelegramMediaFileAttribute] = fileAttributes(for:mimeType, path:path, isMedia: isMedia)
let resource: TelegramMediaResource = path.isDirectory ? LocalFileArchiveMediaResource(randomId: randomId, path: path) : LocalFileReferenceMediaResource(localFilePath:path,randomId:randomId, size: fileSize(path))
media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: resource, previewRepresentations: previewForFile(path, isSecretRelated: isSecretRelated, account: account), videoThumbnails: [], immediateThumbnailData: nil, mimeType: mimeType, size: nil, attributes: attrs)
}
if !container.isFile {
let mimeType = MIMEType(path)
if let container = container as? VoiceSenderContainer {
let mimeType = voiceMime
var attrs:[TelegramMediaFileAttribute] = []
let memoryWaveform:Data? = container.data.waveform
let resource: TelegramMediaResource
if let id = container.id, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
resource = LocalFileMediaResource(fileId: id, size: fileSize(path), isSecretRelated: isSecretRelated)
account.postbox.mediaBox.storeResourceData(resource.id, data: data)
} else {
resource = LocalFileReferenceMediaResource(localFilePath:path, randomId: randomId, isUniquelyReferencedTemporaryFile: true, size: fileSize(path))
}
attrs.append(.Audio(isVoice: true, duration: Int(container.data.duration), title: nil, performer: nil, waveform: memoryWaveform))
media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: resource, previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: mimeType, size: nil, attributes: attrs)
} else if let container = container as? VideoMessageSenderContainer {
var attrs:[TelegramMediaFileAttribute] = []
let resource: TelegramMediaResource
if let id = container.id, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
resource = LocalFileMediaResource(fileId: id, size: fileSize(path), isSecretRelated: isSecretRelated)
account.postbox.mediaBox.storeResourceData(resource.id, data: data)
} else {
resource = LocalFileReferenceMediaResource(localFilePath:path, randomId: randomId, isUniquelyReferencedTemporaryFile: true, size: fileSize(path))
}
attrs.append(TelegramMediaFileAttribute.Video(duration: Int(container.duration), size: PixelDimensions(container.size), flags: [.instantRoundVideo]))
media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: resource, previewRepresentations: previewForFile(path, isSecretRelated: isSecretRelated, account: account), videoThumbnails: [], immediateThumbnailData: nil, mimeType: mimeType, size: nil, attributes: attrs)
} else if mimeType.hasPrefix("image/webp") {
let resource = LocalFileReferenceMediaResource(localFilePath:path, randomId: randomId, isUniquelyReferencedTemporaryFile: false, size: fileSize(path))
media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: resource, previewRepresentations: previewForFile(path, isSecretRelated: isSecretRelated, account: account), videoThumbnails: [], immediateThumbnailData: nil, mimeType: mimeType, size: nil, attributes: fileAttributes(for: mimeType, path: path, isMedia: true))
} else if mimeType.hasPrefix("image/") && !mimeType.hasSuffix("gif"), let imageData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let options = NSMutableDictionary()
options.setValue(true as NSNumber, forKey: kCGImageSourceCreateThumbnailWithTransform as String)
options.setValue(1280 as NSNumber, forKey: kCGImageSourceThumbnailMaxPixelSize as String)
options.setValue(true as NSNumber, forKey: kCGImageSourceCreateThumbnailFromImageAlways as String)
if let imageSource = CGImageSourceCreateWithData(imageData as CFData, nil) {
let image = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options)
if let image = image {
let size = image.size
if size.width / 10 > size.height || size.height < 40 {
makeFileMedia(true)
} else {
let data = compressImageToJPEG(image, quality: 0.83)
let path = NSTemporaryDirectory() + "tg_image_\(arc4random()).jpeg"
if let data = data {
try? data.write(to: URL(fileURLWithPath: path))
}
let scaledSize = size.fitted(CGSize(width: 1280.0, height: 1280.0))
let resource = LocalFileReferenceMediaResource(localFilePath:path,randomId:randomId, isUniquelyReferencedTemporaryFile: true)
media = TelegramMediaImage(imageId: MediaId(namespace: Namespaces.Media.LocalImage, id: randomId), representations: [TelegramMediaImageRepresentation(dimensions: PixelDimensions(scaledSize), resource: resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false)], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: [])
}
} else {
makeFileMedia(true)
}
} else {
makeFileMedia(true)
}
} else if mimeType.hasPrefix("video") {
let attrs:[TelegramMediaFileAttribute] = fileAttributes(for:mimeType, path:path, isMedia: true, inCollage: isCollage)
media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: LocalFileVideoMediaResource(randomId: randomId, path: container.path), previewRepresentations: previewForFile(path, isSecretRelated: isSecretRelated, account: account), videoThumbnails: [], immediateThumbnailData: nil, mimeType: "video/mp4", size: nil, attributes: attrs)
} else if mimeType.hasPrefix("image/gif") {
let attrs:[TelegramMediaFileAttribute] = fileAttributes(for:mimeType, path:path, isMedia: true, inCollage: isCollage)
media = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: LocalFileGifMediaResource(randomId: randomId, path: container.path), previewRepresentations: previewForFile(path, isSecretRelated: isSecretRelated, account: account), videoThumbnails: [], immediateThumbnailData: nil, mimeType: "video/mp4", size: nil, attributes: attrs)
} else {
makeFileMedia(true)
}
} else {
makeFileMedia(false)
}
subscriber.putNext((media,container.caption))
subscriber.putCompletion()
return EmptyDisposable
} |> runOn(resourcesQueue)
}
public static func fileAttributes(for mime:String, path:String, isMedia:Bool = false, inCollage: Bool = false) -> [TelegramMediaFileAttribute] {
var attrs:[TelegramMediaFileAttribute] = []
if mime.hasPrefix("audio/") {
//AVURLAsset* asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:nil];
let asset = AVURLAsset(url: URL(fileURLWithPath: path))
let tags = audioTags(asset)
let parts = path.nsstring.lastPathComponent.components(separatedBy: "-")
let defaultTitle:String
let defaultPerformer:String
if let title = tags["title"], let performer = tags["performer"] {
defaultTitle = title
defaultPerformer = performer
} else if parts.count == 2 {
defaultTitle = parts[0]
defaultPerformer = parts[1]
} else {
defaultTitle = "Untitled"
defaultPerformer = "Unknown Artist"
}
attrs.append(.Audio(isVoice: false, duration: Int(CMTimeGetSeconds(asset.duration)), title: defaultTitle, performer: defaultPerformer, waveform: nil))
}
if mime.hasPrefix("video"), isMedia {
let asset = AVURLAsset(url: URL(fileURLWithPath: path))
let video = asset.tracks(withMediaType: AVMediaType.video).first
let audio = asset.tracks(withMediaType: AVMediaType.audio).first
if let video = video {
var size = video.naturalSize.applying(video.preferredTransform)
size = NSMakeSize(floor(abs(size.width)), floor(abs(size.height)))
attrs.append(TelegramMediaFileAttribute.Video(duration: Int(CMTimeGetSeconds(asset.duration)), size: PixelDimensions(size), flags: []))
attrs.append(TelegramMediaFileAttribute.FileName(fileName: path.nsstring.lastPathComponent.nsstring.deletingPathExtension.appending(".mp4")))
if !inCollage {
if audio == nil, let size = fileSize(path), size < Int32(10 * 1024 * 1024), mime.hasSuffix("mp4") {
attrs.append(TelegramMediaFileAttribute.Animated)
}
}
if !mime.hasSuffix("mp4") {
attrs.append(.hintFileIsLarge)
}
return attrs
}
}
if mime.hasSuffix("gif"), isMedia {
attrs.append(TelegramMediaFileAttribute.Video(duration: 0, size:TGGifConverter.gifDimensionSize(path).pixel, flags: []))
if !inCollage {
attrs.append(TelegramMediaFileAttribute.Animated)
}
attrs.append(TelegramMediaFileAttribute.FileName(fileName: path.nsstring.lastPathComponent.nsstring.deletingPathExtension.appending(".mp4")))
} else if mime.hasPrefix("image"), let image = NSImage(contentsOf: URL(fileURLWithPath: path)), !mime.hasPrefix("image/webp") {
var size = image.size
if size.width == .infinity || size.height == .infinity {
size = image.cgImage(forProposedRect: nil, context: nil, hints: nil)!.size
}
attrs.append(TelegramMediaFileAttribute.ImageSize(size: size.pixel))
attrs.append(TelegramMediaFileAttribute.FileName(fileName: path.nsstring.lastPathComponent))
if mime.hasPrefix("image/webp") {
attrs.append(.Sticker(displayText: "", packReference: nil, maskData: nil))
}
} else if mime.hasPrefix("image/webp") {
var size: NSSize = NSMakeSize(512, 512)
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
size = convertFromWebP(data)?.size ?? size
}
attrs.append(TelegramMediaFileAttribute.ImageSize(size: size.pixel))
attrs.append(TelegramMediaFileAttribute.FileName(fileName: path.nsstring.lastPathComponent))
attrs.append(.Sticker(displayText: "", packReference: nil, maskData: nil))
} else {
let getname:(String)->String = { path in
var result: String = path.nsstring.lastPathComponent
if result.contains("tg_temp_archive_") {
result = "Telegram Archive"
}
if path.isDirectory {
result += ".zip"
}
return result
}
attrs.append(TelegramMediaFileAttribute.FileName(fileName: getname(path)))
}
return attrs
}
public static func forwardMessages(messageIds:[MessageId], context: AccountContext, peerId:PeerId, replyId: MessageId?, hideNames: Bool = false, hideCaptions: Bool = false, silent: Bool = false, atDate: Date? = nil, sendAsPeerId: PeerId? = nil) -> Signal<[MessageId?], NoError> {
var fwdMessages:[EnqueueMessage] = []
let sorted = messageIds.sorted(by: >)
var attributes: [MessageAttribute] = []
if FastSettings.isChannelMessagesMuted(peerId) || silent {
attributes.append(NotificationInfoMessageAttribute(flags: [.muted]))
}
if hideNames || hideCaptions {
attributes.append(ForwardOptionsMessageAttribute(hideNames: hideNames || hideCaptions, hideCaptions: hideCaptions))
}
if let date = atDate {
attributes.append(OutgoingScheduleInfoMessageAttribute(scheduleTime: Int32(date.timeIntervalSince1970)))
}
if let sendAsPeerId = sendAsPeerId {
attributes.append(SendAsMessageAttribute(peerId: sendAsPeerId))
}
let threadId: Int64?
if let replyId = replyId {
threadId = makeMessageThreadId(replyId)
} else {
threadId = nil
}
for msgId in sorted {
fwdMessages.append(EnqueueMessage.forward(source: msgId, threadId: threadId, grouping: messageIds.count > 1 ? .auto : .none, attributes: attributes, correlationId: nil))
}
return enqueueMessages(account: context.account, peerId: peerId, messages: fwdMessages.reversed())
}
public static func shareContact(context: AccountContext, peerId:PeerId, contact:TelegramUser, replyId:MessageId?, sendAsPeerId: PeerId? = nil) -> Signal<[MessageId?], NoError> {
var attributes:[MessageAttribute] = []
if FastSettings.isChannelMessagesMuted(peerId) {
attributes.append(NotificationInfoMessageAttribute(flags: [.muted]))
}
if let sendAsPeerId = sendAsPeerId {
attributes.append(SendAsMessageAttribute(peerId: sendAsPeerId))
}
return enqueueMessages(account: context.account, peerId: peerId, messages: [EnqueueMessage.message(text: "", attributes: attributes, inlineStickers: [:], mediaReference: AnyMediaReference.standalone(media: TelegramMediaContact(firstName: contact.firstName ?? "", lastName: contact.lastName ?? "", phoneNumber: contact.phone ?? "", peerId: contact.id, vCardData: nil)), replyToMessageId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])])
}
public static func enqueue(media:[MediaSenderContainer], context: AccountContext, peerId:PeerId, replyId: MessageId?, silent: Bool = false, atDate:Date? = nil, sendAsPeerId:PeerId? = nil, query: String? = nil) ->Signal<[MessageId?], NoError> {
var senders:[Signal<[MessageId?], NoError>] = []
var attributes:[MessageAttribute] = []
if FastSettings.isChannelMessagesMuted(peerId) || silent {
attributes.append(NotificationInfoMessageAttribute(flags: [.muted]))
}
if let date = atDate {
attributes.append(OutgoingScheduleInfoMessageAttribute(scheduleTime: Int32(date.timeIntervalSince1970)))
}
if let sendAsPeerId = sendAsPeerId {
attributes.append(SendAsMessageAttribute(peerId: sendAsPeerId))
}
if let query = query, !query.isEmpty {
attributes.append(EmojiSearchQueryMessageAttribute(query: query))
}
for path in media {
senders.append(generateMedia(for: path, account: context.account, isSecretRelated: peerId.namespace == Namespaces.Peer.SecretChat) |> mapToSignal { media, caption -> Signal< [MessageId?], NoError> in
return enqueueMessages(account: context.account, peerId: peerId, messages: [EnqueueMessage.message(text: caption, attributes:attributes, inlineStickers: [:], mediaReference: AnyMediaReference.standalone(media: media), replyToMessageId: replyId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])])
})
}
return combineLatest(senders) |> deliverOnMainQueue |> mapToSignal { results -> Signal<[MessageId?], NoError> in
let result = results.reduce([], { messageIds, current -> [MessageId?] in
return messageIds + current
})
return .single(result)
} |> take(1)
}
public static func enqueue(media:Media, context: AccountContext, peerId:PeerId, replyId:MessageId?, silent: Bool = false, atDate: Date? = nil, query: String? = nil, collectionId: ItemCollectionId? = nil) ->Signal<[MessageId?],NoError> {
return enqueue(media: [media], caption: ChatTextInputState(), context: context, peerId: peerId, replyId: replyId, silent: silent, atDate: atDate, query: query, collectionId: collectionId)
}
public static func enqueue(media:[Media], caption: ChatTextInputState, context: AccountContext, peerId:PeerId, replyId:MessageId?, isCollage: Bool = false, additionText: ChatTextInputState? = nil, silent: Bool = false, atDate: Date? = nil, sendAsPeerId: PeerId? = nil, query: String? = nil, collectionId: ItemCollectionId? = nil) ->Signal<[MessageId?],NoError> {
let parsingUrlType: ParsingType
if peerId.namespace != Namespaces.Peer.SecretChat {
parsingUrlType = [.Hashtags]
} else {
parsingUrlType = [.Links, .Hashtags]
}
var attributes:[MessageAttribute] = [TextEntitiesMessageAttribute(entities: caption.messageTextEntities(parsingUrlType))]
let caption = Atomic(value: caption)
if FastSettings.isChannelMessagesMuted(peerId) || silent {
attributes.append(NotificationInfoMessageAttribute(flags: [.muted]))
}
if let date = atDate {
attributes.append(OutgoingScheduleInfoMessageAttribute(scheduleTime: Int32(date.timeIntervalSince1970)))
}
if let sendAsPeerId = sendAsPeerId {
attributes.append(SendAsMessageAttribute(peerId: sendAsPeerId))
}
if let query = query, !query.isEmpty {
attributes.append(EmojiSearchQueryMessageAttribute(query: query))
}
let localGroupingKey = isCollage ? arc4random64() : nil
var upCollections:[ItemCollectionId] = []
if let collectionId = collectionId {
upCollections.append(collectionId)
}
var messages: [EnqueueMessage] = []
let count = media.count
let inlineMdeia = caption.with { $0.inlineMedia }
for (i, media) in media.enumerated() {
let text: String
if media.isInteractiveMedia {
text = caption.swap(.init()).inputText
} else if i == count - 1 {
text = caption.swap(.init()).inputText
} else {
text = ""
}
messages.append(EnqueueMessage.message(text: text, attributes: attributes, inlineStickers: inlineMdeia, mediaReference: AnyMediaReference.standalone(media: media), replyToMessageId: replyId, localGroupingKey: localGroupingKey, correlationId: nil, bubbleUpEmojiOrStickersets: upCollections))
}
if let input = additionText {
var inset:Int = 0
var input:ChatTextInputState = input
if input.attributes.isEmpty {
input = ChatTextInputState(inputText: input.inputText.trimmed)
}
let mapped = cut_long_message( input.inputText, 4096).map { message -> EnqueueMessage in
let subState = input.subInputState(from: NSMakeRange(inset, message.length))
inset += message.length
var attributes:[MessageAttribute] = [TextEntitiesMessageAttribute(entities: subState.messageTextEntities(parsingUrlType))]
if FastSettings.isChannelMessagesMuted(peerId) || silent {
attributes.append(NotificationInfoMessageAttribute(flags: [.muted]))
}
if let date = atDate {
attributes.append(OutgoingScheduleInfoMessageAttribute(scheduleTime: Int32(date.timeIntervalSince1970)))
}
if let sendAsPeerId = sendAsPeerId {
attributes.append(SendAsMessageAttribute(peerId: sendAsPeerId))
}
return EnqueueMessage.message(text: subState.inputText, attributes: attributes, inlineStickers: subState.inlineMedia, mediaReference: nil, replyToMessageId: replyId, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: subState.upCollections)
}
messages.insert(contentsOf: mapped, at: 0)
}
return enqueueMessages(account: context.account, peerId: peerId, messages: messages) |> deliverOnMainQueue |> take(1)
}
}
|
gpl-2.0
|
434526448d777304a22a6b439e1ce8aa
| 54.150883 | 476 | 0.620216 | 5.259299 | false | false | false | false |
fightjc/Paradise_Lost
|
Paradise Lost/Classes/Views/Game/SudokuView.swift
|
3
|
17279
|
//
// SudokuView.swift
// Paradise Lost
//
// Created by Jason Chen on 6/1/16.
// Copyright © 2016 Jason Chen. All rights reserved.
//
import UIKit
protocol SudokuViewDelegate {
func startGameAction(_ didStartGame: Bool, usedSec: Int)
func resetGameAction(_ needAlert: Bool)
func exitGameAction(_ usedSec: Int)
}
class SudokuView: UIView {
fileprivate var didStartGame: Bool = false
fileprivate var timer: Timer = Timer()
var seconds: Int = 0 {
didSet {
if seconds == 0 {
stopTimer()
timeNumberLabel.text = "0:0:0"
}
}
}
var delegate: SudokuViewDelegate? = nil
// MARK: life cycle
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
didStartGame = false
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate func setupView() {
addSubview(titleLabel)
addSubview(startButton)
addSubview(resetButton)
addSubview(exitButton)
addSubview(numberLabel)
addSubview(timeLabel)
addSubview(timeNumberLabel)
startButton.addTarget(self, action: #selector(SudokuView.startGame), for: .touchUpInside)
resetButton.addTarget(self, action: #selector(SudokuView.resetGame), for: .touchUpInside)
exitButton.addTarget(self, action: #selector(SudokuView.exitGame), for: .touchUpInside)
}
override func layoutSubviews() {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-40-[v0(35)]-434-[v1(30)]-8-[v2(30)]-8-[v3(30)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": titleLabel, "v1": startButton, "v2": resetButton, "v3": exitButton]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-509-[v2(30)]-[v0(30)]-[v1(30)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": timeLabel, "v1": timeNumberLabel, "v2": numberLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": titleLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-294-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": startButton]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-294-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": resetButton]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-294-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": exitButton]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-294-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": numberLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-294-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": timeLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-294-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": timeNumberLabel]))
}
// MARK: event response
@objc func startGame() {
didStartGame = !didStartGame
if didStartGame {
startButton.setTitle(LanguageManager.getPublicString(forKey: "pause"), for: UIControlState())
runTimer()
} else {
startButton.setTitle(LanguageManager.getPublicString(forKey: "start"), for: UIControlState())
stopTimer()
}
delegate?.startGameAction(didStartGame, usedSec: seconds)
}
func resetScreen() {
didStartGame = false
// timer
stopTimer()
showSecondText()
// button
startButton.setTitle(LanguageManager.getPublicString(forKey: "start"), for: UIControlState())
}
@objc func resetGame() {
resetScreen()
delegate?.resetGameAction(true)
}
@objc func exitGame() {
stopTimer()
delegate?.exitGameAction(seconds)
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(SudokuView.addASecond), userInfo: nil, repeats: true)
}
func stopTimer() {
if timer.isValid {
timer.invalidate()
}
}
// MARK: private methods
@objc fileprivate func addASecond() {
seconds = seconds + 1
showSecondText()
}
fileprivate func showSecondText() {
var minute: Int = seconds / 60
let hours: Int = minute / 60
minute = minute % 60
let second: Int = seconds % 60
timeNumberLabel.text = "\(hours):\(minute):\(second)"
}
// MARK: getters and setters
fileprivate var titleLabel: UILabel = {
var label = UILabel()
label.text = LanguageManager.getGameString(forKey: "sudoku.titlelabel.text")
label.font = UIFont.boldSystemFont(ofSize: 36)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var numberLabel: UILabel = {
var label = UILabel()
label.text = "NO. 1"
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label;
}()
func setNumber(_ number: Int) {
numberLabel.text = "NO. \(number)"
}
fileprivate var timeLabel: UILabel = {
var label = UILabel()
label.text = LanguageManager.getGameString(forKey: "sudoku.timelabel.text")
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var timeNumberLabel: UILabel = {
var label = UILabel()
label.text = "0:0:0"
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var startButton: UIButton = {
var button = UIButton(type: .system)
button.setTitle(LanguageManager.getPublicString(forKey: "start"), for: UIControlState())
button.isExclusiveTouch = true
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
fileprivate var resetButton: UIButton = {
var button = UIButton(type: .system)
button.setTitle(LanguageManager.getGameString(forKey: "sudoku.resetbutton.title"), for: UIControlState())
button.isExclusiveTouch = true
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
fileprivate var exitButton: UIButton = {
var button = UIButton(type: .system)
button.setTitle(LanguageManager.getPublicString(forKey: "exit"), for: UIControlState())
button.isExclusiveTouch = true
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
}
protocol SudokuGridViewDelegate {
func didRefreshSudoku(_ uSudoku: [Int])
}
class SudokuGridView: UIView {
fileprivate var viewHeight: CGFloat = 0
fileprivate var viewWidth: CGFloat = 0
var delegate: SudokuGridViewDelegate? = nil
var canEnable: Bool = false {
didSet {
selectedPoint = (0, 0)
}
}
/// the point that user selected, (0, 0) means no selected number
var selectedPoint: (Int, Int) = (0, 0) {
didSet {
setNeedsDisplay()
}
}
/// the sudoku with only stable number
var stableSudoku: [Int] = []
/// the numbers in each grid
var sudoku: [Int] = [] {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
let height = rect.height
let width = rect.width
let gridHeight = height / 9
let gridWidth = width / 9
let gridLine: CGFloat = 2.0
let regionLine: CGFloat = 4.0
// background
let path = UIBezierPath(rect: rect)
let fillColor = Color().CosmicLatte
fillColor.setFill()
path.fill()
// line
let gridPath = UIBezierPath()
gridPath.lineWidth = gridLine
let regionPath = UIBezierPath()
regionPath.lineWidth = regionLine
// horizontal
for i in 0...9 {
if i % 3 == 0 {
regionPath.move(to: CGPoint(x: 0, y: gridHeight * CGFloat(i)))
regionPath.addLine(to: CGPoint(x: width, y: gridHeight * CGFloat(i)))
} else {
gridPath.move(to: CGPoint(x: 0, y: gridHeight * CGFloat(i)))
gridPath.addLine(to: CGPoint(x: width, y: gridHeight * CGFloat(i)))
}
}
// vertical
for i in 0...9 {
if i % 3 == 0 {
regionPath.move(to: CGPoint(x: gridWidth * CGFloat(i), y: 0))
regionPath.addLine(to: CGPoint(x: gridWidth * CGFloat(i), y: height))
} else {
gridPath.move(to: CGPoint(x: gridWidth * CGFloat(i), y: 0))
gridPath.addLine(to: CGPoint(x: gridWidth * CGFloat(i), y: height))
}
}
UIColor.black.setStroke()
gridPath.stroke()
regionPath.stroke()
// selected field
if canEnable {
let (x, y) = selectedPoint
if x != 0 && y != 0 {
let selectedRect = UIBezierPath(rect:
CGRect(x: gridWidth * CGFloat(x - 1), y: gridHeight * CGFloat(y - 1), width: gridWidth, height: gridHeight))
Color().BrightOrange.setFill()
selectedRect.fill()
}
}
// numbers
for j in 0..<9 {
for i in 0..<9 {
if sudoku[i + j * 9] != 0 {
let str = "\(sudoku[i + j * 9])"
var attributes: [NSAttributedStringKey: AnyObject] = [:]
if stableSudoku[i + j * 9] != 0 {
// stable number
attributes = [NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 24)!]
} else {
// number can be changed
if !canEnable {
// game pause thus do not show typed number
continue
}
attributes = [NSAttributedStringKey.font: UIFont(name: "Courier", size: 22)!]
}
let centerX = gridWidth * CGFloat(i) + gridWidth / 2
let centerY = gridHeight * CGFloat(j) + gridHeight / 2
str.draw(at: CGPoint(x: centerX - 8, y: centerY - 12), withAttributes: attributes)
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
viewHeight = frame.height
viewWidth = frame.width
selectedPoint = (0, 0)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate func setupView() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SudokuGridView.handleTapGesture(_:)))
addGestureRecognizer(tapGesture)
}
// MARK: event response
@objc func handleTapGesture(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
if !canEnable {
return
}
let pos = sender.location(in: self)
// get point
let i = Int(9 * pos.x / viewWidth) + 1
let j = Int(9 * pos.y / viewHeight) + 1
selectedPoint = (i, j)
}
}
func putNumberToPoint(_ number: Int) {
let (x, y) = selectedPoint
if x != 0 && y != 0 {
let index = x - 1 + (y - 1) * 9
if stableSudoku[index] == 0 {
// not a stable number
sudoku = SudokuManager.putNumber(sudoku, index: index, number: number)
delegate?.didRefreshSudoku(sudoku)
}
}
}
}
protocol SudokuPanelViewDelegate {
func didTapNumber(_ number: Int)
}
/**
3 * 4 panel to control the input, includes 0 ~ 9 number and previous, clear, next button
*/
class SudokuPanelView: UIView {
fileprivate var viewHeight: CGFloat = 0
fileprivate var viewWidth: CGFloat = 0
var delegate: SudokuPanelViewDelegate? = nil
override func draw(_ rect: CGRect) {
// assume that height is 4/3 of width
let height = rect.height
let width = rect.width
let plusHeight: CGFloat = 3.0
// background
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: width, height: width))
let fillColor = UIColor.brown
fillColor.setFill()
path.fill()
// line
let plusPath = UIBezierPath()
plusPath.lineWidth = plusHeight
plusPath.move(to: CGPoint(x: 0, y: width / 3))
plusPath.addLine(to: CGPoint(x: width, y: width / 3))
plusPath.move(to: CGPoint(x: 0, y: width / 3 * 2))
plusPath.addLine(to: CGPoint(x: width, y: width / 3 * 2))
plusPath.move(to: CGPoint(x: width / 3, y: 0))
plusPath.addLine(to: CGPoint(x: width / 3, y: width))
plusPath.move(to: CGPoint(x: width / 3 * 2, y: 0))
plusPath.addLine(to: CGPoint(x: width / 3 * 2, y: width))
UIColor.white.setStroke()
plusPath.stroke()
// numbers
for j in 0..<3 {
for i in 0..<3 {
let str = "\(i + j * 3 + 1)"
let attributes = [
NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 22),
NSAttributedStringKey.foregroundColor: UIColor.white]
let centerX = width / 3 * CGFloat(i)
let centerY = width / 3 * CGFloat(j)
str.draw(at: CGPoint(x: centerX + 18, y: centerY + 11), withAttributes: attributes)
}
}
let buttonCenterY = (width + height) / 2
// previous button
// a triangle
let pTriPath = UIBezierPath()
pTriPath.move(to: CGPoint(x: 0, y: buttonCenterY))
pTriPath.addLine(to: CGPoint(x: width / 12, y: buttonCenterY - width / 24))
pTriPath.addLine(to: CGPoint(x: width / 12, y: buttonCenterY + width / 24))
pTriPath.addLine(to: CGPoint(x: 0, y: buttonCenterY))
UIColor.green.setFill()
pTriPath.fill()
// a rectangle
let pRecPath = UIBezierPath(rect:
CGRect(x: width / 12, y: buttonCenterY - width / 48, width: width / 6, height: width / 24))
UIColor.green.setFill()
pRecPath.fill()
// next button
// a triangle
let nTriPath = UIBezierPath()
nTriPath.move(to: CGPoint(x: width, y: buttonCenterY))
nTriPath.addLine(to: CGPoint(x: width / 12 * 11, y: buttonCenterY - width / 24))
nTriPath.addLine(to: CGPoint(x: width / 12 * 11, y: buttonCenterY + width / 24))
nTriPath.addLine(to: CGPoint(x: width, y: buttonCenterY))
UIColor.green.setFill()
nTriPath.fill()
// a rectangle
let nRecPath = UIBezierPath(rect:
CGRect(x: width / 4 * 3, y: buttonCenterY - width / 48, width: width / 6, height: width / 24))
UIColor.green.setFill()
nRecPath.fill()
// clear
let clearPath = UIBezierPath()
clearPath.lineWidth = plusHeight
clearPath.move(to: CGPoint(x: width / 12 * 5, y: width / 12 * 13))
clearPath.addLine(to: CGPoint(x: width / 12 * 7, y:width / 12 * 15))
clearPath.move(to: CGPoint(x: width / 12 * 7, y: width / 12 * 13))
clearPath.addLine(to: CGPoint(x: width / 12 * 5, y:width / 12 * 15))
UIColor.red.setStroke()
clearPath.stroke()
}
override init(frame: CGRect) {
super.init(frame: frame)
viewHeight = frame.height
viewWidth = frame.width
backgroundColor = UIColor.white
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate func setupView() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SudokuGridView.handleTapGesture(_:)))
addGestureRecognizer(tapGesture)
}
// MARK: event response
func handleTapGesture(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
let pos = sender.location(in: self)
// judge
let i = Int(3 * pos.x / viewWidth) + 1
let j = Int(4 * pos.y / viewHeight)
delegate?.didTapNumber(i + j * 3)
}
}
}
|
mit
|
37b9de51f3acbfe6618f94ce91ff53a8
| 34.55144 | 257 | 0.570726 | 4.552833 | false | false | false | false |
dhf/SwiftForms
|
SwiftForms/controllers/FormViewController.swift
|
1
|
7577
|
//
// FormViewController.swift
// SwiftForms
//
// Created by Miguel Angel Ortuño on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormViewController : UITableViewController {
/// MARK: Types
private struct Static {
static var onceDefaultCellClass: dispatch_once_t = 0
static var defaultCellClasses: [FormRowType : FormBaseCell.Type] = [:]
}
/// MARK: Properties
public var form = FormDescriptor()
/// MARK: Init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// MARK: View life cycle
public override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = form.title
}
/// MARK: Public interface
public func valueForTag(tag: String) -> AnyObject? {
for section in form.sections {
for row in section.rows {
if row.tag == tag {
return row.value
}
}
}
return nil
}
public func setValue(value: NSObject, forTag tag: String) {
for (sectionIndex, section) in form.sections.enumerate() {
if let rowIndex = (section.rows.map { $0.tag }).indexOf(tag),
let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: rowIndex, inSection: sectionIndex)) as? FormBaseCell {
section.rows[rowIndex].value = value
cell.update()
}
}
}
public func indexPathOfTag(tag: String) -> NSIndexPath? {
for (sectionIndex, section) in form.sections.enumerate() {
if let rowIndex = (section.rows.map { $0.tag }).indexOf(tag) {
return NSIndexPath(forRow: rowIndex, inSection: sectionIndex)
}
}
return .None
}
/// MARK: UITableViewDataSource
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return form.sections.count
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return form.sections[section].rows.count
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let rowDescriptor = formRowDescriptorAtIndexPath(indexPath)
let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor)
let reuseIdentifier = NSStringFromClass(formBaseCellClass)
var cell: FormBaseCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? FormBaseCell
if cell == nil {
cell = formBaseCellClass.init(style: .Default, reuseIdentifier: reuseIdentifier)
cell?.formViewController = self
cell?.configure()
}
cell?.rowDescriptor = rowDescriptor
// apply cell custom design
if let cellConfiguration = rowDescriptor.configuration.cellConfiguration {
for (keyPath, value) in cellConfiguration {
cell?.setValue(value, forKeyPath: keyPath)
}
}
return cell!
}
public override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return form.sections[section].headerTitle
}
public override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return form.sections[section].footerTitle
}
/// MARK: UITableViewDelegate
public override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let rowDescriptor = formRowDescriptorAtIndexPath(indexPath)
return formBaseCellClassFromRowDescriptor(rowDescriptor).formRowCellHeight()
}
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let rowDescriptor = formRowDescriptorAtIndexPath(indexPath)
if let selectedRow = tableView.cellForRowAtIndexPath(indexPath) as? FormBaseCell {
let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor)
formBaseCellClass.formViewController(self, didSelectRow: selectedRow)
}
if let didSelectClosure = rowDescriptor.configuration.didSelectClosure {
didSelectClosure()
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
private class func defaultCellClassForRowType(rowType: FormRowType) -> FormBaseCell.Type {
dispatch_once(&Static.onceDefaultCellClass) {
Static.defaultCellClasses[FormRowType.Text] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Number] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.NumbersAndPunctuation] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Decimal] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Name] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Phone] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.URL] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Twitter] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.NamePhone] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Email] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.ASCIICapable] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Password] = FormTextFieldCell.self
Static.defaultCellClasses[FormRowType.Button] = FormButtonCell.self
Static.defaultCellClasses[FormRowType.BooleanSwitch] = FormSwitchCell.self
Static.defaultCellClasses[FormRowType.BooleanCheck] = FormCheckCell.self
Static.defaultCellClasses[FormRowType.SegmentedControl] = FormSegmentedControlCell.self
Static.defaultCellClasses[FormRowType.Picker] = FormPickerCell.self
Static.defaultCellClasses[FormRowType.Date] = FormDateCell.self
Static.defaultCellClasses[FormRowType.Time] = FormDateCell.self
Static.defaultCellClasses[FormRowType.DateAndTime] = FormDateCell.self
Static.defaultCellClasses[FormRowType.Stepper] = FormStepperCell.self
Static.defaultCellClasses[FormRowType.Slider] = FormSliderCell.self
Static.defaultCellClasses[FormRowType.MultipleSelector] = FormSelectorCell.self
Static.defaultCellClasses[FormRowType.MultilineText] = FormTextViewCell.self
}
return Static.defaultCellClasses[rowType]!
}
public func formRowDescriptorAtIndexPath(indexPath: NSIndexPath) -> FormRowDescriptor {
let section = form.sections[indexPath.section]
let rowDescriptor = section.rows[indexPath.row]
return rowDescriptor
}
private func formBaseCellClassFromRowDescriptor(rowDescriptor: FormRowDescriptor) -> FormBaseCell.Type {
let formBaseCellClass: FormBaseCell.Type
if let cellClass = rowDescriptor.configuration.cellClass {
formBaseCellClass = cellClass
} else {
formBaseCellClass = FormViewController.defaultCellClassForRowType(rowDescriptor.rowType)
}
return formBaseCellClass
}
}
|
mit
|
436c5368571d0bdee455c563701e99eb
| 40.620879 | 137 | 0.67538 | 5.497097 | false | false | false | false |
google/android-auto-companion-ios
|
Sources/AndroidAutoConnectedDeviceManager/CommunicationManager.swift
|
1
|
29651
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
@_implementationOnly import AndroidAutoCoreBluetoothProtocols
import AndroidAutoLogger
@_implementationOnly import AndroidAutoMessageStream
@_implementationOnly import AndroidAutoSecureChannel
import CoreBluetooth
import Foundation
/// A delegate to be notified of the current state of secure communication establishment.
protocol CommunicationManagerDelegate: AnyObject {
/// Invoked when the process of encryption setup has begun.
///
/// - Parameters:
/// - communicationManager: The manager handling secure channel establishment.
/// - car: The car for which the encryption setup is in progress.
/// - peripheral: The backing peripheral for the car.
func communicationManager(
_ communicationManager: CommunicationManager,
establishingEncryptionWith car: Car,
peripheral: BLEPeripheral
)
/// Invoked a given car has been set up for secure communication.
///
/// - Parameters:
/// - communicationManager: The manager handling secure channel establishment.
/// - securedCarChannel: The channel that has successfully been established for secure
/// communication.
func communicationManager(
_ communicationManager: CommunicationManager,
didEstablishSecureChannel securedCarChannel: SecuredConnectedDeviceChannel
)
/// Invoked when an error has been encountered during the reconnection.
///
/// - Parameters:
/// - communicationManager: The manager handling secure channel establishment.
/// - error: The error that was encountered.
/// - peripheral: The car a reconnection was attempted with.
func communicationManager(
_ communicationManager: CommunicationManager,
didEncounterError error: CommunicationManagerError,
whenReconnecting peripheral: BLEPeripheral
)
}
/// Possible errors that can result during a secure channel setup.
enum CommunicationManagerError: Error, Equatable {
/// An unknown error occurred and connection could not be established.
case unknown
/// A secure channel was requested to be set up with a car that has not been associated yet.
case notAssociated
/// A secure channel cannot be reestablished with a given car because there is no saved
/// encryption credentials for it.
case noSavedEncryption
/// Saved encryption session is invalid.
case invalidSavedEncryption
/// Failed to establish encryption.
case failedEncryptionEstablishment
/// The remote car does not contains the service that holds the characteristics to read from and
/// write to.
case serviceNotFound
/// The remote car does not contain the characteristics to read from and write to.
case characteristicsNotFound
/// Attempted to connect with an unassociated car.
case unassociatedCar
/// The remote car is not responding to the reconnection flow with the right messages, meaning
/// reconnection cannot occur.
case invalidMessage
/// The required advertisement data is missing.
case missingAdvertisementData
/// The required reconnection helper is missing for the specified peripheral `id`.
case missingReconnectionHelper(UUID)
/// The peripheral's version is not supported.
case versionNotSupported
/// Failed to resolve the version.
case versionResolutionFailed
/// The security version is unresolved.
case unresolvedSecurityVersion
/// The resolved security version doesn't match the helper's security version.
case mismatchedSecurityVersion
/// Attempt to configure a secure channel failed.
case configureSecureChannelFailed
}
/// A manager responsible for handling communication with associated devices.
class CommunicationManager: NSObject {
private static let log = Logger(for: CommunicationManager.self)
/// The amount of time a reconnection attempt has before it has been deemed to have timed out.
static let defaultReconnectionTimeoutDuration = DispatchTimeInterval.seconds(10)
/// The UUIDs of the read and write characteristics that correspond to the different services
/// that are supported.
typealias IOCharacteristicsUUIDs = (
readUUID: CBUUID,
writeUUID: CBUUID
)
static let versionCharacteristics: IOCharacteristicsUUIDs =
(
readUUID: UUIDConfig.readCharacteristicUUID,
writeUUID: UUIDConfig.writeCharacteristicUUID
)
static let advertisementCharacteristicUUID = UUIDConfig.advertisementCharacteristicUUID
static let acknowledgmentMessage = Data("ACK".utf8)
/// Overlay key for the message compression enablement pending support for it.
static let messageCompressionAllowedKey = "MessageCompressionAllowed"
private let connectionHandle: ConnectionHandle
private let uuidConfig: UUIDConfig
private let associatedCarsManager: AssociatedCarsManager
private let secureSessionManager: SecureSessionManager
private let secureBLEChannelFactory: SecureBLEChannelFactory
private let bleVersionResolver: BLEVersionResolver
private let reconnectionHandlerFactory: ReconnectionHandlerFactory
/// Maps identifiers for peripherals to a `DispatchWorkItem` keeping track that should be called
/// if a reconnection attempt has timed out.
private var reconnectionTimeouts: [UUID: DispatchWorkItem] = [:]
/// Whether compression is allowed.
let isMessageCompressionAllowed: Bool
/// The cars waiting for a secure channel to be set up.
var pendingCars: [PendingCar] = []
/// Handlers that are currently in the middle of encryption setup.
var reconnectingHandlers: [ReconnectionHandler] = []
/// `ReconnectionHelper` keyed by peripheral id.
var reconnectionHelpers: [UUID: ReconnectionHelper] = [:]
var timeoutDuration = CommunicationManager.defaultReconnectionTimeoutDuration
weak var delegate: CommunicationManagerDelegate?
/// Creates a `CommunicationManager` with the given storage options.
///
/// - Parameters:
/// - overlay: Overlay of key/value pairs.
/// - connectionHandle: A handle for managing connections to remote cars.
/// - uuidConfig: A configuration for common UUIDs.
/// - associatedCarsManager: Manager for retrieving information about the car that is currently
/// associated with this device.
/// - secureSessionManager: Manager for retrieving and storing secure sessions.
/// - secureBLEChannelFactory: A factory that can create new secure BLE channels.
/// - bleVersionResolver: The version of the message stream to use.
/// - reconnectionHandlerFactory: A factory that can create new `SecuredCarChannelInternal`s.
init(
overlay: Overlay,
connectionHandle: ConnectionHandle,
uuidConfig: UUIDConfig,
associatedCarsManager: AssociatedCarsManager,
secureSessionManager: SecureSessionManager,
secureBLEChannelFactory: SecureBLEChannelFactory,
bleVersionResolver: BLEVersionResolver,
reconnectionHandlerFactory: ReconnectionHandlerFactory
) {
self.connectionHandle = connectionHandle
self.uuidConfig = uuidConfig
self.associatedCarsManager = associatedCarsManager
self.secureSessionManager = secureSessionManager
self.secureBLEChannelFactory = secureBLEChannelFactory
self.bleVersionResolver = bleVersionResolver
self.reconnectionHandlerFactory = reconnectionHandlerFactory
isMessageCompressionAllowed = overlay.isMessageCompressionAllowed
}
/// Add a helper to handle the reconnection handshake details.
///
/// When a peripheral has been discovered, an appropriate helper must be assigned to this manager
/// prior to initiating connection.
///
/// - Parameter helper: The helper to handle reconnection handshake.
func addReconnectionHelper(_ helper: ReconnectionHelper) {
reconnectionHelpers[helper.peripheral.identifier] = helper
}
private func reconnectionHelper(for peripheral: BLEPeripheral) throws -> ReconnectionHelper {
guard let helper = reconnectionHelpers[peripheral.identifier] else {
throw CommunicationManagerError.missingReconnectionHelper(peripheral.identifier)
}
return helper
}
/// Starts the process of setting up a channel for secure communication with the given peripheral.
///
/// - Parameters:
/// - peripheral: The peripheral to set up secure communication with.
/// - id: A unique id that identifies the peripheral. This value can be `nil` if the id is not
/// known at the time of secure channel setup.
func setUpSecureChannel(with peripheral: BLEPeripheral, id: String?) throws {
let pendingCar: PendingCar
let serviceUUIDToDiscover: CBUUID
let helper = try reconnectionHelper(for: peripheral)
if id != nil {
let secureSession = try fetchSecureSession(for: peripheral, id: id!)
pendingCar = PendingCar(car: peripheral, id: id!, secureSession: secureSession)
} else {
pendingCar = PendingCar(car: peripheral)
}
serviceUUIDToDiscover = helper.discoveryUUID(from: uuidConfig)
pendingCars.append(pendingCar)
peripheral.delegate = self
scheduleReconnectionTimeout(for: peripheral)
peripheral.discoverServices([serviceUUIDToDiscover])
}
private func scheduleReconnectionTimeout(for peripheral: BLEPeripheral) {
let notifyReconnectionError = DispatchWorkItem { [weak self] in
Self.log.error(
"Reconnection attempt timed out for car \(peripheral.logName). Notifying delegate.")
self?.notifyDelegateOfError(.failedEncryptionEstablishment, connecting: peripheral)
}
reconnectionTimeouts[peripheral.identifier] = notifyReconnectionError
DispatchQueue.main.asyncAfter(
deadline: .now() + timeoutDuration,
execute: notifyReconnectionError
)
}
/// Returns a saved secure session for the given car or throws an error if the car is
/// unassociated.
private func fetchSecureSession(for car: BLEPeripheral, id: String) throws -> Data {
// Check if the peripheral matches the identifier of a previous association.
guard associatedCarsManager.identifiers.contains(id) else {
Self.log(
"""
Attempted to set up secure channel with unassociated device (\(id). Expected ids: \
\(associatedCarsManager.identifiers)
"""
)
throw CommunicationManagerError.notAssociated
}
guard let secureSession = secureSessionManager.secureSession(for: id) else {
Self.log("No secure session found for car (id: \(id), name: \(car.logName)")
throw CommunicationManagerError.noSavedEncryption
}
return secureSession
}
/// Attempts to resolve the version of the BLE message stream to use.
///
/// The given characteristics are vetted to ensure that they contain the right ones that can
/// receive the unlock signals. If they do not, then this method will do nothing.
///
/// - Parameters:
/// - peripheral: The peripheral to communicate with.
/// - characteristics: The characteristics of the given peripheral.
private func resolveBLEVersion(
with peripheral: BLEPeripheral,
characteristics: [BLECharacteristic]
) {
let ioCharacteristicsUUIDs = CommunicationManager.versionCharacteristics
guard
let (readCharacteristic, writeCharacteristic) =
filter(characteristics, for: ioCharacteristicsUUIDs)
else {
Self.log.error("Missing characteristics for car \(peripheral.logName)")
notifyDelegateOfError(.characteristicsNotFound, connecting: peripheral)
return
}
guard let pendingCar = firstPendingCar(with: peripheral) else {
Self.log.error("No pending car found for \(peripheral.logName)")
notifyDelegateOfError(.characteristicsNotFound, connecting: peripheral)
return
}
pendingCar.readCharacteristic = readCharacteristic
pendingCar.writeCharacteristic = writeCharacteristic
bleVersionResolver.delegate = self
bleVersionResolver.resolveVersion(
with: peripheral,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
}
/// Filters the given characteristics to find the characteristic the car will write to (read
/// characteristic) and the one this device can write to (write characteristic).
///
/// - Parameters:
/// - characteristics: The characteristics to filter.
/// - ioCharacteristicsUUIDs: The read/write characteristics to filter for.
/// - Returns: A tuple containing the read and write characteristics or `nil` if either
/// characteristic cannot be found.
private func filter(
_ characteristics: [BLECharacteristic],
for ioCharacteristicsUUIDs: IOCharacteristicsUUIDs
) -> (readCharacteristic: BLECharacteristic, writeCharacteristic: BLECharacteristic)? {
guard
let readCharacteristic = characteristics.first(where: {
$0.uuid == ioCharacteristicsUUIDs.readUUID
})
else {
Self.log.error("Cannot find read characteristic.")
return nil
}
guard
let writeCharacteristic = characteristics.first(where: {
$0.uuid == ioCharacteristicsUUIDs.writeUUID
})
else {
Self.log.error("Cannot find write characteristic.")
return nil
}
return (readCharacteristic, writeCharacteristic)
}
private func firstPendingCar(with peripheral: BLEPeripheral) -> PendingCar? {
return pendingCars.first(where: { $0.car === peripheral })
}
/// Removes all any cars in the `pendingCars` array that hold the given peripheral.
private func removePendingCars(with peripheral: BLEPeripheral) {
pendingCars.removeAll(where: { $0.car === peripheral })
}
private func notifyDelegateOfError(
_ error: CommunicationManagerError,
connecting peripheral: BLEPeripheral
) {
cleanTimeouts(for: peripheral)
delegate?.communicationManager(self, didEncounterError: error, whenReconnecting: peripheral)
}
private func cleanTimeouts(for peripheral: BLEPeripheral) {
reconnectionTimeouts.removeValue(forKey: peripheral.identifier)?.cancel()
}
/// Returns a log-friendly name for the given `BLEPeripehral`.
private func logName(for peripheral: BLEPeripheral) -> String {
return peripheral.name ?? "no name"
}
}
// MARK: - BLEPeripheralDelegate
extension CommunicationManager: BLEPeripheralDelegate {
func peripheral(_ peripheral: BLEPeripheral, didDiscoverServices error: Error?) {
guard error == nil else {
Self.log.error(
"Error discovering services for car (\(peripheral.logName)): \(error!.localizedDescription)"
)
notifyDelegateOfError(.serviceNotFound, connecting: peripheral)
return
}
guard let services = peripheral.services, services.count > 0 else {
Self.log.error("No services in car \(peripheral.logName)")
notifyDelegateOfError(.serviceNotFound, connecting: peripheral)
return
}
Self.log("Discovered \(services.count) services for car \(peripheral.logName)")
let supportedReconnectionUUIDs = uuidConfig.supportedReconnectionUUIDs
guard let service = services.first(where: { supportedReconnectionUUIDs.contains($0.uuid) })
else {
Self.log.error(
"No service found for \(peripheral.logName) that match supported service UUIDs.")
notifyDelegateOfError(.serviceNotFound, connecting: peripheral)
return
}
peripheral.discoverCharacteristics(
[
Self.versionCharacteristics.writeUUID,
Self.versionCharacteristics.readUUID,
Self.advertisementCharacteristicUUID,
],
for: service
)
}
/// Prepare for transition to version resolution phase.
private func prepareVersionResolution(
for peripheral: BLEPeripheral,
from service: BLEService,
onReadyForHandshake: @escaping () -> Void
) {
do {
let helper = try reconnectionHelper(for: peripheral)
if helper.isReadyForHandshake {
onReadyForHandshake()
return
}
// The advertisement contains data needed to make the helper ready for reconnection.
guard
let advertisementCharacteristic = service.characteristics?.first(where: {
$0.uuid == Self.advertisementCharacteristicUUID
})
else { throw CommunicationManagerError.missingAdvertisementData }
Self.log(
"""
Found advertisement characteristic \(advertisementCharacteristic.uuid.uuidString) \
on car (\(peripheral.logName)) for \
service \(service.uuid.uuidString)
"""
)
helper.onReadyForHandshake = onReadyForHandshake
peripheral.readValue(for: advertisementCharacteristic)
} catch let error as CommunicationManagerError {
notifyDelegateOfError(error, connecting: peripheral)
} catch {
notifyDelegateOfError(.unknown, connecting: peripheral)
}
}
func peripheral(
_ peripheral: BLEPeripheral,
didDiscoverCharacteristicsFor service: BLEService,
error: Error?
) {
guard error == nil else {
Self.log.error(
"""
Error discovering characteristics for car (\(peripheral.logName)): \
\(error!.localizedDescription)
"""
)
notifyDelegateOfError(.characteristicsNotFound, connecting: peripheral)
return
}
guard let characteristics = service.characteristics else {
Self.log.error("No characteristics discovered for car \(peripheral.logName)")
notifyDelegateOfError(.characteristicsNotFound, connecting: peripheral)
return
}
Self.log(
"""
Discovered \(characteristics.count) characteristics on car (\(peripheral.logName)) for \
service \(service.uuid.uuidString)
"""
)
prepareVersionResolution(for: peripheral, from: service) { [weak self] in
self?.resolveBLEVersion(with: peripheral, characteristics: characteristics)
}
}
func peripheral(
_ peripheral: BLEPeripheral,
didUpdateValueFor characteristic: BLECharacteristic,
error: Error?
) {
Self.log(
"""
Received updated value for characteristic \(characteristic.uuid.uuidString) on car \
(\(peripheral.logName))
"""
)
guard characteristic.uuid == Self.advertisementCharacteristicUUID else { return }
do {
let helper = try reconnectionHelper(for: peripheral)
if helper.isReadyForHandshake { return } // Nothing more to do.
guard let advertisementData = characteristic.value else {
Self.log.error(
"""
The advertisement data for peripheral: (\(peripheral.logName)) was requested from \
characteristic: \(characteristic.uuid.uuidString) but the updated value was nil.
"""
)
throw CommunicationManagerError.missingAdvertisementData
}
try helper.prepareForHandshake(withAdvertisementData: advertisementData)
} catch let error as CommunicationManagerError {
notifyDelegateOfError(error, connecting: peripheral)
} catch {
notifyDelegateOfError(.unknown, connecting: peripheral)
}
}
func peripheralIsReadyToWrite(_ peripheral: BLEPeripheral) {}
}
// MARK: - BLEVersionResolverDelegate
extension CommunicationManager: BLEVersionResolverDelegate {
func bleVersionResolver(
_ bleVersionResolver: BLEVersionResolver,
didResolveStreamVersionTo streamVersion: MessageStreamVersion,
securityVersionTo securityVersion: MessageSecurityVersion,
for peripheral: BLEPeripheral
) {
// This shouldn't happen because this case should have been vetted for when characteristics are
// discovered.
guard let pendingCar = firstPendingCar(with: peripheral) else {
Self.log.error("No pending car for (\(peripheral.logName)) to send device id to.")
notifyDelegateOfError(.unknown, connecting: peripheral)
return
}
// This shouldn't happen because the characteristics should have been vetted already before
// version resolution
guard let readCharacteristic = pendingCar.readCharacteristic,
let writeCharacteristic = pendingCar.writeCharacteristic
else {
Self.log.error(
"No read or write characteristic on peripheral (\(peripheral.logName)) to send device id."
)
notifyDelegateOfError(.unknown, connecting: peripheral)
return
}
let messageStream = BLEMessageStreamFactory.makeStream(
version: streamVersion,
peripheral: peripheral,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCompression: isMessageCompressionAllowed
)
pendingCar.messageStream = messageStream
messageStream.delegate = self
guard let helper = reconnectionHelpers[peripheral.identifier] else {
notifyDelegateOfError(.unknown, connecting: peripheral)
return
}
do {
try helper.onResolvedSecurityVersion(securityVersion)
try helper.startHandshake(messageStream: messageStream)
} catch let error as CommunicationManagerError {
notifyDelegateOfError(error, connecting: peripheral)
} catch {
notifyDelegateOfError(.unknown, connecting: peripheral)
}
}
func bleVersionResolver(
_ bleVersionResolver: BLEVersionResolver,
didEncounterError error: BLEVersionResolverError,
for peripheral: BLEPeripheral
) {
switch error {
case BLEVersionResolverError.versionNotSupported:
notifyDelegateOfError(.versionNotSupported, connecting: peripheral)
default:
notifyDelegateOfError(.versionResolutionFailed, connecting: peripheral)
}
}
}
// MARK: - MessageStreamDelegate
extension CommunicationManager: MessageStreamDelegate {
func messageStream(
_ messageStream: MessageStream,
didReceiveMessage message: Data,
params: MessageStreamParams
) {
guard let messageStream = messageStream as? BLEMessageStream else {
fatalError("messageStream: \(messageStream) must be a BLEMessageStream.")
}
let peripheral = messageStream.peripheral
guard let helper = reconnectionHelpers[peripheral.identifier] else {
notifyDelegateOfError(.unknown, connecting: peripheral)
return
}
// Process the handshake message. Then establish the secure channel.
let handshakeResult = Result {
try helper.handleMessage(messageStream: messageStream, message: message)
}
if case let Result.success(isHandshakeComplete) = handshakeResult, !isHandshakeComplete {
// The handshake is incomplete, so nothing more to do until another message arrives.
return
}
// The handshake is complete for this peripheral, so we need to cleanup however we return.
defer {
removePendingCars(with: peripheral)
}
// Handle any error we may have encountered in the handshake.
if case let Result.failure(error) = handshakeResult {
if let error = error as? CommunicationManagerError {
notifyDelegateOfError(error, connecting: peripheral)
} else {
notifyDelegateOfError(.unknown, connecting: peripheral)
}
return
}
// Since the handshake is complete, we expect the helper to have a valid car id.
guard let carId = helper.carId else {
Self.log.error("Missing carId for peripheral (\(peripheral.logName))")
notifyDelegateOfError(.invalidMessage, connecting: peripheral)
return
}
do {
try establishEncryption(messageStream: messageStream, carId: carId)
} catch CommunicationManagerError.noSavedEncryption {
notifyDelegateOfError(.noSavedEncryption, connecting: peripheral)
} catch SecureBLEChannelError.invalidSavedSession {
notifyDelegateOfError(.invalidSavedEncryption, connecting: peripheral)
} catch {
Self.log.error(
"""
Error (\(error.localizedDescription)) establishing secure channel for peripheral
(\(peripheral.logName))
"""
)
notifyDelegateOfError(.failedEncryptionEstablishment, connecting: peripheral)
}
}
/// Establish a secure channel for the specified stream and car.
///
/// - Parameters:
/// - messageStream: The stream used to establish the secure channel.
/// - carId: Car identifier.
/// - Throws: An error it fails to establish a secure channel.
private func establishEncryption(messageStream: MessageStream, carId: String) throws {
var reconnectionHandler = try makeChannel(messageStream: messageStream, carId: carId)
reconnectingHandlers.append(reconnectionHandler)
guard let messageStream = messageStream as? BLEMessageStream else {
fatalError("messageStream: \(messageStream) must be a BLEMessageStream.")
}
delegate?.communicationManager(
self,
establishingEncryptionWith: reconnectionHandler.car,
peripheral: messageStream.peripheral)
reconnectionHandler.delegate = self
try reconnectionHandler.establishEncryption()
}
/// Creates a secured channel with the given stream.
///
/// This method will attempt to retrieve the device id out of the message and then retrieve the
/// associated secure session with that device id.
///
/// - Throws: An error if the secure session is missing.
private func makeChannel(
messageStream: MessageStream,
carId: String
) throws -> ReconnectionHandler {
guard let messageStream = messageStream as? BLEMessageStream else {
fatalError("messageStream: \(messageStream) must be a BLEMessageStream.")
}
let peripheral = messageStream.peripheral
guard let secureSession = secureSessionManager.secureSession(for: carId) else {
Self.log.error(
"No stored secure session with car \(peripheral.logName). Cannot establish encryption."
)
notifyDelegateOfError(.noSavedEncryption, connecting: peripheral)
throw CommunicationManagerError.noSavedEncryption
}
let car = Car(id: carId, name: peripheral.name)
return reconnectionHandlerFactory.makeHandler(
car: car,
connectionHandle: connectionHandle,
secureSession: secureSession,
messageStream: messageStream,
secureBLEChannel: secureBLEChannelFactory.makeChannel(),
secureSessionManager: secureSessionManager
)
}
func messageStream(
_ messageStream: MessageStream,
didEncounterWriteError error: Error,
to recipient: UUID
) {
guard let messageStream = messageStream as? BLEMessageStream else {
fatalError("messageStream: \(messageStream) must be a BLEMessageStream.")
}
Self.log.error(
"Message error \(error.localizedDescription) with car \(messageStream.peripheral.logName)."
)
notifyDelegateOfError(
.invalidMessage, connecting: messageStream.peripheral)
}
func messageStreamEncounteredUnrecoverableError(_ messageStream: MessageStream) {
Self.log.error("Underlying BLEMessageStream encountered unrecoverable error. Disconnecting.")
connectionHandle.disconnect(messageStream)
}
func messageStreamDidWriteMessage(_ messageStream: MessageStream, to recipient: UUID) {
// No-op.
}
}
// MARK: - ReconnectionHandlerDelegate
extension CommunicationManager: ReconnectionHandlerDelegate {
func reconnectionHandler(
_ reconnectionHandler: ReconnectionHandler,
didEstablishSecureChannel securedCarChannel: SecuredConnectedDeviceChannel
) {
guard let helper = try? reconnectionHelper(for: reconnectionHandler.peripheral) else {
Self.log.error("Missing reconnection helper after establishing secure channel.")
delegate?.communicationManager(
self,
didEncounterError: .missingReconnectionHelper(reconnectionHandler.peripheral.identifier),
whenReconnecting: reconnectionHandler.peripheral
)
return
}
helper.configureSecureChannel(
securedCarChannel,
using: connectionHandle
) { [weak self] success in
guard let self = self else { return }
guard success else {
self.delegate?.communicationManager(
self,
didEncounterError: .configureSecureChannelFailed,
whenReconnecting: reconnectionHandler.peripheral)
return
}
self.cleanTimeouts(for: reconnectionHandler.peripheral)
self.delegate?.communicationManager(self, didEstablishSecureChannel: securedCarChannel)
self.reconnectingHandlers.removeAll(where: { $0.car == securedCarChannel.car })
self.reconnectionHelpers[reconnectionHandler.peripheral.identifier] = nil
}
}
func reconnectionHandler(
_ reconnectionHandler: ReconnectionHandler,
didEncounterError error: ReconnectionHandlerError
) {
// This call to notify delegates will clean up any reconnection timeouts.
notifyDelegateOfError(
.failedEncryptionEstablishment,
connecting: reconnectionHandler.peripheral
)
reconnectingHandlers.removeAll(where: { $0.car == reconnectionHandler.car })
reconnectionHelpers[reconnectionHandler.peripheral.identifier] = nil
}
}
// MARK: - Overlay Extensions
extension Overlay {
/// Indicates whether message compression is allowed.
var isMessageCompressionAllowed: Bool {
// Allow for message compression unless the overlay vetoes it.
self[CommunicationManager.messageCompressionAllowedKey] as? Bool ?? true
}
}
|
apache-2.0
|
2c4938e2a3e72b473cb40ed0c03c8fe4
| 35.115713 | 100 | 0.73205 | 5.03498 | false | false | false | false |
mLearningLab/SwiftHandsOn2Adivina
|
JuegoAdivinaTexto/JuegoAdivinaTexto/main.swift
|
1
|
931
|
//
// main.swift
// Juego Adivina (Console Version ver. 1.0)
//
// Created by Alberto Pacheco on 20/07/15.
// Copyright (c) 2015 Alberto Pacheco. All rights reserved.
//
// Ejercicio:
// 1) Modifica ciclo para ofrecer sólo 12 intentos (si se agotan termina e imprime valor oculto)
// 2) Sustituye los "if num" por una sentencia switch/cases, usando patrones
// 3) Si la entrada no es un número, dar oportunidad de repetir intento (no reducir intentos)
import Foundation
var final = false
var oculto = randomNum()
var num: Int!
do {
num = inputNum("Anota número")
if num==nil {
println("Escribiste un valor inválido, intenta de nuevo")
} else if num==oculto {
final = true
} else if num<oculto {
println("Anota num MAYOR")
} else {
println("Anota num menor")
}
} while !final
if final {
println("Ganaste!")
} else {
println("Bye! el número era \(oculto)")
}
|
gpl-2.0
|
ea2fb4128e23f1efed1a8e9471748ba7
| 26.264706 | 96 | 0.656587 | 2.987097 | false | false | false | false |
mssun/pass-ios
|
passAutoFillExtension/Controllers/CredentialProviderViewController.swift
|
2
|
3328
|
//
// CredentialProviderViewController.swift
// passAutoFillExtension
//
// Created by Yishi Lin on 2018/9/24.
// Copyright © 2018 Bob Sun. All rights reserved.
//
import AuthenticationServices
import passKit
class CredentialProviderViewController: ASCredentialProviderViewController {
private lazy var passcodelock: PasscodeExtensionDisplay = { [unowned self] in
PasscodeExtensionDisplay(extensionContext: extensionContext)
}()
private lazy var passwordsViewController: PasswordsViewController = (children.first as! UINavigationController).viewControllers.first as! PasswordsViewController
private lazy var credentialProvider: CredentialProvider = { [unowned self] in
CredentialProvider(viewController: self, extensionContext: extensionContext, afterDecryption: NotificationCenterDispatcher.showOTPNotification)
}()
private lazy var passwordsTableEntries = PasswordStore.shared.fetchPasswordEntityCoreData(withDir: false)
.map(PasswordTableEntry.init)
override func viewDidLoad() {
super.viewDidLoad()
passwordsViewController.dataSource = PasswordsTableDataSource(entries: passwordsTableEntries)
passwordsViewController.selectionDelegate = self
passwordsViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .cancel,
target: self,
action: #selector(cancel)
)
}
override func prepareCredentialList(for serviceIdentifiers: [ASCredentialServiceIdentifier]) {
passcodelock.presentPasscodeLockIfNeeded(self) {
self.view.isHidden = true
} after: { [unowned self] in
self.view.isHidden = false
self.credentialProvider.identifier = serviceIdentifiers.first
let url = serviceIdentifiers.first
.map(\.identifier)
.flatMap(URL.init)
self.passwordsViewController.navigationItem.prompt = url?.host
self.passwordsViewController.showPasswordsWithSuggestion(matching: url?.host ?? "")
}
}
override func provideCredentialWithoutUserInteraction(for credentialIdentity: ASPasswordCredentialIdentity) {
credentialProvider.identifier = credentialIdentity.serviceIdentifier
if !PasscodeLock.shared.hasPasscode, Defaults.isRememberPGPPassphraseOn {
credentialProvider.credentials(for: credentialIdentity)
} else {
extensionContext.cancelRequest(withError: NSError(domain: ASExtensionErrorDomain, code: ASExtensionError.userInteractionRequired.rawValue))
}
}
override func prepareInterfaceToProvideCredential(for credentialIdentity: ASPasswordCredentialIdentity) {
passcodelock.presentPasscodeLockIfNeeded(self) {
self.view.isHidden = true
} after: { [unowned self] in
self.credentialProvider.credentials(for: credentialIdentity)
}
}
@objc
private func cancel(_: AnyObject?) {
extensionContext.cancelRequest(withError: NSError(domain: "PassExtension", code: 0))
}
}
extension CredentialProviderViewController: PasswordSelectionDelegate {
func selected(password: PasswordTableEntry) {
credentialProvider.persistAndProvideCredentials(with: password.passwordEntity.getPath())
}
}
|
mit
|
ede292afc4004664beb6281d746c7879
| 41.653846 | 165 | 0.731289 | 5.436275 | false | false | false | false |
mownier/photostream
|
Photostream/UI/User Activity/UserActivityViewController.swift
|
1
|
4350
|
//
// UserActivityViewController.swift
// Photostream
//
// Created by Mounir Ybanez on 23/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
@objc protocol UserActivityViewControllerAction: class {
func triggerRefresh()
}
class UserActivityViewController: UITableViewController, UserActivityViewControllerAction {
var presenter: UserActivityModuleInterface!
lazy var likeCellPrototype = ActivityTableLikeCell()
lazy var commentCellPrototype = ActivityTableCommentCell()
lazy var followCellPrototype = ActivityTableFollowCell()
lazy var postCellPrototype = ActivityTablePostCell()
lazy var emptyView: GhostView! = {
let view = GhostView()
view.titleLabel.text = "No activities"
return view
}()
lazy var loadingView: UIActivityIndicatorView! = {
let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
view.hidesWhenStopped = true
return view
}()
lazy var refreshView: UIRefreshControl! = {
let view = UIRefreshControl()
view.addTarget(
self,
action: #selector(self.triggerRefresh),
for: .valueChanged)
return view
}()
var shouldShowLoadingView: Bool = false {
didSet {
guard shouldShowLoadingView != oldValue else {
return
}
if shouldShowLoadingView {
loadingView.startAnimating()
tableView.backgroundView = loadingView
} else {
loadingView.stopAnimating()
loadingView.removeFromSuperview()
tableView.backgroundView = nil
}
}
}
var shouldShowRefreshView: Bool = false {
didSet {
if refreshView.superview == nil {
tableView.addSubview(refreshView)
}
if shouldShowLoadingView {
refreshView.beginRefreshing()
} else {
refreshView.endRefreshing()
}
}
}
var shouldShowEmptyView: Bool = false {
didSet {
guard shouldShowEmptyView != oldValue else {
return
}
if shouldShowEmptyView {
emptyView.frame.size = tableView.frame.size
tableView.backgroundView = emptyView
} else {
tableView.backgroundView = nil
emptyView.removeFromSuperview()
}
}
}
override func loadView() {
super.loadView()
tableView.tableFooterView = UIView()
tableView.allowsSelection = false
tableView.separatorStyle = .none
ActivityTableLikeCell.register(in: tableView)
ActivityTableCommentCell.register(in: tableView)
ActivityTableFollowCell.register(in: tableView)
ActivityTablePostCell.register(in: tableView)
likeCellPrototype.frame.size.width = tableView.bounds.width
commentCellPrototype.frame.size.width = tableView.bounds.width
followCellPrototype.frame.size.width = tableView.bounds.width
postCellPrototype.frame.size.width = tableView.bounds.width
navigationItem.title = "Activity"
}
override func viewDidLoad() {
super.viewDidLoad()
presenter.viewDidLoad()
}
func triggerRefresh() {
presenter.refreshActivities()
}
}
extension UserActivityViewController: UserActivityScene {
var controller: UIViewController? {
return self
}
func reloadView() {
tableView.reloadData()
}
func showEmptyView() {
shouldShowEmptyView = true
}
func showRefreshView() {
shouldShowRefreshView = true
}
func showInitialLoadView() {
shouldShowLoadingView = true
}
func hideEmptyView() {
shouldShowEmptyView = false
}
func hideRefreshView() {
shouldShowRefreshView = false
}
func hideInitialLoadView() {
shouldShowLoadingView = false
}
func didRefresh(with error: String?) {
}
func didLoadMore(with error: String?) {
}
}
|
mit
|
8be1910e64be6cf5d35f8dd8ceb38f98
| 25.357576 | 91 | 0.590481 | 5.892954 | false | false | false | false |
P0ed/FireTek
|
Source/SpaceEngine/Systems/PlanetarySystem.swift
|
1
|
552
|
import PowerCore
import SpriteKit
final class PlanetarySystem {
let planets: Store<PlanetComponent>
init(planets: Store<PlanetComponent>) {
self.planets = planets
}
func update() {
for index in planets.indices {
var planet = planets[index]
planet.position += planet.velocity
planet.sprite.position = position(orbit: planet.orbit, angle: planet.position)
planets[index] = planet
}
}
func position(orbit: Float, angle: Float) -> CGPoint {
return CGPoint(x: CGFloat(orbit * cos(angle)), y: CGFloat(orbit * sin(angle)))
}
}
|
mit
|
7e24f56fee8a4b6fba50924ffe034aab
| 22 | 81 | 0.710145 | 3.247059 | false | false | false | false |
Geor9eLau/WorkHelper
|
Carthage/Checkouts/SwiftCharts/SwiftCharts/Axis/ChartAxisYLowLayerDefault.swift
|
1
|
2837
|
//
// ChartAxisYLowLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// A ChartAxisLayer for low Y axes
class ChartAxisYLowLayerDefault: ChartAxisYLayerDefault {
override var low: Bool {return true}
/// The start point of the axis line.
override var lineP1: CGPoint {
return CGPoint(x: self.p1.x + self.lineOffset, y: self.p1.y)
}
/// The end point of the axis line.
override var lineP2: CGPoint {
return CGPoint(x: self.p2.x + self.lineOffset, y: self.p2.y)
}
/// The offset of the axis labels from the edge of the axis bounds
///
/// Imagine the following image rotated 90 degrees counter-clockwise.
///
/// ````
/// ─ ─ ─ ─ ▲
/// Title │
/// │
/// ▼
/// Label
/// ````
fileprivate lazy var labelsOffset: CGFloat = {
return self.axisTitleLabelsWidth + self.settings.axisTitleLabelsToLabelsSpacing
}()
/// The offset of the axis line from the edge of the axis bounds.
///
/// Imagine the following image rotated 90 degrees counter-clockwise.
///
/// ````
/// ─ ─ ─ ─ ▲
/// Title │
/// │
/// │
/// Label │
/// │
/// │
/// ─────── ▼
/// ````
fileprivate lazy var lineOffset: CGFloat = {
return self.labelsOffset + self.labelsMaxWidth + self.settings.labelsToAxisSpacingY + self.settings.axisStrokeWidth
}()
override func initDrawers() {
self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: 0)
self.labelDrawers = self.generateLabelDrawers(offset: self.labelsOffset)
self.lineDrawer = self.generateLineDrawer(offset: self.lineOffset)
}
override func generateLineDrawer(offset: CGFloat) -> ChartLineDrawer {
let halfStrokeWidth = self.settings.axisStrokeWidth / 2 // we want that the stroke ends at the end of the frame, not be in the middle of it
let p1 = CGPoint(x: self.p1.x + offset - halfStrokeWidth, y: self.p1.y)
let p2 = CGPoint(x: self.p2.x + offset - halfStrokeWidth, y: self.p2.y)
return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor, strokeWidth: self.settings.axisStrokeWidth)
}
override func labelsX(offset: CGFloat, labelWidth: CGFloat, textAlignment: ChartLabelTextAlignment) -> CGFloat {
let labelsXRight = self.p1.x + offset
var labelsX: CGFloat
switch textAlignment {
case .right, .default:
labelsX = labelsXRight + self.labelsMaxWidth - labelWidth
case .left:
labelsX = labelsXRight
}
return labelsX
}
}
|
mit
|
e06534beca57ce08f9895f92b747b9a1
| 32.53012 | 147 | 0.612289 | 4.062774 | false | false | false | false |
HeartRateLearning/HRLApp
|
HRLAppTests/Modules/ListWorkoutDates/View/ListWorkoutDatesViewTests.swift
|
1
|
1338
|
//
// ListWorkoutDatesViewTests.swift
// HRLApp
//
// Created by Enrique de la Torre (dev) on 03/02/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import XCTest
@testable import HRLApp
// MARK: - Main body
final class ListWorkoutDatesViewTests: XCTestCase {
// MARK: - Properties
let output = ListWorkoutDatesViewOutputTestDouble()
var sut: ListWorkoutDatesViewController!
// MARK: - Setup / Teardown
override func setUp() {
super.setUp()
let instantiater = ViewControllerInstantiaterHelper()
let viewController = instantiater.viewController(with: Constants.viewControllerId)
sut = viewController as! ListWorkoutDatesViewController
sut.output = output
}
// MARK: - Tests
func test_tableViewDidSelectSecondRow_forwardToOutput() {
// when
let row = 1
let section = 0
let indexPath = IndexPath(row: row, section: section)
sut.tableView(sut.tableView, didSelectRowAt: indexPath)
// then
XCTAssertEqual(output.didSelectDateCount, 1)
XCTAssertEqual(output.lastSelectedDateIndex, row)
}
}
// MARK: - Private body
private extension ListWorkoutDatesViewTests {
enum Constants {
static let viewControllerId = "ListWorkoutDatesViewController"
}
}
|
mit
|
a8281239ab073b7037dcace7004473a6
| 22.45614 | 90 | 0.681376 | 4.427152 | false | true | false | false |
HeartOfCarefreeHeavens/TestKitchen_pww
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBHeaderView.swift
|
1
|
1503
|
//
// CBHeaderView.swift
// TestKitchen
//
// Created by qianfeng on 16/8/19.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CBHeaderView: UIView {
private var titleLabel:UILabel?
private var imageView:UIView?
override init(frame: CGRect) {
super.init(frame: frame)
//背景视图
let bgView = UIView.createView()
bgView.frame = CGRectMake(0, 10, bounds.size.width, bounds.size.height-10)
bgView.backgroundColor = UIColor.whiteColor()
addSubview(bgView)
let titleW:CGFloat = 160
let imageW:CGFloat = 24
let x = (bounds.size.width-titleW-imageW)/2
//标题文字
titleLabel = UILabel.createLabel(nil, font: UIFont.systemFontOfSize(18), textAlignment: .Center, textColor: UIColor.blackColor())
titleLabel?.frame = CGRectMake(x, 10, titleW, bounds.size.height-10)
addSubview(titleLabel!)
//右边图片
imageView = UIImageView.createImageView("")
imageView?.frame = CGRectMake(x+titleW, 10, imageW, imageW)
addSubview(imageView!)
backgroundColor = UIColor(white: 0.8, alpha: 1.0)
}
func configTitle(title:String){
titleLabel?.text = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
8e78d1a48b339625a401fb75230d242a
| 24.016949 | 137 | 0.585366 | 4.541538 | false | false | false | false |
kay-kim/stitch-examples
|
todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/ExtendedJson/MaxKey+ExtendedJson.swift
|
1
|
1742
|
//
// MaxKey+ExtendedJson.swift
// ExtendedJson
//
// Created by Jason Flax on 10/4/17.
// Copyright © 2017 MongoDB. All rights reserved.
//
import Foundation
extension MaxKey: ExtendedJsonRepresentable {
enum CodingKeys: String, CodingKey {
case maxKey = "$maxKey"
}
public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable {
guard let json = xjson as? [String: Any],
let maxKey = json[ExtendedJsonKeys.maxKey.rawValue] as? Int,
maxKey == 1,
json.count == 1 else {
throw BsonError.parseValueFailure(value: xjson, attemptedType: MaxKey.self)
}
return MaxKey()
}
public var toExtendedJson: Any {
return [ExtendedJsonKeys.maxKey.rawValue: 1]
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// assert that this was encoding properly
guard let max = try? container.decode(Int.self, forKey: CodingKeys.maxKey),
max == 1 else {
throw DecodingError.dataCorruptedError(forKey: CodingKeys.maxKey,
in: container,
debugDescription: "Max key was not encoded correctly")
}
self.init()
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(1, forKey: CodingKeys.maxKey)
}
public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool {
if let other = other as? MaxKey {
return self == other
}
return false
}
}
|
apache-2.0
|
37f8e4b5fc0dfb3ad26a55337a58ddc3
| 31.240741 | 105 | 0.600804 | 4.545692 | false | false | false | false |
cavalcantedosanjos/ND-OnTheMap
|
OnTheMap/OnTheMap/ViewControllers/LoginViewController.swift
|
1
|
4659
|
//
// LoginViewController.swift
// OnTheMap
//
// Created by Joao Anjos on 06/02/17.
// Copyright © 2017 Joao Anjos. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
// MARK: - Storyboard Restoration
class func newInstanceFromStoryboard() -> LoginViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
return vc
}
// MARK: - Properties
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var loginButton: CustomButton!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
enableActivityIndicator(enable: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
// MARK: - Actions
@IBAction func loginButton_clicked(_ sender: Any) {
guard let username = emailTextField.text, !username.isEmpty else {
showMessage(message: "Required E-mail.", title: "Invalid Field!")
return
}
guard let password = passwordTextField.text, !password.isEmpty else {
showMessage(message: "Required Password.", title: "Invalid Field!")
return
}
self.view.endEditing(true)
login(username: username, password: password)
}
@IBAction func singUpButton_clicked(_ sender: Any) {
UIApplication.shared.open(URL(string: "https://www.udacity.com/account/auth#!/signup")!, options: [:], completionHandler: nil)
}
// MARK: - Services
func login(username: String, password: String) {
enableActivityIndicator(enable: true)
StudentService.sharedInstance().autentication(username: username, password: password, onSuccess: { (key) in
User.current.key = key
self.performSegue(withIdentifier: "tabBarSegue", sender: nil)
}, onFailure: { (error) in
self.showMessage(message: error.error!, title: "")
}, onCompleted: {
self.enableActivityIndicator(enable: false)
})
}
// MARK: - Helpers
func showMessage(message: String, title: String) {
let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
func enableActivityIndicator(enable: Bool){
if enable {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
loginButton.isUserInteractionEnabled = !enable
activityIndicator.isHidden = !enable
}
// MARK: - Keyboard
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(_ notification:Notification) {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
let heightKeyboard = keyboardSize.cgRectValue.height - 60
self.view.frame.origin.y = heightKeyboard * (-1)
}
func keyboardWillHide(notification: Notification) {
self.view.frame.origin.y = 0
}
}
// MARK: - UITextFieldDelegate
extension LoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
|
mit
|
3b2b174e952daa90cc91b172888604b4
| 33 | 146 | 0.643839 | 5.305239 | false | false | false | false |
marketplacer/Dodo
|
Dodo/Style/DodoButtonDefaultStyles.swift
|
6
|
2568
|
import UIKit
/**
Default styles for the bar button.
Default styles are used when individual element styles are not set.
*/
public struct DodoButtonDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
accessibilityLabel = _accessibilityLabel
hideOnTap = _hideOnTap
horizontalMarginToBar = _horizontalMarginToBar
icon = _icon
image = _image
onTap = _onTap
size = _size
tintColor = _tintColor
}
// ---------------------------
private static let _accessibilityLabel: String? = nil
/**
This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc.
*/
public static var accessibilityLabel = _accessibilityLabel
// ---------------------------
private static let _hideOnTap = false
/// When true it hides the bar when the button is tapped.
public static var hideOnTap = _hideOnTap
// ---------------------------
private static let _horizontalMarginToBar: CGFloat = 10
/// Margin between the bar edge and the button
public static var horizontalMarginToBar = _horizontalMarginToBar
// ---------------------------
private static let _icon: DodoIcons? = nil
/// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property.
public static var icon = _icon
// ---------------------------
private static let _image: UIImage? = nil
/// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property.
public static var image = _image
// ---------------------------
private static let _onTap: DodoButtonOnTap? = nil
/// Supply a function that will be called when user taps the button.
public static var onTap = _onTap
// ---------------------------
private static let _size = CGSize(width: 25, height: 25)
/// Size of the button.
public static var size = _size
// ---------------------------
private static let _tintColor: UIColor? = nil
/// Replaces the color of the image or icon. The original colors are used when nil.
public static var tintColor = _tintColor
// ---------------------------
}
|
mit
|
8c22c04583f97bd6f9d37d6aae5fb2d8
| 24.68 | 260 | 0.617212 | 5.372385 | false | false | false | false |
sarahspins/Loop
|
Loop/Views/BatteryLevelHUDView.swift
|
1
|
797
|
//
// BatteryLevelHUDView.swift
// Naterade
//
// Created by Nathan Racklyeft on 5/2/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
final class BatteryLevelHUDView: HUDView {
@IBOutlet private var imageView: UIImageView!
private lazy var numberFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.numberStyle = .PercentStyle
return formatter
}()
var batteryLevel: Double? {
didSet {
if let value = batteryLevel, level = numberFormatter.stringFromNumber(value) {
caption.text = level
} else {
caption.text = nil
}
imageView.image = UIImage.batteryHUDImageWithLevel(batteryLevel)
}
}
}
|
apache-2.0
|
b2429756b9f9ecdcd622916c888cbefd
| 21.111111 | 90 | 0.621859 | 4.944099 | false | false | false | false |
KaushalElsewhere/AllHandsOn
|
CleanSwiftTry/CleanSwiftTry/Scenes/CreateOrder/CreateOrderInteractor.swift
|
1
|
1702
|
//
// CreateOrderInteractor.swift
// CleanSwiftTry
//
// Created by Kaushal Elsewhere on 10/05/2017.
// Copyright (c) 2017 Elsewhere. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol CreateOrderInteractorInput {
var shippingMethods: [String] { get }
func calculatePrice(_ request: CreateOrder_Price_Request)
func doSomething(_ request: CreateOrder.Something.Request)
func getPaymentOptions()
}
protocol CreateOrderInteractorOutput {
func presentPrice(_ resonse: CreateOrder_Price_Response)
func presentSomething(_ response: CreateOrder.Something.Response)
}
class CreateOrderInteractor: CreateOrderInteractorInput {
var output: CreateOrderInteractorOutput!
var worker: CreateOrderWorker!
var shippingMethods = [
"Pickup",
"Domestic Delivery",
"International Delivery"
]
internal var prices = [10, 20, 30]
// MARK: - Business logic
func doSomething(_ request: CreateOrder.Something.Request) {
// NOTE: Create some Worker to do the work
worker = CreateOrderWorker()
worker.doSomeWork()
// NOTE: Pass the result to the Presenter
let response = CreateOrder.Something.Response()
output.presentSomething(response)
}
func calculatePrice(_ request: CreateOrder_Price_Request) {
let response = CreateOrder_Price_Response(price: prices[request.selectedIndex])
output.presentPrice(response)
}
func getPaymentOptions() {
//
}
}
|
mit
|
d05594deccdb6f90264b3991d862a8e1
| 26.015873 | 87 | 0.680964 | 4.740947 | false | false | false | false |
XenosInAHat/ballotbox
|
ballot_box_ios/BallotBox/BallotBox/MasterViewController.swift
|
1
|
2896
|
//
// MasterViewController.swift
// BallotBox
//
// Created by Brendan Cazier on 12/5/14.
// Copyright (c) 2014 BallotBox. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var objects = NSMutableArray()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insertObject(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row] as NSDate
(segue.destinationViewController as DetailViewController).detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = objects[indexPath.row] as NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
|
mit
|
2f29f6d3ebff35ebbeaba7e188250264
| 33.070588 | 157 | 0.685773 | 5.453861 | false | false | false | false |
patrick-sheehan/cwic
|
Source/UIImageView.swift
|
1
|
944
|
//
// UIImageView.swift
// CWIC
//
// Created by Patrick Sheehan on 12/6/17.
// Copyright © 2017 Síocháin Solutions. All rights reserved.
//
import UIKit
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFill) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFill) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
|
gpl-3.0
|
462fe21b81fa68e686df945ad21d2f61
| 30.366667 | 94 | 0.666312 | 4.200893 | false | false | false | false |
lioonline/Swift
|
XML/XML/RootViewController.swift
|
1
|
6400
|
//
// RootViewController.swift
// XML
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// 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
class RootViewController: UITableViewController, NSURLConnectionDelegate, NSXMLParserDelegate {
var xmlData:NSMutableData? = nil
var songs:NSMutableArray = []
var song:Song = Song(title: "")
var currentStringValue: NSMutableString? = NSMutableString() //Variable Global
override func viewDidLoad() {
super.viewDidLoad()
println("First Ejecution")
var url = NSURL(string: "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml")
var request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30)
self.xmlData = NSMutableData()
NSURLConnection(request: request, delegate: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("AAAAAA \(songs.count)")
return songs.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("celda") as UITableViewCell
var elem = songs[indexPath.row] as Song
println("AAAAAA \(elem.myTitle)")
cell.textLabel.text = (elem.myTitle) as String
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 connection(connection: NSURLConnection!, didFailWithError error: NSError!){
println("URL access error")
self.xmlData = nil
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.xmlData!.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!){
var xmlCheck = NSString(data: self.xmlData!, encoding: NSUTF8StringEncoding)
//println("XML recived: \(xmlCheck)")
var parser:NSXMLParser = NSXMLParser(data: self.xmlData)
parser.delegate = self
parser.shouldResolveExternalEntities = true
parser.parse()
for(var i=0; i<songs.count;i++){
var elem = songs[i] as Song
println(elem.myTitle)
}
self.tableView.reloadData()
}
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!){
if(elementName == "feed") {
//init array
songs = NSMutableArray()
return
}
if(elementName == "entry") {
//Find new song. Create object of song class.
song = Song(title: "")
return
}
if(elementName == "title") {
currentStringValue = NSMutableString(capacity: 50)
}
}
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
if(currentStringValue != nil) {
//NSMutableString where we save characters of actual item
currentStringValue = NSMutableString(capacity: 50)
}
currentStringValue?.appendString(string)
}
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!){
if(elementName == "entry"){
//add song to array
songs.addObject(song)
}
if(elementName == "title"){
//if we find a title save it in nsstring characters
song.myTitle = currentStringValue!
}
}
}
|
gpl-3.0
|
8c1d2ba65e86462175e9d3248ef940c3
| 34.75419 | 180 | 0.65125 | 5.22449 | false | false | false | false |
shadanan/mado
|
Antlr4Runtime/Sources/Antlr4/misc/utils/CommonUtil.swift
|
1
|
3247
|
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
//
// CommonUtil.swift
// antlr.swift
//
// Created by janyou on 15/9/4.
//
import Foundation
func errPrint(_ msg: String) {
fputs(msg + "\n", __stderrp)
}
public func +(lhs: String, rhs: Int) -> String {
return lhs + String(rhs)
}
public func +(lhs: Int, rhs: String) -> String {
return String(lhs) + rhs
}
public func +(lhs: String, rhs: Token) -> String {
return lhs + rhs.description
}
public func +(lhs: Token, rhs: String) -> String {
return lhs.description + rhs
}
infix operator >>> : BitwiseShiftPrecedence
func >>>(lhs: Int32, rhs: Int32) -> Int32 {
let left = UInt32(bitPattern: lhs)
let right = UInt32(bitPattern: rhs) % 32
return Int32(bitPattern: left >> right)
}
func >>>(lhs: Int64, rhs: Int64) -> Int64 {
let left = UInt64(bitPattern: lhs)
let right = UInt64(bitPattern: rhs) % 64
return Int64(bitPattern: left >> right)
}
func >>>(lhs: Int, rhs: Int) -> Int {
let numberOfBits: UInt = MemoryLayout<UInt>.size == MemoryLayout<UInt64>.size ? 64 : 32
let left = UInt(bitPattern: lhs)
let right = UInt(bitPattern: rhs) % numberOfBits
return Int(bitPattern: left >> right)
}
func synced(_ lock: AnyObject, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
func intChar2String(_ i: Int) -> String {
return String(Character(integerLiteral: i))
}
func log(_ message: String = "", file: String = #file, function: String = #function, lineNum: Int = #line) {
// #if DEBUG
print("FILE: \(URL(fileURLWithPath: file).pathComponents.last!),FUNC: \(function), LINE: \(lineNum) MESSAGE: \(message)")
// #else
// do nothing
// #endif
}
func RuntimeException(_ message: String = "", file: String = #file, function: String = #function, lineNum: Int = #line) {
// #if DEBUG
let info = "FILE: \(URL(fileURLWithPath: file).pathComponents.last!),FUNC: \(function), LINE: \(lineNum) MESSAGE: \(message)"
// #else
// let info = "FILE: \(NSURL(fileURLWithPath: file).pathComponents!.last!),FUNC: \(function), LINE: \(lineNum) MESSAGE: \(message)"
// #endif
fatalError(info)
}
func toInt(_ c: Character) -> Int {
return c.unicodeValue
}
func toInt32(_ data: [Character], _ offset: Int) -> Int {
return data[offset].unicodeValue | (data[offset + 1].unicodeValue << 16)
}
func toLong(_ data: [Character], _ offset: Int) -> Int64 {
let mask: Int64 = 0x00000000FFFFFFFF
let lowOrder: Int64 = Int64(toInt32(data, offset)) & mask
return lowOrder | Int64(toInt32(data, offset + 2) << 32)
}
func toUUID(_ data: [Character], _ offset: Int) -> UUID {
let leastSigBits: Int64 = toLong(data, offset)
let mostSigBits: Int64 = toLong(data, offset + 4)
return UUID(mostSigBits: mostSigBits, leastSigBits: leastSigBits)
}
func ==<T:Equatable>(_ lhs: [T?], _ rhs: [T?]) -> Bool {
if lhs.count != rhs.count {
return false
}
for i in 0..<lhs.count {
if lhs[i] != rhs[i] {
return false
}
}
return true
}
|
mit
|
9bda082eb74d97ac254b3bb3a071d924
| 25.398374 | 135 | 0.625192 | 3.4 | false | false | false | false |
Higgcz/Buildasaur
|
BuildaHeartbeatKit/Heartbeat.swift
|
3
|
3134
|
//
// Heartbeat.swift
// Buildasaur
//
// Created by Honza Dvorsky on 17/09/2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import ekgclient
import BuildaUtils
public protocol HeartbeatManagerDelegate {
func numberOfRunningSyncers() -> Int
}
//READ: https://github.com/czechboy0/Buildasaur/tree/master#heartpulse-heartbeat
@objc public class HeartbeatManager: NSObject {
public var delegate: HeartbeatManagerDelegate?
private let client: EkgClient
private let creationTime: Double
private var timer: NSTimer?
private let interval: Double = 24 * 60 * 60 //send heartbeat once in 24 hours
public init(server: String) {
let bundle = NSBundle.mainBundle()
let appIdentifier = EkgClientHelper.pullAppIdentifierFromBundle(bundle) ?? "Unknown app"
let version = EkgClientHelper.pullVersionFromBundle(bundle) ?? "?"
let buildNumber = EkgClientHelper.pullBuildNumberFromBundle(bundle) ?? "?"
let appInfo = AppInfo(appIdentifier: appIdentifier, version: version, build: buildNumber)
let host = NSURL(string: server)!
let serverInfo = ServerInfo(host: host)
let userDefaults = NSUserDefaults.standardUserDefaults()
self.creationTime = NSDate().timeIntervalSince1970
let client = EkgClient(userDefaults: userDefaults, appInfo: appInfo, serverInfo: serverInfo)
self.client = client
}
deinit {
self.stop()
}
public func start() {
self.sendLaunchedEvent()
self.startSendingHeartbeat()
}
public func stop() {
self.stopSendingHeartbeat()
}
private func sendEvent(event: Event) {
var sendReal = true
#if DEBUG
sendReal = false
#endif
guard sendReal else {
Log.info("Not sending events in debug environment")
return
}
Log.info("Sending heartbeat event \(event.jsonify())")
self.client.sendEvent(event) {
if let error = $0 {
Log.error("Failed to send a heartbeat event. Error \(error)")
}
}
}
private func sendLaunchedEvent() {
self.sendEvent(LaunchEvent())
}
private func sendHeartbeatEvent() {
let uptime = NSDate().timeIntervalSince1970 - self.creationTime
let numberOfRunningSyncers = self.delegate?.numberOfRunningSyncers() ?? 0
self.sendEvent(HeartbeatEvent(uptime: uptime, numberOfRunningSyncers: numberOfRunningSyncers))
}
func _timerFired(timer: NSTimer?=nil) {
self.sendHeartbeatEvent()
}
private func startSendingHeartbeat() {
//send once now
self._timerFired()
self.timer?.invalidate()
self.timer = NSTimer.scheduledTimerWithTimeInterval(
self.interval,
target: self,
selector: "_timerFired:",
userInfo: nil,
repeats: true)
}
private func stopSendingHeartbeat() {
timer?.invalidate()
}
}
|
mit
|
b81577651d43dbccec1cc2b2cd11ddfe
| 28.280374 | 102 | 0.625598 | 4.902973 | false | false | false | false |
zzycami/MaterialUIKit
|
MeterialUIKit/MeterialUIKit/Class/MeterialCheckBox.swift
|
1
|
36515
|
//
// MeterialCheckbox.swift
// MeterialUIKit
//
// Created by damingdan on 14/12/30.
// Copyright (c) 2014年 com.metalmind. All rights reserved.
//
import UIKit
extension UIColor {
class func colorWith(value:Int)->UIColor {
var redValue = CGFloat(value & 0xFF0000 >> 16)/255.0;
var greenValue = CGFloat(value & 0x00FF00 >> 8)/255.0;
var blueValue = CGFloat(value & 0x0000FF)/255.0;
return UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1);
}
}
@objc public protocol MeterialCheckboxDelegate: NSObjectProtocol {
/** An optional protocol method for detecting when the checkbox state changed. You can check its current state here with 'checkbox.isChecked'. */
optional func checkboxChangedState(checkBox: MeterialCheckBox);
}
/** A nice recommended value for size. (eg. [[BFPaperCheckbox alloc] initWithFrame:CGRectMake(x, y, bfPaperCheckboxDefaultRadius * 2, bfPaperCheckboxDefaultRadius * 2)]; */
public let CheckboxDefaultRadius:CGFloat = 39.0;
// -animation durations:
private let AnimationDurationConstant = 0.18;
private let TapCircleGrowthDurationConstant = AnimationDurationConstant*2;
// -tap-circle's size:
private let TapCircleDiameterStartValue:CGFloat = 1.0;
// -tap-circle's beauty:
private let TapFillConstant:CGFloat = 0.3;
// -checkbox's beauty:
private let CheckboxSideLength:CGFloat = 9.0;
// -animation function names:
// For spinning box clockwise while shrinking:
private let box_spinClockwiseAnimationLeftLine = "leftLineSpin";
private let box_spinClockwiseAnimationTopLine = "topLineSpin";
private let box_spinClockwiseAnimationRightLine = "rightLineSpin";
private let box_spinClockwiseAnimationBottomLine = "bottomLineSpin";
// For spinning box counterclockwise while growing:
private let box_spinCounterclockwiseAnimationLeftLine = "leftLineSpin2";
private let box_spinCounterclockwiseAnimationTopLine = "topLineSpin2";
private let box_spinCounterclockwiseAnimationRightLine = "rightLineSpin2";
private let box_spinCounterclockwiseAnimationBottomLine = "bottomLineSpin2";
// For drawing an empty checkbox:
private let box_drawLeftLine = "leftLineStroke";
private let box_drawTopLine = "topLineStroke";
private let box_drawRightLine = "rightLineStroke";
private let box_drawBottomLine = "bottomLineStroke";
// For drawing checkmark:
private let mark_drawShortLine = "smallCheckmarkLine";
private let mark_drawLongLine = "largeCheckmarkLine";
// For removing checkbox:
private let box_eraseLeftLine = "leftLineStroke2";
private let box_eraseTopLine = "topLineStroke2";
private let box_eraseRightLine = "rightLineStroke2";
private let box_eraseBottomLine = "bottomLineStroke2";
// removing checkmark:
private let mark_eraseShortLine = "smallCheckmarkLine2";
private let mark_eraseLongLine = "largeCheckmarkLine2";
@IBDesignable
public class MeterialCheckBox: UIButton, UIGestureRecognizerDelegate {
// MARK: Default Initializers
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
self.setupWithRadius();
}
public override init() {
super.init();
self.setupWithRadius();
}
public override init(frame: CGRect) {
var defaultFrame = frame;
// if frame == CGRectZero {
// defaultFrame.size = CGSizeMake(CheckboxDefaultRadius*2, CheckboxDefaultRadius*2);
// }
super.init(frame: defaultFrame);
self.setupWithRadius();
}
// MARK: Custom Initializers
func setupWithRadius() {
// println("checkbox frame(\(frame.origin.x), \(frame.origin.y), \(frame.size.width), \(frame.size.height))");
// println("checkbox bounds(\(bounds.origin.x), \(bounds.origin.y), \(bounds.size.width), \(bounds.size.height))");
self.tintColor = UIColor.colorWith(0x616161);
self.layer.masksToBounds = true;
self.clipsToBounds = true;
self.layer.shadowOpacity = 0.0;
self.layer.cornerRadius = self.radius;
self.backgroundColor = UIColor.clearColor();
for layer in [lineLeft, lineBottom, lineRight, lineTop] {
layer.fillColor = UIColor.clearColor().CGColor;
layer.anchorPoint = CGPointZero;
layer.lineJoin = kCALineJoinRound;
layer.lineCap = kCALineCapSquare;
layer.contentsScale = self.layer.contentsScale;
layer.lineWidth = 2.0;
layer.strokeColor = self.tintColor!.CGColor;
// initialize with an empty path so we can animate the path w/o having to check for NULLs.
var dummyPath:CGPathRef = CGPathCreateMutable();
layer.path = dummyPath;
self.layer.addSublayer(layer);
}
//isChecked ? drawCheckmark(false) : drawCheckBoxAnimated(false);
self.addTarget(self, action: "onCheckBoxTouchDown:", forControlEvents: UIControlEvents.TouchDown);
self.addTarget(self, action: "onCheckBoxTouchUpAndSwitchStates:", forControlEvents: UIControlEvents.TouchUpInside);
self.addTarget(self, action: "onCheckBoxTouchUp:", forControlEvents: UIControlEvents.TouchUpOutside);
self.addTarget(self, action: "onCheckBoxTouchUp:", forControlEvents: UIControlEvents.TouchCancel);
var tapGuesture = UITapGestureRecognizer(target: self, action: nil);
tapGuesture.delegate = self;
self.gestureRecognizers = [tapGuesture];
UIView.setAnimationDidStopSelector("animationDidStop:finished:");
}
private var initializing:Bool = true;
public override func layoutSubviews() {
// The attirbutes of the view is not initialize in the init function, in layoutSubviews, all the attributes have been initialized. so , we can do some thing here.
println("layoutSubviews:\(isChecked), finishedAnimations:\(finishedAnimations)");
var frame = self.frame;
println("frame :\(frame)");
if initializing {
isChecked ? drawCheckmark(false) : drawCheckBoxAnimated(false);
initializing = false;
}
}
// MARK: Gesture Recognizer Delegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
var location:CGPoint = touch.locationInView(self);
println("location: x = \(location.x), y = \(location.y)");
tapPoint = location;
return false;// Disallow recognition of tap gestures. We just needed this to grab that tasty tap location.
}
// MARK: Public Interface
/** A UIColor to use for the checkmark color. Note that self.tintColor will be used for the square box color. */
@IBInspectable
public var checkmarkColor:(UIColor) = UIColor.colorWith(0x259b24);
/** A flag to set to YES to have the tap-circle ripple from point of touch. If this is set to NO, the tap-circle will always ripple from the center of the button. Default is YES. */
@IBInspectable
public var rippleFromTapLocation:Bool = true;
/** The UIColor to use for the circle which appears where you tap to check the box. NOTE: Setting this defeats the "Smart Color" ability of the tap circle. Alpha values less than 1 are recommended. */
@IBInspectable
public var tapCirclePositiveColor:UIColor?
/** The UIColor to use for the circle which appears where you tap to uncheck the box. NOTE: Setting this defeats the "Smart Color" ability of the tap circle. Alpha values less than 1 are recommended. */
@IBInspectable
public var tapCircleNegativeColor:UIColor?
/** A BOOL representing the state of the checkbox. YES means checked, NO means unchecked. **/
@IBInspectable
public var isChecked:Bool = false;
/** A delegate to use our protocol with! */
var delegate:MeterialCheckboxDelegate?
/**
* Use this function to manually/programmatically switch the state of this checkbox.
*
* @param animated A BOOL flag to choose whether or not to animate the change.
*/
public func switchStatesAnimated(animated:Bool) {
// As long as this comment remains, Animating the change will take the regular path, statically changing the state will take a second path. I would like to combine the two but right now this is faster and easier.
if animated {
_switchStateAnimated(animated);
}else {
isChecked ? uncheckAnimated(animated) : checkAnimated(animated);
}
}
/**
* Use this function to manually check the checkbox. Does nothing if already checked.
*
* @param animated A BOOL flag to choose whether or not to animate the change.
*/
public func checkAnimated(animated:Bool) {
if isChecked {
return;
}
isChecked = true;
self.delegate?.checkboxChangedState?(self);
if animated {
self.spinCheckbox(animated, angle1: M_PI_4, angle2: -5*M_PI_4, radiusDenominator: 4, duration: AnimationDurationConstant);
}else {
self.drawCheckmark(animated);
}
}
/**
* Use this function to manually uncheck the checkbox. Does nothing if already unchecked.
*
* @param animated A BOOL flag to choose whether or not to animate the change.
*/
public func uncheckAnimated(animated:Bool) {
if !isChecked {
return;
}
isChecked = false;
self.delegate?.checkboxChangedState?(self);
if animated {
self.shrinkAwayCheckmark(animated);
}else {
self.drawCheckmark(animated);
}
}
// MARK: Pirvate Method And Property
private var centerPoint:CGPoint = CGPointZero;
private var tapPoint:CGPoint = CGPointZero;
private var lineLeft:CAShapeLayer = CAShapeLayer(); // Also used for checkmark left, shorter line.
private var lineTop:CAShapeLayer = CAShapeLayer();
private var lineRight:CAShapeLayer = CAShapeLayer();
private var lineBottom:CAShapeLayer = CAShapeLayer(); // Also used for checkmark right, longer line.
private var rippleAnimationQueue:[CAShapeLayer] = [];
private var deathRowForCircleLayers:[CAShapeLayer] = [];// This is where old circle layers go to be killed :(
private var radius:CGFloat = CheckboxDefaultRadius;
private var checkboxSidesCompletedAnimating:Int = 0; // This should bounce between 0 and 4, representing the number of checkbox sides which have completed animating.
private var checkmarkSidesCompletedAnimating:Int = 0; // This should bounce between 0 and 2, representing the number of checkmark sides which have completed animating.
private var finishedAnimations:Bool = true;
// MARK: Animation
private func growTapCircle() {
// Spawn a growing circle that "ripples" through the button:
var tapCircleDiameterEndValue = self.rippleFromTapLocation ? self.radius*4 : self.radius*2;// if the circle comes from the center, its the perfect size. otherwise it will be quite small.
var tapCircleFinalDiameter = self.rippleFromTapLocation ? self.radius*4 : self.radius*2;// if the circle comes from the center, its the perfect size. otherwise it will be quite small.
// Create a UIView which we can modify for its frame value later (specifically, the ability to use .center):
var tapCircleLayerSizerView = UIView(frame: CGRectMake(0, 0, tapCircleFinalDiameter, tapCircleFinalDiameter));
tapCircleLayerSizerView.center = self.rippleFromTapLocation ? self.tapPoint : CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
// Calculate starting path:
var startingRectSizerView = UIView(frame: CGRectMake(0, 0, TapCircleDiameterStartValue, TapCircleDiameterStartValue));
startingRectSizerView.center = tapCircleLayerSizerView.center;
// Create starting circle path:
var startingCirclePath = UIBezierPath(roundedRect: startingRectSizerView.frame, cornerRadius: TapCircleDiameterStartValue/2);
// Calculate ending path:
var endingRectSizerView = UIView(frame: CGRectMake(0, 0, tapCircleDiameterEndValue, tapCircleDiameterEndValue));
endingRectSizerView.center = tapCircleLayerSizerView.center;
// Cretae ending circle path:
var endingCirclePath = UIBezierPath(roundedRect: endingRectSizerView.frame, cornerRadius: tapCircleDiameterEndValue/2);
// Create tap circle:
var tapCicle = CAShapeLayer();
tapCicle.strokeColor = UIColor.clearColor().CGColor;
tapCicle.borderColor = UIColor.clearColor().CGColor;
tapCicle.borderWidth = 0;
tapCicle.path = startingCirclePath.CGPath;
// Set tap circle layer's background color:
if self.isChecked {
// It is currently checked, so we are unchecking it:
if let negativeColor = self.tapCircleNegativeColor {
tapCicle.fillColor = negativeColor.CGColor;
}else {
tapCicle.fillColor = UIColor.colorWith(0x616161).CGColor;
}
}else {
// It is currently unchecked, so we are checking it:
if let positiveColor = self.tapCirclePositiveColor {
tapCicle.fillColor = positiveColor.CGColor;
}else {
tapCicle.fillColor = self.checkmarkColor.CGColor;
}
}
// Add tap circle to array and view:
rippleAnimationQueue.append(tapCicle);
layer.insertSublayer(tapCicle, atIndex: 0);
/*
* Animations:
*/
// Grow tap-circle animation (performed on mask layer):
//UIView.setAnimationDidStopSelector("animationDidStop:finished:");
var tapCircleGrowthAnimation = CABasicAnimation(keyPath: "path");
tapCircleGrowthAnimation.delegate = self;
tapCircleGrowthAnimation.fromValue = startingCirclePath.CGPath;
tapCircleGrowthAnimation.toValue = endingCirclePath.CGPath;
tapCircleGrowthAnimation.fillMode = kCAFillModeForwards;
tapCircleGrowthAnimation.removedOnCompletion = false;
tapCircleGrowthAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut);
tapCircleGrowthAnimation.duration = TapCircleGrowthDurationConstant;
tapCircleGrowthAnimation.setValue("tapGrowth", forKey: "id");
// Fade in self.animationLayer:
var fadeInAnimation = CABasicAnimation(keyPath: "opacity");
fadeInAnimation.duration = AnimationDurationConstant;
fadeInAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
fadeInAnimation.fromValue = 0.0;
fadeInAnimation.toValue = 1.0;
fadeInAnimation.removedOnCompletion = false;
fadeInAnimation.fillMode = kCAFillModeForwards;
// Add the animations to the layers:
tapCicle.addAnimation(tapCircleGrowthAnimation, forKey: "animatePath");
tapCicle.addAnimation(fadeInAnimation, forKey: "opacityAnimation");
}
private func fadeTapCircleOut() {
if rippleAnimationQueue.count > 0 {
var tempAnimationLayer = self.rippleAnimationQueue.first;
if tempAnimationLayer != nil {
self.deathRowForCircleLayers.insert(tempAnimationLayer!, atIndex: 0);
}
rippleAnimationQueue.removeAtIndex(0);
var fadeOutAnimation = CABasicAnimation(keyPath: "opacity");
fadeOutAnimation.setValue("fadeCircleOut", forKey: "id");
fadeOutAnimation.delegate = self;
fadeOutAnimation.fromValue = tempAnimationLayer?.opacity;
fadeOutAnimation.toValue = 0;
fadeOutAnimation.fillMode = kCAFillModeForwards;
fadeOutAnimation.duration = AnimationDurationConstant;
fadeOutAnimation.removedOnCompletion = false;
tempAnimationLayer?.addAnimation(fadeOutAnimation, forKey: "opacityAnimation");
}
}
private func spinCheckbox(animated:Bool, angle1:Double, angle2:Double, radiusDenominator:CGFloat, duration:Double) {
finishedAnimations = false;
checkmarkSidesCompletedAnimating = 0;
lineLeft.opacity = 1;
lineTop.opacity = 1;
lineRight.opacity = 1;
lineBottom.opacity = 1;
var ratioDenominator = radiusDenominator*4;
var radius = CheckboxSideLength/radiusDenominator;
var ratio = CheckboxSideLength/ratioDenominator;
var offset = radius - ratio;
var slightOffsetForCheckmarkCentering = CGPointMake(4, 9);// Hardcoded in the most offensive way. Forgive me Father, for I have sinned.
var newLeftPath = self.createCenteredLineWithRadius(radius, angle: angle2, offset: CGPointMake(-offset - slightOffsetForCheckmarkCentering.x, -offset + slightOffsetForCheckmarkCentering.y));
var newTopPath = self.createCenteredLineWithRadius(radius, angle: angle1, offset: CGPointMake(offset - slightOffsetForCheckmarkCentering.x, -offset + slightOffsetForCheckmarkCentering.y));
var newRightPath = self.createCenteredLineWithRadius(radius, angle: angle2, offset: CGPointMake(offset - slightOffsetForCheckmarkCentering.x, offset + slightOffsetForCheckmarkCentering.y));
var newBottomPath = self.createCenteredLineWithRadius(radius, angle: angle1, offset: CGPointMake(-offset - slightOffsetForCheckmarkCentering.x, offset + slightOffsetForCheckmarkCentering.y));
if animated {
var newPaths = [newLeftPath, newTopPath, newRightPath, newBottomPath];
var lines = [lineLeft, lineTop, lineRight, lineBottom];
var animationkeys = ["spinLeftLine", "spinTopLine", "spinRightLine", "spinBottomLine"];
var counterValues = [box_spinCounterclockwiseAnimationLeftLine, box_spinCounterclockwiseAnimationTopLine, box_spinCounterclockwiseAnimationRightLine, box_spinCounterclockwiseAnimationBottomLine];
var values = [box_spinClockwiseAnimationLeftLine, box_spinClockwiseAnimationTopLine, box_spinClockwiseAnimationRightLine, box_spinClockwiseAnimationBottomLine];
for i in 0...3 {
var lineAnimation = CABasicAnimation(keyPath: "path");
lineAnimation.removedOnCompletion = false;
lineAnimation.duration = duration;
lineAnimation.fromValue = lines[i].path;
lineAnimation.toValue = newPaths[i];
lineAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lineAnimation.delegate = self;
lineAnimation.setValue(self.isChecked ?values[i]:counterValues[i], forKey: "id");
lines[i].addAnimation(lineAnimation, forKey: animationkeys[i]);
}
}
self.lineLeft.path = newLeftPath;
self.lineTop.path = newTopPath;
self.lineRight.path = newRightPath;
self.lineBottom.path = newBottomPath;
}
private func drawCheckBoxAnimated(animated:Bool) {
lineLeft.opacity = 1;
lineTop.opacity = 1;
lineRight.opacity = 1;
lineBottom.opacity = 1;
var newLeftPath:CGPathRef = createCenteredLineWithRadius(CheckboxSideLength, angle: M_PI_2, offset: CGPointMake(-CheckboxSideLength, 0));
var newTopPath:CGPathRef = createCenteredLineWithRadius(CheckboxSideLength, angle: 0, offset: CGPointMake(0, -CheckboxSideLength));
var newRightPath:CGPathRef = createCenteredLineWithRadius(CheckboxSideLength, angle: M_PI_2, offset: CGPointMake(CheckboxSideLength, 0));
var newBottomPath:CGPathRef = createCenteredLineWithRadius(CheckboxSideLength, angle: 0, offset: CGPointMake(0, CheckboxSideLength));
if animated {
var newPaths = [newLeftPath, newTopPath, newRightPath, newBottomPath];
var lines = [lineLeft, lineTop, lineRight, lineBottom];
var vlues = [box_drawLeftLine, box_drawTopLine, box_drawRightLine, box_drawBottomLine];
var pathAnimationKeys = ["animateLeftLinePath", "animateTopLinePath", "animateRightLinePath", "animateBottomLinePath"];
var colorAnimationKeys = ["animateLeftLineStrokeColor", "animateTopLineStrokeColor", "animateRightLineStrokeColor", "animateBottomLineStrokeColor"];
for var i = 0;i < 4;i++ {
var pathAnimation = CABasicAnimation(keyPath: "path");
pathAnimation.removedOnCompletion = false;
pathAnimation.duration = AnimationDurationConstant;
pathAnimation.fromValue = lines[i].path;
pathAnimation.toValue = newPaths[i];
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
pathAnimation.setValue(vlues[i], forKey: "id");
pathAnimation.delegate = self;
lines[i].addAnimation(pathAnimation, forKey: pathAnimationKeys[i]);
var colorAnimation = CABasicAnimation(keyPath: "strokeColor");
colorAnimation.removedOnCompletion = false;
colorAnimation.duration = AnimationDurationConstant;
colorAnimation.fromValue = lines[i].strokeColor;
colorAnimation.toValue = tintColor!.CGColor;
colorAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lines[i].addAnimation(colorAnimation, forKey: colorAnimationKeys[i]);
}
}
lineLeft.path = newLeftPath;
lineTop.path = newTopPath;
lineRight.path = newRightPath;
lineBottom.path = newBottomPath;
lineLeft.strokeColor = tintColor!.CGColor;
lineTop.strokeColor = tintColor!.CGColor;
lineRight.strokeColor = tintColor!.CGColor;
lineBottom.strokeColor = tintColor!.CGColor;
}
private func drawCheckmark(animated:Bool) {
self.lineTop.opacity = 0;
self.lineLeft.opacity = 0;
var checkmarkSmallSideLength = CheckboxSideLength * 0.6;
var checkmarkLargeSideLength = CheckboxSideLength * 1.3;
var smallSideOffset = CGPointMake(-9, 5); // Hardcoded in the most offensive way.
var largeSideOffset = CGPointMake(3.5, 0.5); // Hardcoded in the most offensive way. Forgive me father, for I have sinned!
// Right path will become the large part of the checkmark:
var newRightPath = self.createCenteredLineWithRadius(checkmarkLargeSideLength, angle: -5 * M_PI_4, offset: largeSideOffset);
// Bottom path will become the small part of the checkmark:
var newBottomPath = self.createCenteredLineWithRadius(checkmarkSmallSideLength, angle: M_PI_4, offset: smallSideOffset);
if animated {
var lineRightAnimation = CABasicAnimation(keyPath: "path");
lineRightAnimation.removedOnCompletion = false;
lineRightAnimation.duration = AnimationDurationConstant;
lineRightAnimation.fromValue = lineRight.path;
lineRightAnimation.toValue = newRightPath;
lineRightAnimation.setValue(mark_drawLongLine, forKey: "id");
lineRightAnimation.delegate = self;
lineRightAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lineRight.addAnimation(lineRightAnimation, forKey: "animateRightLinePath");
var lineBottomAnimation = CABasicAnimation(keyPath: "path");
lineBottomAnimation.removedOnCompletion = false;
lineBottomAnimation.duration = AnimationDurationConstant;
lineBottomAnimation.fromValue = lineBottom.path;
lineBottomAnimation.toValue = newBottomPath;
lineBottomAnimation.setValue(mark_drawShortLine, forKey: "id");
lineBottomAnimation.delegate = self;
lineBottomAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lineBottom.addAnimation(lineBottomAnimation, forKey: "animateBottomLinePath");
}else {
lineRight.strokeColor = checkmarkColor.CGColor;
lineLeft.strokeColor = checkmarkColor.CGColor;
}
lineRight.path = newRightPath;
lineBottom.path = newBottomPath;
}
private func shrinkAwayCheckmark(animated:Bool) {
finishedAnimations = false;
checkmarkSidesCompletedAnimating = 0;
var radiusDenominator:CGFloat = 18;
var ratioDenominator = radiusDenominator * 4;
var radius = CheckboxSideLength/radiusDenominator;
var ratio = CheckboxSideLength/ratioDenominator;
var offset = radius - ratio;
var slightOffsetForCheckmarkCentering = CGPointMake(3, 11);// Hardcoded in the most offensive way. Forgive me Father, for I have sinned.
var newRightPath:CGPathRef = createCenteredLineWithRadius(radius, angle: -5 * M_PI_4, offset: CGPointMake(offset - slightOffsetForCheckmarkCentering.x, offset + slightOffsetForCheckmarkCentering.y));
var newBottomPath:CGPathRef = createCenteredLineWithRadius(radius, angle: M_PI_4, offset: CGPointMake(-offset - slightOffsetForCheckmarkCentering.x, offset + slightOffsetForCheckmarkCentering.y));
if animated {
var newPaths = [newRightPath, newBottomPath];
var lines = [lineRight, lineBottom];
var values = [mark_eraseLongLine, mark_eraseShortLine];
var pathAnimationKeys = ["animateRightLinePath", "animateBottomLinePath"];
var colorAnimationKeys = ["animateRightLineStrokeColor", "animateBottomLineStrokeColor"];
for i in 0...1 {
var pathAnimation = CABasicAnimation(keyPath: "path");
pathAnimation.removedOnCompletion = false;
pathAnimation.duration = AnimationDurationConstant;
pathAnimation.fromValue = lines[i].path;
pathAnimation.toValue = newPaths[i];
pathAnimation.setValue(values[i], forKey: "id");
pathAnimation.delegate = self;
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lines[i].addAnimation(pathAnimation, forKey: pathAnimationKeys[i]);
var colorAnimation = CABasicAnimation(keyPath: "strokeColor");
colorAnimation.removedOnCompletion = false;
colorAnimation.duration = AnimationDurationConstant;
colorAnimation.fromValue = lines[i].strokeColor;
colorAnimation.toValue = tintColor!.CGColor;
colorAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lines[i].addAnimation(colorAnimation, forKey: colorAnimationKeys[i]);
}
}
lineRight.path = newRightPath;
lineBottom.path = newBottomPath;
lineLeft.strokeColor = tintColor!.CGColor;
lineTop.strokeColor = tintColor!.CGColor;
lineRight.strokeColor = tintColor!.CGColor;
lineBottom.strokeColor = tintColor!.CGColor;
}
// This fucntion only modyfies the checkbox. When it's animation is complete, it calls a function to draw the checkmark.
private func shrinkAwayCheckboxAnimated(animated:Bool) {
lineLeft.opacity = 1;
lineTop.opacity = 1;
lineRight.opacity = 1;
lineBottom.opacity = 1;
var radiusDenominator:CGFloat = 20;
var ratioDenominator = radiusDenominator * 4;
var radius = CheckboxSideLength/radiusDenominator;
var ratio = CheckboxSideLength/ratioDenominator;
var offset = radius - ratio;
var slightOffsetForCheckmarkCentering = CGPointMake(4, 9);// Hardcoded in the most offensive way. Forgive me Father, for I have sinned.
var duration = AnimationDurationConstant/4;
var newLeftPath:CGPathRef = createCenteredLineWithRadius(radius, angle: -5 * M_PI_4, offset: CGPointMake(-offset - slightOffsetForCheckmarkCentering.x, -offset + slightOffsetForCheckmarkCentering.y));
var newTopPath:CGPathRef = createCenteredLineWithRadius(radius, angle: M_PI_4, offset: CGPointMake(offset - slightOffsetForCheckmarkCentering.x, -offset + slightOffsetForCheckmarkCentering.y));
var newRightPath:CGPathRef = createCenteredLineWithRadius(radius, angle: -5 * M_PI_4, offset: CGPointMake(offset - slightOffsetForCheckmarkCentering.x, offset + slightOffsetForCheckmarkCentering.y));
var newBottomPath:CGPathRef = createCenteredLineWithRadius(radius, angle: M_PI_4, offset: CGPointMake(-offset - slightOffsetForCheckmarkCentering.x, offset + slightOffsetForCheckmarkCentering.y));
if animated {
var newPaths = [newLeftPath, newTopPath, newRightPath, newBottomPath];
var lines = [lineLeft, lineTop, lineRight, lineBottom];
var values = [box_eraseLeftLine, box_eraseTopLine, box_eraseRightLine, box_eraseBottomLine];
var pathAnimationKeys = ["animateLeftLinePath", "animateTopLinePath", "animateRightLinePath", "animateBottomLinePath"];
var colorAnimationKeys = ["animateLeftLineStrokeColor", "animateTopLineStrokeColor", "animateRightLineStrokeColor", "animateBottomLineStrokeColor"];
for i in 0...3 {
var pathAnimation = CABasicAnimation(keyPath: "path");
pathAnimation.removedOnCompletion = false;
pathAnimation.duration = duration;
pathAnimation.fromValue = lines[i].path;
pathAnimation.toValue = newPaths[i];
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lines[i].addAnimation(pathAnimation, forKey: pathAnimationKeys[i]);
var colorAnimation = CABasicAnimation(keyPath: "strokeColor");
colorAnimation.removedOnCompletion = false;
colorAnimation.duration = duration;
colorAnimation.fromValue = lines[i].strokeColor;
colorAnimation.toValue = tintColor!.CGColor;
colorAnimation.setValue(values[i], forKey: "id");
colorAnimation.delegate = self;
colorAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
lines[i].addAnimation(colorAnimation, forKey: colorAnimationKeys[i]);
}
}
lineLeft.path = newLeftPath;
lineTop.path = newTopPath;
lineRight.path = newRightPath;
lineBottom.path = newBottomPath;
lineLeft.strokeColor = checkmarkColor.CGColor;
lineTop.strokeColor = checkmarkColor.CGColor;
lineRight.strokeColor = checkmarkColor.CGColor;
lineBottom.strokeColor = checkmarkColor.CGColor;
}
public override func prepareForInterfaceBuilder() {
}
func createCenteredLineWithRadius(radius:CGFloat, angle:Double, offset:CGPoint)->CGPathRef {
centerPoint = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
var path = CGPathCreateMutable();
var c = CGFloat(cos(angle));
var s = CGFloat(sin(angle));
CGPathMoveToPoint(path, nil,
centerPoint.x + offset.x + radius*c,
centerPoint.y + offset.y + radius*s);
CGPathAddLineToPoint(path, nil,
centerPoint.x + offset.x - radius*c,
centerPoint.y + offset.y - radius*s);
return path;
}
func onCheckBoxTouchDown(sender: MeterialCheckBox) {
println("Touch down handler");
growTapCircle();
}
func onCheckBoxTouchUp(sender: MeterialCheckBox) {
println("Touch up handler");
fadeTapCircleOut();
}
func onCheckBoxTouchUpAndSwitchStates(sender: MeterialCheckBox) {
println("Touch Up handler with switching states");
if !finishedAnimations {
fadeTapCircleOut();
return;
}
_switchStateAnimated(true);
}
private func _switchStateAnimated(animated:Bool) {
// Change states:
isChecked = !isChecked;
println("self.isCheched:\(isChecked)");
// Notify our delegate that we changed states!
self.delegate?.checkboxChangedState?(self);
if isChecked {
// Shrink checkBOX:
self.spinCheckbox(true, angle1: M_PI_4, angle2: -5*M_PI_4, radiusDenominator: 4, duration: AnimationDurationConstant);
}else {
// Shrink checkMARK:
self.shrinkAwayCheckmark(true);
}
self.fadeTapCircleOut();
}
override public func animationDidStop(animation:CAAnimation, finished flag:Bool) {
var key = animation.valueForKey("id") as? String;
//println("key:\(key)");
if (key == "fadeCircleOut") {
if self.deathRowForCircleLayers.count > 0 {
self.deathRowForCircleLayers[0].removeFromSuperlayer();
self.deathRowForCircleLayers.removeAtIndex(0);
}
}else if(key == box_drawLeftLine ||
key == box_drawTopLine ||
key == box_drawRightLine ||
key == box_drawBottomLine) {
self.checkboxSidesCompletedAnimating++ ;
if self.checkboxSidesCompletedAnimating >= 4 {
self.checkboxSidesCompletedAnimating = 0;
self.finishedAnimations = true;
println("FINISHED drawing BOX");
}
}else if(key == box_spinClockwiseAnimationLeftLine ||
key == box_spinClockwiseAnimationTopLine ||
key == box_spinClockwiseAnimationRightLine ||
key == box_spinClockwiseAnimationBottomLine) {
self.checkboxSidesCompletedAnimating++ ;
if self.checkboxSidesCompletedAnimating >= 4 {
self.checkboxSidesCompletedAnimating = 0;
self.shrinkAwayCheckboxAnimated(true);
println("FINISHED spinning box CCW");
}
}else if(key == box_spinCounterclockwiseAnimationLeftLine ||
key == box_spinCounterclockwiseAnimationTopLine ||
key == box_spinCounterclockwiseAnimationRightLine ||
key == box_spinCounterclockwiseAnimationBottomLine) {
self.checkboxSidesCompletedAnimating++ ;
if self.checkboxSidesCompletedAnimating >= 4 {
self.checkboxSidesCompletedAnimating = 0;
self.finishedAnimations = true;
self.drawCheckBoxAnimated(true);
println("FINISHED spinning box CCW");
}
}else if(key == mark_drawShortLine ||
key == mark_drawLongLine) {
self.checkmarkSidesCompletedAnimating++ ;
if self.checkmarkSidesCompletedAnimating >= 2 {
self.checkmarkSidesCompletedAnimating = 0;
self.finishedAnimations = true;
println("FINISHED drawing checkmark");
}
}else if(key == mark_eraseShortLine ||
key == mark_eraseLongLine) {
self.checkmarkSidesCompletedAnimating++ ;
if self.checkmarkSidesCompletedAnimating >= 2 {
self.checkmarkSidesCompletedAnimating = 0;
self.spinCheckbox(true, angle1: M_PI_4, angle2: -5*M_PI_4, radiusDenominator: 4, duration: AnimationDurationConstant/2);
println("FINISHED shrinking checkmark");
}
}else if(key == box_eraseLeftLine ||
key == box_eraseTopLine ||
key == box_eraseRightLine ||
key == box_eraseBottomLine) {
self.checkboxSidesCompletedAnimating++ ;
if self.checkboxSidesCompletedAnimating >= 4 {
self.checkboxSidesCompletedAnimating = 0;
self.drawCheckmark(true);
println("FINISHED spinning box CCW");
}
}
}
}
|
mit
|
8351dfa0cd7e3a321a58057fb0bb601c
| 49.85376 | 220 | 0.666831 | 4.940866 | false | false | false | false |
SwiftKit/Cuckoo
|
OCMock/StubRecorder.swift
|
2
|
2827
|
//
// StubRecorder.swift
// Cuckoo
//
// Created by Matyáš Kříž on 06/09/2019.
//
public class StubRecorder<OUT> {
private let recorder: OCMStubRecorder
public init(recorder: OCMStubRecorder) {
self.recorder = recorder
}
public func thenThrow(_ error: Error) {
let exception = NSException(name: NSExceptionName(rawValue: error.localizedDescription), reason: error.localizedDescription, userInfo: [:])
recorder.andThrow(exception)
}
public func thenCallRealImplementation() {
recorder.andForwardToRealObject()
}
}
public extension StubRecorder where OUT: NSValueConvertible {
func thenReturn(_ value: OUT) {
recorder.andReturn(value.toNSValue())
}
func then(do block: @escaping ([Any]) -> OUT) {
recorder.andDo { invocation in
guard let invocation = invocation else { return }
let result = block(invocation.arguments()).toNSValue()
invocation.setReturn(result)
invocation.retainArguments()
}
}
}
public extension StubRecorder where OUT == Void {
func thenDoNothing() {
recorder.andDo { _ in }
}
func then(do block: @escaping ([Any]) -> Void) {
recorder.andDo { invocation in
guard let invocation = invocation else { return }
block(invocation.arguments())
invocation.retainArguments()
}
}
}
public extension StubRecorder where OUT: NSObject {
func thenReturn(_ object: OUT) {
recorder.andReturn(object)
}
func then(do block: @escaping ([Any]) -> OUT) {
recorder.andDo { invocation in
guard let invocation = invocation else { return }
var result = block(invocation.arguments())
invocation.setReturnValue(&result)
invocation.retainArguments()
}
}
}
public extension StubRecorder where OUT: CuckooOptionalType, OUT.Wrapped: NSObject {
func thenReturn(_ object: OUT) {
recorder.andReturn(object)
}
func then(do block: @escaping ([Any]) -> OUT) {
recorder.andDo { invocation in
guard let invocation = invocation else { return }
var result = block(invocation.arguments())
invocation.setReturnValue(&result)
invocation.retainArguments()
}
}
}
public extension StubRecorder where OUT: Sequence, OUT.Element: NSObject {
func thenReturn(_ object: OUT) {
recorder.andReturn(object)
}
func then(do block: @escaping ([Any]) -> OUT) {
recorder.andDo { invocation in
guard let invocation = invocation else { return }
var result = block(invocation.arguments())
invocation.setReturnValue(&result)
invocation.retainArguments()
}
}
}
|
mit
|
9f52c10248b84b7f9d45c7943d8281c2
| 26.940594 | 147 | 0.621545 | 4.618658 | false | false | false | false |
joerocca/GitHawk
|
Classes/Issues/Request/IssueRequestSectionController.swift
|
1
|
1082
|
//
// IssueRequestSectionController.swift
// Freetime
//
// Created by Ryan Nystrom on 7/12/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
final class IssueRequestSectionController: ListGenericSectionController<IssueRequestModel> {
override func sizeForItem(at index: Int) -> CGSize {
guard let width = collectionContext?.containerSize.width,
let object = self.object
else { fatalError("Collection context must be set") }
return CGSize(
width: width,
height: object.attributedText.textViewSize(width).height
)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: IssueRequestCell.self, for: self, at: index) as? IssueRequestCell,
let object = self.object
else { fatalError("Missing collection context, cell incorrect type, or object missing") }
cell.configure(object)
cell.delegate = viewController
return cell
}
}
|
mit
|
53cee434c1584e8ad04a0c5d5bb3b4fc
| 31.757576 | 134 | 0.680851 | 4.762115 | false | false | false | false |
jayliew/codepath-tips
|
tips/ViewController.swift
|
1
|
7737
|
//
// ViewController.swift
// tips
//
// Created by Jay Liew on 1/6/16.
// Copyright © 2016 Jay Liew. All rights reserved.
//
import UIKit
extension UIColor {
// Extend UIColor to allow HTML-style hex values
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Bad red hex value: 0 - 255 only")
assert(green >= 0 && green <= 255, "Bad green hex value: 0 - 255 only")
assert(blue >= 0 && blue <= 255, "Bad blue hex value: 0 - 255 only")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
}
class ViewController: UIViewController, UITextFieldDelegate {
// MARK: Outlets
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipTextLabel: UILabel!
@IBOutlet weak var onePerson: UIImageView!
@IBOutlet weak var twoPersonA: UIImageView!
@IBOutlet weak var twoPersonB: UIImageView!
@IBOutlet weak var totalForTwoLabel: UILabel!
@IBOutlet weak var threePersonA: UIImageView!
@IBOutlet weak var threePersonB: UIImageView!
@IBOutlet weak var threePersonC: UIImageView!
@IBOutlet weak var totalForThreeLabel: UILabel!
@IBOutlet weak var billAmountLabel: UILabel!
let pink = UIColor(red:0xF8, green: 0xDB, blue: 0xDA)
let lightPink = UIColor(red:0xF6, green: 0xCA, blue: 0xC8)
let blue = UIColor(red:0x91, green:0xA4, blue:0xD0)
override func viewDidLoad() {
super.viewDidLoad()
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
totalForTwoLabel.text = "$0.00"
totalForThreeLabel.text = "$0.00"
billField.becomeFirstResponder()
billField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let defaults = UserDefaults.standard
tipControl.selectedSegmentIndex = defaults.integer(forKey: "default_tip_index")
// Set theme color
if defaults.bool(forKey: "dark_theme") == true {
self.view.backgroundColor = UIColor(red:0x91, green:0xA4, blue:0xD0)
billField.backgroundColor = blue
billField.textColor = UIColor.black
billField.backgroundColor = pink
tipControl.tintColor = pink
tipControl.backgroundColor = blue
tipControl.layer.cornerRadius = 3
tipControl.layer.shadowColor = UIColor.black.cgColor
tipControl.layer.shadowOffset = CGSize(width: 3, height: 3)
tipControl.layer.shadowOpacity = 0.3
tipControl.layer.shadowRadius = 3.0
tipTextLabel.textColor = UIColor.black
tipLabel.textColor = UIColor.black
totalLabel.textColor = UIColor.black
totalForTwoLabel.textColor = UIColor.black
totalForThreeLabel.textColor = UIColor.black
}else{
self.view.backgroundColor = pink
//self.view.backgroundColor = UIColor(red:0xF6, green: 0xCA, blue: 0xC8)
tipControl.tintColor = UIColor(red:0x91, green:0xA4, blue:0xD0)
tipControl.backgroundColor = UIColor.white
tipControl.layer.cornerRadius = 3
tipControl.layer.shadowColor = UIColor.black.cgColor
tipControl.layer.shadowOffset = CGSize(width: 3, height: 3)
tipControl.layer.shadowOpacity = 0.3
tipControl.layer.shadowRadius = 3.0
billField.backgroundColor = UIColor.white
tipTextLabel.textColor = UIColor.black
billField.textColor = UIColor.black
billField.backgroundColor = UIColor.white
tipLabel.textColor = UIColor.black
totalLabel.textColor = UIColor.black
totalForTwoLabel.textColor = UIColor.black
totalForThreeLabel.textColor = UIColor.black
}
if defaults.object(forKey: "billAmount") != nil {
// grab value from NSUserDefaults if it exists
billField.text = String(defaults.double(forKey: "billAmount"))
onEditingChanged(billField)
}
}
// MARK: UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
// This provides input sanitization to prevent an invalid Float from being entered
let oldText = textField.text ?? ""
let newText = oldText + string
if oldText.range(of: ".") != nil && string.range(of: ".") != nil {
return false
}
if let _ = Float(newText){
return true
}else{
return false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var currencyFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
let localeString = String(describing: Locale.current)
let charOne = localeString[localeString.startIndex]
let charTwo = localeString[localeString.index(after: localeString.startIndex)]
let newLocale: String?
if(charOne == "e" && charTwo == "n"){
newLocale = "en_US"
}else{
// e.g. gb_gb or de_de
newLocale = String(charOne) + String(charTwo) + "_" + String(charOne) + String(charTwo)
}
formatter.locale = Locale(identifier: newLocale!)
// print(">>>" + String(describing: formatter.locale) + "<<<")
return formatter
}
@IBAction func backFromSettings(_ sender: UIStoryboardSegue){
}
@IBAction func onEditingChanged(_ sender: AnyObject) {
let billAmount = NSString(string: billField.text!).doubleValue
let tipPercentages = [0.18, 0.2, 0.22]
let tipPercentage = tipPercentages[tipControl.selectedSegmentIndex]
let tip = billAmount * tipPercentage
let total = billAmount + tip
tipLabel.text = currencyFormatter.string(from: NSNumber(value: tip))
totalLabel.text = currencyFormatter.string(from: NSNumber(value: total))
totalForTwoLabel.text = currencyFormatter.string(from: NSNumber(value: (total / 2)))
totalForThreeLabel.text = currencyFormatter.string(from: NSNumber(value: (total / 3)))
totalForTwoLabel.alpha = 0
totalForThreeLabel.alpha = 0
twoPersonA.alpha = 0
twoPersonB.alpha = 0
threePersonA.alpha = 0
threePersonB.alpha = 0
threePersonC.alpha = 0
UIView.animate(withDuration:0.5, animations: {
self.totalForTwoLabel.alpha = 1
self.twoPersonA.alpha = 1
self.twoPersonB.alpha = 1
})
UIView.animate(withDuration:1.0, animations: {
self.totalForThreeLabel.alpha = 1
self.threePersonA.alpha = 1
self.threePersonB.alpha = 1
self.threePersonC.alpha = 1
})
}
override func viewWillDisappear(_ animated: Bool){
super.viewWillDisappear(animated)
let defaults = UserDefaults.standard
defaults.set(NSString(string: billField.text!).doubleValue, forKey: "billAmount")
}
@IBAction func onTap(_ sender: AnyObject) {
view.endEditing(true)
}
}
|
mit
|
5f6974af5d569bbf5f86acc00bdcef08
| 35.149533 | 127 | 0.614788 | 4.615752 | false | false | false | false |
ConanMTHu/animated-tab-bar
|
RAMAnimatedTabBarController/Animations/TransitionAniamtions/RAMTransitionItemAnimation.swift
|
1
|
3497
|
// RAMTransitionItemAniamtions.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class RAMTransitionItemAniamtions : RAMItemAnimation {
var transitionOptions : UIViewAnimationOptions!
@IBInspectable var iconSelectedColor: UIColor!
override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionNone
}
override func playAnimation(icon : UIImageView, textLable : UILabel) {
selectedColor(icon, textLable: textLable)
UIView.transitionWithView(icon, duration: NSTimeInterval(duration), options: transitionOptions, animations: {
}, completion: { finished in
})
}
override func deselectAnimation(icon : UIImageView, textLable : UILabel, defaultTextColor : UIColor) {
var renderImage = icon.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
icon.image = renderImage;
textLable.textColor = defaultTextColor
}
override func selectedState(icon : UIImageView, textLable : UILabel) {
selectedColor(icon, textLable: textLable)
}
func selectedColor(icon : UIImageView, textLable : UILabel) {
if iconSelectedColor != nil {
var renderImage = icon.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
icon.image = renderImage;
icon.tintColor = iconSelectedColor
}
textLable.textColor = textSelectedColor
}
}
class RAMFlipLeftTransitionItemAniamtions : RAMTransitionItemAniamtions {
override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromLeft
}
}
class RAMFlipRightTransitionItemAniamtions : RAMTransitionItemAniamtions {
override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromRight
}
}
class RAMFlipTopTransitionItemAniamtions : RAMTransitionItemAniamtions {
override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromTop
}
}
class RAMFlipBottomTransitionItemAniamtions : RAMTransitionItemAniamtions {
override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromBottom
}
}
|
mit
|
198ab927cbe3025df7a763d98fce7f44
| 32.314286 | 117 | 0.703174 | 5.266566 | false | false | false | false |
prebid/prebid-mobile-ios
|
Example/PrebidDemo/PrebidDemoSwift/Examples/AdMob/AdMobDisplayBannerViewController.swift
|
1
|
2970
|
/* Copyright 2019-2022 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import PrebidMobile
import GoogleMobileAds
import PrebidMobileAdMobAdapters
fileprivate let storedImpDisplayBanner = "imp-prebid-banner-320-50"
fileprivate let storedResponseDisplayBanner = "response-prebid-banner-320-50"
fileprivate let adMobAdUnitDisplayBannerRendering = "ca-app-pub-5922967660082475/9483570409"
class AdMobDisplayBannerViewController: BannerBaseViewController, GADBannerViewDelegate {
// Prebid
private var prebidAdMobMediaitonAdUnit: MediationBannerAdUnit!
private var mediationDelegate: AdMobMediationBannerUtils!
// AdMob
private var gadBanner: GADBannerView!
override func loadView() {
super.loadView()
Prebid.shared.storedAuctionResponse = storedResponseDisplayBanner
createAd()
}
func createAd() {
// 1. Create a GADRequest
let gadRequest = GADRequest()
// 2. Create a GADBannerView
gadBanner = GADBannerView(adSize: GADAdSizeFromCGSize(adSize))
gadBanner.adUnitID = adMobAdUnitDisplayBannerRendering
gadBanner.delegate = self
gadBanner.rootViewController = self
// Add GMA SDK banner view to the app UI
bannerView.addSubview(gadBanner)
// 3. Create an AdMobMediationBannerUtils
mediationDelegate = AdMobMediationBannerUtils(gadRequest: gadRequest, bannerView: gadBanner)
// 4. Create a MediationBannerAdUnit
prebidAdMobMediaitonAdUnit = MediationBannerAdUnit(
configID: storedImpDisplayBanner,
size: adSize,
mediationDelegate: mediationDelegate
)
// 5. Make a bid request to Prebid Server
prebidAdMobMediaitonAdUnit.fetchDemand { [weak self] result in
PrebidDemoLogger.shared.info("Prebid demand fetch for AdMob \(result.name())")
// 6. Load ad
self?.gadBanner.load(gadRequest)
}
}
//MARK: - GADBannerViewDelegate
func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
}
func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
PrebidDemoLogger.shared.error("AdMob did fail to receive ad with error: \(error)")
prebidAdMobMediaitonAdUnit?.adObjectDidFailToLoadAd(adObject: gadBanner, with: error)
}
}
|
apache-2.0
|
c776dd558dbb38214655b7fe3ca9df11
| 34.783133 | 100 | 0.700673 | 4.876847 | false | false | false | false |
lkzhao/MCollectionView
|
Examples/GridExample/GridViewController.swift
|
1
|
2332
|
//
// GridViewController.swift
// MCollectionViewExample
//
// Created by Luke Zhao on 2016-06-05.
// Copyright © 2016 lkzhao. All rights reserved.
//
import UIKit
import MCollectionView
let kGridCellSize = CGSize(width: 100, height: 100)
let kGridSize = (width: 20, height: 20)
let kGridCellPadding:CGFloat = 10
class GridViewController: UIViewController {
var collectionView: MCollectionView!
var items:[Int] = []
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...kGridSize.width * kGridSize.height {
items.append(i)
}
view.backgroundColor = UIColor(white: 0.97, alpha: 1.0)
view.clipsToBounds = true
collectionView = MCollectionView(frame:view.bounds)
collectionView.collectionDelegate = self
collectionView.wabble = true
view.addSubview(collectionView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
collectionView.contentInset = UIEdgeInsetsMake(topLayoutGuide.length, 0, 0, 0)
}
}
// collectionview datasource and layout
extension GridViewController: MCollectionViewDelegate {
func numberOfItemsInCollectionView(_ collectionView: MCollectionView) -> Int {
return items.count
}
func collectionView(_ collectionView: MCollectionView, viewForIndex index: Int) -> UIView {
let v = collectionView.dequeueReusableView(UILabel.self) ?? UILabel()
v.backgroundColor = UIColor.lightGray
v.text = "\(items[index])"
return v
}
func collectionView(_ collectionView: MCollectionView, identifierForIndex index: Int) -> String {
return "\(items[index])"
}
func collectionView(_ collectionView: MCollectionView, frameForIndex index: Int) -> CGRect {
let i = index
return CGRect(x: CGFloat(i % kGridSize.width) * (kGridCellSize.width + kGridCellPadding),
y: CGFloat(i / kGridSize.width) * (kGridCellSize.height + kGridCellPadding),
width: kGridCellSize.width,
height: kGridCellSize.height)
}
func collectionView(_ collectionView: MCollectionView, willDrag cell: UIView, at index: Int) -> Bool {
return true
}
func collectionView(_ collectionView: MCollectionView, moveItemAt index: Int, to: Int) -> Bool {
items.insert(items.remove(at: index), at: to)
return true
}
}
|
mit
|
4284d5fa5bdb15ef6fa6c2054fa09953
| 31.375 | 104 | 0.709996 | 4.42315 | false | false | false | false |
Sharelink/Bahamut
|
Bahamut/SignInViewController.swift
|
1
|
10087
|
//
// SignInViewController.swift
// Bahamut
//
// Created by AlexChow on 15/7/29.
// Copyright (c) 2015年 GStudio. All rights reserved.
//
import UIKit
import JavaScriptCore
import MBProgressHUD
@objc protocol SignInViewControllerJSProtocol : JSExport
{
func alert(msg:String)
func showPrivacy()
func registAccount(username:String,_ password:String)
func loginAccount(username:String,_ password:String)
}
//MARK: SignInViewController
class SignInViewController: UIViewController,UIWebViewDelegate,SignInViewControllerJSProtocol
{
private var webPageView: UIWebView!{
didSet{
webPageView.hidden = true
webPageView.scrollView.showsHorizontalScrollIndicator = false
webPageView.scrollView.showsVerticalScrollIndicator = false
webPageView.scrollView.scrollEnabled = false
webPageView.scalesPageToFit = true
webPageView.delegate = self
self.view.addSubview(webPageView)
}
}
private var launchScr:UIView!
private func setBackgroundView()
{
launchScr = MainNavigationController.getLaunchScreen(self.view.bounds)
self.view.addSubview(launchScr)
self.view.bringSubviewToFront(launchScr)
}
private func launchScrEaseOut()
{
UIView.animateWithDuration(1, animations: { () -> Void in
self.launchScr.alpha = 0
}) { (flag) -> Void in
self.launchScr.removeFromSuperview()
}
}
override func viewDidLoad() {
super.viewDidLoad()
changeNavigationBarColor()
self.view.backgroundColor = UIColor.whiteColor()
webPageView = UIWebView(frame: self.view.bounds)
setBackgroundView()
ServiceContainer.instance.addObserver(self, selector: #selector(SignInViewController.allServicesReady(_:)), name: ServiceContainer.OnAllServicesReady, object: nil)
loginAccountId = UserSetting.lastLoginAccountId
refreshWebView()
}
func allServicesReady(_:NSNotification)
{
ServiceContainer.instance.removeObserver(self)
self.view.backgroundColor = UIColor.blackColor()
if let hud = self.refreshingHud
{
hud.hideAsync(false)
}
self.webPageView.hidden = true
self.view.backgroundColor = UIColor.blackColor()
}
private func refreshWebView()
{
if loginAccountId != nil{
authenticate()
}else
{
registAccount()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(SignInViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(SignInViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object:nil)
if developerShown
{
developerShown = false
refreshWebView()
}
}
func keyboardWillHide(_:NSNotification)
{
webPageView.scrollView.scrollEnabled = false
}
func keyboardWillShow(_:NSNotification)
{
webPageView.scrollView.scrollEnabled = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private var registAccountUrl:String{
let url = Sharelink.mainBundle().pathForResource("register_\(SharelinkSetting.lang)", ofType: "html", inDirectory: "WebAssets/Sharelink")
return url!
}
private var authenticationURL: String {
let url = Sharelink.mainBundle().pathForResource("login_\(SharelinkSetting.lang)", ofType: "html", inDirectory: "WebAssets/Sharelink")
return url!
}
private var webViewUrl:String!{
didSet{
if webPageView != nil{
let req = NSURLRequest(URL: NSURL(string: webViewUrl)!)
webPageView.loadRequest(req)
}
}
}
var loginAccountId:String!
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
}
func webViewDidStartLoad(webView: UIWebView) {
}
func webViewDidFinishLoad(webView: UIWebView) {
if self.webPageView.hidden
{
self.webPageView.hidden = false
launchScrEaseOut()
}
if let jsContext:JSContext = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as? JSContext
{
jsContext.setObject(self, forKeyedSubscript: "controller")
jsContext.exceptionHandler = jsExceptionHandler
}
}
func jsExceptionHandler(context:JSContext!,value:JSValue!) {
self.playToast("JS_ERROR".localizedString())
}
var registedAccountName:String!
private var refreshingHud:MBProgressHUD!
private func validateToken(serverUrl:String, accountId:String, accessToken: String)
{
let accountService = ServiceContainer.getService(AccountService)
let hud = self.showActivityHudWithMessage("",message: "LOGINING".localizedString() )
accountService.validateAccessToken(serverUrl, accountId: accountId, accessToken: accessToken, callback: { (loginSuccess, message) -> Void in
hud.hideAsync(true)
if loginSuccess{
self.refreshingHud = self.showActivityHudWithMessage("",message:"REFRESHING".localizedString())
}else{
self.playToast( message)
}
}) { (registApiServer) -> Void in
hud.hideAsync(true)
self.registNewUser(accountId,registApi: registApiServer,accessToken:accessToken)
}
}
private var refreshHud:MBProgressHUD!
private func registNewUser(accountId:String,registApi:String,accessToken:String)
{
let registModel = RegistSharelinkModel()
registModel.accessToken = accessToken
registModel.registUserServer = registApi
registModel.accountId = accountId
registModel.userName = registedAccountName ?? "Sharelinker"
registModel.region = SharelinkSetting.contry.lowercaseString
let newUser = Sharelinker()
newUser.motto = "Sharelink"
newUser.nickName = registedAccountName ?? "Sharelinker"
let hud = self.showActivityHudWithMessage("",message:"REGISTING".localizedString())
ServiceContainer.getService(AccountService).registNewUser(registModel, newUser: newUser){ isSuc,msg,validateResult in
hud.hideAsync(true)
if isSuc
{
self.refreshHud = self.showActivityHudWithMessage("",message:"REFRESHING".localizedString())
}else
{
self.playToast(msg)
}
}
}
private func authenticate()
{
var url = authenticationURL
if let aId = loginAccountId
{
url = "\(url)?accountId=\(aId)"
}else
{
url = "\(url)"
}
webViewUrl = url
}
private func registAccount()
{
let url = "\(registAccountUrl)?loginApi=\(SharelinkSetting.loginApi)®istApi=\(SharelinkSetting.registAccountApi)"
webViewUrl = url
}
//MARK: implements jsProtocol
func registAccount(username: String,_ password: String) {
if DeveloperMainPanelController.isShowDeveloperPanel(self,id:username,psw:password){
self.developerShown = true
return
}
self.hideKeyBoard()
MobClick.event("CLICK_REGIST")
let hud = self.showActivityHud()
BahamutRFKit.sharedInstance.registBahamutAccount(SharelinkSetting.registAccountApi, username: username, passwordOrigin: password, phone_number: nil, email: nil) { (isSuc, errorMsg, registResult) -> Void in
hud.hide(false)
if isSuc
{
self.showAlert("REGIST_SUC_TITLE".localizedString(), msg: String(format: "REGIST_SUC_MSG".localizedString(), registResult.accountId))
self.loginAccountId = registResult.accountId
self.registedAccountName = registResult.accountName
self.authenticate()
}else{
self.playToast(errorMsg.localizedString())
}
}
}
func loginAccount(username: String,_ password: String) {
if DeveloperMainPanelController.isShowDeveloperPanel(self,id:username,psw:password){
self.developerShown = true
return
}
self.hideKeyBoard()
let hud = self.showActivityHudWithMessage(nil, message: "LOGINING".localizedString())
BahamutRFKit.sharedInstance.loginBahamutAccount(SharelinkSetting.loginApi, accountInfo: username, passwordOrigin: password) { (isSuc, errorMsg, loginResult) -> Void in
hud.hide(true)
if isSuc
{
self.validateToken(loginResult.appServiceUrl, accountId: loginResult.accountID, accessToken: loginResult.accessToken)
}else
{
self.playToast(errorMsg.localizedString())
}
}
}
func alert(msg: String) {
let alert = UIAlertController(title:"SHARELINK".localizedString(), message: msg.localizedString(), preferredStyle: .Alert)
alert.addAction(UIAlertAction(title:"I_SEE".localizedString(), style: .Cancel){ _ in})
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.presentViewController(alert, animated: true, completion: nil)
}
}
func showPrivacy() {
SimpleBrowser.openUrl(self.navigationController!, url: SharelinkConfig.bahamutConfig.appPrivacyPage)
}
//MARK: Developer Panel
private var developerShown = false
}
|
mit
|
9234b063081d8657945eba6fe8f44dfe
| 34.385965 | 213 | 0.639663 | 5.098584 | false | false | false | false |
shirai/SwiftLearning
|
playground/エクステンション.playground/Contents.swift
|
1
|
4421
|
//: Playground - noun: a place where people can play
import UIKit
/* エクステンション...拡張
計算型プロパティと静的な計算型プロパティ(計算型の型プロパティ)を追加できます。
インスタンスメソッドと型メソッドを追加できます。
イニシャライザを追加できます。(追加できるのはコンビニエンスイニシャライザのみです。指定イニシャライザやデイニシャライザは追加できません。)
サブスクリプトを追加できます。
ネストした型を定義してそれを使うことができます。
新たなプロトコルに適合させることができます。 */
// 計算型プロパティの追加
extension Int{ //Int型の拡張
//16進数
var hex: String{
return String(self, radix: 16)
}
//8進数
var oct: String{
return String(self, radix: 8)
}
//2進数
var bin: String{
return String(self, radix: 2)
}
}
print(30.hex)
print(30.oct)
print(30.bin)
/* 構造体にイニシャライザを追加する */
struct Person{
let name: String
var email: String
var age: Int
}
let taro = Person(name: "山田太郎", email: "[email protected]", age: 35)
//イニシャライザの追加
extension Person {
init(csv: String) {
let data = csv.components(separatedBy: ",")
var name: String? = nil
var email: String? = nil
var age: Int? = nil
if data.count > 0 { name = data[0].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()}
if data.count > 1 { email = data[1].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() }
if data.count > 2 { age = Int(data[2].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased())}
self.init(name: name!, email: email!, age: age!)
}
}
let csv: String = "\"山田次郎\", \"[email protected]\", 35"
let ziro = Person(csv: csv)
print("名前:\(ziro.name) メール:\(ziro.email) 年齢:\(ziro.age)")
/* メソッドの追加 */
//String型に文字列を反転するreverseメソッドを追加
extension String {
mutating func reverse() {
var str = ""
for ch in characters {
str = String(ch) + str
}
self = str
}
}
//受け取った関数型の処理を繰り返すメソッドを追加
extension Int {
func times(task: () -> ()) {
for _ in 0..<self {
task()
}
}
}
3.times( task: { print("Hello, Swift") } )
/* サブスクリプトの追加 */
extension String {
subscript(i: Int) -> Character {
let idx = index(self.startIndex, offsetBy: i)
//let idx = advance(self.startIndex, index)
return self[idx]
}
}
let text = "吾輩は猫である。"
print(text[3])
//ネストした型の追加
extension String {
enum `Type` {
case URL, EMail, Telephone, Other
}
// 文字列の種類
var type: Type {
// URL
var regex = try! NSRegularExpression(pattern:"^(https?|ftp)(:\\/\\/[-_.!~*\\'()a-zA-Z0-9;\\/?:\\@&=+\\$,%#]+)$", options: NSRegularExpression.Options.caseInsensitive)
if regex.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: self.characters.count)) > 0 {
return .URL
}
// メールアドレス
regex = try! NSRegularExpression(pattern:"^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$", options: NSRegularExpression.Options.caseInsensitive)
if regex.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: self.characters.count)) > 0 {
return .EMail
}
// 電話番号
regex = try! NSRegularExpression(pattern:"^\\d{1,4}-?\\d{4}$|\\d{2,5}-?\\d{1,4}-?\\d{4}$", options: NSRegularExpression.Options.caseInsensitive)
if regex.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: self.characters.count)) > 0 {
return .Telephone
}
return .Other
}
}
let url = "http://example.com?id=test&num=123"
print(url.type == .URL) // true
let email = "[email protected]"
print(email.type == .EMail) // true
let phone = "03-123-9876"
print(phone.type == .Telephone) // true
let text2 = "Hello, Swift!"
print(text2.type == .Other) // true
|
mit
|
8e6a5f6e33fbb3b5afdfe0908cc59cac
| 26.444444 | 174 | 0.6 | 3.02449 | false | false | false | false |
euskadi31/ngram-swift
|
Package.swift
|
1
|
471
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Ngram open source project
//
// Copyright (c) 2016 Axel Etcheverry.
// Licensed under MIT
//
// See LICENSE.md for license information
// See CONTRIBUTORS.txt for the list of ngram project authors
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "Ngram"
)
|
mit
|
220cf95eeb7342877bf8fd6c961804bd
| 26.705882 | 80 | 0.473461 | 5.413793 | false | false | false | false |
SeaHub/ImgTagging
|
ImgTagger/ImgTagger/ServerPushData.swift
|
1
|
1335
|
//
// ServerPushData.swift
// ImgTagger
//
// Created by SeaHub on 2017/6/27.
// Copyright © 2017年 SeaCluster. All rights reserved.
//
import UIKit
import SwiftyJSON
struct ServerPushDataJSONParsingKeys {
static let kImageIDKey = "i_id"
static let kImageURLKey = "url"
static let kFilenamekey = "filename"
static let kCreatedAtKey = "created_at"
static let kUpadatedAtKey = "updated_at"
static let kImageKey = "finalTag"
}
class ServerPushData: NSObject {
let imageID: Int!
let imageURL: String!
let filename: String!
var image: Image?
var createdAt: String? = nil
var updatedAt: String? = nil
init(JSON: Dictionary<String, JSON>) {
self.imageID = JSON[ServerPushDataJSONParsingKeys.kImageIDKey]!.int!
self.imageURL = JSON[ServerPushDataJSONParsingKeys.kImageURLKey]!.string!
self.filename = JSON[ServerPushDataJSONParsingKeys.kFilenamekey]!.string!
self.createdAt = JSON[ServerPushDataJSONParsingKeys.kCreatedAtKey]!.string
self.updatedAt = JSON[ServerPushDataJSONParsingKeys.kUpadatedAtKey]!.string
if let image = JSON[ServerPushDataJSONParsingKeys.kImageKey]!.dictionary {
self.image = Image(JSON: image)
} else {
self.image = nil
}
}
}
|
gpl-3.0
|
0d1a95acbfe552d66927d99b852dac50
| 30.714286 | 83 | 0.67042 | 3.784091 | false | false | false | false |
yunzixun/V2ex-Swift
|
Controller/NodeTopicListViewController.swift
|
1
|
7261
|
//
// NodeTopicListViewController.swift
// V2ex-Swift
//
// Created by huangfeng on 2/3/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class NodeTopicListViewController: BaseViewController ,UITableViewDataSource,UITableViewDelegate {
var node:NodeModel?
var nodeId:String?
var favorited:Bool = false
var favoriteUrl:String? {
didSet{
let startIndex = favoriteUrl?.range(of: "/", options: .backwards, range: nil, locale: nil)
let endIndex = favoriteUrl?.range(of: "?")
let nodeId = favoriteUrl?[Range<String.Index>(startIndex!.upperBound ..< endIndex!.lowerBound)]
if let nodeId = nodeId , let favoriteUrl = favoriteUrl {
self.nodeId = String(nodeId)
if favoriteUrl.hasPrefix("/favorite"){
favorited = false
}
else{
favorited = true
}
self.setupFavorite()
}
}
}
var followButton:UIButton?
fileprivate var topicList:Array<TopicListModel>?
var currentPage = 1
fileprivate var _tableView :UITableView!
fileprivate var tableView: UITableView {
get{
if(_tableView != nil){
return _tableView!;
}
_tableView = UITableView();
_tableView.cancelEstimatedHeight()
_tableView.backgroundColor = V2EXColor.colors.v2_backgroundColor
_tableView.separatorStyle = UITableViewCellSeparatorStyle.none;
regClass(_tableView, cell: HomeTopicListTableViewCell.self)
_tableView.delegate = self
_tableView.dataSource = self
return _tableView!;
}
}
override func viewDidLoad() {
super.viewDidLoad()
if self.node?.nodeId == nil {
return;
}
self.title = self.node?.nodeName
self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints{ (make) -> Void in
make.top.right.bottom.left.equalTo(self.view);
}
self.showLoadingView()
self.tableView.mj_header = V2RefreshHeader(refreshingBlock: {[weak self] () -> Void in
self?.refresh()
})
self.tableView.mj_header.beginRefreshing()
let footer = V2RefreshFooter(refreshingBlock: {[weak self] () -> Void in
self?.getNextPage()
})
footer?.centerOffset = -4
self.tableView.mj_footer = footer
}
func refresh(){
self.currentPage = 1
//如果有上拉加载更多 正在执行,则取消它
if self.tableView.mj_footer.isRefreshing {
self.tableView.mj_footer.endRefreshing()
}
//根据 tab name 获取帖子列表
TopicListModel.getTopicList(self.node!.nodeId!, page: self.currentPage){
[weak self](response:V2ValueResponse<([TopicListModel],String?)>) -> Void in
if response.success {
if let weakSelf = self {
weakSelf.topicList = response.value?.0
weakSelf.favoriteUrl = response.value?.1
weakSelf.tableView.reloadData()
}
}
self?.tableView.mj_header.endRefreshing()
self?.hideLoadingView()
}
}
func getNextPage(){
if let count = self.topicList?.count, count <= 0{
self.tableView.mj_footer.endRefreshing()
return;
}
self.currentPage += 1
TopicListModel.getTopicList(self.node!.nodeId!, page: self.currentPage){
[weak self](response:V2ValueResponse<([TopicListModel],String?)>) -> Void in
if response.success {
if let weakSelf = self , let value = response.value {
weakSelf.topicList! += value.0
weakSelf.tableView.reloadData()
}
else{
self?.currentPage -= 1
}
}
self?.tableView.mj_footer.endRefreshing()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let list = self.topicList {
return list.count;
}
return 0;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let item = self.topicList![indexPath.row]
let titleHeight = item.topicTitleLayout?.textBoundingRect.size.height ?? 0
// 上间隔 头像高度 头像下间隔 标题高度 标题下间隔 cell间隔
let height = 12 + 35 + 12 + titleHeight + 12 + 8
return height
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = getCell(tableView, cell: HomeTopicListTableViewCell.self, indexPath: indexPath);
cell.bindNodeModel(self.topicList![indexPath.row]);
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.topicList![indexPath.row]
if let id = item.topicId {
let topicDetailController = TopicDetailViewController();
topicDetailController.topicId = id ;
self.navigationController?.pushViewController(topicDetailController, animated: true)
tableView .deselectRow(at: indexPath, animated: true);
}
}
}
extension NodeTopicListViewController {
func setupFavorite(){
if(self.followButton != nil){
return;
}
let followButton = UIButton(frame:CGRect(x: 0, y: 0, width: 26, height: 26))
followButton.addTarget(self, action: #selector(toggleFavoriteState), for: .touchUpInside)
let followItem = UIBarButtonItem(customView: followButton)
//处理间距
let fixedSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpaceItem.width = -5
self.navigationItem.rightBarButtonItems = [fixedSpaceItem,followItem]
self.followButton = followButton;
refreshButtonImage()
}
func refreshButtonImage() {
let followImage = self.favorited == true ? UIImage(named: "ic_favorite")! : UIImage(named: "ic_favorite_border")!
self.followButton?.setImage(followImage.withRenderingMode(.alwaysTemplate), for: UIControlState())
}
@objc func toggleFavoriteState(){
if(self.favorited == true){
unFavorite()
}
else{
favorite()
}
refreshButtonImage()
}
func favorite() {
TopicListModel.favorite(self.nodeId!, type: 0)
self.favorited = true
V2Success("收藏成功")
}
func unFavorite() {
TopicListModel.favorite(self.nodeId!, type: 1)
self.favorited = false
V2Success("取消收藏了~")
}
}
|
mit
|
13daa49f958a2d57d949b55f1b1822c2
| 33.143541 | 121 | 0.574552 | 4.945253 | false | false | false | false |
Sadmansamee/quran-ios
|
Quran/QuartersDataSource.swift
|
1
|
1312
|
//
// QuartersDataSource.swift
// Quran
//
// Created by Mohamed Afifi on 4/22/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
import GenericDataSources
class QuartersDataSource: BasicDataSource<Quarter, QuarterTableViewCell> {
let numberFormatter = NumberFormatter()
// this is needed as of swift 2.2 as class don't inherit constructors from generic based.
override init(reuseIdentifier: String) {
super.init(reuseIdentifier: reuseIdentifier)
}
override func ds_collectionView(_ collectionView: GeneralCollectionView,
configure cell: QuarterTableViewCell,
with item: Quarter,
at indexPath: IndexPath) {
let progress = CGFloat(item.order % 4) / 4
let circleProgress = progress == 0 ? 1 : progress
let hizb = item.order / 4 + 1
cell.circleLabel.text = numberFormatter.format(NSNumber(value: hizb))
cell.circleLabel.isHidden = circleProgress != 1
cell.circleView.progress = circleProgress
cell.name.text = item.ayahText
cell.descriptionLabel.text = item.ayah.localizedName
cell.startPage.text = numberFormatter.format(NSNumber(value: item.startPageNumber))
}
}
|
mit
|
06f295c73561e9386689e9c2d248aa52
| 34.432432 | 93 | 0.652937 | 4.802198 | false | false | false | false |
1000copy/fin
|
Common/V2EXColor.swift
|
1
|
7840
|
//
// V2EXColor.swift
// V2ex-Swift
//
// Created by huangfeng on 1/11/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
//import KVOController
func colorWith255RGB(_ r:CGFloat , g:CGFloat, b:CGFloat) ->UIColor {
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 255)
}
func colorWith255RGBA(_ r:CGFloat , g:CGFloat, b:CGFloat,a:CGFloat) ->UIColor {
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a/255)
}
func createImageWithColor(_ color:UIColor) -> UIImage{
return createImageWithColor(color, size: CGSize(width: 1, height: 1))
}
func createImageWithColor(_ color:UIColor,size:CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext();
context?.setFillColor(color.cgColor);
context?.fill(rect);
let theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage!;
}
//使用协议 方便以后切换颜色配置文件、或者做主题配色之类乱七八糟产品经理最爱的功能
protocol V2EXColorProtocol{
var v2_backgroundColor: UIColor { get }
var v2_navigationBarTintColor: UIColor { get }
var v2_TopicListTitleColor : UIColor { get }
var v2_TopicListUserNameColor : UIColor { get }
var v2_TopicListDateColor : UIColor { get }
var v2_LinkColor : UIColor { get }
var v2_TextViewBackgroundColor: UIColor { get }
var v2_CellWhiteBackgroundColor : UIColor { get }
var v2_NodeBackgroundColor : UIColor { get }
var v2_SeparatorColor : UIColor { get }
var v2_LeftNodeBackgroundColor : UIColor { get }
var v2_LeftNodeBackgroundHighLightedColor : UIColor { get }
var v2_LeftNodeTintColor: UIColor { get }
/// 小红点背景颜色
var v2_NoticePointColor : UIColor { get }
var v2_ButtonBackgroundColor : UIColor { get }
}
class V2EXDefaultColor: NSObject,V2EXColorProtocol {
static let sharedInstance = V2EXDefaultColor()
fileprivate override init(){
super.init()
}
var v2_backgroundColor : UIColor{
get{
return colorWith255RGB(242, g: 243, b: 245);
}
}
var v2_navigationBarTintColor : UIColor{
get{
return colorWith255RGB(102, g: 102, b: 102);
}
}
var v2_TopicListTitleColor : UIColor{
get{
return colorWith255RGB(15, g: 15, b: 15);
}
}
var v2_TopicListUserNameColor : UIColor{
get{
return colorWith255RGB(53, g: 53, b: 53);
}
}
var v2_TopicListDateColor : UIColor{
get{
return colorWith255RGB(173, g: 173, b: 173);
}
}
var v2_LinkColor : UIColor {
get {
return colorWith255RGB(119, g: 128, b: 135)
}
}
var v2_TextViewBackgroundColor :UIColor {
get {
return colorWith255RGB(255, g: 255, b: 255)
}
}
var v2_CellWhiteBackgroundColor :UIColor {
get {
return colorWith255RGB(255, g: 255, b: 255)
}
}
var v2_NodeBackgroundColor : UIColor {
get {
return colorWith255RGB(242, g: 242, b: 242)
}
}
var v2_SeparatorColor : UIColor {
get {
return colorWith255RGB(190, g: 190, b: 190)
}
}
var v2_LeftNodeBackgroundColor : UIColor {
get {
return colorWith255RGBA(255, g: 255, b: 255, a: 76)
}
}
var v2_LeftNodeBackgroundHighLightedColor : UIColor {
get {
return colorWith255RGBA(255, g: 255, b: 255, a: 56)
}
}
var v2_LeftNodeTintColor : UIColor {
get {
return colorWith255RGBA(0, g: 0, b: 0, a: 140)
}
}
var v2_NoticePointColor : UIColor {
get {
return colorWith255RGB(207, g: 70, b: 71)
}
}
var v2_ButtonBackgroundColor : UIColor {
get {
return colorWith255RGB(85, g: 172, b: 238)
}
}
}
/// Dark Colors
class V2EXDarkColor: NSObject,V2EXColorProtocol {
static let sharedInstance = V2EXDarkColor()
fileprivate override init(){
super.init()
}
var v2_backgroundColor : UIColor{
get{
return colorWith255RGB(32, g: 31, b: 35);
}
}
var v2_navigationBarTintColor : UIColor{
get{
return colorWith255RGB(165, g: 165, b: 165);
}
}
var v2_TopicListTitleColor : UIColor{
get{
return colorWith255RGB(145, g: 145, b: 145);
}
}
var v2_TopicListUserNameColor : UIColor{
get{
return colorWith255RGB(125, g: 125, b: 125);
}
}
var v2_TopicListDateColor : UIColor{
get{
return colorWith255RGB(100, g: 100, b: 100);
}
}
var v2_LinkColor : UIColor {
get {
return colorWith255RGB(119, g: 128, b: 135)
}
}
var v2_TextViewBackgroundColor :UIColor {
get {
return colorWith255RGB(35, g: 34, b: 38)
}
}
var v2_CellWhiteBackgroundColor :UIColor {
get {
return colorWith255RGB(35, g: 34, b: 38)
}
}
var v2_NodeBackgroundColor : UIColor {
get {
return colorWith255RGB(40, g: 40, b: 40)
}
}
var v2_SeparatorColor : UIColor {
get {
return colorWith255RGB(46, g: 45, b: 49)
}
}
var v2_LeftNodeBackgroundColor : UIColor {
get {
return colorWith255RGBA(255, g: 255, b: 255, a: 76)
}
}
var v2_LeftNodeBackgroundHighLightedColor : UIColor {
get {
return colorWith255RGBA(255, g: 255, b: 255, a: 56)
}
}
var v2_LeftNodeTintColor : UIColor {
get {
return colorWith255RGBA(0, g: 0, b: 0, a: 140)
}
}
var v2_NoticePointColor : UIColor {
get {
return colorWith255RGB(207, g: 70, b: 71)
}
}
var v2_ButtonBackgroundColor : UIColor {
get {
return colorWith255RGB(207, g: 70, b: 71)
}
}
}
class V2EXColor :NSObject {
fileprivate static let STYLE_KEY = "styleKey"
static let V2EXColorStyleDefault = "Default"
static let V2EXColorStyleDark = "Dark"
fileprivate static var _colors:V2EXColorProtocol?
static var colors :V2EXColorProtocol {
get{
if let c = V2EXColor._colors {
return c
}
else{
if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault{
return V2EXDefaultColor.sharedInstance
}
else{
return V2EXDarkColor.sharedInstance
}
}
}
set{
V2EXColor._colors = newValue
}
}
dynamic var style:String
static let sharedInstance = V2EXColor()
fileprivate override init(){
if let style = Setting.shared.STYLE_KEY {
self.style = style
}
else{
self.style = V2EXColor.V2EXColorStyleDefault
}
super.init()
}
func setStyleAndSave(_ style:String){
if self.style == style {
return
}
if style == V2EXColor.V2EXColorStyleDefault {
V2EXColor.colors = V2EXDefaultColor.sharedInstance
}
else{
V2EXColor.colors = V2EXDarkColor.sharedInstance
}
self.style = style
Setting.shared.STYLE_KEY = style
}
}
|
mit
|
93bfcb25a275aaa81ff73484ab414bc9
| 24.071197 | 85 | 0.558668 | 4.005688 | false | false | false | false |
mortenjust/cleartext-mac
|
Simpler/LanguagePopupButton.swift
|
1
|
1338
|
//
// LanguagePopupButton.swift
// Simpler
//
// Created by Morten Just Petersen on 11/26/15.
// Copyright © 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
class LanguagePopupButton: NSPopUpButton {
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override func mouseUp(with theEvent: NSEvent) {
Swift.print("mouse is up")
}
override func didCloseMenu(_ menu: NSMenu, with event: NSEvent?) {
styleItems()
}
func setup(){
self.wantsLayer = true
populateItems()
styleItems()
style()
}
func style(){
layer?.backgroundColor = NSColor(red:0.902, green:0.902, blue:0.902, alpha:0.5).cgColor
}
func populateItems(){
for l in C.languages {
self.addItem(withTitle: l.name)
}
}
func styleItems(){
let menuAttributes = [
NSForegroundColorAttributeName : C.languageItemColor
]
for item in self.itemArray {
let s = NSMutableAttributedString(string: item.title, attributes: menuAttributes)
item.attributedTitle = s
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
}
|
gpl-3.0
|
7c8b4710aae2690d040873ef766e6cb7
| 20.918033 | 95 | 0.573672 | 4.471572 | false | false | false | false |
exyte/Macaw
|
Source/animation/types/ContentsAnimation.swift
|
1
|
3131
|
internal class ContentsAnimation: AnimationImpl<[Node]> {
init(animatedGroup: Group, valueFunc: @escaping (Double) -> [Node], animationDuration: Double, delay: Double = 0.0, autostart: Bool = false, fps: UInt = 30) {
super.init(observableValue: animatedGroup.contentsVar, valueFunc: valueFunc, animationDuration: animationDuration, delay: delay, fps: fps)
type = .contents
node = animatedGroup
if autostart {
self.play()
}
}
init(animatedGroup: Group, factory: @escaping (() -> ((Double) -> [Node])), animationDuration: Double, delay: Double = 0.0, autostart: Bool = false, fps: UInt = 30) {
super.init(observableValue: animatedGroup.contentsVar, factory: factory, animationDuration: animationDuration, delay: delay, fps: fps)
type = .contents
node = animatedGroup
if autostart {
self.play()
}
}
open override func reverse() -> Animation {
let factory = { () -> (Double) -> [Node] in
let original = self.timeFactory()
return { (t: Double) -> [Node] in
original(1.0 - t)
}
}
let reversedAnimation = ContentsAnimation(animatedGroup: node as! Group,
factory: factory, animationDuration: duration, fps: logicalFps)
reversedAnimation.progress = progress
reversedAnimation.completion = completion
return reversedAnimation
}
}
public extension AnimatableVariable where T: ContentsInterpolation {
func animation(_ f: @escaping (Double) -> [Node]) -> Animation {
let group = node! as! Group
return ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: 1.0, delay: 0.0, autostart: false)
}
func animation(_ f: @escaping ((Double) -> [Node]), during: Double = 1.0, delay: Double = 0.0) -> Animation {
let group = node! as! Group
return ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: during, delay: delay, autostart: false)
}
func animation(during: Double = 1.0, delay: Double = 0.0, _ f: @escaping ((Double) -> [Node])) -> Animation {
let group = node! as! Group
return ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: during, delay: delay, autostart: false)
}
func animate(_ f: @escaping (Double) -> [Node]) {
let group = node! as! Group
_ = ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: 1.0, delay: 0.0, autostart: true)
}
func animate(_ f: @escaping ((Double) -> [Node]), during: Double = 1.0, delay: Double = 0.0) {
let group = node! as! Group
_ = ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: during, delay: delay, autostart: true)
}
func animate(during: Double = 1.0, delay: Double = 0.0, _ f: @escaping ((Double) -> [Node])) {
let group = node! as! Group
_ = ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: during, delay: delay, autostart: true)
}
}
|
mit
|
4dabf9f65e18569b1746a69823d2de8b
| 42.486111 | 170 | 0.62504 | 4.213997 | false | false | false | false |
keygx/PAssert
|
Source/PAssert.swift
|
1
|
7630
|
//
// PAssert.swift
//
// Created by keygx on 2015/08/06.
// Copyright (c) 2015年 keygx. All rights reserved.
//
import XCTest
// MARK: - PAssert
public func PAssert<T>( _ lhs: @autoclosure() -> T, _ comparison: (T, T) -> Bool, _ rhs: @autoclosure() -> T,
filePath: StaticString = #file, lineNumber: UInt = #line, function: String = #function) {
let pa = PAssertHelper()
let result = comparison(lhs(), rhs())
if !result {
var source = pa.readSource(filePath.description)
if !source.isEmpty {
source = pa.removeComment(source)
source = pa.removeMultilinesComment(source)
let out = pa.output(source, comparison: result, lhs: lhs(), rhs: rhs(),
fileName: pa.getFilename(filePath.description), lineNumber: lineNumber, function: function)
XCTFail(out, file: filePath, line:UInt(lineNumber))
}
} else {
print("")
print("[\(pa.getDateTime()) \(pa.getFilename(filePath.description)):\(lineNumber) \(function)] \(lhs())")
print("")
}
}
private class PAssertHelper {
init() {}
// MARK: - get datetime
func getDateTime() -> String {
let now = Date()
let dateFormatter = DateFormatter()
let localeIdentifier = Locale.current.identifier
dateFormatter.locale = Locale(identifier: localeIdentifier)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: now)
}
// MARK: - read source file
func readSource(_ filePath: String) -> String {
var source = ""
do {
let code = try String(contentsOfFile:filePath, encoding: String.Encoding.utf8)
source = code
} catch let error as NSError {
print(error)
}
return source
}
// MARK: - remove comments
func removeComment(_ source: String) -> String {
var formatted = ""
let pattern = "[ \t]*//.*"
let replace = ""
formatted = source.replacingOccurrences(of: pattern, with: replace, options: NSString.CompareOptions.regularExpression, range: nil)
return formatted
}
// MARK: - remove multiline comments
func removeMultilinesComment(_ source: String) -> String {
var formatted = ""
let pattern = "/\\*.*?\\*/"
let replace = ""
formatted = source.replacingOccurrences(of: pattern, with: replace, options: NSString.CompareOptions.regularExpression, range: nil)
return formatted
}
// MARK: - get literal
func getLiteral(_ source: String, lineNumber: UInt) -> String {
var tmpLine = ""
var literal = ""
var lineIndex: UInt = 1
var startBracket = 0
var endBracket = 0
source.enumerateLines {
line, stop in
if lineIndex >= lineNumber {
tmpLine = line.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
for char in tmpLine.characters {
if char == "(" {
startBracket += 1
}
if char == ")" {
endBracket += 1
}
}
if startBracket == endBracket {
stop = true
}
literal += tmpLine
}
lineIndex += 1
}
return literal
}
// MARK: - formatt literal
func formattLiteral(_ literal: String) -> String {
var formatted = ""
let pattern = "(,\\s*)"
let replace = ", "
formatted = literal.replacingOccurrences(of: pattern, with: replace, options: NSString.CompareOptions.regularExpression, range: nil)
return formatted
}
// MARK: - get line indexes
func getIndexes(_ literal: String) -> Array<Int> {
var location = 0
var length = 0
let pattern = ",(\\s*)[==|!=|>|<|>=|<=|===|!==|~=]+(\\s*),(\\s*)"
var indexes: Array<Int> = [0, 0, 0]
do {
let regexp: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options())
regexp.enumerateMatches(in: literal, options: [], range: NSMakeRange(0, literal.characters.count),
using: {(result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result {
location = result.range.location
length = result.range.length
}
})
indexes[0] = "=> ".characters.count + "PAssert(".characters.count
indexes[1] = "=> ".characters.count + location + 1
indexes[2] = indexes[1] + length - 1 - 2
} catch let error as NSError {
print(error)
}
return indexes
}
// MARK: - get file name
func getFilename(_ filePath: String) -> String {
var fileName = ""
if let match = filePath.range(of: "[^/]*$", options: .regularExpression) {
fileName = String(filePath[match])
}
return fileName
}
// MARK: - repeat character
func repeatCharacter(_ char: String, length: Int) -> String {
var chars = ""
if length > 0 {
for _ in 0..<length {
chars += char
}
}
return chars
}
// MARK: - print result
func output<T>(_ source: String?, comparison: Bool, lhs: T, rhs: T, fileName: String, lineNumber: UInt, function: String) -> String {
let title = "=== Assertion Failed ============================================="
let file = "FILE: \(fileName)"
var out = "\n\n\(title)\n"
out += "DATE: \(getDateTime())\n"
out += "\(file)\n"
out += "LINE: \(lineNumber)\n"
out += "FUNC: \(function)\n"
if let src = source {
var literal = getLiteral(src, lineNumber: lineNumber) // return: PAssert(lhs, comparison, rhs)
let indexes = getIndexes(literal)
literal = "=> " + formattLiteral(literal)
out += "\n"
out += "\(literal)\n"
var lValue = "\(lhs)"
lValue = (lValue == "") ? "\"\"" : lValue
lValue = "\(lValue)"
var rValue = "\(rhs)"
rValue = (rValue == "") ? "\"\"" : rValue
rValue = "\(rValue)"
let space1 = repeatCharacter(" ", length: indexes[0])
let space2 = repeatCharacter(" ", length: indexes[1] - indexes[0])
let space3 = repeatCharacter(" ", length: indexes[2] - indexes[1])
out += "\(space1)|\(space2)|\(space3)|\n"
out += "\(space1)|\(space2)|\(space3)\(rValue)\n"
out += "\(space1)|\(space2)|\n"
out += "\(space1)|\(space2)\(comparison)\n"
out += "\(space1)|\n"
out += "\(space1)\(lValue)\n"
} else {
out += "\n"
out += "=> PAssert(... ///// Could not output /////\n"
out += "\n"
}
return out
}
}
|
mit
|
5aacd5b6cafebb043f47a17032dc5f53
| 31.459574 | 146 | 0.49043 | 4.806553 | false | false | false | false |
chenchangqing/learniosframe
|
CJMvvm/CJMvvm/Models/Enums/CJCollectionViewHeaderModelTypeEnum.swift
|
1
|
1139
|
//
// CJCollectionViewHeaderModelTypeEnum.swift
// CJMvvm
//
// Created by green on 15/8/25.
// Copyright (c) 2015年 com.chenchangqing. All rights reserved.
//
import Foundation
enum CJCollectionViewHeaderModelTypeEnum : String {
case MultipleChoice = "多选"
case SingleChoice = "单选"
case SingleClick = "单击"
static let allValues = [MultipleChoice,SingleChoice,SingleClick]
// 位置
var index : Int {
get {
for var i = 0; i < CJCollectionViewHeaderModelTypeEnum.allValues.count; i++ {
if self == CJCollectionViewHeaderModelTypeEnum.allValues[i] {
return i
}
}
return -1
}
}
// 查询指定位置的元素
static func instance(index:Int) -> CJCollectionViewHeaderModelTypeEnum? {
if index >= 0 && index < CJCollectionViewHeaderModelTypeEnum.allValues.count {
return CJCollectionViewHeaderModelTypeEnum.allValues[index]
}
return nil
}
}
|
apache-2.0
|
9bcd57c4d2c8f9a0cf8f72c7d6562db5
| 23.533333 | 89 | 0.563917 | 4.634454 | false | false | false | false |
practicalswift/swift
|
test/Constraints/generics.swift
|
1
|
27875
|
// RUN: %target-typecheck-verify-swift -enable-objc-interop
infix operator +++
protocol ConcatToAnything {
static func +++ <T>(lhs: Self, other: T)
}
func min<T : Comparable>(_ x: T, y: T) -> T {
if y < x { return y }
return x
}
func weirdConcat<T : ConcatToAnything, U>(_ t: T, u: U) {
t +++ u
t +++ 1
u +++ t // expected-error{{argument type 'U' does not conform to expected type 'ConcatToAnything'}}
}
// Make sure that the protocol operators don't get in the way.
var b1, b2 : Bool
_ = b1 != b2
extension UnicodeScalar {
func isAlpha2() -> Bool {
return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z")
}
}
protocol P {
static func foo(_ arg: Self) -> Self
}
struct S : P {
static func foo(_ arg: S) -> S {
return arg
}
}
func foo<T : P>(_ arg: T) -> T {
return T.foo(arg)
}
// Associated types and metatypes
protocol SomeProtocol {
associatedtype SomeAssociated
}
func generic_metatypes<T : SomeProtocol>(_ x: T)
-> (T.Type, T.SomeAssociated.Type)
{
return (type(of: x), type(of: x).SomeAssociated.self)
}
// Inferring a variable's type from a call to a generic.
struct Pair<T, U> { } // expected-note 3 {{'T' declared as parameter to type 'Pair'}} expected-note 2 {{'U' declared as parameter to type 'Pair'}}
func pair<T, U>(_ x: T, _ y: U) -> Pair<T, U> { }
var i : Int, f : Float
var p = pair(i, f)
// Conformance constraints on static variables.
func f1<S1 : Sequence>(_ s1: S1) {}
var x : Array<Int> = [1]
f1(x)
// Inheritance involving generics and non-generics.
class X {
func f() {}
}
class Foo<T> : X {
func g() { }
}
class Y<U> : Foo<Int> {
}
func genericAndNongenericBases(_ x: Foo<Int>, y: Y<()>) {
x.f()
y.f()
y.g()
}
func genericAndNongenericBasesTypeParameter<T : Y<()>>(_ t: T) {
t.f()
t.g()
}
protocol P1 {}
protocol P2 {}
func foo<T : P1>(_ t: T) -> P2 {
return t // expected-error{{return expression of type 'T' does not conform to 'P2'}}
}
func foo2(_ p1: P1) -> P2 {
return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}}
}
// <rdar://problem/14005696>
protocol BinaryMethodWorkaround {
associatedtype MySelf
}
protocol Squigglable : BinaryMethodWorkaround {
}
infix operator ~~~
func ~~~ <T : Squigglable>(lhs: T, rhs: T) -> Bool where T.MySelf == T {
return true
}
extension UInt8 : Squigglable {
typealias MySelf = UInt8
}
var rdar14005696 : UInt8
_ = rdar14005696 ~~~ 5
// <rdar://problem/15168483>
public struct SomeIterator<C: Collection, Indices: Sequence>
: IteratorProtocol, Sequence
where C.Index == Indices.Iterator.Element {
var seq : C
var indices : Indices.Iterator
public typealias Element = C.Iterator.Element
public mutating func next() -> Element? {
fatalError()
}
public init(elements: C, indices: Indices) {
fatalError()
}
}
func f1<T>(seq: Array<T>) {
let x = (seq.indices).lazy.reversed()
SomeIterator(elements: seq, indices: x) // expected-warning{{unused}}
SomeIterator(elements: seq, indices: seq.indices.reversed()) // expected-warning{{unused}}
}
// <rdar://problem/16078944>
func count16078944<T>(_ x: Range<T>) -> Int { return 0 }
func test16078944 <T: Comparable>(lhs: T, args: T) -> Int {
return count16078944(lhs..<args) // don't crash
}
// <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy()
class r22409190ManagedBuffer<Value, Element> {
final var value: Value { get {} set {}}
func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) -> R) -> R {
}
}
class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> {
deinit {
self.withUnsafeMutablePointerToElements { elems -> Void in
elems.deinitialize(count: self.value) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
}
}
}
// <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))'
func r22459135() {
func h<S : Sequence>(_ sequence: S) -> S.Iterator.Element
where S.Iterator.Element : FixedWidthInteger {
return 0
}
func g(_ x: Any) {}
func f(_ x: Int) {
g(h([3]))
}
func f2<TargetType: AnyObject>(_ target: TargetType, handler: @escaping (TargetType) -> ()) {
let _: (AnyObject) -> () = { internalTarget in
handler(internalTarget as! TargetType)
}
}
}
// <rdar://problem/19710848> QoI: Friendlier error message for "[] as Set"
// <rdar://problem/22326930> QoI: "argument for generic parameter 'Element' could not be inferred" lacks context
_ = [] as Set // expected-error {{protocol type 'Any' cannot conform to 'Hashable' because only concrete types can conform to protocols}}
//<rdar://problem/22509125> QoI: Error when unable to infer generic archetype lacks greatness
func r22509125<T>(_ a : T?) { // expected-note {{in call to function 'r22509125'}}
r22509125(nil) // expected-error {{generic parameter 'T' could not be inferred}}
}
// <rdar://problem/24267414> QoI: error: cannot convert value of type 'Int' to specified type 'Int'
struct R24267414<T> { // expected-note {{'T' declared as parameter to type 'R24267414'}}
static func foo() -> Int {}
}
var _ : Int = R24267414.foo() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{24-24=<Any>}}
// https://bugs.swift.org/browse/SR-599
func SR599<T: FixedWidthInteger>() -> T.Type { return T.self } // expected-note {{in call to function 'SR599()'}}
_ = SR599() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/19215114> QoI: Poor diagnostic when we are unable to infer type
protocol Q19215114 {}
protocol P19215114 {}
// expected-note @+1 {{in call to function 'body9215114'}}
func body9215114<T: P19215114, U: Q19215114>(_ t: T) -> (_ u: U) -> () {}
func test9215114<T: P19215114, U: Q19215114>(_ t: T) -> (U) -> () {
//Should complain about not being able to infer type of U.
let f = body9215114(t) // expected-error {{generic parameter 'T' could not be inferred}}
return f
}
// <rdar://problem/21718970> QoI: [uninferred generic param] cannot invoke 'foo' with an argument list of type '(Int)'
class Whatever<A: Numeric, B: Numeric> { // expected-note 2 {{'A' declared as parameter to type 'Whatever'}}
static func foo(a: B) {}
static func bar() {}
}
Whatever.foo(a: 23) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}}
// <rdar://problem/21718955> Swift useless error: cannot invoke 'foo' with no arguments
Whatever.bar() // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}}
// <rdar://problem/27515965> Type checker doesn't enforce same-type constraint if associated type is Any
protocol P27515965 {
associatedtype R
func f() -> R
}
struct S27515965 : P27515965 {
func f() -> Any { return self }
}
struct V27515965 {
init<T : P27515965>(_ tp: T) where T.R == Float {}
// expected-note@-1 {{where 'T.R' = 'Any'}}
}
func test(x: S27515965) -> V27515965 {
return V27515965(x)
// expected-error@-1 {{initializer 'init(_:)' requires the types 'Any' and 'Float' be equivalent}}
}
protocol BaseProto {}
protocol SubProto: BaseProto {}
@objc protocol NSCopyish {
func copy() -> Any
}
struct FullyGeneric<Foo> {} // expected-note 11 {{'Foo' declared as parameter to type 'FullyGeneric'}} expected-note 1 {{generic type 'FullyGeneric' declared here}}
struct AnyClassBound<Foo: AnyObject> {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound'}} expected-note {{generic type 'AnyClassBound' declared here}}
// expected-note@-1{{requirement specified as 'Foo' : 'AnyObject'}}
struct AnyClassBound2<Foo> where Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound2'}}
// expected-note@-1{{requirement specified as 'Foo' : 'AnyObject' [with Foo = Any]}}
struct ProtoBound<Foo: SubProto> {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound'}} expected-note {{generic type 'ProtoBound' declared here}}
struct ProtoBound2<Foo> where Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound2'}}
struct ObjCProtoBound<Foo: NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound'}} expected-note {{generic type 'ObjCProtoBound' declared here}}
struct ObjCProtoBound2<Foo> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound2'}}
struct ClassBound<Foo: X> {} // expected-note {{generic type 'ClassBound' declared here}}
struct ClassBound2<Foo> where Foo: X {} // expected-note {{generic type 'ClassBound2' declared here}}
struct ProtosBound<Foo> where Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound'}} expected-note {{generic type 'ProtosBound' declared here}}
struct ProtosBound2<Foo: SubProto & NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound2'}}
struct ProtosBound3<Foo: SubProto> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound3'}}
struct AnyClassAndProtoBound<Foo> where Foo: AnyObject, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound'}}
struct AnyClassAndProtoBound2<Foo> where Foo: SubProto, Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound2'}}
struct ClassAndProtoBound<Foo> where Foo: X, Foo: SubProto {} // expected-note {{where 'Foo' = 'X'}}
struct ClassAndProtosBound<Foo> where Foo: X, Foo: SubProto, Foo: NSCopyish {} // expected-note 2 {{where 'Foo' = 'X'}}
struct ClassAndProtosBound2<Foo> where Foo: X, Foo: SubProto & NSCopyish {} // expected-note 2 {{where 'Foo' = 'X'}}
extension Pair {
init(first: T) {}
init(second: U) {}
var first: T { fatalError() }
var second: U { fatalError() }
}
func testFixIts() {
_ = FullyGeneric() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<Any>}}
_ = FullyGeneric<Any>()
_ = AnyClassBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<AnyObject>}}
_ = AnyClassBound<Any>() // expected-error {{'AnyClassBound' requires that 'Any' be a class type}}
_ = AnyClassBound<AnyObject>()
_ = AnyClassBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<AnyObject>}}
_ = AnyClassBound2<Any>() // expected-error {{'AnyClassBound2' requires that 'Any' be a class type}}
_ = AnyClassBound2<AnyObject>()
_ = ProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#Foo: SubProto#>>}}
_ = ProtoBound<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: SubProto#>>}}
_ = ProtoBound2<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ObjCProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<NSCopyish>}}
_ = ObjCProtoBound<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound<NSCopyish>()
_ = ObjCProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{22-22=<NSCopyish>}}
_ = ObjCProtoBound2<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound2<NSCopyish>()
_ = ProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound3() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = AnyClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{28-28=<<#Foo: SubProto & AnyObject#>>}}
_ = AnyClassAndProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{29-29=<<#Foo: SubProto & AnyObject#>>}}
_ = ClassAndProtoBound() // expected-error {{referencing initializer 'init()' on 'ClassAndProtoBound' requires that 'X' conform to 'SubProto'}}
_ = ClassAndProtosBound()
// expected-error@-1 {{referencing initializer 'init()' on 'ClassAndProtosBound' requires that 'X' conform to 'NSCopyish'}}
// expected-error@-2 {{referencing initializer 'init()' on 'ClassAndProtosBound' requires that 'X' conform to 'SubProto'}}
_ = ClassAndProtosBound2()
// expected-error@-1 {{referencing initializer 'init()' on 'ClassAndProtosBound2' requires that 'X' conform to 'NSCopyish'}}
// expected-error@-2 {{referencing initializer 'init()' on 'ClassAndProtosBound2' requires that 'X' conform to 'SubProto'}}
_ = Pair() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, Any>}}
_ = Pair(first: S()) // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<S, Any>}}
_ = Pair(second: S()) // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, S>}}
}
func testFixItClassBound() {
// We infer a single class bound for simple cases in expressions...
let x = ClassBound()
let x1: String = x // expected-error {{cannot convert value of type 'ClassBound<X>' to specified type 'String'}}
let y = ClassBound2()
let y1: String = y // expected-error {{cannot convert value of type 'ClassBound2<X>' to specified type 'String'}}
// ...but not in types.
let z1: ClassBound // expected-error {{reference to generic type 'ClassBound' requires arguments in <...>}} {{21-21=<X>}}
let z2: ClassBound2 // expected-error {{reference to generic type 'ClassBound2' requires arguments in <...>}} {{22-22=<X>}}
}
func testFixItCasting(x: Any) {
_ = x as! FullyGeneric // expected-error {{generic parameter 'Foo' could not be inferred in cast to 'FullyGeneric<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}}
}
func testFixItContextualKnowledge() {
// FIXME: These could propagate backwards.
let _: Int = Pair().first // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}}
let _: Int = Pair().second // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}}
}
func testFixItTypePosition() {
let _: FullyGeneric // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{22-22=<Any>}}
let _: ProtoBound // expected-error {{reference to generic type 'ProtoBound' requires arguments in <...>}} {{20-20=<<#Foo: SubProto#>>}}
let _: ObjCProtoBound // expected-error {{reference to generic type 'ObjCProtoBound' requires arguments in <...>}} {{24-24=<NSCopyish>}}
let _: AnyClassBound // expected-error {{reference to generic type 'AnyClassBound' requires arguments in <...>}} {{23-23=<AnyObject>}}
let _: ProtosBound // expected-error {{reference to generic type 'ProtosBound' requires arguments in <...>}} {{21-21=<<#Foo: NSCopyish & SubProto#>>}}
}
func testFixItNested() {
_ = Array<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}}
_ = [FullyGeneric]() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any>}}
_ = FullyGeneric<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}}
_ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}}
FullyGeneric,
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric // FIXME: We could diagnose both of these, but we don't.
>()
_ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}}
FullyGeneric<Any>,
FullyGeneric
>()
_ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}}
FullyGeneric,
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric<Any>
>()
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}}
FullyGeneric()
)
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric<Any>(),
FullyGeneric() // expected-note {{explicitly specify the generic arguments to fix this issue}}
)
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}}
FullyGeneric<Any>()
)
}
// rdar://problem/26845038
func occursCheck26845038(a: [Int]) {
_ = Array(a)[0]
}
// rdar://problem/29633747
extension Array where Element: Hashable {
public func trimmed(_ elements: [Element]) -> SubSequence {
return []
}
}
func rdar29633747(characters: String) {
let _ = Array(characters).trimmed(["("])
}
// Null pointer dereference in noteArchetypeSource()
class GenericClass<A> {}
// expected-note@-1 {{'A' declared as parameter to type 'GenericClass'}}
func genericFunc<T>(t: T) {
_ = [T: GenericClass] // expected-error {{generic parameter 'A' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
// expected-error@-2 3 {{type 'T' does not conform to protocol 'Hashable'}}
}
struct SR_3525<T> {}
func sr3525_arg_int(_: inout SR_3525<Int>) {}
func sr3525_arg_gen<T>(_: inout SR_3525<T>) {}
func sr3525_1(t: SR_3525<Int>) {
let _ = sr3525_arg_int(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
func sr3525_2(t: SR_3525<Int>) {
let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
func sr3525_3<T>(t: SR_3525<T>) {
let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
class testStdlibType {
let _: Array // expected-error {{reference to generic type 'Array' requires arguments in <...>}} {{15-15=<Any>}}
}
// rdar://problem/32697033
protocol P3 {
associatedtype InnerAssoc
}
protocol P4 {
associatedtype OuterAssoc: P3
}
struct S3 : P3 {
typealias InnerAssoc = S4
}
struct S4: P4 {
typealias OuterAssoc = S3
}
public struct S5 {
func f<Model: P4, MO> (models: [Model])
where Model.OuterAssoc == MO, MO.InnerAssoc == Model {
}
func g<MO, Model: P4> (models: [Model])
where Model.OuterAssoc == MO, MO.InnerAssoc == Model {
}
func f(arr: [S4]) {
f(models: arr)
g(models: arr)
}
}
// rdar://problem/24329052 - QoI: call argument archetypes not lining up leads to ambiguity errors
struct S_24329052<T> { // expected-note {{generic parameter 'T' of generic struct 'S_24329052' declared here}}
var foo: (T) -> Void
// expected-note@+1 {{generic parameter 'T' of instance method 'bar(_:)' declared here}}
func bar<T>(_ v: T) { foo(v) }
// expected-error@-1 {{cannot convert value of type 'T' (generic parameter of instance method 'bar(_:)') to expected argument type 'T' (generic parameter of generic struct 'S_24329052')}}
}
extension Sequence {
var rdar24329052: (Element) -> Void { fatalError() }
// expected-note@+1 {{generic parameter 'Element' of instance method 'foo24329052(_:)' declared here}}
func foo24329052<Element>(_ v: Element) { rdar24329052(v) }
// expected-error@-1 {{cannot convert value of type 'Element' (generic parameter of instance method 'foo24329052(_:)') to expected argument type 'Self.Element' (associated type of protocol 'Sequence')}}
}
func rdar27700622<E: Comparable>(_ input: [E]) -> [E] {
let pivot = input.first!
let lhs = input.dropFirst().filter { $0 <= pivot }
let rhs = input.dropFirst().filter { $0 > pivot }
return rdar27700622(lhs) + [pivot] + rdar27700622(rhs) // Ok
}
// rdar://problem/22898292 - Type inference failure with constrained subclass
protocol P_22898292 {}
do {
func construct_generic<T: P_22898292>(_ construct: () -> T) -> T { return construct() }
class A {}
class B : A, P_22898292 {}
func foo() -> B { return B() }
func bar(_ value: A) {}
func baz<T: A>(_ value: T) {}
func rdar_22898292_1() {
let x = construct_generic { foo() } // returns A
bar(x) // Ok
bar(construct_generic { foo() }) // Ok
}
func rdar22898292_2<T: B>(_ d: T) {
_ = { baz($0) }(construct_generic { d }) // Ok
}
}
// rdar://problem/35541153 - Generic parameter inference bug
func rdar35541153() {
func foo<U: Equatable, V: Equatable, C: Collection>(_ c: C) where C.Element == (U, V) {}
func bar<K: Equatable, V, C: Collection>(_ c: C, _ k: K, _ v: V) where C.Element == (K, V) {}
let x: [(a: Int, b: Int)] = []
let y: [(k: String, v: Int)] = []
foo(x) // Ok
bar(y, "ultimate question", 42) // Ok
}
// rdar://problem/38159133 - [SR-7125]: Swift 4.1 Xcode 9.3b4 regression
protocol P_38159133 {}
do {
class Super {}
class A: Super, P_38159133 {}
class B: Super, P_38159133 {}
func rdar38159133(_ a: A?, _ b: B?) {
let _: [P_38159133] = [a, b].compactMap { $0 } // Ok
}
}
func rdar35890334(_ arr: inout [Int]) {
_ = arr.popFirst() // expected-error {{referencing instance method 'popFirst()' on 'Collection' requires the types '[Int]' and 'ArraySlice<Int>' be equivalent}}
}
// rdar://problem/39616039
func rdar39616039() {
func foo<V>(default: V, _ values: [String: V]) -> V {
return values["foo"] ?? `default`
}
var a = foo(default: 42, ["foo": 0])
a += 1 // ok
var b = foo(default: 42.0, ["foo": 0])
b += 1 // ok
var c = foo(default: 42.0, ["foo": Float(0)])
c += 1 // ok
}
// https://bugs.swift.org/browse/SR-8075
func sr8075() {
struct UIFont {
init(ofSize: Float) {}
}
func switchOnCategory<T>(_ categoryToValue: [Int: T]) -> T {
fatalError()
}
let _: UIFont = .init(ofSize: switchOnCategory([0: 15.5, 1: 20.5]))
}
// rdar://problem/40537858 - Ambiguous diagnostic when type is missing conformance
func rdar40537858() {
struct S {
struct Id {}
var id: Id
}
struct List<T: Collection, E: Hashable> { // expected-note {{where 'E' = 'S.Id'}}
typealias Data = T.Element
init(_: T, id: KeyPath<Data, E>) {}
}
var arr: [S] = []
_ = List(arr, id: \.id) // expected-error {{referencing initializer 'init(_:id:)' on 'List' requires that 'S.Id' conform to 'Hashable'}}
enum E<T: P> { // expected-note 2 {{where 'T' = 'S'}}
case foo(T)
case bar([T])
}
var s = S(id: S.Id())
let _: E = .foo(s) // expected-error {{enum case 'foo' requires that 'S' conform to 'P'}}
let _: E = .bar([s]) // expected-error {{enum case 'bar' requires that 'S' conform to 'P'}}
}
// https://bugs.swift.org/browse/SR-8934
struct BottleLayout {
let count : Int
}
let arr = [BottleLayout]()
let layout = BottleLayout(count:1)
let ix = arr.firstIndex(of:layout) // expected-error {{argument type 'BottleLayout' does not conform to expected type 'Equatable'}}
let _: () -> UInt8 = { .init("a" as Unicode.Scalar) } // expected-error {{missing argument label 'ascii:' in call}}
// https://bugs.swift.org/browse/SR-9068
func compare<C: Collection, Key: Hashable, Value: Equatable>(c: C)
-> Bool where C.Element == (key: Key, value: Value)
{
_ = Dictionary(uniqueKeysWithValues: Array(c))
}
// https://bugs.swift.org/browse/SR-7984
struct SR_7984<Bar> {
func doSomething() {}
}
extension SR_7984 where Bar: String {} // expected-error {{type 'Bar' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'Bar == String' to require 'Bar' to be 'String'}} {{28-29= ==}}
protocol SR_7984_Proto {
associatedtype Bar
}
extension SR_7984_Proto where Bar: String {} // expected-error {{type 'Self.Bar' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'Bar == String' to require 'Bar' to be 'String'}} {{34-35= ==}}
protocol SR_7984_HasFoo {
associatedtype Foo
}
protocol SR_7984_HasAssoc {
associatedtype Assoc: SR_7984_HasFoo
}
struct SR_7984_X<T: SR_7984_HasAssoc> {}
extension SR_7984_X where T.Assoc.Foo: String {} // expected-error {{type 'T.Assoc.Foo' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Assoc.Foo == String' to require 'T.Assoc.Foo' to be 'String'}} {{38-39= ==}}
struct SR_7984_S<T: Sequence> where T.Element: String {} // expected-error {{type 'T.Element' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Element == String' to require 'T.Element' to be 'String'}} {{46-47= ==}}
func SR_7984_F<T: Sequence>(foo: T) where T.Element: String {} // expected-error {{type 'T.Element' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Element == String' to require 'T.Element' to be 'String'}} {{52-53= ==}}
protocol SR_7984_P {
func S<T : Sequence>(bar: T) where T.Element: String // expected-error {{type 'T.Element' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Element == String' to require 'T.Element' to be 'String'}} {{47-48= ==}}
}
struct A<T: String> {} // expected-error {{type 'T' constrained to non-protocol, non-class type 'String'}}
struct B<T> where T: String {} // expected-error {{type 'T' constrained to non-protocol, non-class type 'String'}}
protocol C {
associatedtype Foo: String // expected-error {{inheritance from non-protocol, non-class type 'String'}} expected-error {{type 'Self.Foo' constrained to non-protocol, non-class type 'String'}}
}
protocol D {
associatedtype Foo where Foo: String // expected-error {{type 'Self.Foo' constrained to non-protocol, non-class type 'String'}}
}
func member_ref_with_explicit_init() {
struct S<T: P> { // expected-note {{where 'T' = 'Int'}}
init(_: T) {}
init(_: T, _ other: Int = 42) {}
}
_ = S.init(42)
// expected-error@-1 {{generic struct 'S' requires that 'Int' conform to 'P'}}
}
|
apache-2.0
|
c10fb94b5b5448019a517138b267efbb
| 39.457184 | 250 | 0.671785 | 3.635237 | false | false | false | false |
wujianguo/GitHubKit
|
GitHubApp/Classes/Pagination/PaginationTableViewDataSource.swift
|
1
|
4242
|
//
// PaginationTableViewDataSource.swift
// GitHubKit
//
// Created by wujianguo on 16/8/25.
//
//
import UIKit
import GitHubKit
import ObjectMapper
import Alamofire
protocol PaginationTableViewDataSourceRefreshable: class {
var refreshing: Bool { get }
func endRefreshing()
}
extension UIRefreshControl: PaginationTableViewDataSourceRefreshable {
}
class PaginationTableViewDataSource<T: Mappable>: NSObject, UITableViewDataSource {
init(cellIdentifier: String, refreshable: PaginationTableViewDataSourceRefreshable, firstRequest: AuthorizationRequest) {
super.init()
self.cellIdentifier = cellIdentifier
self.refreshable = refreshable
self.firstRequest = firstRequest
}
var firstRequest: AuthorizationRequest! = nil
var loginRequired: Bool {
return false
}
var cellIdentifier: String = ""
weak var refreshable: PaginationTableViewDataSourceRefreshable?
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
if let c = cell as? PaginationTableViewCell<T> {
c.item = items[indexPath.row]
}
if indexPath.row == items.count - 1 {
paginationNext(tableView)
}
return cell
}
var items = [T]()
var firstPage: String?
var lastPage: String?
var nextPage: String?
var firstPageEtag: String?
var firstPageLastModified: NSDate?
var currentRequest: AuthorizationRequest?
func paginationNext(tableView: UITableView) {
guard !refreshable!.refreshing else { return }
guard nextPage != nil else { return }
if let current = currentRequest?.url {
if current == lastPage || current == nextPage {
return
}
}
currentRequest?.cancel()
currentRequest = AuthorizationRequest(url: nextPage!, loginRequired: loginRequired)
currentRequest!.responseArray { (response: Response<GitHubArray<T>, NSError>) in
if let ret = response.result.value {
if self.items.count == 0 {
self.firstPageEtag = ret.eTag
self.firstPageLastModified = ret.lastModified
}
var indexPaths = [NSIndexPath]()
for i in 0..<ret.array.count {
indexPaths.append(NSIndexPath(forRow: i + self.items.count, inSection: 0))
}
self.items.appendContentsOf(ret.array)
if let link = ret.firstPageLink {
self.firstPage = link
}
if let link = ret.lastPageLink {
self.lastPage = link
}
if let link = ret.nextPageLink {
self.nextPage = link
}
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
}
}
}
func refresh(tableView: UITableView) {
guard refreshable!.refreshing else { return }
currentRequest?.cancel()
currentRequest = AuthorizationRequest(url: firstRequest.url, eTag: firstPageEtag, lastModified: firstPageLastModified, loginRequired: loginRequired)
currentRequest!.responseArray { (response: Response<GitHubArray<T>, NSError>) in
self.refreshable?.endRefreshing()
if let ret = response.result.value {
self.firstPageEtag = ret.eTag
self.firstPageLastModified = ret.lastModified
self.items = ret.array
if let link = ret.firstPageLink {
self.firstPage = link
}
if let link = ret.lastPageLink {
self.lastPage = link
}
self.nextPage = ret.nextPageLink
tableView.reloadData()
}
}
}
}
|
mit
|
5b4cd237d879b6cb1ba7d21aacb6813e
| 31.381679 | 156 | 0.608204 | 5.403822 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureAccountPicker/UI/Model/AccountPickerRowAccountGroup.swift
|
1
|
1124
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import ComposableArchitectureExtensions
import SwiftUI
extension AccountPickerRow {
public struct AccountGroup: Equatable, Identifiable {
// MARK: - Public Properties
public let id: AnyHashable
// MARK: - Internal Properties
var title: String
var description: String
// MARK: - Init
public init(
id: AnyHashable,
title: String,
description: String
) {
self.id = id
self.title = title
self.description = description
}
}
}
extension AccountPickerRow.AccountGroup {
public struct Balances {
// MARK: - Public Properties
public var fiatBalance: LoadingState<String>
public var currencyCode: LoadingState<String>
// MARK: - Init
public init(
fiatBalance: LoadingState<String>,
currencyCode: LoadingState<String>
) {
self.fiatBalance = fiatBalance
self.currencyCode = currencyCode
}
}
}
|
lgpl-3.0
|
d2152f9af92bc6fc66ba37c31504447c
| 20.596154 | 62 | 0.586821 | 5.478049 | false | false | false | false |
toshiapp/toshi-ios-client
|
Toshi/Controllers/Sign In/SplashNavigationController.swift
|
1
|
1508
|
// 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
class SplashNavigationController: UINavigationController {
convenience init() {
self.init(rootViewController: SplashViewController())
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.barStyle = .default
navigationBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
navigationBar.shadowImage = UIImage()
let titleTextAttributes: [NSAttributedStringKey: Any] = [
.font: Theme.regular(size: 17),
.foregroundColor: Theme.darkTextColor
]
navigationBar.titleTextAttributes = titleTextAttributes
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return viewControllers.count == 1 ? .lightContent : .default
}
}
|
gpl-3.0
|
75d216d5eaff6e0a30c719b2a83f80b0
| 34.904762 | 84 | 0.694297 | 5.094595 | false | false | false | false |
wess/overlook
|
Sources/overlook/commands/router.swift
|
1
|
1026
|
//
// default.swift
// overlook
//
// Created by Wesley Cope on 9/30/16.
//
//
import SwiftCLI
import Rainbow
import config
public class OverlookRouter: Router {
public var current:Command
public var exitImmediately = false
public init(_ defaultCommand:Command) {
self.current = defaultCommand
}
public func route(commands: [Command], aliases: [String : String], arguments: RawArguments) -> Command? {
guard let name = arguments.unclassifiedArguments.first else {
return current
}
let cmd = aliases[name.value] ?? name.value
if let command = commands.first(where: { $0.name == cmd }) {
name.classification = .commandName
current = command
}
var next = name.next
while next != nil {
if next?.value == "-h" || next?.value == "--help" {
exitImmediately = true
break
}
next = next?.next
}
if cmd.hasPrefix("-") {
return nil
}
return current
}
}
|
mit
|
c2e1d93cdab9998ec67c138b6dec92ee
| 18.358491 | 107 | 0.58577 | 4.153846 | false | false | false | false |
HarukaMa/iina
|
iina/Regex.swift
|
1
|
1497
|
//
// Regex.swift
// iina
//
// Created by lhc on 12/1/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
class Regex {
static let aspect = Regex("\\A\\d+(\\.\\d+)?:\\d+(\\.\\d+)?\\Z")
static let httpFileName = Regex("attachment; filename=(.+?)\\Z")
static let tagVersion = Regex("\\Av(\\d+\\.\\d+\\.\\d+)\\Z")
static let urlDetect = Regex("^(https?|ftp)://[^\\s/$.?#].[^\\s]*$")
static let iso639_2Desc = Regex("^.+?\\(([a-z]{3})\\)$")
static let geometry = Regex("^((\\d+%?)?(x(\\d+%?))?)?((\\+|\\-)(\\d+%?)(\\+|\\-)(\\d+%?))?$")
var regex: NSRegularExpression?
init (_ pattern: String) {
if let exp = try? NSRegularExpression(pattern: pattern, options: []) {
self.regex = exp
} else {
Utility.fatal("Cannot create regex \(pattern)")
}
}
func matches(_ str: String) -> Bool {
if let matches = regex?.numberOfMatches(in: str, options: [], range: NSMakeRange(0, str.characters.count)) {
return matches > 0
} else {
return false
}
}
func captures(in str: String) -> [String] {
var result: [String] = []
if let match = regex?.firstMatch(in: str, options: [], range: NSMakeRange(0, str.characters.count)) {
for i in 0..<match.numberOfRanges {
let range = match.rangeAt(i)
if range.length > 0 {
result.append((str as NSString).substring(with: match.rangeAt(i)))
} else {
result.append("")
}
}
}
return result
}
}
|
gpl-3.0
|
8bb7b0d10f4eda545854ca60f4c8b8b4
| 27.769231 | 112 | 0.546791 | 3.462963 | false | false | false | false |
jifusheng/MyDouYuTV
|
DouYuTV/DouYuTV/Classes/Home/View/RecommendCycleView.swift
|
1
|
4531
|
//
// RecommendCycleView.swift
// DouYuTV
//
// Created by 王建伟 on 2016/11/19.
// Copyright © 2016年 jifusheng. All rights reserved.
// 图片轮播视图
import UIKit
private let kCycleIdentifier = "CycleCollectionCell"
class RecommendCycleView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
fileprivate var cycleTimer : Timer?
var cycleModels : [CycleModel]? {
didSet {
//1、刷新表格
collectionView.reloadData()
//2、设置pageControl的个数
pageControl.numberOfPages = cycleModels?.count ?? 0
//3、显示pageControl
pageControl.isHidden = false
//4、默认让collectionView滚动到中间某一个item
let indexPath = IndexPath(item: pageControl.numberOfPages * 100, section: 0)
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .left)
//5、添加定时器(先移除后添加)
removeCycleTimer()
addCycleTimer()
}
}
override func awakeFromNib() {
super.awakeFromNib()
//设置该控件不随父控件的拉伸而拉伸
autoresizingMask = .init(rawValue: 0)
//隐藏pageControl
pageControl.isHidden = true
//设置collectionView的数据源和代理
collectionView.dataSource = self
collectionView.delegate = self
//注册cell
collectionView.register(UINib(nibName: "CycleCollectionCell", bundle: nil), forCellWithReuseIdentifier: kCycleIdentifier)
}
}
// MARK: - 提供一个快速创建的方法
extension RecommendCycleView {
class func recommendCycleView() -> RecommendCycleView {
return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)!.first as! RecommendCycleView
}
}
// MARK: - 实现collectionView的数据源方法
extension RecommendCycleView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0) * 1000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleIdentifier, for: indexPath) as! CycleCollectionCell
cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count]
return cell
}
}
// MARK: - 实现collectionView的代理方法
extension RecommendCycleView : UICollectionViewDelegateFlowLayout {
// MARK: - 设置item的size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.bounds.size
}
// MARK: - 监听collectionView的滚动
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
let currentPage : Int = Int((offsetX + scrollView.frame.width * 0.5) / scrollView.frame.width)
pageControl.currentPage = currentPage % (cycleModels?.count ?? 1)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycleTimer()
}
}
// MARK: - 对定时器的操作方法
extension RecommendCycleView {
// MARK: - 添加定时器
func addCycleTimer() {
cycleTimer = Timer(timeInterval: 3, target: self, selector: #selector(scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: .commonModes)
}
// MARK: - 移除定时器
func removeCycleTimer() {
//从运行循环中移除
cycleTimer?.invalidate()
cycleTimer = nil
}
// MARK: - 滚动到下一张
@objc private func scrollToNext() {
//获取当前的偏移量
var currentOffsetX = collectionView.contentOffset.x
let allCount = collectionView(collectionView, numberOfItemsInSection: 0)
let width = collectionView.bounds.width
if currentOffsetX == CGFloat(allCount - 1) * width {
currentOffsetX = -width
}
//计算要偏移的位置
let offsetX = currentOffsetX + width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
|
mit
|
d45c3947a7f5667b69e26032bc30f929
| 34.982906 | 160 | 0.674822 | 5.072289 | false | false | false | false |
oceannw/OCWebAction
|
OCWebAction/OCWebAction/OCWebConnectionProtocol.swift
|
1
|
5732
|
//
// OCWebConnectionProtocol.swift
//
// Created by oceannw on 15/10/28.
// Copyright © 2015年 oceannw. All rights reserved.
//
import Foundation
protocol OCWebConnectionProtocol{
func connect(configure:OCWebActionConfigureProtocol , handler:OCWebResultHandlerProtocol)throws -> OCTransferableProtocol
}
class OCSynchronousURLSession: OCWebConnectionProtocol {
private var semphore = dispatch_semaphore_create(0)
func connect(configure:OCWebActionConfigureProtocol , handler:OCWebResultHandlerProtocol)throws -> OCTransferableProtocol{
let request = try configureDownloadRequest(configure)
let session = NSURLSession.sharedSession()
var result:NSData?
var resultError:NSError?
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if OCWebActionManager.enableLog{
NSLog("OCWebAction操作接口:%@,返回response响应数据:%@", configure.url! , response ?? "暂无")
if data == nil{
NSLog("OCWebAction操作接口:%@,返回内容:%@", configure.url! ,"无返回内容")
}
if error != nil{
NSLog("OCWebAction操作接口:%@,返回异常:%@", configure.url! ,error!)
}
}
resultError = error
result = data
dispatch_semaphore_signal(self.semphore)
}
dataTask.resume()
dispatch_semaphore_wait(semphore, DISPATCH_TIME_FOREVER)
if resultError != nil{
throw resultError!
}
let resultDictionary = try handler.handler(result)
if OCWebActionManager.enableLog{
NSLog("OCWebAction操作接口:%@,返回内容:%@", configure.url! ,resultDictionary)
}
let transferedResult = configure.transfer(resultDictionary)
return transferedResult
}
/**
配置NSURLRequest
:param: configure 配置参数
:returns: 配置后的NSURLRequest
*/
private func configureDownloadRequest(configure:OCWebActionConfigureProtocol)throws ->NSURLRequest{
switch configure.httpMethod{
case .Post:
return try configureDownloadRequestForPost(configure)
case .Get:
return try configureDownloadRequestForGet(configure)
}
}
private func configureDownloadRequestForPost(configure:OCWebActionConfigureProtocol)throws ->NSURLRequest{
let url = try handlerURL(configure.url)
let request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy
, timeoutInterval: 60)
request.HTTPMethod = configure.httpMethod.rawValue
if configure.headerFields != nil{
for (key,value) in configure.headerFields!{
request.setValue(value, forHTTPHeaderField: key)
}
}
if configure.parameters != nil{
let mergeParameterString = mergeParatemers(configure.parameters!)
let mergeParameterData = mergeParameterString.dataUsingEncoding(configure.encodeInt)
guard mergeParameterData != nil else{
throw NSError(domain: kOCWebErrorDomain , code: OCWebError.ParameterEncodingFailure.rawValue, userInfo: nil)
}
request.HTTPBody = mergeParameterData!
if OCWebActionManager.enableLog{
NSLog("OCWebAction操作接口:%@,输出参数:%@", configure.url! , NSString(data: mergeParameterData ?? NSData(), encoding: configure.encodeInt) ?? "解码失败" )
}
}
return request
}
private func configureDownloadRequestForGet(var configure:OCWebActionConfigureProtocol)throws ->NSURLRequest{
if configure.parameters != nil{
let mergeParameterString = mergeParatemers(configure.parameters!)
if configure.url != nil{
configure.url! += "?" + mergeParameterString
}
if OCWebActionManager.enableLog{
NSLog("OCWebAction操作接口:%@,输出参数:%@", configure.url! , mergeParameterString)
}
}
let url = try handlerURL(configure.url)
let request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy
, timeoutInterval: 20)
request.HTTPMethod = configure.httpMethod.rawValue
if configure.headerFields != nil{
for (key,value) in configure.headerFields!{
request.setValue(value, forHTTPHeaderField: key)
}
}
return request
}
/**
拼接参数
:param: parameters 参数
:returns: 结果
*/
private func mergeParatemers(parameters:[String:String]) -> String{
var result = ""
var index = 0
for ( key , value ) in parameters{
if index == 0{
result += "\(key)=\(value)"
}else{
result += "&\(key)=\(value)"
}
index++
}
return result
}
/**
处理url字符串,并返回NSURL对象
:param: url url字符串
:returns: NSURL对象
*/
private func handlerURL(url:String?) throws -> NSURL{
guard url != nil else{
throw NSError(domain: kOCWebErrorDomain, code: OCWebError.URLIsNil.rawValue , userInfo: nil)
}
let result = NSURL(string: url!)
guard result != nil else{
throw NSError(domain: kOCWebErrorDomain, code: OCWebError.URLIsNil.rawValue, userInfo: nil)
}
return result!
}
}
|
mit
|
0c35270962049f392d99e613f4940010
| 36.442177 | 158 | 0.615846 | 4.848458 | false | true | false | false |
harlanhaskins/Swifter-1
|
Sources/SwifterHelp.swift
|
2
|
4742
|
//
// SwifterHelp.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/**
GET help/configuration
Returns the current configuration used by Twitter including twitter.com slugs which are not usernames, maximum photo resolutions, and t.co URL lengths.
It is recommended applications request this endpoint when they are loaded, but no more than once a day.
*/
public func getHelpConfiguration(success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "help/configuration.json"
self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) }, failure: failure)
}
/**
GET help/languages
Returns the list of languages supported by Twitter along with their ISO 639-1 code. The ISO 639-1 code is the two letter value to use if you include lang with any of your requests.
*/
public func getHelpLanguages(success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "help/languages.json"
self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) }, failure: failure)
}
/**
GET help/privacy
Returns Twitter's Privacy Policy.
*/
public func getHelpPrivacy(success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "help/privacy.json"
self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json["privacy"]) }, failure: failure)
}
/**
GET help/tos
Returns the Twitter Terms of Service in the requested format. These are not the same as the Developer Rules of the Road.
*/
public func getHelpTermsOfService(success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "help/tos.json"
self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json["tos"]) }, failure: failure)
}
/**
GET application/rate_limit_status
Returns the current rate limits for methods belonging to the specified resource families.
Each 1.1 API resource belongs to a "resource family" which is indicated in its method documentation. You can typically determine a method's resource family from the first component of the path after the resource version.
This method responds with a map of methods belonging to the families specified by the resources parameter, the current remaining uses for each of those resources within the current rate limiting window, and its expiration time in epoch time. It also includes a rate_limit_context field that indicates the current access token or application-only authentication context.
You may also issue requests to this method without any parameters to receive a map of all rate limited GET methods. If your application only uses a few of methods, please explicitly provide a resources parameter with the specified resource families you work with.
When using app-only auth, this method's response indicates the app-only auth rate limiting context.
Read more about REST API Rate Limiting in v1.1 and review the limits.
*/
public func getRateLimits(for resources: [String], success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "application/rate_limit_status.json"
var parameters = Dictionary<String, Any>()
parameters["resources"] = resources.joined(separator: ",")
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
}
|
mit
|
edb8229e4c6b7cd7ca9700e995032f8c
| 46.42 | 373 | 0.716575 | 4.503324 | false | false | false | false |
RoverPlatform/rover-ios
|
Sources/Experiences/UI/ScreenViewController.swift
|
1
|
24893
|
//
// ScreenViewController.swift
// Rover
//
// Created by Sean Rucker on 2017-08-17.
// Copyright © 2017 Rover Labs Inc. All rights reserved.
//
import SafariServices
import UIKit
// swiftlint:disable type_body_length
/// The `ScreenViewController` displays a Rover screen within an `ExperienceViewController` and is responsible for
/// handling button taps. It posts [`Notification`s](https://developer.apple.com/documentation/foundation/notification)
/// through the default [`NotificationCenter`](https://developer.apple.com/documentation/foundation/notificationcenter)
/// when it is presented, dismissed and viewed.
open class ScreenViewController: UICollectionViewController, UICollectionViewDataSourcePrefetching, PollCellDelegate {
public let experience: Experience
public let campaignID: String?
public let screen: Screen
public let viewControllerFactory: (Experience, Screen) -> UIViewController?
override open var preferredStatusBarStyle: UIStatusBarStyle {
switch screen.statusBar.style {
case .dark:
#if swift(>=5.1)
if #available(iOS 13.0, *) {
return .darkContent
} else {
return .default
}
#else
return .default
#endif
case .light:
return .lightContent
}
}
public init(
collectionViewLayout: UICollectionViewLayout,
experience: Experience,
campaignID: String?,
screen: Screen,
viewControllerFactory: @escaping (Experience, Screen) -> UIViewController?
) {
self.experience = experience
self.campaignID = campaignID
self.screen = screen
self.viewControllerFactory = viewControllerFactory
super.init(collectionViewLayout: collectionViewLayout)
collectionView?.prefetchDataSource = self
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundView = UIImageView()
configureTitle()
configureNavigationItem()
configureBackgroundColor()
configureBackgroundImage()
registerReusableViews()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureNavigationBar()
}
@objc
open func close() {
dismiss(animated: true, completion: nil)
}
// MARK: Notifications
private var sessionIdentifier: String {
var identifier = "experience-\(experience.id)-screen-\(screen.id)"
if let campaignID = self.campaignID {
identifier = "\(identifier)-campaign-\(campaignID)"
}
return identifier
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
var userInfo: [String: Any] = [
ScreenViewController.experienceUserInfoKey: experience,
ScreenViewController.screenUserInfoKey: screen
]
if let campaignID = campaignID {
userInfo[ScreenViewController.campaignIDUserInfoKey] = campaignID
}
NotificationCenter.default.post(
name: ScreenViewController.screenPresentedNotification,
object: self,
userInfo: userInfo
)
SessionController.shared.registerSession(identifier: sessionIdentifier) { [weak self] duration in
userInfo[ScreenViewController.durationUserInfoKey] = duration
NotificationCenter.default.post(
name: ScreenViewController.screenViewedNotification,
object: self,
userInfo: userInfo
)
}
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
var userInfo: [String: Any] = [
ScreenViewController.experienceUserInfoKey: experience,
ScreenViewController.screenUserInfoKey: screen
]
if let campaignID = campaignID {
userInfo[ScreenViewController.campaignIDUserInfoKey] = campaignID
}
NotificationCenter.default.post(
name: ScreenViewController.screenDismissedNotification,
object: self,
userInfo: userInfo
)
SessionController.shared.unregisterSession(identifier: sessionIdentifier)
}
// MARK: Configuration
private func configureNavigationBar() {
guard let navigationBar = navigationController?.navigationBar else {
return
}
// Background color
let backgroundColor: UIColor = {
if !screen.titleBar.useDefaultStyle {
return screen.titleBar.backgroundColor.uiColor
}
if let appearanceColor = UINavigationBar.appearance().barTintColor {
return appearanceColor
}
if let defaultColor = UINavigationBar().barTintColor {
return defaultColor
}
return UIColor(red: (247 / 255), green: (247 / 255), blue: (247 / 255), alpha: 1)
}()
navigationBar.barTintColor = backgroundColor
// Button color
navigationBar.tintColor = {
if !screen.titleBar.useDefaultStyle {
return screen.titleBar.buttonColor.uiColor
}
if let appearanceColor = UINavigationBar.appearance().tintColor {
return appearanceColor
}
if let defaultColor = UINavigationBar().tintColor {
return defaultColor
}
return UIColor(red: 0.0, green: 122 / 255, blue: 1.0, alpha: 1)
}()
// Title color
var textAttributes = navigationBar.titleTextAttributes ?? [NSAttributedString.Key: Any]()
textAttributes[NSAttributedString.Key.foregroundColor] = {
if !screen.titleBar.useDefaultStyle {
return screen.titleBar.textColor.uiColor
}
if let appearanceColor = UINavigationBar.appearance().titleTextAttributes?[NSAttributedString.Key.foregroundColor] as? UIColor {
return appearanceColor
}
if let defaultColor = UINavigationBar().titleTextAttributes?[NSAttributedString.Key.foregroundColor] as? UIColor {
return defaultColor
}
return UIColor.black
}()
navigationBar.titleTextAttributes = textAttributes
if #available(iOS 15, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.backgroundColor = backgroundColor
appearance.titleTextAttributes = textAttributes
navigationBar.standardAppearance = appearance
navigationBar.scrollEdgeAppearance = appearance
}
}
private func configureNavigationItem() {
switch screen.titleBar.buttons {
case .back:
navigationItem.rightBarButtonItem = nil
navigationItem.setHidesBackButton(false, animated: true)
case .both:
navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Close", comment: "Rover Close"), style: .plain, target: self, action: #selector(close))
navigationItem.setHidesBackButton(false, animated: true)
case .close:
navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Close", comment: "Rover Close"), style: .plain, target: self, action: #selector(close))
navigationItem.setHidesBackButton(true, animated: true)
}
}
private func configureTitle() {
title = screen.titleBar.text
}
private func configureBackgroundColor() {
collectionView?.backgroundColor = screen.background.color.uiColor
}
private func configureBackgroundImage() {
let backgroundImageView = collectionView!.backgroundView as! UIImageView
backgroundImageView.alpha = 0.0
backgroundImageView.image = nil
// Background color is used for tiled backgrounds
backgroundImageView.backgroundColor = UIColor.clear
let background = screen.background
backgroundImageView.isAccessibilityElement = !(background.image?.isDecorative ?? true)
backgroundImageView.accessibilityLabel = background.image?.accessibilityLabel
switch background.contentMode {
case .fill:
backgroundImageView.contentMode = .scaleAspectFill
case .fit:
backgroundImageView.contentMode = .scaleAspectFit
case .original:
backgroundImageView.contentMode = .center
case .stretch:
backgroundImageView.contentMode = .scaleToFill
case .tile:
backgroundImageView.contentMode = .center
}
if let image = ImageStore.shared.image(for: background, frame: backgroundImageView.frame) {
if case .tile = background.contentMode {
backgroundImageView.backgroundColor = UIColor(patternImage: image)
} else {
backgroundImageView.image = image
}
backgroundImageView.alpha = 1.0
} else {
ImageStore.shared.fetchImage(for: background, frame: backgroundImageView.frame) { [weak backgroundImageView] image in
guard let image = image else {
return
}
if case .tile = background.contentMode {
backgroundImageView?.backgroundColor = UIColor(patternImage: image)
} else {
backgroundImageView?.image = image
}
UIView.animate(withDuration: 0.25) {
backgroundImageView?.alpha = 1.0
}
}
}
}
// MARK: Reuseable Views
/// Register the `UITableViewCell` class to use for each of the various block types and the supplementary view class
/// to use for rows. You can override this method to provide a custom cell for a specific block.
open func registerReusableViews() {
collectionView?.register(
BlockCell.self,
forCellWithReuseIdentifier: ScreenViewController.blockCellReuseIdentifier
)
collectionView?.register(
BarcodeCell.self,
forCellWithReuseIdentifier: ScreenViewController.barcodeCellReuseIdentifier
)
collectionView?.register(
ButtonCell.self,
forCellWithReuseIdentifier: ScreenViewController.buttonCellReuseIdentifier
)
collectionView?.register(
ImageCell.self,
forCellWithReuseIdentifier: ScreenViewController.imageCellReuseIdentifier
)
collectionView?.register(
TextCell.self,
forCellWithReuseIdentifier: ScreenViewController.textCellReuseIdentifier
)
collectionView?.register(
WebViewCell.self,
forCellWithReuseIdentifier: ScreenViewController.webViewCellReuseIdentifier
)
collectionView?.register(
TextPollCell.self,
forCellWithReuseIdentifier: ScreenViewController.textPollViewCellReuseIdentifier
)
collectionView.register(
ImagePollCell.self,
forCellWithReuseIdentifier: ScreenViewController.imagePollViewCellReuseIdentifier
)
collectionView?.register(
RowView.self,
forSupplementaryViewOfKind: "row",
withReuseIdentifier: ScreenViewController.rowSupplementaryViewReuseIdentifier
)
}
private func cellReuseIdentifier(at indexPath: IndexPath) -> String {
let block = screen.rows[indexPath.section].blocks[indexPath.row]
switch block {
case _ as BarcodeBlock:
return ScreenViewController.barcodeCellReuseIdentifier
case _ as ButtonBlock:
return ScreenViewController.buttonCellReuseIdentifier
case _ as ImageBlock:
return ScreenViewController.imageCellReuseIdentifier
case _ as TextBlock:
return ScreenViewController.textCellReuseIdentifier
case _ as WebViewBlock:
return ScreenViewController.webViewCellReuseIdentifier
case _ as TextPollBlock:
return ScreenViewController.textPollViewCellReuseIdentifier
case _ as ImagePollBlock:
return ScreenViewController.imagePollViewCellReuseIdentifier
default:
return ScreenViewController.blockCellReuseIdentifier
}
}
private func supplementaryViewReuseIdentifier(at indexPath: IndexPath) -> String {
return ScreenViewController.rowSupplementaryViewReuseIdentifier
}
// MARK: UICollectionViewDataSource
override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return screen.rows[section].blocks.count
}
override open func numberOfSections(in collectionView: UICollectionView) -> Int {
return screen.rows.count
}
override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let reuseIdentifier = cellReuseIdentifier(at: indexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
if let pollCell = cell as? PollCell {
pollCell.delegate = self
}
if let attributes = collectionViewLayout.layoutAttributesForItem(at: indexPath) as? ScreenLayoutAttributes, let clipRect = attributes.clipRect {
let maskLayer = CAShapeLayer()
maskLayer.path = CGPath(rect: clipRect, transform: nil)
cell.layer.mask = maskLayer
} else {
cell.layer.mask = nil
}
guard let blockCell = cell as? BlockCell else {
return cell
}
let block = screen.rows[indexPath.section].blocks[indexPath.row]
if let pollCell = blockCell as? PollCell {
pollCell.experienceID = self.experience.id
}
blockCell.configure(with: block)
return blockCell
}
override open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let reuseIdentifier = supplementaryViewReuseIdentifier(at: indexPath)
let view = collectionView.dequeueReusableSupplementaryView(ofKind: reuseIdentifier, withReuseIdentifier: reuseIdentifier, for: indexPath)
guard let rowView = view as? RowView else {
return view
}
let row = screen.rows[indexPath.section]
rowView.configure(with: row)
return rowView
}
// MARK: UICollectionViewDataSourcePrefetching
open func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
indexPaths.forEach { indexPath in
guard let frame = collectionViewLayout.layoutAttributesForItem(at: indexPath)?.frame else {
return
}
let block = screen.rows[indexPath.section].blocks[indexPath.row]
ImageStore.shared.fetchImage(for: block.background, frame: frame)
if let image = (block as? ImageBlock)?.image {
ImageStore.shared.fetchImage(for: image, frame: frame)
}
}
}
// MARK: UICollectionViewDelegate
override open func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
let row = screen.rows[indexPath.section]
let block = row.blocks[indexPath.row]
return block is ButtonBlock || block.tapBehavior != BlockTapBehavior.none
}
override open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
defer {
collectionView.deselectItem(at: indexPath, animated: true)
}
let row = screen.rows[indexPath.section]
let block = row.blocks[indexPath.row]
switch block.tapBehavior {
case .goToScreen(let screenID):
navigateToScreen(screenID: screenID)
case .none, .custom:
break
case let .openURL(url, dismiss):
openURL(url, dismiss: dismiss)
case .presentWebsite(let url):
presentWebsite(at: url)
}
var userInfo: [String: Any] = [
ScreenViewController.experienceUserInfoKey: experience,
ScreenViewController.screenUserInfoKey: screen,
ScreenViewController.blockUserInfoKey: block
]
if let campaignID = campaignID {
userInfo[ScreenViewController.campaignIDUserInfoKey] = campaignID
}
NotificationCenter.default.post(
name: ScreenViewController.blockTappedNotification,
object: self,
userInfo: userInfo
)
}
// MARK: Block Tap Actions
/// Navigate to another screen in the experience. This method is called by the `ScreenViewController` in response
/// to a block tap configured to navigate to a screen. The default implementation constructs a new view controller
/// using the `viewControllerFactory` and pushes it onto the navigation stack. You can override this method if you
/// need to change this behavior.
open func navigateToScreen(screenID: String) {
guard let nextScreen = experience.screens.first(where: { $0.id == screenID }), let navigationController = navigationController else {
return
}
if let viewController = viewControllerFactory(experience, nextScreen) {
navigationController.pushViewController(viewController, animated: true)
}
}
/// Open a URL. This method is called by the `ScreenViewController` in response to a block tap configured to
/// open a URL. The default implementation calls `open(_:options:completionHandler:)` on `UIApplication.shared` and
/// dismisses the entire experience if the `dismiss` paramter is true. You can override this method if you need to
/// change this behavior.
open func openURL(_ url: URL, dismiss: Bool) {
if dismiss {
self.dismiss(animated: true, completion: {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
})
} else {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
/// Present a website at the given URL in a view controller. This method is called by the `ScreenViewController` in
/// response to a block tap configured to present a website. The default implementation constructs a new view
/// controller by calling the `websiteViewController(url:)` factory method and presents it modally. You can override
/// this method if you need to change this behavior.
open func presentWebsite(at url: URL) {
let websiteViewController = self.websiteViewController(url: url)
present(websiteViewController, animated: true, completion: nil)
}
// MARK: Poll Answer
func didCastVote(on pollBlock: PollBlock, for option: PollOption) {
var userInfo: [String: Any] = [
ScreenViewController.experienceUserInfoKey: experience,
ScreenViewController.screenUserInfoKey: screen,
ScreenViewController.blockUserInfoKey: pollBlock,
ScreenViewController.optionUserInfoKey: option
]
if let campaignID = campaignID {
userInfo[ScreenViewController.campaignIDUserInfoKey] = campaignID
}
NotificationCenter.default.post(
name: ScreenViewController.pollAnsweredNotification,
object: self,
userInfo: userInfo
)
}
// MARK: Factories
/// Construct a view controller to use for presenting websites. The default implementation returns an instance
/// of `SFSafariViewController`. You can override this method if you want to use a different view controller.
open func websiteViewController(url: URL) -> UIViewController {
return SFSafariViewController(url: url)
}
}
// MARK: Reuse Identifiers
extension ScreenViewController {
public static let blockCellReuseIdentifier = "block"
public static let barcodeCellReuseIdentifier = "barcode"
public static let buttonCellReuseIdentifier = "button"
public static let imageCellReuseIdentifier = "image"
public static let textCellReuseIdentifier = "text"
public static let webViewCellReuseIdentifier = "webView"
public static let rowSupplementaryViewReuseIdentifier = "row"
public static let textPollViewCellReuseIdentifier = "textPoll"
public static let imagePollViewCellReuseIdentifier = "imagePoll"
}
// MARK: Notifications
extension ScreenViewController {
/// The `ScreenViewController` sends this notification when it is presented.
public static let screenPresentedNotification = Notification.Name("io.rover.screenPresentedNotification")
/// The `ScreenViewController` sends this notification when it is dismissed.
public static let screenDismissedNotification = Notification.Name("io.rover.screenDismissedNotification")
/// The `ScreenViewController` sends this notification when a user finishes viewing a screen. The user starts
/// viewing a screen when the view controller is presented and finishes when it is dismissed. The duration the
/// user viewed the screen is included in the `durationUserInfoKey`.
///
/// If the user quickly dismisses the view controller and presents it again (or backgrounds the app and restores it)
/// the view controller considers this part of the same "viewing session". The notification is not sent until the
/// user dismisses the view controller and a specified time passes (default is 10 seconds).
///
/// This notification is useful for tracking the amount of time users spend viewing a screen. However if you want to
/// be notified immediately when a user views a screen you should use the `screenPresentedNotification`.
public static let screenViewedNotification = Notification.Name("io.rover.screenViewedNotification")
/// The `ScreenViewController` sends this when a `UIView` representing a specific block somewhere within the view
/// controller's hierarchy was tapped by the user.
public static let blockTappedNotification = Notification.Name("io.rover.blockTappedNotification")
/// The `ScreenViewController` sends this notification when a user casts a vote on a Poll in an experience.
public static let pollAnsweredNotification = Notification.Name("io.rover.pollAnsweredNotification")
}
// MARK: User Info Keys
extension ScreenViewController {
/// A key whose value is the `Experience` associated with the `ScreenViewController`.
public static let experienceUserInfoKey = "experienceUserInfoKey"
/// A key whose value is the `Screen` associated with the `ScreenViewController`.
public static let screenUserInfoKey = "screenUserInfoKey"
/// A key whose value is the `Block` that was tapped which triggered a `blockTappedNotification`.
public static let blockUserInfoKey = "blockUserInfoKey"
/// A key whose value is the poll `Option` that was tapped which triggered a `pollAnsweredNotification`.
public static let optionUserInfoKey = "optionUserInfoKey"
/// A key whose value is an optional `String` containing the `campaignID` passed into the `RoverViewController` when
/// it was initialized.
public static let campaignIDUserInfoKey = "campaignIDUserInfoKey"
/// A key whose value is a `Double` representing the duration of an experience session.
public static let durationUserInfoKey = "durationUserInfoKey"
}
|
apache-2.0
|
8961887d134f3a2449dd3f6a3ddfb697
| 38.8272 | 177 | 0.649807 | 5.886025 | false | false | false | false |
icenel/EDLightBox
|
EDLightBoxSample/ViewController.swift
|
1
|
1149
|
//
// ViewController.swift
// EDLightBoxSample
//
// Created by Edward Anthony on 7/31/15.
// Copyright (c) 2015 Edward Anthony. All rights reserved.
//
import UIKit
class ViewController: UIViewController, EDLightBoxDelegate {
@IBOutlet weak var imageView: UIImageView!
let lightBox = EDLightBox()
override func viewDidLoad() {
super.viewDidLoad()
// You can set low resolution image here
var lowResolutionImageURL = NSURL(string: "http://imageshack.com/a/img537/7851/gEmPzw.jpg")!
imageView.image = UIImage(data: NSData(contentsOfURL: lowResolutionImageURL)!)
lightBox.delegate = self
// Install light box
lightBox.installOnImageView(imageView)
}
func parentViewControllerForLightBox(lightBox: EDLightBox) -> UIViewController {
return self
}
func imageURLForLightBox(lightBox: EDLightBox) -> NSURL {
// High resolution image for light box
var highResolutionImageURL = NSURL(string: "http://imageshack.com/a/img907/7184/7qC5Ls.jpg")!
return highResolutionImageURL
}
}
|
mit
|
3a0314c51ed991af091339753080fe86
| 26.357143 | 101 | 0.662315 | 4.271375 | false | false | false | false |
mattgmg1990/iButterMeUp
|
Butter Me Up/ViewController.swift
|
1
|
1678
|
//
// ViewController.swift
// Butter Me Up
//
// Created by Matthew Garnes on 9/26/14.
// Copyright (c) 2014 Matt Garnes. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet var complimentTextView : UITextView!
@IBOutlet var tvTapGestureListener : UIGestureRecognizer!
var butterModel : ButterModel!
var synthesizer = AVSpeechSynthesizer()
/*
class Subscriber : NSObject {
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: ) {
println("observeValueForKey: (object)")
let tv = UITextView(object);
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
}
*/
override func viewDidLoad() {
super.viewDidLoad()
butterModel = ButterModel()
}
@IBAction func showNextCompliment(sender: AnyObject) {
complimentTextView.selectable = true
var compliment = butterModel.getCompliment()
complimentTextView.text = compliment
speakCompliment(compliment)
complimentTextView.selectable = false
}
func speakCompliment(compliment: String) {
var utterance = AVSpeechUtterance(string: compliment)
synthesizer.speakUtterance(utterance)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
0a076253938c3c266d14469052162b84
| 28.964286 | 127 | 0.653754 | 4.584699 | false | false | false | false |
Eonil/HomeworkApp1
|
Driver/HomeworkApp1/KeyworkInputFormViewController.swift
|
1
|
3165
|
//
// KeyworkInputFormViewController.swift
// HomeworkApp1
//
// Created by Hoon H. on 2015/02/26.
//
//
import Foundation
import UIKit
/// Takes keyword user input.
final class KeyworkdInputFormViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.navigationItem.title = "Homework 1"
userInputTextField.placeholder = "Type keyword to search. (e.g. 'cat')"
userInputTextField.returnKeyType = UIReturnKeyType.Google
userInputTextField.borderStyle = UITextBorderStyle.RoundedRect
userInputTextField.setTranslatesAutoresizingMaskIntoConstraints(false)
if userInputTextField.superview == nil {
self.view.addSubview(userInputTextField)
self.view.addConstraints([
NSLayoutConstraint(item: userInputTextField, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: userInputTextField, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -100),
NSLayoutConstraint(item: userInputTextField, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -20),
NSLayoutConstraint(item: userInputTextField, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 0, constant: 44),
])
}
////
reactions.owner = self
userInputTextField.delegate = reactions
}
override func viewWillAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
////
private let userInputTextField = UITextField()
private let reactions = ReactionController()
}
@objc
private class ReactionController: NSObject, UITextFieldDelegate {
weak var owner: KeyworkdInputFormViewController?
@objc
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@objc
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
return true
}
@objc
func textFieldDidEndEditing(textField: UITextField) {
let nc = UINavigationController()
let vc = KeywordSlideViewController()
vc.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "userDidTapDoneButton:")
vc.keywordString = textField.text
nc.pushViewController(vc, animated: false)
owner!.navigationController!.presentViewController(nc, animated: true) { () -> Void in
}
}
@objc
func userDidTapDoneButton(AnyObject?) {
owner!.navigationController!.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
}
|
mit
|
47739ec6eb1cf914dbb845dc36efbc73
| 26.051282 | 210 | 0.764297 | 4.225634 | false | false | false | false |
rlaferla/InfiniteTableView
|
InfiniteTableView/ViewController.swift
|
1
|
2291
|
//
// ViewController.swift
// InfiniteTableView
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView:UITableView!
let cache = Cache()
var scrollDirection:ScrollDirectionType = .none
var lastScrollPosition:CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.dataSource = self
self.cache.limit = 45
self.cache.loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in aTableView: UITableView) -> Int {
return self.cache.numberOfSections()
}
func tableView(_ aTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cache.numberOfRows(for: section)
}
func tableView(_ aTableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let date = self.cache.section(for: section)
let df = DateFormatter()
df.dateStyle = .short
let ds = df.string(from: date)
return "Section \(ds)"
}
func tableView(_ aTableView: UITableView, cellForRowAt anIndexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let record = self.cache.row(for: anIndexPath)
let df = DateFormatter()
df.dateStyle = .short
let ds = df.string(from: record.date)
cell.textLabel!.text = "\(record.row!): \(ds) - \(record.number!) at \(anIndexPath.section)-\(anIndexPath.row)"
return cell
}
func updateScrollDirection() {
// print("updateScrollDirection()")
let scrollPosition = self.tableView.contentOffset.y
if scrollPosition > self.lastScrollPosition {
self.scrollDirection = .down
}
else if scrollPosition < self.lastScrollPosition {
self.scrollDirection = .up
}
else {
self.scrollDirection = .none
}
self.lastScrollPosition = scrollPosition
}
}
|
mit
|
cd7a129c493d1125e4983ab191ab7194
| 28.753247 | 119 | 0.620253 | 5.148315 | false | false | false | false |
fespinoza/linked-ideas-osx
|
LinkedIdeas-Shared/Sources/Models/2DMath/Line.swift
|
1
|
2280
|
//
// Line.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 25/02/16.
// Copyright © 2016 Felipe Espinoza Dev. All rights reserved.
//
import CoreGraphics
public struct Line: PointInterceptable {
var pointA: CGPoint
var pointB: CGPoint
public init(pointA: CGPoint, pointB: CGPoint) {
self.pointA = pointA
self.pointB = pointB
}
var gradient: CGFloat {
return (pointB.y - pointA.y) / (pointB.x - pointA.x)
}
var intersectionWithYAxis: CGFloat {
if isConstantLineOnY() {
return pointA.y
}
return pointA.y - pointA.x * gradient
}
var intersectionWithXAxis: CGFloat {
if isConstantLineOnX() {
return pointA.x
}
return -intersectionWithYAxis / gradient
}
func evaluateX(_ xPoint: CGFloat) -> CGFloat {
return gradient * xPoint + intersectionWithYAxis
}
func evaluateY(_ yPoint: CGFloat) -> CGFloat {
return (yPoint - intersectionWithYAxis) / gradient
}
func isConstantLineOnX() -> Bool {
return gradient.isInfinite
}
func isConstantLineOnY() -> Bool {
return gradient == 0
}
func isParallelTo(_ line: Line) -> Bool {
return abs(gradient) == abs(line.gradient)
}
var description: String {
return "L(x) = \(gradient)*x + \(intersectionWithYAxis)"
}
// it does not considate the same lines: the answer is all the points
public func intersectionPointWith(_ line: Line) -> CGPoint? {
if isParallelTo(line) {
return nil
}
if line.isConstantLineOnX() {
let intersectionX = line.intersectionWithXAxis
let intersectionY = evaluateX(intersectionX)
return CGPoint(x: intersectionX, y: intersectionY)
}
if isConstantLineOnX() {
let intersectionX = intersectionWithXAxis
let intersectionY = line.evaluateX(intersectionX)
return CGPoint(x: intersectionX, y: intersectionY)
}
let intersectionX: CGFloat = (line.intersectionWithYAxis - intersectionWithYAxis) / (gradient - line.gradient)
let intersectionY: CGFloat = evaluateX(intersectionX)
return CGPoint(x: intersectionX, y: intersectionY)
}
public func intersectionPointWithinBoundaries(
_ line: Line, lineBoundaryP1 point1: CGPoint, lineBoundaryP2 point2: CGPoint
) -> CGPoint? {
return nil
}
}
|
mit
|
677536871779d735bb0fb6b09810aa9f
| 24.897727 | 114 | 0.683633 | 3.92931 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Controller/UI/Product/views/SLVProductInfo3Cell.swift
|
1
|
845
|
//
// SLVProductInfo3Cell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 7..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
/*
판매자/스타일/하자/엑세사리/추천착샷/비슷한 상품/코멘트 타이틀 셀
*/
class SLVProductInfo3Cell: UITableViewCell {
@IBOutlet weak var mainTitleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var moreButton: UIButton!
var cellIndex = 0
override public func awakeFromNib() {
super.awakeFromNib()
}
//TODO: 추후 처리할 것 ....
@IBAction func touchMore(_ sender: Any) {
if cellIndex == 13 {//추천 착용 사진 더보기
}
else if cellIndex == 15 {//비슷한 상품
}
}
}
|
mit
|
acc53707cd9b124481fce613edca6ec5
| 19 | 55 | 0.589189 | 3.259912 | false | false | false | false |
hanzhuzi/XRNetworkAutoCheck
|
XRNetworkAutoCheck/XRNetworkAutoCheck/ViewController.swift
|
1
|
1346
|
//
// ViewController.swift
// XRNetworkAutoCheck
//
// Created by 寒竹子 on 16/4/10.
// Copyright © 2016年 黯丶野火. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
XRNetworkCheckTool.sharedTool().getNetworkTypeWithClosure { (networkType) in
var netStatusTemp = "未知网络"
switch networkType {
case .XRNet_UNEnable:
netStatusTemp = "网络已断开,请检查您的网络"
case .XRNet_2G:
netStatusTemp = "已切换到2G网络"
case .XRNet_3G:
netStatusTemp = "已切换到3G网络"
case .XRNet_4G:
netStatusTemp = "已切换到4G网络"
case .XRNet_WiFi:
netStatusTemp = "已切换到WiFi网络"
case .XRNet_NUKnow:
break
}
dispatch_async(dispatch_get_main_queue(), {
UIApplication.sharedApplication().keyWindow?.showHUD(netStatusTemp)
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
53582c422305a1d23d44163a0429df7e
| 24.979167 | 84 | 0.534884 | 4.3 | false | false | false | false |
sedler/AlamofireRSSParser
|
Pod/Classes/AlamofireRSSParser.swift
|
1
|
11494
|
//
// AlamofireRSSParser.swift
// Pods
//
// Created by Donald Angelillo on 3/2/16.
//
//
import Foundation
import Alamofire
extension Alamofire.DataRequest {
/**
Creates a response serializer that returns an `RSSFeed` object initialized from the response data.
- Returns: An RSS response serializer.
*/
public static func RSSResponseSerializer() -> DataResponseSerializer<RSSFeed> {
return DataResponseSerializer { request, response, data, error in
guard error == nil else {
return .failure(error!)
}
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = NSError(domain: "com.alamofirerssparser", code: -6004, userInfo: [NSLocalizedFailureReasonErrorKey: failureReason])
return .failure(error)
}
let parser = AlamofireRSSParser(data: validData)
let parsedResults: (feed: RSSFeed?, error: NSError?) = parser.parse()
if let feed = parsedResults.feed {
return .success(feed)
} else {
return .failure(parsedResults.error!)
}
}
}
/**
Adds a handler to be called once the request has finished.
- Parameter completionHandler: A closure to be executed once the request has finished.
- Returns: The request.
*/
@discardableResult
public func responseRSS(_ completionHandler: @escaping (DataResponse<RSSFeed>) -> Void) -> Self {
return response(
responseSerializer: DataRequest.RSSResponseSerializer(),
completionHandler: completionHandler
)
}
//public func responseRSS(parser parser: AlamofireRSSParser?, completionHandler: Response<RSSFeed, NSError> -> Void) -> Self {
// return response(responseSerializer: Request.RSSResponseSerializer(parser), completionHandler: completionHandler)
//}
}
/**
This class does the bulk of the work. Implements the `NSXMLParserDelegate` protocol.
Unfortunately due to this it's also required to implement the `NSObject` protocol.
And unfortunately due to that there doesn't seem to be any way to make this class have a valid public initializer,
despite it being marked public. I would love to have it be publicly accessible because I would like to able to pass
a custom-created instance of this class with configuration properties set into `responseRSS` (see the commented out overload above)
*/
open class AlamofireRSSParser: NSObject, XMLParserDelegate {
var parser: XMLParser? = nil
var feed: RSSFeed? = nil
var parsingItems: Bool = false
var currentItem: RSSItem? = nil
var currentString: String!
var currentAttributes: [String: String]? = nil
var parseError: NSError? = nil
open var data: Data? = nil {
didSet {
if let data = data {
self.parser = XMLParser(data: data)
self.parser?.delegate = self
}
}
}
override init() {
self.parser = XMLParser();
super.init()
}
init(data: Data) {
self.parser = XMLParser(data: data)
super.init()
self.parser?.delegate = self
}
/**
Kicks off the RSS parsing.
- Returns: A tuple containing an `RSSFeed` object if parsing was successful (`nil` otherwise) and
an `NSError` object if an error occurred (`nil` otherwise).
*/
func parse() -> (feed: RSSFeed?, error: NSError?) {
self.feed = RSSFeed()
self.currentItem = nil
self.currentAttributes = nil
self.currentString = String()
self.parser?.parse()
return (feed: self.feed, error: self.parseError)
}
//MARK: - NSXMLParserDelegate
open func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
self.currentString = String()
self.currentAttributes = attributeDict
if ((elementName == "item") || (elementName == "entry")) {
self.currentItem = RSSItem()
}
}
open func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
//if we're at the item level
if let currentItem = self.currentItem {
if ((elementName == "item") || (elementName == "entry")) {
self.feed?.items.append(currentItem)
return
}
if (elementName == "title") {
currentItem.title = self.currentString
}
if (elementName == "description") {
currentItem.itemDescription = self.currentString
}
if (elementName == "content:encoded") {
currentItem.content = self.currentString
}
if (elementName == "link") {
currentItem.link = self.currentString
}
if (elementName == "guid") {
currentItem.guid = self.currentString
}
if (elementName == "author") {
currentItem.author = self.currentString
}
if (elementName == "comments") {
currentItem.comments = self.currentString
}
if (elementName == "source") {
currentItem.source = self.currentString
}
if (elementName == "pubDate") {
if let date = RSSDateFormatter.rfc822DateFormatter().date(from: self.currentString) {
currentItem.pubDate = date
} else if let date = RSSDateFormatter.rfc822DateFormatter2().date(from: self.currentString) {
currentItem.pubDate = date
}
}
if (elementName == "published") {
if let date = RSSDateFormatter.publishedDateFormatter().date(from: self.currentString) {
currentItem.pubDate = date
} else if let date = RSSDateFormatter.publishedDateFormatter2().date(from: self.currentString) {
currentItem.pubDate = date
}
}
if (elementName == "media:thumbnail") {
if let attributes = self.currentAttributes {
if let url = attributes["url"] {
currentItem.mediaThumbnail = url
}
}
}
if (elementName == "media:content") {
if let attributes = self.currentAttributes {
if let url = attributes["url"] {
currentItem.mediaContent = url
}
}
}
if (elementName == "jms-featured-image") {
currentItem.featuredImage = self.currentString
}
//if we're at the top level
} else {
if (elementName == "title") {
self.feed?.title = self.currentString
}
if (elementName == "description") {
self.feed?.feedDescription = self.currentString
}
if (elementName == "link") {
self.feed?.link = self.currentString
}
if (elementName == "language") {
self.feed?.language = self.currentString
}
if (elementName == "copyright") {
self.feed?.copyright = self.currentString
}
if (elementName == "managingEditor") {
self.feed?.managingEditor = self.currentString
}
if (elementName == "webMaster") {
self.feed?.webMaster = self.currentString
}
if (elementName == "generator") {
self.feed?.generator = self.currentString
}
if (elementName == "docs") {
self.feed?.docs = self.currentString
}
if (elementName == "ttl") {
if let ttlInt = Int(currentString) {
self.feed?.ttl = NSNumber(value: ttlInt)
}
}
if (elementName == "pubDate") {
if let date = RSSDateFormatter.rfc822DateFormatter().date(from: self.currentString) {
self.feed?.pubDate = date
} else if let date = RSSDateFormatter.rfc822DateFormatter2().date(from: self.currentString) {
self.feed?.pubDate = date
}
}
if (elementName == "published") {
if let date = RSSDateFormatter.publishedDateFormatter().date(from: self.currentString) {
self.feed?.pubDate = date
} else if let date = RSSDateFormatter.publishedDateFormatter2().date(from: self.currentString) {
self.feed?.pubDate = date
}
}
if (elementName == "lastBuildDate") {
if let date = RSSDateFormatter.rfc822DateFormatter().date(from: self.currentString) {
self.feed?.lastBuildDate = date
} else if let date = RSSDateFormatter.rfc822DateFormatter2().date(from: self.currentString) {
self.feed?.lastBuildDate = date
}
}
}
}
open func parser(_ parser: XMLParser, foundCharacters string: String) {
self.currentString.append(string)
}
open func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
self.parseError = parseError as NSError?
self.parser?.abortParsing()
}
}
/**
Struct containing various `NSDateFormatter` s
*/
struct RSSDateFormatter {
static func rfc822DateFormatter() -> DateFormatter {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
return dateFormatter
}
static func rfc822DateFormatter2() -> DateFormatter {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
return dateFormatter
}
static func publishedDateFormatter() -> DateFormatter {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return dateFormatter
}
static func publishedDateFormatter2() -> DateFormatter {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssz"
return dateFormatter
}
}
|
mit
|
80ed13a5d68d799c6629c0f2d28b62ad
| 34.91875 | 178 | 0.546981 | 5.313916 | false | false | false | false |
ello/ello-ios
|
Sources/Controllers/Stream/Presenters/PromotionalHeaderSubscriptionCellPresenter.swift
|
1
|
737
|
////
/// PromotionalHeaderSubscriptionCellPresenter.swift
//
struct PromotionalHeaderSubscriptionCellPresenter {
static func configure(
_ cell: UICollectionViewCell,
streamCellItem: StreamCellItem,
streamKind: StreamKind,
indexPath: IndexPath,
currentUser: User?
) {
guard
let cell = cell as? PromotionalHeaderSubscriptionCell,
let pageHeader = streamCellItem.jsonable as? PageHeader
else { return }
if let currentUser = currentUser, let categoryId = pageHeader.categoryId {
cell.isSubscribed = currentUser.subscribedTo(categoryId: categoryId)
}
else {
cell.isSubscribed = false
}
}
}
|
mit
|
84a7a555a4615a71793bdd55f6976322
| 27.346154 | 82 | 0.639077 | 5.419118 | false | false | false | false |
audiokit/AudioKit
|
Tests/AudioKitTests/Node Tests/Effects Tests/DiodeClipperTests.swift
|
2
|
1138
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AudioKit
import XCTest
class DiodeClipperTests: XCTestCase {
func testDefault() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = DiodeClipper(input)
input.play()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testParameters1() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = DiodeClipper(input, cutoffFrequency: 1000, gain: 1.0)
input.play()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testParameters2() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = DiodeClipper(input, cutoffFrequency: 2000, gain: 2.0)
input.play()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
}
|
mit
|
e47a944f0ad2a27f2be86c2e1ead2ea4
| 28.947368 | 100 | 0.630931 | 4.093525 | false | true | false | false |
open-telemetry/opentelemetry-swift
|
Sources/Instrumentation/NetworkStatus/NetworkStatusInjector.swift
|
1
|
1604
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
#if os(iOS) && !targetEnvironment(macCatalyst)
import CoreTelephony
import Foundation
import Network
import OpenTelemetryApi
public class NetworkStatusInjector {
private var netstat: NetworkStatus
public init(netstat: NetworkStatus) {
self.netstat = netstat
}
public func inject(span: Span) {
let (type, subtype, carrier) = netstat.status()
span.setAttribute(key: "net.host.connection.type", value: AttributeValue.string(type))
if let subtype: String = subtype {
span.setAttribute(key: "net.host.connection.subtype", value: AttributeValue.string(subtype))
}
if let carrierInfo: CTCarrier = carrier {
if let carrierName = carrierInfo.carrierName {
span.setAttribute(key: "net.host.carrier.name", value: AttributeValue.string(carrierName))
}
if let isoCountryCode = carrierInfo.isoCountryCode {
span.setAttribute(key: "net.host.carrier.icc", value: AttributeValue.string(isoCountryCode))
}
if let mobileCountryCode = carrierInfo.mobileCountryCode {
span.setAttribute(key: "net.host.carrier.mcc", value: AttributeValue.string(mobileCountryCode))
}
if let mobileNetworkCode = carrierInfo.mobileNetworkCode {
span.setAttribute(key: "net.host.carrier.mnc", value: AttributeValue.string(mobileNetworkCode))
}
}
}
}
#endif // os(iOS) && !targetEnvironment(macCatalyst)
|
apache-2.0
|
5f959da1451a91500b28d8177d90655b
| 33.12766 | 111 | 0.660224 | 4.505618 | false | false | false | false |
FlaneurApp/FlaneurOpen
|
Example/FlaneurOpen/MenuNavigationController.swift
|
1
|
2743
|
//
// MenuNavigationController.swift
// FlaneurOpen_Example
//
// Created by Mickaël Floc'hlay on 30/01/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import FlaneurOpen
enum MenuOption: String {
case legacyMenu = "Legacy Menu"
case grayscaleDemo = "Grayscale Views"
case segmentedCollectionView = "SegmentedCollectionView"
case searchViewController = "Search view controller"
case simpleMapView = "Simple Map View"
case progressModalViewController = "Progress Modal view controller"
}
extension MenuOption {
var cellDescriptor: TableViewCellDescriptor {
return TableViewCellDescriptor(reuseIdentifier: "menuItem", configure: self.configureCell)
}
func configureCell(_ cell: MenuOptionCell) {
cell.textLabel?.text = self.rawValue
}
}
final class MenuOptionCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/// The root menu of demo options.
class MenuNavigationController: UINavigationController {
let optionsViewController: ItemsViewController<MenuOption> = {
let menuOptionItems: [MenuOption] = [
.legacyMenu,
.grayscaleDemo,
.segmentedCollectionView,
.searchViewController,
.simpleMapView,
.progressModalViewController
]
let result = ItemsViewController<MenuOption>(items: menuOptionItems, cellDescriptor: { $0.cellDescriptor })
result.navigationItem.title = "Flaneur Open Demos"
return result
}()
override func viewDidLoad() {
super.viewDidLoad()
self.viewControllers = [ optionsViewController ]
optionsViewController.didSelect = { menuOption in
switch menuOption {
case .legacyMenu:
self.performSegue(withIdentifier: "legacyMenueSegue", sender: self)
case .grayscaleDemo:
self.pushViewController(GrayscalingViewController(), animated: true)
case .segmentedCollectionView:
self.pushViewController(SegmentedCollectionViewController(), animated: true)
case .searchViewController:
self.pushViewController(DemoSearchViewController(), animated: true)
case .simpleMapView:
self.pushViewController(MapDemoViewController(), animated: true)
case .progressModalViewController:
self.pushViewController(DemoProgressModalViewController(), animated: true)
}
}
}
}
|
mit
|
148255cc38978c478ac4c8634aeda11d
| 34.141026 | 115 | 0.67676 | 5.230916 | false | false | false | false |
Senspark/ee-x
|
src/ios/ee/firebase_remote_config/FirebaseRemoteConfigBridge.swift
|
1
|
8444
|
//
// FirebaseRemoteConfigBridge.swift
// ee-x-a16b5188
//
// Created by eps on 2/2/21.
//
import RxSwift
private let kPrefix = "FirebaseRemoteConfigBridge"
private let kInitialize = "\(kPrefix)Initialize"
private let kSetSettings = "\(kPrefix)SetSettings"
private let kSetDefaults = "\(kPrefix)SetDefaults"
private let kFetch = "\(kPrefix)Fetch"
private let kActivate = "\(kPrefix)Activate"
private let kGetBool = "\(kPrefix)GetBool"
private let kGetLong = "\(kPrefix)GetLong"
private let kGetDouble = "\(kPrefix)GetDouble"
private let kGetString = "\(kPrefix)GetString"
@objc(EEFirebaseRemoteConfigBridge)
class FirebaseRemoteConfigBridge: NSObject, IPlugin {
private let _bridge: IMessageBridge
private let _logger: ILogger
private var _plugin: RemoteConfig?
public required init(_ bridge: IMessageBridge, _ logger: ILogger) {
_bridge = bridge
_logger = logger
_plugin = nil
super.init()
registerHandlers()
}
public func destroy() {
deregisterHandlers()
}
func registerHandlers() {
_bridge.registerAsyncHandler(kInitialize) { _, resolver in
self.initialize()
.subscribe(
onSuccess: {
result in resolver(Utils.toString(result))
}, onError: {
_ in resolver(Utils.toString(false))
})
}
_bridge.registerAsyncHandler(kFetch) { message, resolver in
let dict = EEJsonUtils.convertString(toDictionary: message)
guard let fetchInterval = dict["fetchInterval"] as? Int64 else {
assert(false, "Unexpected value")
return
}
self.fetch(fetchInterval)
.subscribe(
onSuccess: {
result in resolver("\(result)")
}, onError: {
_ in resolver("\(RemoteConfigFetchStatus.failure)")
})
}
_bridge.registerAsyncHandler(kActivate) { _, resolver in
self.activate()
.subscribe(
onSuccess: {
result in resolver(Utils.toString(result))
}, onError: {
_ in resolver(Utils.toString(false))
})
}
_bridge.registerAsyncHandler(kSetDefaults) { message, resolver in
let dict = EEJsonUtils.convertString(toDictionary: message)
guard let defaults = dict["defaults"] as? [String: NSObject] else {
assert(false, "Unexpected value")
return
}
self.setDefaults(defaults)
.subscribe(
onSuccess: {
_ in resolver("")
}, onError: {
_ in resolver("")
})
}
_bridge.registerHandler(kGetBool) { message in
Utils.toString(self.getBool(message))
}
_bridge.registerHandler(kGetLong) { message in
"\(self.getLong(message))"
}
_bridge.registerHandler(kGetDouble) { message in
"\(self.getDouble(message))"
}
_bridge.registerHandler(kGetString) { message in
self.getString(message)
}
}
func deregisterHandlers() {
_bridge.deregisterHandler(kInitialize)
_bridge.deregisterHandler(kSetSettings)
_bridge.deregisterHandler(kSetDefaults)
_bridge.deregisterHandler(kFetch)
_bridge.deregisterHandler(kActivate)
_bridge.deregisterHandler(kGetBool)
_bridge.deregisterHandler(kGetLong)
_bridge.deregisterHandler(kGetDouble)
_bridge.deregisterHandler(kGetString)
}
func initialize() -> Single<Bool> {
return Single<Bool>.create { single in
Thread.runOnMainThread {
if FirebaseInitializer.instance.initialize() {
// OK.
} else {
single(.success(false))
}
RemoteConfig.remoteConfig().ensureInitialized { _ in
Thread.runOnMainThread {
self._plugin = RemoteConfig.remoteConfig()
single(.success(true))
}
}
}
return Disposables.create()
}
.subscribeOn(MainScheduler())
}
func setSettings(_ fetchTimeOut: Int64, _ fetchInterval: Int64) -> Single<Void> {
return Single<Void>.create { single in
Thread.runOnMainThread {
guard let plugin = self._plugin else {
assert(false, "Please call initialize() first")
return
}
let settings = RemoteConfigSettings()
settings.fetchTimeout = TimeInterval(fetchTimeOut)
settings.minimumFetchInterval = TimeInterval(fetchInterval)
plugin.configSettings = settings
single(.success(Void()))
}
return Disposables.create()
}
.subscribeOn(MainScheduler())
}
func fetch(_ fetchInterval: Int64) -> Single<Int> {
return Single<Int>.create { single in
Thread.runOnMainThread {
guard let plugin = self._plugin else {
assert(false, "Please call initialize() first")
return
}
plugin.fetch { status, _ in
Thread.runOnMainThread {
switch status {
case .success: single(.success(0))
case .noFetchYet: single(.success(1))
case .failure: single(.success(2))
case .throttled: single(.success(3))
@unknown default:
single(.success(2))
}
}
}
}
return Disposables.create()
}
.subscribeOn(MainScheduler())
}
func activate() -> Single<Bool> {
return Single<Bool>.create { single in
Thread.runOnMainThread {
guard let plugin = self._plugin else {
assert(false, "Please call initialize() first")
return
}
plugin.activate { changed, _ in
Thread.runOnMainThread {
single(.success(changed))
}
}
}
return Disposables.create()
}
.subscribeOn(MainScheduler())
}
func setDefaults(_ defaults: [String: NSObject]) -> Single<Void> {
return Single<Void>.create { single in
Thread.runOnMainThread {
guard let plugin = self._plugin else {
assert(false, "Please call initialize() first")
return
}
plugin.setDefaults(defaults)
single(.success(Void()))
}
return Disposables.create()
}
.subscribeOn(MainScheduler())
}
func getBool(_ key: String) -> Bool {
guard let plugin = _plugin else {
assert(false, "Please call initialize() first")
return false
}
let value = plugin.configValue(forKey: key)
return value.boolValue
}
func getLong(_ key: String) -> Int64 {
guard let plugin = _plugin else {
assert(false, "Please call initialize() first")
return 0
}
let value = plugin.configValue(forKey: key)
return value.numberValue.int64Value
}
func getDouble(_ key: String) -> Double {
guard let plugin = _plugin else {
assert(false, "Please call initialize() first")
return 0
}
let value = plugin.configValue(forKey: key)
return value.numberValue.doubleValue
}
func getString(_ key: String) -> String {
guard let plugin = _plugin else {
assert(false, "Please call initialize() first")
return ""
}
let value = plugin.configValue(forKey: key)
return value.stringValue ?? ""
}
}
|
mit
|
15005b07fcf6fed97c9b019928274de2
| 33.748971 | 85 | 0.517527 | 5.251244 | false | true | false | false |
rnystrom/GitHawk
|
Local Pods/SwipeCellKit/Source/SwipeActionButton.swift
|
2
|
3559
|
//
// SwipeActionButton.swift
//
// Created by Jeremy Koch.
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
class SwipeActionButton: UIButton {
var spacing: CGFloat = 8
var shouldHighlight = true
var highlightedBackgroundColor: UIColor?
var maximumImageHeight: CGFloat = 0
var verticalAlignment: SwipeVerticalAlignment = .centerFirstBaseline
var currentSpacing: CGFloat {
return (currentTitle?.isEmpty == false && maximumImageHeight > 0) ? spacing : 0
}
var alignmentRect: CGRect {
let contentRect = self.contentRect(forBounds: bounds)
let titleHeight = titleBoundingRect(with: verticalAlignment == .centerFirstBaseline ? CGRect.infinite.size : contentRect.size).height
let totalHeight = maximumImageHeight + titleHeight + currentSpacing
return contentRect.center(size: CGSize(width: contentRect.width, height: totalHeight))
}
convenience init(action: SwipeAction) {
self.init(frame: .zero)
contentHorizontalAlignment = .center
tintColor = action.textColor ?? .white
highlightedBackgroundColor = action.highlightedBackgroundColor ?? UIColor.black.withAlphaComponent(0.1)
titleLabel?.font = action.font ?? UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
titleLabel?.textAlignment = .center
titleLabel?.lineBreakMode = .byWordWrapping
titleLabel?.numberOfLines = 0
accessibilityLabel = action.accessibilityLabel
tintColor = action.tintColor
setTitle(action.title, for: .normal)
setTitleColor(tintColor, for: .normal)
setImage(action.image, for: .normal)
setImage(action.highlightedImage ?? action.image, for: .highlighted)
}
override var isHighlighted: Bool {
didSet {
guard shouldHighlight else { return }
backgroundColor = isHighlighted ? highlightedBackgroundColor : .clear
}
}
func preferredWidth(maximum: CGFloat) -> CGFloat {
let width = maximum > 0 ? maximum : CGFloat.greatestFiniteMagnitude
let textWidth = titleBoundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)).width
let imageWidth = currentImage?.size.width ?? 0
return min(width, max(textWidth, imageWidth) + contentEdgeInsets.left + contentEdgeInsets.right)
}
func titleBoundingRect(with size: CGSize) -> CGRect {
guard let title = currentTitle, let font = titleLabel?.font else { return .zero }
return title.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: [NSAttributedStringKey.font: font], context: nil)
}
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
var rect = contentRect.center(size: titleBoundingRect(with: contentRect.size).size)
rect.origin.y = alignmentRect.minY + maximumImageHeight + currentSpacing
return rect
}
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
var rect = contentRect.center(size: currentImage?.size ?? .zero)
rect.origin.y = alignmentRect.minY + (maximumImageHeight - rect.height) / 2
return rect
}
}
extension CGRect {
func center(size: CGSize) -> CGRect {
let dx = width - size.width
let dy = height - size.height
return CGRect(x: origin.x + dx * 0.5, y: origin.y + dy * 0.5, width: size.width, height: size.height)
}
}
|
mit
|
b168574084292f7cee23ae66330d63f8
| 37.258065 | 143 | 0.671164 | 4.941667 | false | false | false | false |
wangxin20111/WXWeiBo
|
WXWeibo/WXWeibo/Classes/NewFeature/WXNewFeatureController.swift
|
1
|
5582
|
//
// WXNewFeatureController.swift
// WXWeibo
//
// Created by 王鑫 on 16/7/12.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
import PureLayout
private let reuseIdentifier = "Cell"
var WXScreenWidth = UIScreen.mainScreen().bounds.size.width
let WXNotificationCenter = NSNotificationCenter.defaultCenter()
class WXNewFeatureController: UICollectionViewController {
//MARK: - 基本属性
private let flowLayout = UICollectionViewFlowLayout()
//MARK: - 懒加载对象
//MARK: - 对外提供的对象方法
//MARK: - 对外提供的类方法
//MARK: - Vc的生命周期函数
init(){
super.init(collectionViewLayout: flowLayout)
}
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: flowLayout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.registerClass(WXNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView!.bounces = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
flowLayout.itemSize = UIScreen.mainScreen().bounds.size
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
}
//MARK: - 私有方法
}
extension WXNewFeatureController{
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! WXNewFeatureCell
cell.imageIndex = indexPath.item
return cell
}
//当cell展示完毕后会调用这个方法
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if indexPath.item == 3 {
let cl = cell as! WXNewFeatureCell
cl.startAnim()
}
}
}
class WXNewFeatureCell:UICollectionViewCell{
//对外开放一个index属性
var imageIndex : NSInteger? {
didSet{
imageView.image = UIImage(named: "new_feature_\(imageIndex! + 1)")
lab.text = "new_feature_\(imageIndex! + 1)"
//判断如果是第4个页面,我们就去添加一个按钮
if imageIndex! + 1 == 4 {
confirmBtn.hidden = false
contentView.addSubview(confirmBtn)
}
}
}
//懒加载数据
private lazy var imageView : UIImageView = {
return UIImageView()
}()
private lazy var lab : UILabel = UILabel()
private lazy var confirmBtn:UIButton = {
let btn = UIButton()
btn.hidden = true
btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted)
btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal)
btn.addTarget(self, action: "comfirmBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
//执行动画的方法
func startAnim(){
//设置动画
confirmBtn.transform = CGAffineTransformMakeScale(0, 0)
UIView.animateWithDuration(2.8, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 2.8, options: UIViewAnimationOptions(rawValue: 0), animations: {
self.confirmBtn.transform = CGAffineTransformIdentity
}, completion: { (_) in
self.confirmBtn.enabled = true
self.confirmBtn.userInteractionEnabled = true
})
}
//MARK:-自定义一个collctionView
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//创建子控件
private func setupUI(){
contentView.addSubview(imageView)
contentView.addSubview(lab)
setNeedsUpdateConstraints()
}
//设置按钮的点击事件
func comfirmBtnClick(){
WXNotificationCenter.postNotificationName(WXChangeRootViewControllerNotification, object: true)
}
//初始化的时候,如果不去调用的话,不走这个方法,很恶心,所以初始化完毕一定要去调用一下
override func updateConstraints() {
super.updateConstraints()
imageView.autoPinEdgesToSuperviewEdges()
lab.autoPinEdgesToSuperviewEdges()
if imageIndex == 3 {
let size = confirmBtn.currentBackgroundImage?.size
confirmBtn.autoSetDimensionsToSize(size!)
confirmBtn.autoAlignAxisToSuperviewAxis(ALAxis.Vertical)
confirmBtn.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: 100)
}
}
}
|
mit
|
a286dc6f5f5429a9b769f3551a5c6836
| 31.462963 | 166 | 0.669139 | 5.206931 | false | false | false | false |
Quobject/boscode-learn
|
code/arduino/major/Dogboot/xcode/testbluetooth/testbluetooth/ViewController.swift
|
1
|
5675
|
//
// ViewController.swift
// testbluetooth
//
// Created by Matthias Ludwig on 21/8/20.
// Copyright © 2020 Quobject. All rights reserved.
//
import CoreBluetooth
import UIKit
class ViewController: UIViewController, CBPeripheralDelegate, CBCentralManagerDelegate {
public static let SERVICE_NAME = "HMSoft"
//public static let SERVICE_NAME = "MLT-BT05"
private let SCAN_NUMBER_OF_ITEMS = 10;
private var scans = 0;
private var centralManager: CBCentralManager!
private var peripheralDict: [String: CBPeripheral] = [:];
private var peripheral: CBPeripheral!
private var characteristic: CBCharacteristic!
@IBOutlet weak var scanButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
centralManager = CBCentralManager(delegate: self, queue: nil)
scanButton.isEnabled = false
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
print("Central state update")
if central.state != .poweredOn {
print("Central is not powered on")
} else {
scanButton.isEnabled = true
}
}
@IBAction func scan(_ sender: Any) {
print("Central scanning");
centralManager.scanForPeripherals(withServices: [], options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if (scans > SCAN_NUMBER_OF_ITEMS) {
self.centralManager.stopScan()
print("scanning done");
for (name, n2) in peripheralDict {
print("did discover \(name) \(n2)")
}
if let p = peripheralDict[ViewController.SERVICE_NAME] {
print("found: \(ViewController.SERVICE_NAME)");
self.peripheral = p;
self.peripheral.delegate = self
self.centralManager.connect(self.peripheral, options: nil)
scanButton.titleLabel?.text = "Connected"
scanButton.titleLabel?.textColor = UIColor.green;
} else {
print("not found: \(ViewController.SERVICE_NAME)");
scanButton.titleLabel?.textColor = UIColor.red;
}
}
scans += 1;
if let name = peripheral.name {
//let uid = peripheral.identifier
if peripheralDict[name] == nil {
peripheralDict[name] = peripheral;
}
}
// Connect!"
//self.centralManager.connect(self.peripheral, options: nil)
}
// The handler if we do connect succesfully
func centralManager(_ central: CBCentralManager, didConnect peripheral:
CBPeripheral) {
if peripheral == self.peripheral {
print("Connected to your \(ViewController.SERVICE_NAME) Board")
peripheral.discoverServices(nil)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
//print("didDiscoverServices")
if let services = peripheral.services {
for service in services {
//print("service found \(service.uuid)")
peripheral.discoverCharacteristics([], for: service);
//return;
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let e = error {
print("ERROR didDiscoverCharacteristicsFor \(e)")
return
}
if let characteristics = service.characteristics {
//print("didDiscoverCharacteristicsFor \(service.uuid)")
// for characteristic in characteristics {
// print("characteristics \(characteristic.uuid)")
// }
self.characteristic = characteristics[0];
//printCharacteristicProperties();
peripheral.readValue(for: characteristic)
peripheral.setNotifyValue(true, for: self.characteristic)
}
}
@IBOutlet weak var myLabel: UILabel!
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard let data = characteristic.value else { return }
print(data)
if let ds = String(data: data, encoding: String.Encoding.utf8) {
let index = ds.index(ds.startIndex, offsetBy: 4)
let mySubstring = ds.suffix(from: index) // playground
let t = Double(mySubstring)!/10.0
myLabel.text = ("\(t)°C")
print(ds)
}
}
func write(_ value: String) {
let value1 = value.data(using: String.Encoding.utf8)
if let v = value1 {
if let ch = self.characteristic {
self.peripheral.writeValue(v, for: ch, type: .withoutResponse);
print("write \(value) ");
}
}
}
func printCharacteristicProperties() {
if let char = self.characteristic {
if char.properties.contains(.writeWithoutResponse) {
print("char.properties.contains(.writeWithoutResponse)")
}
if char.properties.contains(.read) {
print("char.properties.contains(.read)")
}
print("property found: \(char.properties)")
}
}
}
|
mit
|
51cc448a482343b7aa5cb1ebc2500619
| 33.174699 | 148 | 0.575004 | 5.291978 | false | false | false | false |
skarppi/cavok
|
CAVOK/Weather/Timeslot/TimeslotDraverView.swift
|
1
|
5378
|
//
// TimeslotView.swift
// CAV-OK
//
// Created by Juho Kolehmainen on 27.3.2021.
//
import SwiftUI
struct TimeslotDrawerView: View {
@Environment(\.colorScheme) var colorScheme
@EnvironmentObject var state: TimeslotState
@State var status: String = "Loading"
@State var statusColor = Color.primary
@GestureState var cursor = CGPoint.zero
let updateTimestampsTimer = Timer.publish(every: 60, on: .main, in: .common).autoconnect()
var body: some View {
VStack(spacing: 4) {
Capsule()
.fill(Color.secondary)
.frame(width: 36, height: 5)
Text(status)
.font(.body)
.padding(.leading, 15)
.foregroundColor(
statusColor.lighter(by: colorScheme == .dark ? 0.4 : 0))
.frame(maxWidth: .infinity, minHeight: 40, alignment: .leading)
.background(Color(.secondarySystemFill))
.cornerRadius(10)
timeline.gesture(
DragGesture(minimumDistance: 0, coordinateSpace: .global)
.updating($cursor) { (value, state, _) in
state = value.location
})
}
.padding(.top, 4)
.onReceive(state.$selectedIndex) { index in
refreshStatus(slot: state.slots[safe: index])
}
.onChange(of: state.slots) { slots in
refreshStatus(slot: slots[safe: state.selectedIndex])
}
.onReceive(updateTimestampsTimer) { _ in
refreshStatus(slot: state.slots[safe: state.selectedIndex])
}
.onAppear {
refreshStatus(slot: state.slots[safe: state.selectedIndex])
}
}
private var timeline: some View {
HStack(spacing: 0) {
ForEach(Array(state.slots.enumerated()), id: \.element) { (index, slot) in
Text(slot.title)
.font(.caption)
.foregroundColor(.secondary)
.frame(maxWidth: .infinity)
.padding(EdgeInsets(top: 10, leading: 3, bottom: 10, trailing: 3))
.background(
Rectangle()
.fill(Color(slot.color)
.opacity(colorScheme == .dark ? 0.9 : 0.4))
)
.border(state.selectedIndex == index
? (colorScheme == .dark ? Color.white : Color.black)
: Color.clear)
.background(self.rectReader(index: index))
}
}
.background(
RoundedRectangle(cornerRadius: 5, style: .continuous)
.stroke(Color.gray, lineWidth: 1))
}
func rectReader(index: Int) -> some View {
return GeometryReader { (geometry) -> AnyView in
if geometry.frame(in: .global).contains(self.cursor) {
DispatchQueue.main.async {
state.selectedIndex = index
}
}
return AnyView(Rectangle().fill(Color.clear))
}
}
private func status(slot: Timeslot) -> String {
let timestamps = slot.observations.map({ $0.datetime })
let oldest = timestamps.min()!
let latest = timestamps.max()!
let oldestMinutes = Int(abs(oldest.timeIntervalSinceNow) / 60)
let latestMinutes = Int(abs(latest.timeIntervalSinceNow) / 60)
if oldest == latest || oldestMinutes >= 120 {
return since(minutes: latestMinutes)
} else if oldestMinutes < 60 {
return "\(latestMinutes)-\(since(minutes: oldestMinutes))"
} else {
return "\(since(minutes: latestMinutes))-\(since(minutes: oldestMinutes))"
}
}
private func since(minutes: Int) -> String {
let formatter = DateComponentsFormatter()
if minutes < 60*6 {
formatter.allowedUnits = [.hour, .minute]
} else {
formatter.allowedUnits = [.day, .hour]
}
formatter.unitsStyle = .brief
formatter.zeroFormattingBehavior = .dropLeading
return formatter.string(from: Double(minutes * 60))!
}
private func refreshStatus(slot: Timeslot?) {
guard let slot = slot else {
self.status = "No Data"
return
}
let status = status(slot: slot)
self.status = "\(status) ago"
self.statusColor = Color(ColorRamp.color(for: slot.date))
}
}
struct TimeslotDraverView_Previews: PreviewProvider {
static func state() -> TimeslotState {
let state = TimeslotState()
state.slots = [
Timeslot(date: Date(), observations: []),
Timeslot(date: Date().addMinutes(30), observations: [])
]
state.slots[0].color = UIColor.red
state.slots[1].color = UIColor.blue
state.selectedIndex = 0
return state
}
static var previews: some View {
ForEach(ColorScheme.allCases,
id: \.self,
content:
TimeslotDrawerView()
.environmentObject(state())
.background(Color(.secondarySystemGroupedBackground))
.preferredColorScheme
)
}
}
|
mit
|
d51bea16800c1d3d3787f29cdc655f82
| 31.011905 | 94 | 0.534585 | 4.738326 | false | false | false | false |
gregomni/swift
|
test/Concurrency/Backdeploy/weak_linking.swift
|
4
|
1351
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -target x86_64-apple-macosx12.0 -module-name main -emit-ir -o %t/new.ir
// RUN: %FileCheck %s --check-prefix=NEW < %t/new.ir
// RUN: %target-swift-frontend %s -target x86_64-apple-macosx10.15 -module-name main -emit-ir -o %t/old.ir -disable-availability-checking
// RUN: %FileCheck %s --check-prefix=OLD < %t/old.ir
// RUN: %target-swift-frontend %s -target x86_64-apple-macosx10.15 -O -module-name main -emit-ir -o %t/optimized.ir -disable-availability-checking
// RUN: %FileCheck %s --check-prefix=OPTIMIZED < %t/optimized.ir
// REQUIRES: OS=macosx
// NEW-NOT: extern_weak
// OLD: @"$sScPMn" = extern_weak global
// OLD: declare extern_weak swiftcc i8* @swift_task_alloc
// OLD: declare extern_weak swiftcc %swift.metadata_response @"$sScPMa"
// OLD: declare extern_weak swiftcc i8 @"$sScP8rawValues5UInt8Vvg"
// OPTIMIZED: @swift_async_extendedFramePointerFlags = extern_weak global i8*
// OPTIMIZED: @_swift_async_extendedFramePointerFlagsUser = linkonce_odr hidden global i8** @swift_async_extendedFramePointerFlags
// OPTIMIZED: @llvm.used =
// OPTIMIZED-SAME: (i8*** @_swift_async_extendedFramePointerFlagsUser to i8*)
@available(macOS 12.0, *)
public func g() async -> String { "hello" }
@available(macOS 12.0, *)
public func f() async {
Task {
print(await g())
}
}
|
apache-2.0
|
a5f83d2eed3ea32b77d40548454a3c7d
| 42.580645 | 146 | 0.710585 | 2.911638 | false | false | false | false |
slavapestov/swift
|
test/1_stdlib/PrintPointer.swift
|
2
|
1500
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
#if _runtime(_ObjC)
import ObjectiveC
#endif
let PrintTests = TestSuite("PrintPointer")
PrintTests.test("Printable") {
let nullUP = UnsafeMutablePointer<Float>()
let fourByteUP = UnsafeMutablePointer<Float>(bitPattern: 0xabcd1234 as UInt)
#if !(arch(i386) || arch(arm))
let eightByteAddr: UInt = 0xabcddcba12344321
let eightByteUP = UnsafeMutablePointer<Float>(bitPattern: eightByteAddr)
#endif
#if arch(i386) || arch(arm)
let expectedNull = "0x00000000"
expectPrinted("0xabcd1234", fourByteUP)
#else
let expectedNull = "0x0000000000000000"
expectPrinted("0x00000000abcd1234", fourByteUP)
expectPrinted("0xabcddcba12344321", eightByteUP)
#endif
expectPrinted(expectedNull, nullUP)
expectPrinted("UnsafeBufferPointer(start: \(expectedNull), length: 0)",
UnsafeBufferPointer(start: nullUP, count: 0))
expectPrinted("UnsafeMutableBufferPointer(start: \(expectedNull), length: 0)",
UnsafeMutableBufferPointer(start: nullUP, count: 0))
expectPrinted(expectedNull, COpaquePointer())
expectPrinted(expectedNull, CVaListPointer(_fromUnsafeMutablePointer: nullUP))
#if _runtime(_ObjC)
expectPrinted(expectedNull, AutoreleasingUnsafeMutablePointer<Int>())
#endif
}
runAllTests()
|
apache-2.0
|
79e41d404d33a1df09868845f24de239
| 31.608696 | 80 | 0.769333 | 4.132231 | false | true | false | false |
wess/Cargo
|
Sources/validation/rules/length.swift
|
2
|
475
|
import Foundation
public struct LengthValidationRule : ValidationRule {
public var error:ValidationError = .length
private let min:UInt
private let max:UInt
public var handler:ValidationHandler {
return { value in
guard let val = value else { return (false, self.error) }
return (validate(val, pattern: .length(self.min, self.max)), self.error)
}
}
public init(min:UInt = 1, max:UInt = 5000) {
self.min = min
self.max = max
}
}
|
mit
|
0d8fcbdcb882ad8d7bfa2c414a43c01d
| 21.619048 | 78 | 0.671579 | 3.830645 | false | false | false | false |
Witcast/witcast-ios
|
WiTcast/Library/FeedRefreshHeader.swift
|
1
|
1943
|
//
// FeedRefreshHeader.swift
// setscope-ios
//
// Created by Tanakorn Phoochaliaw on 7/12/2560 BE.
// Copyright © 2560 Tanakorn Phoochaliaw. All rights reserved.
//
import Foundation
import UIKit
import PullToRefreshKit
class FeedRefreshHeader:UIView,RefreshableHeader{
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
imageView.frame = CGRect(x: 0, y: 0, width: 27, height: 10)
imageView.center = CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0)
imageView.image = UIImage(named: "loading15")
addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - RefreshableHeader -
func heightForRefreshingState()->CGFloat{
return 50
}
func stateDidChanged(_ oldState: RefreshHeaderState, newState: RefreshHeaderState) {
if newState == .pulling{
UIView.animate(withDuration: 0.3, animations: {
self.imageView.transform = CGAffineTransform.identity
})
}
if newState == .idle{
UIView.animate(withDuration: 0.3, animations: {
self.imageView.transform = CGAffineTransform(translationX: 0, y: -50)
})
}
}
func didBeginRefreshingState(){
imageView.image = nil
let images = (0...29).map{return $0 < 10 ? "loading0\($0)" : "loading\($0)"}
imageView.animationImages = images.map{return UIImage(named:$0)!}
imageView.animationDuration = Double(images.count) * 0.04
imageView.startAnimating()
}
func didBeginEndRefershingAnimation(_ result:RefreshResult){}
func didCompleteEndRefershingAnimation(_ result:RefreshResult){
imageView.animationImages = nil
imageView.stopAnimating()
imageView.image = UIImage(named: "loading15")
}
}
|
apache-2.0
|
5a1a0f8872746cad971110849f271467
| 31.915254 | 88 | 0.641092 | 4.325167 | false | false | false | false |
bellots/usefulExtensions
|
UsefulExtensions/UINavigationItemExtensions.swift
|
1
|
674
|
//
// UINavigationItemExtensions.swift
// JoeBee
//
// Created by Andrea Bellotto on 14/11/16.
// Copyright © 2016 JoeBee Srl. All rights reserved.
//
import Foundation
import UIKit
extension UINavigationItem{
public func addDismissLeftButton(target:AnyObject, selector:Selector, image:UIImage, scale:CGFloat){
self.hidesBackButton = true
let originalImage = image
let scaledIcon = UIImage(cgImage: originalImage.cgImage!, scale: scale, orientation: originalImage.imageOrientation)
let leftItem = UIBarButtonItem(image: scaledIcon, style: .plain, target: target, action: selector)
self.leftBarButtonItem = leftItem
}
}
|
mit
|
4a0af0baa26ed6a8f62bf5bd66ed453d
| 32.65 | 124 | 0.729569 | 4.427632 | false | false | false | false |
SECH-Tag-EEXCESS-Browser/iOSX-App
|
SechQueryComposer/SechQueryComposer/JsonRecommendation.swift
|
1
|
1281
|
//
// JsonRecommendation.swift
// SechQueryComposer
//
// Copyright © 2015 Peter Stoehr. All rights reserved.
//
import Foundation
class JsonRecommendation {
private var pRecommendations : [EEXCESSRecommendation]?
var recommendations : [EEXCESSRecommendation]? {
get {
return pRecommendations
}
}
init? (data : NSData)
{
let jsonT = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as AnyObject
guard let json = jsonT else {
return nil
}
extractRecommendatins(json)
}
private func extractRecommendatins(json : AnyObject)
{
guard let jsonData = JSONData.fromObject(json) else
{
return
}
guard let allResults = jsonData["result"]?.array as [JSONData]! else
{
return
}
pRecommendations = []
for i in allResults
{
let u = (i["documentBadge"]?["uri"]?.string)!
let p = (i["documentBadge"]?["provider"]?.string)!
let t = (i["title"]?.string!)!
let newRecommendation = EEXCESSRecommendation(title: t, provider: p, uri: u)
pRecommendations?.append(newRecommendation)
}
}
}
|
mit
|
da830811816a07fece42648d1ae5a76c
| 24.62 | 95 | 0.567188 | 4.688645 | false | false | false | false |
fellipecaetano/Democracy-iOS
|
Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/MersenneTwister.swift
|
3
|
4648
|
//
// MersenneTwister.swift
// RandomKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// 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.
//
// Copyright (c) 2008-2017 Matt Gallagher (http://cocoawithlove.com). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
// FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH
// THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
/// A generator that uses the [Mersenne Twister][MT] algorithm.
///
/// [MT]: https://en.wikipedia.org/wiki/Mersenne_Twister
public struct MersenneTwister: RandomBytesGenerator, Seedable, SeedableFromRandomGenerator {
/// The number of `UInt64` values in a `_State`.
private static let _stateCount: Int = 312
/// A default global instance seeded with `DeviceRandom.default`.
public static var `default` = seeded
/// A default global instance that reseeds itself with `DeviceRandom.default`.
public static var defaultReseeding = reseeding
/// The internal state's type.
private typealias _State = _Array312<UInt64>
/// The internal state.
private var _state: _State = _zero312()
private var _index: Int
/// Creates an instance from `seed`.
public init(seed: UInt64) {
_index = MersenneTwister._stateCount
let state = _contents(of: &_state)
state[0] = seed
for i in 1 ..< MersenneTwister._stateCount {
state[i] = 6364136223846793005 &* (state[i &- 1] ^ (state[i &- 1] >> 62)) &+ UInt64(i)
}
}
/// Returns random `Bytes`.
public mutating func randomBytes() -> UInt64 {
let state = _contents(of: &_state)
if _index == MersenneTwister._stateCount {
let n = MersenneTwister._stateCount
let m = n / 2
let a: UInt64 = 0xB5026F5AA96619E9
let lowerMask: UInt64 = (1 << 31) - 1
let upperMask: UInt64 = ~lowerMask
var (i, j, stateM) = (0, m, state[m])
repeat {
let x1 = (state[i] & upperMask) | (state[i &+ 1] & lowerMask)
state[i] = state[i &+ m] ^ (x1 >> 1) ^ ((state[i &+ 1] & 1) &* a)
let x2 = (state[j] & upperMask) | (state[j &+ 1] & lowerMask)
state[j] = state[j &- m] ^ (x2 >> 1) ^ ((state[j &+ 1] & 1) &* a)
(i, j) = (i &+ 1, j &+ 1)
} while i != m &- 1
let x3 = (state[m &- 1] & upperMask) | (stateM & lowerMask)
state[m &- 1] = state[n &- 1] ^ (x3 >> 1) ^ ((stateM & 1) &* a)
let x4 = (state[n &- 1] & upperMask) | (state[0] & lowerMask)
state[n &- 1] = state[m &- 1] ^ (x4 >> 1) ^ ((state[0] & 1) &* a)
_index = 0
}
var result = state[_index]
_index = _index &+ 1
result ^= (result >> 29) & 0x5555555555555555
result ^= (result << 17) & 0x71D67FFFEDA60000
result ^= (result << 37) & 0xFFF7EEE000000000
result ^= result >> 43
return result
}
}
|
mit
|
4add1b586163a6087ab5ea51d98143dd
| 40.464286 | 98 | 0.628338 | 3.876461 | false | false | false | false |
gjiazhe/NipponColorsForIOS
|
NipponColors/NameLabel.swift
|
1
|
3031
|
//
// NameLabel.swift
// NipponColors
//
// Created by 郭佳哲 on 3/6/16.
// Copyright © 2016 郭佳哲. All rights reserved.
//
import UIKit
@IBDesignable
public class NameLabel: UIView {
@IBInspectable
var nameJA: String = ""
@IBInspectable
var nameEN: String = ""
let labelNameJA = UILabel()
let labelNameEN = UILabel()
public override func drawRect(rect: CGRect) {
drawNameJA()
drawNameEN()
}
func drawNameJA() {
labelNameJA.textColor = UIColor(white: 1.0, alpha: 0.7)
labelNameJA.numberOfLines = 0
updateNameJA()
self.addSubview(labelNameJA)
}
func drawNameEN() {
labelNameEN.textColor = UIColor(white: 1.0, alpha: 0.7)
labelNameEN.layer.bounds.size.width = self.layer.bounds.width
labelNameEN.adjustsFontSizeToFitWidth = true
labelNameEN.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
labelNameEN.textAlignment = NSTextAlignment.Center
updateNameEN()
self.addSubview(labelNameEN)
}
func updateNameJA() {
let fontSize: CGFloat = self.layer.bounds.width * 0.7
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = NSLineBreakMode.ByCharWrapping
let attributes: [String : AnyObject] = [NSFontAttributeName: UIFont(name: "Helvetica Neue", size: fontSize)!, NSParagraphStyleAttributeName: paragraphStyle]
let bound = nameJA.boundingRectWithSize(CGSizeMake(fontSize, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
labelNameJA.frame = CGRect(x: (self.layer.bounds.width-fontSize)/2, y: 0, width: bound.width, height: bound.height)
labelNameJA.attributedText = NSAttributedString(string: nameJA, attributes: attributes)
}
func updateNameEN() {
labelNameEN.text = nameEN
labelNameEN.layer.bounds.size.height = labelNameEN.font.pointSize
labelNameEN.layer.position = CGPoint(x: self.layer.bounds.size.width/2, y: labelNameJA.layer.bounds.height + 8)
}
public func updateName(nameEN nameEN: String, nameJA: String, animate:Bool, withDuration duration:CFTimeInterval) {
if animate {
UIView.animateWithDuration(duration, animations: { () -> Void in
self.labelNameEN.alpha = 0
self.labelNameJA.alpha = 0}) {(finish) -> Void in
self.nameEN = nameEN
self.nameJA = nameJA
self.updateNameJA()
self.updateNameEN()
UIView.animateWithDuration(duration, animations: { () -> Void in
self.labelNameEN.alpha = 0.7
self.labelNameJA.alpha = 0.7
})
}
} else {
self.nameEN = nameEN
self.nameJA = nameJA
updateNameJA()
updateNameEN()
}
}
}
|
apache-2.0
|
fd7bbb560a3312b5a709d658b04645a6
| 37.202532 | 176 | 0.612657 | 4.367583 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/TakeOrder/器械信息/Model/OIWhRelModel.swift
|
1
|
549
|
//
// OIWhRelModel.swift
// OMS-WH
//
// Created by xuech on 2017/10/19.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class OIWhRelModel: CommonPaseModel {
var isDefaultWarehouse : String = ""
//medMIWarehouse Code WH000004
var medMIWarehouse = ""
var oIName = ""
var oIOrgCode = ""
var relationDesc = ""
var wHName = ""
}
class InventoryModel: CommonPaseModel {
var inventory : NSNumber = 0
var medMIInternalNo = ""
var medMIWarehouse = ""
var oIOrgCode = ""
}
|
mit
|
89e4de5148b7677c3fb86d41751aae41
| 17.2 | 50 | 0.628205 | 3.25 | false | false | false | false |
willlarche/material-components-ios
|
components/Typography/examples/TypographyFontListExample.swift
|
2
|
4709
|
/*
Copyright 2016-present the Material Components for iOS authors. 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 MaterialComponents.MaterialTypography
// This example is primarily a visual example of the various Typography fonts. The code below is a
// standard UIKit table view configuration using Auto Layout for height calculation.
class TypographyFontListExampleViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorStyle = .none
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 50
}
override func numberOfSections(in tableView: UITableView) -> Int {
return strings.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fonts.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
}
cell!.textLabel!.text = strings[indexPath.section]
cell!.textLabel!.font = fonts[indexPath.row]
cell!.textLabel!.alpha = fontOpacities[indexPath.row]
cell!.textLabel!.numberOfLines = 0
cell!.textLabel!.lineBreakMode = .byWordWrapping
if cell!.textLabel!.font.pointSize > 100 && indexPath.section == 0 {
cell!.textLabel!.text = "MDC"
}
cell!.detailTextLabel!.text = fontStyleNames[indexPath.row]
cell!.detailTextLabel!.font = MDCTypography.captionFont()
cell!.detailTextLabel!.alpha = MDCTypography.captionFontOpacity()
cell!.selectionStyle = .none
return cell!
}
convenience init() {
self.init(style: .plain)
}
override init(style: UITableViewStyle) {
super.init(style: style)
self.title = "Font list"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let strings = [
"Material Design Components",
"A quick brown fox jumped over the lazy dog.",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"1234567890",
"!@#$%^&*()-=_+[]\\;',./<>?:\""
]
let fonts = [
// Common UI fonts.
MDCTypography.headlineFont(),
MDCTypography.titleFont(),
MDCTypography.subheadFont(),
MDCTypography.body2Font(),
MDCTypography.body1Font(),
MDCTypography.captionFont(),
MDCTypography.buttonFont(),
// Display fonts (extra large fonts)
MDCTypography.display1Font(),
MDCTypography.display2Font(),
MDCTypography.display3Font(),
MDCTypography.display4Font()
]
let fontOpacities = [
// Common UI fonts.
MDCTypography.headlineFontOpacity(),
MDCTypography.titleFontOpacity(),
MDCTypography.subheadFontOpacity(),
MDCTypography.body2FontOpacity(),
MDCTypography.body1FontOpacity(),
MDCTypography.captionFontOpacity(),
MDCTypography.buttonFontOpacity(),
// Display fonts (extra large fonts)
MDCTypography.display1FontOpacity(),
MDCTypography.display2FontOpacity(),
MDCTypography.display3FontOpacity(),
MDCTypography.display4FontOpacity()
]
let fontStyleNames = [
// Common UI fonts.
"Headline Font",
"Title Font",
"Subhead Font",
"Body 2 Font",
"Body 1 Font",
"Caption Font",
"Button Font",
// Display fonts (extra large fonts)
"Display 1 Font",
"Display 2 Font",
"Display 3 Font",
"Display 4 Font"
]
}
// MARK: - CatalogByConvention
extension TypographyFontListExampleViewController {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Typography and Fonts", "Typography"]
}
@objc class func catalogDescription() -> String {
return "The Typography component provides methods for displaying text using the type sizes and"
+ " opacities from the Material Design specifications."
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return true
}
}
|
apache-2.0
|
899a31b6ee56ba4d4fa953e90597276b
| 28.248447 | 99 | 0.708855 | 4.653162 | false | false | false | false |
zisko/swift
|
test/IRGen/dynamic_self_metadata.swift
|
1
|
2008
|
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil %s -emit-ir -parse-as-library | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: Not a SIL test because we can't parse dynamic Self in SIL.
// <rdar://problem/16931299>
// CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }>
@inline(never) func id<T>(_ t: T) -> T {
return t
}
// CHECK-LABEL: define hidden swiftcc void @"$S21dynamic_self_metadata2idyxxlF"
class C {
class func fromMetatype() -> Self? { return nil }
// CHECK-LABEL: define hidden swiftcc i64 @"$S21dynamic_self_metadata1CC12fromMetatypeACXDSgyFZ"(%swift.type* swiftself)
// CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8
// CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: store i64 0, i64* [[CAST1]], align 8
// CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8
// CHECK: ret i64 [[LOAD]]
func fromInstance() -> Self? { return nil }
// CHECK-LABEL: define hidden swiftcc i64 @"$S21dynamic_self_metadata1CC12fromInstanceACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself)
// CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8
// CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: store i64 0, i64* [[CAST1]], align 8
// CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8
// CHECK: ret i64 [[LOAD]]
func dynamicSelfArgument() -> Self? {
return id(nil)
}
// CHECK-LABEL: define hidden swiftcc i64 @"$S21dynamic_self_metadata1CC0A12SelfArgumentACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself)
// CHECK: [[CAST1:%.+]] = bitcast %T21dynamic_self_metadata1CC* %0 to [[METATYPE:%.+]]
// CHECK: [[TYPE1:%.+]] = call %swift.type* @swift_getObjectType([[METATYPE]] [[CAST1]])
// CHECK: [[TYPE2:%.+]] = call %swift.type* @"$SSqMa"(%swift.type* [[TYPE1]])
// CHECK: call swiftcc void @"$S21dynamic_self_metadata2idyxxlF"({{.*}}, %swift.type* [[TYPE2]])
}
|
apache-2.0
|
c22a47835fa8f3cb2dbec39ef60138d4
| 46.809524 | 140 | 0.625498 | 3.243942 | false | false | false | false |
dvaughn1712/perfect-routing
|
PerfectServer/main.swift
|
2
|
573
|
//
// main.swift
// PerfectServer
//
// Created by Kyle Jessup on 2015-10-23.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
try startServer()
|
unlicense
|
e35238fe456441822371c471fdef6053
| 26.285714 | 80 | 0.502618 | 4.815126 | false | false | false | false |
benlangmuir/swift
|
test/AutoDiff/SILOptimizer/Inputs/nontrivial_loadable_type.swift
|
21
|
1632
|
import _Differentiation
/// A non-trivial, loadable type.
///
/// Used to test differentiation transform coverage.
struct NontrivialLoadable<T> {
fileprivate class Box {
fileprivate var value: T
init(_ value: T) {
self.value = value
}
}
private var handle: Box
init(_ value: T) {
self.handle = Box(value)
}
var value: T {
get { handle.value }
set { handle.value = newValue }
}
}
extension NontrivialLoadable: ExpressibleByFloatLiteral
where T: ExpressibleByFloatLiteral {
init(floatLiteral value: T.FloatLiteralType) {
self.handle = Box(T(floatLiteral: value))
}
}
extension NontrivialLoadable: ExpressibleByIntegerLiteral
where T: ExpressibleByIntegerLiteral {
init(integerLiteral value: T.IntegerLiteralType) {
self.handle = Box(T(integerLiteral: value))
}
}
extension NontrivialLoadable: Equatable where T: Equatable {
static func == (lhs: NontrivialLoadable, rhs: NontrivialLoadable) -> Bool {
return lhs.value == rhs.value
}
}
extension NontrivialLoadable: AdditiveArithmetic where T: AdditiveArithmetic {
static var zero: NontrivialLoadable { return NontrivialLoadable(T.zero) }
static func + (lhs: NontrivialLoadable, rhs: NontrivialLoadable)
-> NontrivialLoadable
{
return NontrivialLoadable(lhs.value + rhs.value)
}
static func - (lhs: NontrivialLoadable, rhs: NontrivialLoadable)
-> NontrivialLoadable
{
return NontrivialLoadable(lhs.value - rhs.value)
}
}
extension NontrivialLoadable: Differentiable
where T: Differentiable, T == T.TangentVector {
typealias TangentVector = NontrivialLoadable<T.TangentVector>
}
|
apache-2.0
|
4ba6105909cdaa6e563a1b5c2fbaa33e
| 25.322581 | 78 | 0.727941 | 4.58427 | false | false | false | false |
Witcast/witcast-ios
|
WiTcast/ViewController/MainEP/MainEPListView/MainEPViewController.swift
|
1
|
4696
|
//
// MainEPViewController.swift
// WiTcast
//
// Created by Tanakorn Phoochaliaw on 7/17/16.
// Copyright © 2016 Tanakorn Phoochaliaw. All rights reserved.
//
import UIKit
import SwiftyJSON
import RealmSwift
import Kingfisher
class MainEPViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var mainTable: UITableView!
let realm = try! Realm()
var lists : Results<MainEpisode>!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = Color.white
prepareToolbar()
NotificationCenter.default.addObserver(self, selector: #selector(MainEPViewController.loadMain(_:)),name:NSNotification.Name(rawValue: "load_main"), object: nil)
lists = realm.objects(MainEpisode.self)
self.mainTable.register(UINib(nibName: "MainEPTableViewCell", bundle: nil), forCellReuseIdentifier: "MainEPTableViewCell");
self.mainTable.separatorStyle = UITableViewCellSeparatorStyle.none;
self.mainTable.register(UINib(nibName: "MainEPHeaderTableViewCell", bundle: nil), forCellReuseIdentifier: "MainEPHeaderTableViewCell");
let colorView = UIView();
colorView.backgroundColor = UIColor.clear;
UITableViewCell.appearance().selectedBackgroundView = colorView;
if UIScreen.main.bounds.width == 414 {
self.mainTable.rowHeight = 211.0
}
else if UIScreen.main.bounds.width == 375 {
self.mainTable.rowHeight = 198.0
}
self.mainTable.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (UIScreen.main.bounds.size.height - 129))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadMain(_ notification: NSNotification){
lists = realm.objects(MainEpisode.self)
self.mainTable.reloadData();
}
// MARK: Table view processing
func numberOfSections(in tableView: UITableView) -> Int {
return lists.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainEPTableViewCell", for: indexPath as IndexPath) as! MainEPTableViewCell
cell.lblDetail.font = UIFont(name: font_regular, size: cell.lblDetail.font.pointSize);
cell.lblDetail.text = "\(lists[indexPath.section].dsc)";
let URLString = lists[indexPath.section].imageUrl;
let url = URL(string: URLString)!
cell.imgBackgroud.kf.setImage(with: url)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = ItemMainEpViewController(nibName: "ItemMainEpViewController", bundle: nil);
vc.titleString = lists[indexPath.section].title;
vc.epID = lists[indexPath.section].mainEpisodeId;
let itemNav = ItemMainEpToolbarController(rootViewController: vc)
navigationController?.pushViewController(itemNav, animated: true);
tableView.deselectRow(at: indexPath as IndexPath, animated: true);
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "MainEPHeaderTableViewCell") as! MainEPHeaderTableViewCell
headerCell.lblEpTitle.font = UIFont(name: font_header_regular, size: headerCell.lblEpTitle.font.pointSize);
headerCell.lblItemCount.font = UIFont(name: font_header_regular, size: headerCell.lblItemCount.font.pointSize);
headerCell.lblEpTitle.text = "\(lists[section].title)";
headerCell.lblItemCount.text = "\(lists[section].subEpisodeCount) Part";
return headerCell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60.0;
}
}
extension MainEPViewController {
fileprivate func prepareToolbar() {
guard let toolbar = toolbarController?.toolbar else {
return
}
toolbar.title = "WiTcast"
toolbar.titleLabel.textColor = .black
toolbar.titleLabel.textAlignment = .center
toolbar.titleLabel.font = UIFont(name: font_header_regular, size: 28);
}
}
|
apache-2.0
|
1c0829c327db5e5e169b8a9a1b69cec9
| 36.862903 | 169 | 0.67114 | 4.865285 | false | false | false | false |
tardieu/swift
|
stdlib/public/core/LifetimeManager.swift
|
6
|
6254
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluate `f()` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluate `f(x)` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
extension String {
/// Invokes the given closure on the contents of the string, represented as a
/// pointer to a null-terminated sequence of UTF-8 code units.
///
/// The `withCString(_:)` method ensures that the sequence's lifetime extends
/// through the execution of `body`. The pointer argument to `body` is only
/// valid for the lifetime of the closure. Do not escape it from the closure
/// for later use.
///
/// - Parameter body: A closure that takes a pointer to the string's UTF-8
/// code unit sequence as its sole argument. If the closure has a return
/// value, it is used as the return value of the `withCString(_:)` method.
/// The pointer argument is valid only for the duration of the closure's
/// execution.
/// - Returns: The return value of the `body` closure, if any.
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.utf8CString.withUnsafeBufferPointer {
try body($0.baseAddress!)
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Invokes the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a mutable pointer to `arg` as its sole
/// argument. If the closure has a return value, it is used as the return
/// value of the `withUnsafeMutablePointer(to:_:)` function. The pointer
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafePointer(to:_:)`
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in/out parameters (and default-constructible out
/// parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `arg` as its sole argument. If
/// the closure has a return value, it is used as the return value of the
/// `withUnsafePointer(to:_:)` function. The pointer argument is valid
/// only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafeMutablePointer(to:_:)`
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
@available(*, unavailable, renamed: "withUnsafeMutablePointer(to:_:)")
public func withUnsafeMutablePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, renamed: "withUnsafePointer(to:_:)")
public func withUnsafePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
|
apache-2.0
|
e11f013d8bd1ae22ed6143e99f4f1198
| 34.134831 | 88 | 0.676847 | 4.079583 | false | false | false | false |
SawyerHood/mal
|
swift3/Sources/printer.swift
|
1
|
1784
|
func pr_str(_ obj: MalVal, _ print_readably: Bool = true) -> String {
switch obj {
case MalVal.MalList(let lst, _):
let elems = lst.map { pr_str($0, print_readably) }
return "(" + elems.joined(separator: " ") + ")"
case MalVal.MalVector(let lst, _):
let elems = lst.map { pr_str($0, print_readably) }
return "[" + elems.joined(separator: " ") + "]"
case MalVal.MalHashMap(let dict, _):
let elems = dict.map {
pr_str(MalVal.MalString($0), print_readably) +
" " + pr_str($1, print_readably)
}
return "{" + elems.joined(separator: " ") + "}"
case MalVal.MalString(let str):
//print("kw: '\(str[str.startIndex])'")
if str.characters.count > 0 && str[str.startIndex] == "\u{029e}" {
return ":" + str[str.index(after: str.startIndex)..<str.endIndex]
} else if print_readably {
let s1 = str.replacingOccurrences(of: "\\", with: "\\\\")
let s2 = s1.replacingOccurrences(of: "\"", with: "\\\"")
let s3 = s2.replacingOccurrences(of: "\n", with: "\\n")
return "\"" + s3 + "\""
} else {
return str
}
case MalVal.MalSymbol(let str):
return str
case MalVal.MalInt(let i): return String(i)
case MalVal.MalNil: return "nil"
case MalVal.MalFalse: return "false"
case MalVal.MalTrue: return "true"
case MalVal.MalFunc(_, nil, _, _, _, _):
return "#<native function>"
case MalVal.MalFunc(_, let ast, _, let params, _, _):
return "(fn* \(pr_str(params![0])) \(pr_str(ast![0])))"
case MalVal.MalAtom(let ma):
return "(atom \(pr_str(ma.val, print_readably)))"
default:
return String(obj)
}
}
|
mpl-2.0
|
df3c5012bcf922ff24cd3f1f242847c6
| 40.488372 | 77 | 0.529709 | 3.640816 | false | false | false | false |
vapor/node
|
Sources/Node/Core/Node.swift
|
1
|
991
|
public struct Node: StructuredDataWrapper {
public static let defaultContext = emptyContext
public var wrapped: StructuredData
public var context: Context
public init(_ wrapped: StructuredData, in context: Context?) {
self.wrapped = wrapped
self.context = context ?? emptyContext
}
}
extension Node: FuzzyConverter {
public static func represent<T>(_ any: T, in context: Context) throws -> Node? {
guard let r = any as? NodeRepresentable else {
return nil
}
return try r.makeNode(in: context)
}
public static func initialize<T>(node: Node) throws -> T? {
guard let type = T.self as? NodeInitializable.Type else {
return nil
}
return try type.init(node: node) as? T
}
}
extension Node: NodeConvertible {
public init(node: Node) {
self = node
}
public func makeNode(in context: Context?) -> Node {
return self
}
}
|
mit
|
12da5b248cb10358530781d6dfcbe2d2
| 25.078947 | 84 | 0.610494 | 4.504545 | false | false | false | false |
FTChinese/iPhoneApp
|
Pods/FolioReaderKit/Source/ScrollScrubber.swift
|
1
|
6627
|
//
// ScrollScrubber.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 7/14/16.
// Copyright © 2016 FolioReader. All rights reserved.
//
import UIKit
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
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
enum ScrollDirection: Int {
case none
case right
case left
case up
case down
init() {
self = .none
}
}
class ScrollScrubber: NSObject, UIScrollViewDelegate {
weak var delegate: FolioReaderCenter!
var showSpeed = 0.6
var hideSpeed = 0.6
var hideDelay = 1.0
var visible = false
var usingSlider = false
var slider: UISlider!
var hideTimer: Timer!
var scrollStart: CGFloat!
var scrollDelta: CGFloat!
var scrollDeltaTimer: Timer!
var frame: CGRect! {
didSet {
self.slider.frame = frame
}
}
init(frame:CGRect) {
super.init()
slider = UISlider()
slider.layer.anchorPoint = CGPoint(x: 0, y: 0)
slider.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
slider.alpha = 0
self.frame = frame
reloadColors()
// less obtrusive knob and fixes jump: http://stackoverflow.com/a/22301039/484780
let thumbImg = UIImage(readerImageNamed: "knob")
let thumbImgColor = thumbImg!.imageTintColor(readerConfig.tintColor).withRenderingMode(.alwaysOriginal)
slider.setThumbImage(thumbImgColor, for: UIControlState())
slider.setThumbImage(thumbImgColor, for: .selected)
slider.setThumbImage(thumbImgColor, for: .highlighted)
slider.addTarget(self, action: #selector(ScrollScrubber.sliderChange(_:)), for: .valueChanged)
slider.addTarget(self, action: #selector(ScrollScrubber.sliderTouchDown(_:)), for: .touchDown)
slider.addTarget(self, action: #selector(ScrollScrubber.sliderTouchUp(_:)), for: .touchUpInside)
slider.addTarget(self, action: #selector(ScrollScrubber.sliderTouchUp(_:)), for: .touchUpOutside)
}
func reloadColors() {
slider.minimumTrackTintColor = readerConfig.tintColor
slider.maximumTrackTintColor = isNight(readerConfig.nightModeSeparatorColor, readerConfig.menuSeparatorColor)
}
// MARK: - slider events
func sliderTouchDown(_ slider:UISlider) {
usingSlider = true
show()
}
func sliderTouchUp(_ slider:UISlider) {
usingSlider = false
hideAfterDelay()
}
func sliderChange(_ slider:UISlider) {
let movePosition = height()*CGFloat(slider.value)
let offset = isDirection(CGPoint(x: 0, y: movePosition), CGPoint(x: movePosition, y: 0))
scrollView().setContentOffset(offset, animated: false)
}
// MARK: - show / hide
func show() {
cancelHide()
visible = true
if slider.alpha <= 0 {
UIView.animate(withDuration: showSpeed, animations: {
self.slider.alpha = 1
}, completion: { (Bool) -> Void in
self.hideAfterDelay()
})
} else {
slider.alpha = 1
if usingSlider == false {
hideAfterDelay()
}
}
}
func hide() {
visible = false
resetScrollDelta()
UIView.animate(withDuration: hideSpeed, animations: {
self.slider.alpha = 0
})
}
func hideAfterDelay() {
cancelHide()
hideTimer = Timer.scheduledTimer(timeInterval: hideDelay, target: self, selector: #selector(ScrollScrubber.hide), userInfo: nil, repeats: false)
}
func cancelHide() {
if hideTimer != nil {
hideTimer.invalidate()
hideTimer = nil
}
if visible == false {
slider.layer.removeAllAnimations()
}
visible = true
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if scrollDeltaTimer != nil {
scrollDeltaTimer.invalidate()
scrollDeltaTimer = nil
}
if scrollStart == nil {
scrollStart = scrollView.contentOffset.forDirection()
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard readerConfig.scrollDirection == .vertical || readerConfig.scrollDirection == .defaultVertical || readerConfig.scrollDirection == .horizontalWithVerticalContent else {
return
}
if visible && usingSlider == false {
setSliderVal()
}
if( slider.alpha > 0 ){
show()
} else if delegate.currentPage != nil && scrollStart != nil {
scrollDelta = scrollView.contentOffset.forDirection() - scrollStart
if scrollDeltaTimer == nil && scrollDelta > (pageHeight * 0.2 ) || (scrollDelta * -1) > (pageHeight * 0.2) {
show()
resetScrollDelta()
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
resetScrollDelta()
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
scrollDeltaTimer = Timer(timeInterval:0.5, target: self, selector: #selector(ScrollScrubber.resetScrollDelta), userInfo: nil, repeats: false)
RunLoop.current.add(scrollDeltaTimer, forMode: RunLoopMode.commonModes)
}
func resetScrollDelta() {
if scrollDeltaTimer != nil {
scrollDeltaTimer.invalidate()
scrollDeltaTimer = nil
}
scrollStart = scrollView().contentOffset.forDirection()
scrollDelta = 0
}
func setSliderVal() {
slider.value = Float(scrollTop() / height())
}
// MARK: - utility methods
fileprivate func scrollView() -> UIScrollView {
return delegate.currentPage!.webView.scrollView
}
fileprivate func height() -> CGFloat {
return delegate.currentPage!.webView.scrollView.contentSize.height - pageHeight + 44
}
fileprivate func scrollTop() -> CGFloat {
return delegate.currentPage!.webView.scrollView.contentOffset.forDirection()
}
}
|
mit
|
fb2dfde68cf51d04ba71178816333eae
| 27.076271 | 180 | 0.589194 | 4.84711 | false | false | false | false |
calkinssean/TIY-Assignments
|
Day 23/SpotifyAPI 2/Artist.swift
|
1
|
1945
|
//
// Artist.swift
// SpotifyAPI
//
// Created by Sean Calkins on 2/29/16.
// Copyright © 2016 Dape App Productions LLC. All rights reserved.
//
import Foundation
// NSCoding Constants
let kArtistIdString = "idString"
let kArtistName = "name"
let kArtistImageUrls = "imageUrls"
let kArtistAlbums = "alubms"
class Artist: NSObject, NSCoding {
var idString: String = ""
var name: String = ""
var imageUrls: [String] = [""]
var albums = [Album]()
override init() {
}
init(dict: JSONDictionary) {
if let idString = dict["id"] as? String {
self.idString = idString
} else {
print("couldn't parse artist id")
}
if let name = dict["name"] as? String {
self.name = name
} else {
print("couldn't parse artist name")
}
if let items = dict["images"] as? JSONArray {
for item in items {
if let imageUrl = item["url"] as? String {
self.imageUrls.append(imageUrl)
} else {
print("error with artist image url")
}
}
print(imageUrls.count)
}
}
required init?(coder aDecoder: NSCoder) {
self.idString = aDecoder.decodeObjectForKey(kArtistIdString) as! String
self.name = aDecoder.decodeObjectForKey(kArtistName) as! String
self.imageUrls = aDecoder.decodeObjectForKey(kArtistImageUrls) as! [String]
self.albums = aDecoder.decodeObjectForKey(kArtistAlbums) as! [Album]
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(idString, forKey: kArtistIdString)
aCoder.encodeObject(name, forKey: kArtistName)
aCoder.encodeObject(imageUrls, forKey: kArtistImageUrls)
aCoder.encodeObject(albums, forKey: kArtistAlbums)
}
}
|
cc0-1.0
|
89b7839a785b1558b067889531da6723
| 27.602941 | 83 | 0.580247 | 4.388262 | false | false | false | false |
bradleymackey/WWDC-2017
|
EmojiSort.playground/Sources/ContainerView.swift
|
1
|
1333
|
import Foundation
import UIKit
public final class ContainerView: UIView {
// MARK: Properties
private var teacherView:TeacherView
private var optionView:OptionView
private var sortingView:EmojiSortView
// MARK: Init
public init(emojiToSort: [Emoji], teacher: EmojiTeacher) {
let frame = CGRect(x: 0, y: 0, width: 600, height: 350)
let teachRect = CGRect(x: 0, y: 0, width: frame.width/2, height: frame.height/2)
teacherView = TeacherView(frame: teachRect, teacher: teacher)
let optionRect = CGRect(x: frame.width/2, y: 0, width: frame.width/2, height: frame.height/2)
optionView = OptionView(frame: optionRect)
let sortingRect = CGRect(x: 0, y: frame.height/2, width: frame.width, height: frame.height/2)
sortingView = EmojiSortView(frame: sortingRect, emojis: emojiToSort.shuffled())
// set delegates to enable communication between views
optionView.sortDelegate = sortingView
optionView.teacherDelegate = teacherView
sortingView.delegate = optionView
teacherView.sortViewDelegate = sortingView
teacherView.optionsDelegate = optionView
super.init(frame: frame)
self.addSubview(teacherView)
self.addSubview(optionView)
self.addSubview(sortingView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
9f349fd7fa2b7f39f2ec6be2cded561b
| 27.978261 | 95 | 0.741935 | 3.564171 | false | false | false | false |
roshkadev/Form
|
Form/Classes/Button.swift
|
1
|
2829
|
//
// Button.swift
// Pods
//
// Created by Paul Von Schrottky on 4/23/17.
//
//
import UIKit
/// An `ButtonEvent` is a user-interaction driven event associated with an `ButtonEvent`.
public enum ButtonEvent {
case tap // User taps button.
case submit // Same as `tap`, but transmits intent of submission to form.
case formOnChange // The containing `Form` received a `FormEvent.onChange` event.
case formOnSubmit // The containing `Form` received a `FormEvent.onSubmit` event.
}
final public class Button: NSObject, Field {
// #MARK - Field
public var form: Form!
public var row: Row!
public var view: FieldView
public var contentView: UIView
public var stackView: UIStackView
public var title: String?
public var label: FieldLabel?
public var key: String?
public var value: Any?
public var padding = Space.default
public var button: UIButton
public var formBindings = [(event: FormEvent, field: Field, handler: ((Field) -> Void))]()
public var handlers = [(event: ButtonEvent, handler: ((Button) -> Void))]()
public override init() {
view = FieldView()
stackView = UIStackView()
if let title = title {
label = FieldLabel()
label?.text = title
}
button = UIButton()
contentView = button
super.init()
setupStackView()
button.heightAnchor.constraint(equalToConstant: 44).isActive = true
button.addTarget(self, action: #selector(action), for: .touchUpInside)
}
func action(button: UIButton) {
// Fire any tap-related handlers for this button.
handlers.filter { $0.event == .tap || $0.event == .submit }.forEach { $0.handler(self) }
}
public func didChangeContentSizeCategory() {
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body)
}
@discardableResult
public func title(_ text: String?) -> Self {
button.setTitle(text, for: .normal)
return self
}
@discardableResult
public func style(_ style: ((Button) -> Void)) -> Self {
style(self)
return self
}
@discardableResult
public func bind(_ event: ButtonEvent, handler: @escaping ((Button) -> Void)) -> Self {
switch event {
case .tap:
handlers.append((event, handler))
case .submit:
handlers.append((event, handler))
case .formOnChange:
formBindings.append((.onChange, self, { field in
handler(self)
}))
case .formOnSubmit:
formBindings.append((.onSubmit, self, { field in
handler(self)
}))
}
return self
}
}
|
mit
|
691de25c1a17e9295eba056def310a53
| 28.46875 | 96 | 0.58784 | 4.469194 | false | false | false | false |
TTVS/NightOut
|
Clubber/ActivityModel.swift
|
1
|
741
|
//
// ActivityModel.swift
// Clubber
//
// Created by Terra on 9/14/15.
// Copyright (c) 2015 Dino Media Asia. All rights reserved.
//
import Foundation
import UIKit
class ActivityModel {
var userImage: UIImage
var comment: String
var commentImage: UIImage
init(usersImage: String, comments: String, commentsImage: String) {
if let img1 = UIImage(named: usersImage) {
userImage = img1
} else {
userImage = UIImage(named: "A")!
}
self.comment = comments
if let img2 = UIImage(named: commentsImage) {
commentImage = img2
} else {
commentImage = UIImage(named: "A")!
}
}
}
|
apache-2.0
|
65ff3344006347ddc46d9143f399e2e1
| 20.2 | 71 | 0.557355 | 4.258621 | false | false | false | false |
Hout/Period
|
Pod/Classes/PeriodComparisons.swift
|
1
|
1678
|
//
// PeriodComparable.swift
// Pods
//
// Created by Jeroen Houtzager on 09/11/15.
//
//
extension Period: Comparable {}
// MARK: - Protocol Comparable
//
/// Implements "less than" comparisons for periods.
///
/// - Parameters:
/// - lperiod: the left hand period
/// - rperiod: the right hand period
///
/// - Returns: `true` if `lperiod` is earlier than `rperiod` without overlap.
///
public func <(lperiod: Period, rperiod: Period) -> Bool {
return lperiod.endDate.compare(rperiod.startDate) == .OrderedAscending
}
/// Implements "greater than" comparisons for periods.
///
/// - Parameters:
/// - lperiod: the left hand period
/// - rperiod: the right hand period
///
/// - Returns: `true` if `lperiod` is later than `rperiod` without overlap.
///
public func >(lperiod: Period, rperiod: Period) -> Bool {
return lperiod.startDate.compare(rperiod.endDate) == .OrderedDescending
}
/// Implements "greater than or equal" comparisons for periods.
///
/// - Parameters:
/// - lperiod: the left hand period
/// - rperiod: the right hand period
///
/// - Returns: `true` if `lperiod` starts later than `rperiod` does.
///
public func >=(lperiod: Period, rperiod: Period) -> Bool {
return lperiod.startDate.compare(rperiod.startDate) != .OrderedAscending
}
/// Implements "less than or equal" comparisons for periods.
///
/// - Parameters:
/// - lperiod: the left hand period
/// - rperiod: the right hand period
///
/// - Returns: `true` if `lperiod` ends earlier than `rperiod` does.
///
public func <=(lperiod: Period, rperiod: Period) -> Bool {
return lperiod.endDate.compare(rperiod.endDate) != .OrderedDescending
}
|
mit
|
9ad25fedfc9818cad549b6b42461037d
| 26.508197 | 77 | 0.662694 | 3.577825 | false | false | false | false |
vector-im/vector-ios
|
Riot/Managers/Call/PiPAnimator.swift
|
1
|
5262
|
//
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
@objc enum PiPAnimationType: Int {
case enter
case exit
}
@objcMembers
class PiPAnimator: NSObject {
private enum Constants {
static let pipViewSize: CGSize = CGSize(width: 90, height: 130)
}
let animationDuration: TimeInterval
let animationType: PiPAnimationType
weak var pipViewDelegate: PiPViewDelegate?
init(animationDuration: TimeInterval,
animationType: PiPAnimationType,
pipViewDelegate: PiPViewDelegate?) {
self.animationDuration = animationDuration
self.animationType = animationType
self.pipViewDelegate = pipViewDelegate
super.init()
}
private func enterAnimation(context: UIViewControllerContextTransitioning) {
guard let keyWindow = UIApplication.shared.keyWindow else {
context.completeTransition(false)
return
}
guard let fromVC = context.viewController(forKey: .from) else {
context.completeTransition(false)
return
}
if let pipable = fromVC as? PictureInPicturable {
pipable.willEnterPiP?()
}
fromVC.willMove(toParent: nil)
// TODO: find a way to call this at the end of animation
context.completeTransition(true)
fromVC.removeFromParent()
let pipView = PiPView(frame: fromVC.view.bounds)
pipView.contentView = fromVC.view
pipView.delegate = pipViewDelegate
keyWindow.addSubview(pipView)
let scale = Constants.pipViewSize.width/pipView.frame.width
let transform = CGAffineTransform(scaleX: scale, y: scale)
let targetSize = Constants.pipViewSize
pipView.cornerRadius = pipView.cornerRadius / scale
let animator = UIViewPropertyAnimator(duration: animationDuration, dampingRatio: 1) {
pipView.transform = transform
pipView.move(in: keyWindow,
targetSize: targetSize)
}
animator.addCompletion { (position) in
if let pipable = fromVC as? PictureInPicturable {
pipable.didEnterPiP?()
}
fromVC.dismiss(animated: false, completion: nil)
}
animator.startAnimation()
}
private func exitAnimation(context: UIViewControllerContextTransitioning) {
guard let keyWindow = UIApplication.shared.keyWindow else {
context.completeTransition(false)
return
}
guard let toVC = context.viewController(forKey: .to) else {
context.completeTransition(false)
return
}
if let pipable = toVC as? PictureInPicturable {
pipable.willExitPiP?()
}
guard let snapshot = toVC.view.snapshotView(afterScreenUpdates: true) else {
context.completeTransition(false)
return
}
guard let pipView = toVC.view.superview as? PiPView else {
return
}
context.containerView.addSubview(toVC.view)
context.containerView.addSubview(snapshot)
toVC.view.isHidden = true
toVC.additionalSafeAreaInsets = keyWindow.safeAreaInsets
pipView.contentView = nil
pipView.removeFromSuperview()
snapshot.frame = pipView.frame
let animator = UIViewPropertyAnimator(duration: animationDuration, dampingRatio: 1) {
snapshot.frame = context.finalFrame(for: toVC)
}
animator.addCompletion { (position) in
toVC.additionalSafeAreaInsets = .zero
toVC.view.frame = context.finalFrame(for: toVC)
toVC.view.isHidden = false
snapshot.removeFromSuperview()
if let pipable = toVC as? PictureInPicturable {
pipable.didExitPiP?()
}
context.completeTransition(!context.transitionWasCancelled)
}
animator.startAnimation()
}
}
extension PiPAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch animationType {
case .enter:
enterAnimation(context: transitionContext)
case .exit:
exitAnimation(context: transitionContext)
}
}
}
|
apache-2.0
|
8ca5cf040fe9556f2f6b55bca92a2e9e
| 31.282209 | 109 | 0.628278 | 5.509948 | false | false | false | false |
yonekawa/SwiftFlux
|
SwiftFluxTests/Utils/ReduceStoreSpec.swift
|
1
|
2279
|
//
// ReduceStoreSpec.swift
// SwiftFlux
//
// Created by Kenichi Yonekawa on 11/18/15.
// Copyright © 2015 mog2dev. All rights reserved.
//
import Quick
import Nimble
import Result
import SwiftFlux
class ReduceStoreSpec: QuickSpec {
struct CalculateActions {
struct Plus: Action {
typealias Payload = Int
let number: Int
func invoke(dispatcher: Dispatcher) {
dispatcher.dispatch(self, result: Result(value: number))
}
}
struct Minus: Action {
typealias Payload = Int
let number: Int
func invoke(dispatcher: Dispatcher) {
dispatcher.dispatch(self, result: Result(value: number))
}
}
}
class CalculateStore: ReduceStore<Int> {
init() {
super.init(initialState: 0)
self.reduce(CalculateActions.Plus.self) { (state, result) -> Int in
switch result {
case .Success(let number): return state + number
default: return state
}
}
self.reduce(CalculateActions.Minus.self) { (state, result) -> Int in
switch result {
case .Success(let number): return state - number
default: return state
}
}
}
}
override func spec() {
let store = CalculateStore()
var results = [Int]()
beforeEach { () -> () in
results = []
store.subscribe { () -> () in
results.append(store.state)
}
}
afterEach({ () -> () in
store.unregister()
})
it("should calculate state with number") {
ActionCreator.invoke(CalculateActions.Plus(number: 3))
ActionCreator.invoke(CalculateActions.Plus(number: 3))
ActionCreator.invoke(CalculateActions.Minus(number: 2))
ActionCreator.invoke(CalculateActions.Minus(number: 1))
expect(results.count).to(equal(4))
expect(results[0]).to(equal(3))
expect(results[1]).to(equal(6))
expect(results[2]).to(equal(4))
expect(results[3]).to(equal(3))
}
}
}
|
mit
|
fedcf87ea6458f70ad195fd09ddf7cf0
| 27.475 | 80 | 0.528973 | 4.630081 | false | false | false | false |
WalletOne/P2P
|
P2PCore/Models/Deal.swift
|
1
|
3039
|
//
// Deal.swift
// P2P_iOS
//
// Created by Vitaliy Kuzmenko on 17/07/2017.
// Copyright © 2017 Wallet One. All rights reserved.
//
import Foundation
extension String {
var uppercaseFirst: String {
let first = String(prefix(1)).capitalized
let other = String(dropFirst())
return first + other
}
}
public let DealStateIdCreated = "Created"
public let DealStateIdPaymentProcessing = "PaymentProcessing"
public let DealStateIdPaymentHold = "PaymentHold"
public let DealStateIdPaymentProcessError = "PaymentProcessError"
public let DealStateIdPaid = "Paid"
public let DealStateIdPayoutProcessing = "PayoutProcessing"
public let DealStateIdPayoutProcessError = "PayoutProcessError"
public let DealStateIdCompleted = "Completed"
public let DealStateIdCanceling = "Canceling"
public let DealStateIdCancelError = "CancelError"
public let DealStateIdCanceled = "Canceled"
public let DealTypeIdDeferred = "Deferred"
public let DealTypeIdInstant = "Instant"
extension Array where Element: Deal {
public var platformDealIds: [String] { return map({ $0.platformDealId }) }
}
@objc public class Deal: NSObject, Mappable {
public var platformDealId: String = ""
public var dealStateId: String = ""
public var createDate: Date?
public var updatedate: Date?
public var expireDate: Date?
public var amount: NSDecimalNumber = 0.0
public var currencyId: CurrencyId = .rub
public var payerCommissionAmount: NSDecimalNumber = 0.0
public var platformBonusAmount: NSDecimalNumber = 0.0
public var platformPayerId: String = ""
public var payerPaymentToolId: Int = 0
public var payerPhoneNumber: String = ""
public var platformBeneficiaryId: String = ""
public var beneficiaryPaymentToolId: Int = 0
public var shortDescription: String = ""
public var fullDescription: String = ""
public var dealTypeId: String = ""
public required init(json: [String: Any]) {
platformDealId = map(json["PlatformDealId"], "")
dealStateId = map(json["DealStateId"], "")
createDate = map(json["CreateDate"])
updatedate = map(json["UpdateDate"])
expireDate = map(json["ExpireDate"])
amount = map(json["Amount"], 0.0)
currencyId = map(json["CurrencyId"], .rub)
payerCommissionAmount = map(json["PayerCommissionAmount"], 0.0)
platformBonusAmount = map(json["PlatformBonusAmount"], 0.0)
platformPayerId = map(json["PlatformPayerId"], "")
payerPhoneNumber = map(json["PayerPhoneNumber"], "")
payerPaymentToolId = map(json["PayerPaymentToolId"], 0)
platformBeneficiaryId = map(json["PlatformBeneficiaryId"], "")
beneficiaryPaymentToolId = map(json["BeneficiaryPaymentToolId"], 0)
shortDescription = map(json["ShortDescription"], "")
fullDescription = map(json["FullDescription"], "")
dealTypeId = map(json["DealTypeId"], "")
}
}
|
mit
|
bba9bb6469bc5feb1ff1f5574a6d5631
| 30.645833 | 78 | 0.678736 | 4.352436 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.