repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dalu93/SwiftHelpSet | refs/heads/master | Sources/UIKIt/SwiftyTableView.swift | mit | 1 | //
// SwiftyTableView.swift
// SwiftHelpSet
//
// Created by Luca D'Alberti on 7/14/16.
// Copyright © 2016 dalu93. All rights reserved.
//
import UIKit
public class SwiftyTableView: UITableView {
fileprivate var _configureNumberOfSections: (() -> Int)?
/// It is called everytime `numberOfSectionsInTableView(tableView: UITableView)` is called
public func configureNumberOfSections(closure: @escaping (() -> Int)) -> Self {
_configureNumberOfSections = closure
return self
}
fileprivate var _numberOfRowsPerSection: ((_ section: Int) -> Int)?
/// It is called everytime `tableView(tableView: UITableView, numberOfRowsInSection section: Int)` is called
public func numberOfRowsPerSection(closure: @escaping ((_ section: Int) -> Int)) -> Self {
_numberOfRowsPerSection = closure
return self
}
fileprivate var _cellForIndexPath: ((_ indexPath: IndexPath) -> UITableViewCell)?
/// It is called everytime `tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)` is called
public func cellForIndexPath(closure: @escaping ((_ indexPath: IndexPath) -> UITableViewCell)) -> Self {
_cellForIndexPath = closure
return self
}
fileprivate var _onCellSelection: ((_ indexPath: IndexPath) -> ())?
/// It is called everytime `tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)` is called
public func onCellSelection(closure: @escaping ((_ indexPath: IndexPath) -> ())) -> Self {
_onCellSelection = closure
return self
}
fileprivate var _onScroll: ((_ scrollView: UIScrollView) -> ())?
/// It is called everytime `scrollViewDidScroll(scrollView: UIScrollView)` is called
public func onScroll(closure: @escaping ((_ scrollView: UIScrollView) -> ())) -> Self {
_onScroll = closure
return self
}
fileprivate var _footerInSection: ((_ section: Int) -> UIView?)?
/// It is called everytime `tableView(tableView: UITableView, viewForFooterInSection section: Int)` is called
public func footerInSection(closure: @escaping ((_ section: Int) -> UIView?)) -> Self {
_footerInSection = closure
return self
}
fileprivate var _headerInSection: ((_ section: Int) -> UIView?)?
/// It is called everytime `tableView(tableView: UITableView, viewForHeaderInSection section: Int)` is called
public func headerInSection(closure: @escaping ((_ section: Int) -> UIView?)) -> Self {
_headerInSection = closure
return self
}
override public init(frame: CGRect, style: UITableViewStyle) {
super.init(
frame: frame,
style: style
)
_setupProtocols()
}
required public init?(coder aDecoder: NSCoder) {
super.init(
coder: aDecoder
)
_setupProtocols()
}
}
// MARK: - Helpers
private extension SwiftyTableView {
func _setupProtocols() {
self.delegate = self
self.dataSource = self
}
}
// MARK: - UITableViewDataSource
extension SwiftyTableView: UITableViewDataSource {
@nonobjc public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return _configureNumberOfSections?() ?? 0
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _numberOfRowsPerSection?(section) ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return _cellForIndexPath?(indexPath) ?? UITableViewCell()
}
}
// MARK: - UITableViewDelegate
extension SwiftyTableView: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
_onCellSelection?(indexPath)
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return _footerInSection?(section)
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return _headerInSection?(section)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
_onScroll?(scrollView)
}
}
| da936f7789424557a8f03c9e72ed6899 | 34.483607 | 124 | 0.661585 | false | false | false | false |
abarisain/skugga | refs/heads/master | Apple/iOS/Share/ProgressNotifier.swift | apache-2.0 | 1 | //
// ProgressNotifier.swift
// Skugga
//
// Created by Arnaud Barisain-Monrose on 18/09/2016.
// Copyright © 2016 NamelessDev. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
protocol ProgressNotifier {
func uploadStarted(itemURL: URL?)
func uploadProgress(_ progress: Double)
func uploadSuccess(url: String)
func uploadFailed(error: NSError)
}
class NotificationProgressNotifier: AlertProgressNotifier {
static let notificationUploadIdentifier = "extension_upload"
var alreadyNotifiedProgress = false
var cachedItemURL: URL?
required init(vc: UIViewController) {
super.init(vc: vc)
}
override func uploadStarted(itemURL: URL?) {
super.uploadStarted(itemURL: itemURL)
cachedItemURL = itemURL
let content = UNMutableNotificationContent()
content.body = "Uploading..."
content.sound = nil
let request = UNNotificationRequest.init(identifier: NotificationProgressNotifier.notificationUploadIdentifier, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
override func uploadProgress(_ progress: Double) {
super.uploadProgress(progress)
let percentage = floor(progress)
if (percentage >= 60 && !alreadyNotifiedProgress) {
alreadyNotifiedProgress = true
let content = UNMutableNotificationContent()
content.body = "Uploading... \(percentage) %"
content.sound = nil
let request = UNNotificationRequest.init(identifier: NotificationProgressNotifier.notificationUploadIdentifier, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
}
override func uploadSuccess(url: String) {
super.uploadSuccess(url: url)
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [NotificationProgressNotifier.notificationUploadIdentifier])
let content = UNMutableNotificationContent()
content.title = "Image uploaded"
content.body = "\(url)"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "upload_success"
content.userInfo["url"] = url
appendAttachment(content: content)
let request = UNNotificationRequest.init(identifier: UUID.init().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
override func uploadFailed(error: NSError) {
super.uploadFailed(error: error)
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [NotificationProgressNotifier.notificationUploadIdentifier])
let content = UNMutableNotificationContent()
content.title = "Couldn't upload image"
content.body = "\(error)"
content.sound = UNNotificationSound.default()
appendAttachment(content: content)
let request = UNNotificationRequest.init(identifier: UUID.init().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
func appendAttachment(content: UNMutableNotificationContent) {
if let cachedItemURL = cachedItemURL {
do {
let attachment = try UNNotificationAttachment(identifier: "image", url: cachedItemURL, options: nil)
content.attachments = [attachment]
} catch {
print("Error while adding notification attachment \(error)")
}
}
}
}
class AlertProgressNotifier: ProgressNotifier {
var alert: UIAlertController?
weak var viewController: UIViewController?
required init(vc: UIViewController) {
viewController = vc
}
func uploadStarted(itemURL: URL?) {
if let viewController = viewController {
alert = UIAlertController(title: "Uploading...", message: "", preferredStyle: .alert)
viewController.present(alert!, animated: true, completion: nil)
}
}
func uploadProgress(_ progress: Double) {
alert?.message = NSString(format: "%d %%", floor(progress*100)) as String
}
func uploadSuccess(url: String) {
alert?.dismiss(animated: true, completion: nil)
}
func uploadFailed(error: NSError) {
let presentError = { () -> Void in
let alert = UIAlertController(title: "Error", message: "Couldn't upload image : \(error) \(error.userInfo)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: { (action: UIAlertAction!) -> () in
self.viewController?.extensionContext!.cancelRequest(withError: error)
}))
self.viewController?.present(alert, animated: true, completion: nil)
}
if let previousAlert = alert {
previousAlert.dismiss(animated: true, completion: presentError)
} else {
presentError()
}
}
}
| 0d7f5ad9734ffc30e71ede8a42661eb1 | 35.027778 | 155 | 0.652274 | false | false | false | false |
Adorkable/StoryboardKit | refs/heads/master | StoryboardKitTests/ViewInstanceInfoTests.swift | mit | 1 | //
// ViewInstanceInfoTests.swift
// StoryboardKit
//
// Created by Ian on 6/30/15.
// Copyright (c) 2015 Adorkable. All rights reserved.
//
import XCTest
import StoryboardKit
class ViewInstanceInfoTests: XCTestCase {
var applicationInfo : ApplicationInfo?
var viewInstanceInfoId = "IKn-pG-61R"
var viewInstanceInfo : ViewInstanceInfo?
override func setUp() {
self.continueAfterFailure = false
super.setUp()
applicationInfo = ApplicationInfo()
do
{
try StoryboardFileParser.parse(applicationInfo!, pathFileName: storyboardPathBuilder()! )
} catch let error as NSError
{
XCTAssertNil(error, "Expected parse to not throw an error: \(error)")
}
self.viewInstanceInfo = applicationInfo?.viewInstanceWithId(self.viewInstanceInfoId)
}
func testClassInfo() {
let className = "UIView"
let classInfo = self.applicationInfo?.viewClassWithClassName(className)
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertNotNil(classInfo, "\(self.viewInstanceInfo!)'s classInfo should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.classInfo, classInfo!, "\(self.viewInstanceInfo!)'s classInfo should be equal to \(classInfo!)")
}
func testId() {
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertEqual(self.viewInstanceInfo!.id, self.viewInstanceInfoId, "\(self.viewInstanceInfo!)'s id should be equal to \(self.viewInstanceInfo)")
}
func testFrame() {
let equalTo = CGRect(x: 0, y: 0, width: 600, height: 600)
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
// XCTAssertNotNil(self.viewInstanceInfo!.frame, "\(self.viewInstanceInfo)'s frame should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.frame!, equalTo, "\(self.viewInstanceInfo!)'s frame should be equal to \(equalTo)")
}
func testAutoResizingMaskWidthSizable() {
let equalTo = true
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertEqual(self.viewInstanceInfo!.autoResizingMaskWidthSizable, equalTo, "\(self.viewInstanceInfo!)'s autoResizingMaskWidthSizable should be equal to \(equalTo)")
}
func testAutoResizingMaskHeightSizable() {
let equalTo = true
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertEqual(self.viewInstanceInfo!.autoResizingMaskHeightSizable, equalTo, "\(self.viewInstanceInfo!)'s autoResizingMaskHeightSizable should be equal to \(equalTo)")
}
func testSubviews() {
let equalTo = 4
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertNotNil(self.viewInstanceInfo!.subviews, "\(self.viewInstanceInfo!)'s subviews should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.subviews!.count, equalTo, "\(self.viewInstanceInfo!)'s subview count should be equal to \(equalTo)")
}
func testBackgroundColor() {
let equalTo = NSColor(calibratedWhite: 0.66666666666666663, alpha: 1.0)
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertNotNil(self.viewInstanceInfo!.backgroundColor, "\(self.viewInstanceInfo!)'s background color should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.backgroundColor!, equalTo, "\(self.viewInstanceInfo!)'s background color count should be equal to \(equalTo)")
}
}
| 54f3d40072f9394c87327e774dea7576 | 40.5 | 176 | 0.694026 | false | true | false | false |
a1137611824/YWSmallDay | refs/heads/master | smallDay/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// smallDay
//
// Created by Mac on 17/3/14.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
setKeyValue()
columnInit()
//传值之后的处理事件
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.showMianViewController), name: showMainTabBarController_Notification, object: nil)
return true
}
// MARK: -状态栏初始化
func columnInit() {
//在plist设置viewcontroller-base status为no意思是交由uiapplication来管理
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
UIApplication.sharedApplication().statusBarHidden = false
}
// MARK: - 判断是否进入引导界面
private func setKeyValue() {
window = UIWindow(frame: MainBounds)
window?.rootViewController = showLeadPage()
window?.makeKeyAndVisible()
}
// MARK: - 引导界面设置
func showLeadPage() -> UIViewController{
let versionStr = "CFBundleShortVersionString"
let currentVersion = NSBundle.mainBundle().infoDictionary![versionStr]
//取出之前的版本号
let defaults = NSUserDefaults.standardUserDefaults()
let oldVersion = defaults.stringForKey(versionStr) ?? ""
//比较当前版本是否在老版本基础上降低了
if currentVersion?.compare(oldVersion) == NSComparisonResult.OrderedDescending {
//将新的版本号存入手机
defaults.setObject(currentVersion, forKey: versionStr)
//将数据同步到文件当中,避免丢失
defaults.synchronize()
return LeadPageViewController()
}
return YWMainTabBarController()
}
//进入首页面
func showMianViewController() {
let mainTabBarVC = YWMainTabBarController()
self.window!.rootViewController = mainTabBarVC
//设置首页面导航栏格式
// let nav = mainTabBarVC.viewControllers![0] as? MainNavigationController
// (nav?.viewControllers[0] as! MainViewController).pushcityView()
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 6bffd44784e86f95e3f4a2cedfc613fe | 38.484848 | 285 | 0.704272 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Account/Tests/AccountTests/Feedly/FeedlyLogoutOperationTests.swift | mit | 1 | //
// FeedlyLogoutOperationTests.swift
// AccountTests
//
// Created by Kiel Gillard on 15/11/19.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import XCTest
@testable import Account
import RSCore
import Secrets
class FeedlyLogoutOperationTests: XCTestCase {
private var account: Account!
private let support = FeedlyTestSupport()
override func setUp() {
super.setUp()
account = support.makeTestAccount()
}
override func tearDown() {
if let account = account {
support.destroy(account)
}
super.tearDown()
}
private func getTokens(for account: Account) throws -> (accessToken: Credentials, refreshToken: Credentials) {
guard let accessToken = try account.retrieveCredentials(type: .oauthAccessToken), let refreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) else {
XCTFail("Unable to retrieve access and/or refresh token from account.")
throw CredentialsError.incompleteCredentials
}
return (accessToken, refreshToken)
}
class TestFeedlyLogoutService: FeedlyLogoutService {
var mockResult: Result<Void, Error>?
var logoutExpectation: XCTestExpectation?
func logout(completion: @escaping (Result<Void, Error>) -> ()) {
guard let result = mockResult else {
XCTFail("Missing mock result. Test may time out because the completion will not be called.")
return
}
DispatchQueue.main.async {
completion(result)
self.logoutExpectation?.fulfill()
}
}
}
func testCancel() {
let service = TestFeedlyLogoutService()
service.logoutExpectation = expectation(description: "Did Call Logout")
service.logoutExpectation?.isInverted = true
let accessToken: Credentials
let refreshToken: Credentials
do {
(accessToken, refreshToken) = try getTokens(for: account)
} catch {
XCTFail("Could not retrieve credentials to verify their integrity later.")
return
}
let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log)
// If this expectation is not fulfilled, the operation is not calling `didFinish`.
let completionExpectation = expectation(description: "Did Finish")
logout.completionBlock = { _ in
completionExpectation.fulfill()
}
MainThreadOperationQueue.shared.add(logout)
MainThreadOperationQueue.shared.cancelOperations([logout])
waitForExpectations(timeout: 1)
XCTAssertTrue(logout.isCanceled)
do {
let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken)
let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken)
XCTAssertEqual(accountAccessToken, accessToken)
XCTAssertEqual(accountRefreshToken, refreshToken)
} catch {
XCTFail("Could not verify tokens were left intact. Did the operation delete them?")
}
}
func testLogoutSuccess() {
let service = TestFeedlyLogoutService()
service.logoutExpectation = expectation(description: "Did Call Logout")
service.mockResult = .success(())
let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log)
// If this expectation is not fulfilled, the operation is not calling `didFinish`.
let completionExpectation = expectation(description: "Did Finish")
logout.completionBlock = { _ in
completionExpectation.fulfill()
}
MainThreadOperationQueue.shared.add(logout)
waitForExpectations(timeout: 1)
XCTAssertFalse(logout.isCanceled)
do {
let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken)
let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken)
XCTAssertNil(accountAccessToken)
XCTAssertNil(accountRefreshToken)
} catch {
XCTFail("Could not verify tokens were deleted.")
}
}
class TestLogoutDelegate: FeedlyOperationDelegate {
var error: Error?
var didFailExpectation: XCTestExpectation?
func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) {
self.error = error
didFailExpectation?.fulfill()
}
}
func testLogoutMissingAccessToken() {
support.removeCredentials(matching: .oauthAccessToken, from: account)
let (_, service) = support.makeMockNetworkStack()
service.credentials = nil
let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log)
let delegate = TestLogoutDelegate()
delegate.didFailExpectation = expectation(description: "Did Fail")
logout.delegate = delegate
// If this expectation is not fulfilled, the operation is not calling `didFinish`.
let completionExpectation = expectation(description: "Did Finish")
logout.completionBlock = { _ in
completionExpectation.fulfill()
}
MainThreadOperationQueue.shared.add(logout)
waitForExpectations(timeout: 1)
XCTAssertFalse(logout.isCanceled)
do {
let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken)
XCTAssertNil(accountAccessToken)
} catch {
XCTFail("Could not verify tokens were deleted.")
}
XCTAssertNotNil(delegate.error, "Should have failed with error.")
if let error = delegate.error {
switch error {
case CredentialsError.incompleteCredentials:
break
default:
XCTFail("Expected \(CredentialsError.incompleteCredentials)")
}
}
}
func testLogoutFailure() {
let service = TestFeedlyLogoutService()
service.logoutExpectation = expectation(description: "Did Call Logout")
service.mockResult = .failure(URLError(.timedOut))
let accessToken: Credentials
let refreshToken: Credentials
do {
(accessToken, refreshToken) = try getTokens(for: account)
} catch {
XCTFail("Could not retrieve credentials to verify their integrity later.")
return
}
let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log)
// If this expectation is not fulfilled, the operation is not calling `didFinish`.
let completionExpectation = expectation(description: "Did Finish")
logout.completionBlock = { _ in
completionExpectation.fulfill()
}
MainThreadOperationQueue.shared.add(logout)
waitForExpectations(timeout: 1)
XCTAssertFalse(logout.isCanceled)
do {
let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken)
let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken)
XCTAssertEqual(accountAccessToken, accessToken)
XCTAssertEqual(accountRefreshToken, refreshToken)
} catch {
XCTFail("Could not verify tokens were left intact. Did the operation delete them?")
}
}
}
| ba2eb8ebaf94513cbc67891a18fd01c4 | 29.313364 | 167 | 0.745819 | false | true | false | false |
AliSoftware/SwiftGen | refs/heads/develop | Tests/SwiftGenKitTests/CoreDataTests.swift | mit | 1 | //
// SwiftGenKit UnitTests
// Copyright © 2020 SwiftGen
// MIT Licence
//
@testable import SwiftGenKit
import TestUtils
import XCTest
final class CoreDataTests: XCTestCase {
func testEmpty() throws {
let parser = try CoreData.Parser()
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "empty", sub: .coreData)
}
func testDefaults() throws {
let parser = try CoreData.Parser()
do {
try parser.searchAndParse(path: Fixtures.resource(for: "Model.xcdatamodeld", sub: .coreData))
} catch {
print("Error: \(error.localizedDescription)")
}
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "defaults", sub: .coreData)
}
// MARK: - Custom options
func testUnknownOption() throws {
do {
_ = try CoreData.Parser(options: ["SomeOptionThatDoesntExist": "foo"])
XCTFail("Parser successfully created with an invalid option")
} catch ParserOptionList.Error.unknownOption(let key, _) {
// That's the expected exception we want to happen
XCTAssertEqual(key, "SomeOptionThatDoesntExist", "Failed for unexpected option \(key)")
} catch let error {
XCTFail("Unexpected error occured: \(error)")
}
}
}
| 90c40725e655b28d551283fb1420899c | 27.159091 | 99 | 0.682809 | false | true | false | false |
SwiftKit/Staging | refs/heads/master | Source/DispatchHelpers.swift | mit | 1 | //
// DispatchHelpers.swift
// SwiftKit
//
// Created by Tadeas Kriz on 08/01/16.
// Copyright © 2016 Tadeas Kriz. All rights reserved.
//
import Foundation
public func cancellableDispatchAfter(_ seconds: Double, queue: DispatchQueue = DispatchQueue.main, block: @escaping () -> ()) -> Cancellable {
let delay = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
return cancellableDispatchAfter(delay, on: queue, block: block)
}
public func cancellableDispatchAfter(_ time: DispatchTime, on queue: DispatchQueue, block: @escaping () -> ()) -> Cancellable {
var cancelled: Bool = false
queue.asyncAfter(deadline: time) {
if cancelled == false {
block()
}
}
return CancellableToken {
cancelled = true
}
}
public func cancellableDispatchAsync(on queue: DispatchQueue = DispatchQueue.main, block: @escaping () -> ()) -> Cancellable {
var cancelled: Bool = false
queue.async {
if cancelled == false {
block()
}
}
return CancellableToken {
cancelled = true
}
}
| 97a8c3c7555cc0b48d649314c9d0f930 | 27.3 | 142 | 0.637809 | false | false | false | false |
softwarenerd/TSNPeerNetworking | refs/heads/master | Source/TSNPeerNetworking.swift | mit | 1 | //
// TSNPeerNetworking.swift
// TSNPeerNetworking
//
// Created by Brian Lambert on 1/27/16.
// Copyright © 2016 Microsoft. All rights reserved.
//
import Foundation
import MultipeerConnectivity
// TSNPeerNetworking class.
public class TSNPeerNetworking: NSObject
{
// The TSNPeerNetworkingDelegate.
public weak var delegate: TSNPeerNetworkingDelegate?
// The local peer ID key.
let LocalPeerIDKey = "LocalPeerIDKey"
// The advertise service type.
private var advertiseServiceType: String?
// The browse service type.
private var browseServiceType: String?
// The local peer identifier.
private var localPeerID: MCPeerID!
private var localPeerDisplayName: String!
// The session.
private var session: MCSession!
// The nearby service advertiser.
private var nearbyServiceAdvertiser: MCNearbyServiceAdvertiser!
// The nearby service browser.
private var nearbyServiceBrowser: MCNearbyServiceBrowser!
// Returns a value which indicates whether peers are connected.
public var peersAreConnected: Bool
{
get
{
return session.connectedPeers.count != 0
}
}
// Initializer.
public init(advertiseServiceType advertiseServiceTypeIn: String?, browseServiceType browseServiceTypeIn: String?)
{
// Initialize.
advertiseServiceType = advertiseServiceTypeIn
browseServiceType = browseServiceTypeIn
}
// Starts.
public func start()
{
// Obtain user defaults and see if we have a serialized local peer ID. If we do, deserialize it. If not, make one
// and serialize it for later use. If we don't serialize and reuse the local peer ID, we'll see duplicates
// of this local peer in sessions.
let userDefaults = NSUserDefaults.standardUserDefaults()
if let data = userDefaults.dataForKey(LocalPeerIDKey)
{
// Deserialize the local peer ID.
localPeerID = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! MCPeerID
}
else
{
// Allocate and initialize a new local peer ID.
localPeerID = MCPeerID(displayName: UIDevice.currentDevice().name)
// Serialize and save the peer ID in user defaults.
let data = NSKeyedArchiver.archivedDataWithRootObject(localPeerID)
userDefaults.setValue(data, forKey: LocalPeerIDKey)
userDefaults.synchronize()
}
// Set the local peer display name.
localPeerDisplayName = localPeerID.displayName
// Allocate and initialize the session.
session = MCSession(peer: localPeerID,
securityIdentity: nil,
encryptionPreference: .Required)
session.delegate = self
// Allocate and initialize the nearby service advertizer.
if let advertiseServiceType = advertiseServiceType
{
nearbyServiceAdvertiser = MCNearbyServiceAdvertiser(peer: localPeerID, discoveryInfo: nil, serviceType: advertiseServiceType)
nearbyServiceAdvertiser.delegate = self
}
// Allocate and initialize the nearby service browser.
if let browseServiceType = browseServiceType
{
nearbyServiceBrowser = MCNearbyServiceBrowser(peer: localPeerID, serviceType: browseServiceType)
nearbyServiceBrowser.delegate = self
}
// Start advertising the local peer and browsing for nearby peers.
nearbyServiceAdvertiser?.startAdvertisingPeer()
nearbyServiceBrowser?.startBrowsingForPeers()
// Log.
log("Started.")
}
// Stops peer networking.
public func stop()
{
// Stop advertising the local peer and browsing for nearby peers.
nearbyServiceAdvertiser?.stopAdvertisingPeer()
nearbyServiceBrowser?.stopBrowsingForPeers()
// Disconnect the session.
session.disconnect()
// Clean up.
nearbyServiceAdvertiser = nil
nearbyServiceBrowser = nil
session = nil
localPeerID = nil
// Log.
log("Stopped.")
}
// Sends data.
public func sendData(data: NSData) -> Bool
{
// If there are no connected peers, we cannot send the data.
let connectedPeers = session.connectedPeers
if connectedPeers.count == 0
{
// Log.
log("Unable to send \(data.length) bytes. There are no peers are connected.")
return false
}
// There are connected peers. Try to send the data to each of them.
var errorsOccurred = false
for peerId in connectedPeers
{
// Try to send.
do
{
try session.sendData(data, toPeers: [peerId], withMode: .Reliable)
log("Sent \(data.length) bytes to peer \(peerId.displayName).")
}
catch
{
log("Failed to send \(data.length) bytes to peer \(peerId.displayName). Error: \(error).")
errorsOccurred = true
break
}
}
// Done.
return !errorsOccurred
}
}
// MCNearbyServiceAdvertiserDelegate.
extension TSNPeerNetworking: MCNearbyServiceAdvertiserDelegate
{
// Incoming invitation request. Call the invitationHandler block with true
// and a valid session to connect the inviting peer to the session.
public func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void)
{
// Accept the invitation.
invitationHandler(true, session);
// Log.
log("Accepted invitation from peer \(peerID.displayName).")
}
// Advertising did not start due to an error.
public func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError)
{
log("Failed to start advertising. Error: \(error)")
}
}
// MCSessionDelegate.
extension TSNPeerNetworking: MCNearbyServiceBrowserDelegate
{
// Found a nearby advertising peer.
public func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]?)
{
// Invite the peer to the session.
nearbyServiceBrowser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 30.0)
// Log.
log("Found peer \(peerID.displayName) and invited.")
}
// A nearby peer has stopped advertising.
public func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID)
{
log("Lost peer \(peerID.displayName).")
}
// Browsing did not start due to an error.
public func browser(browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: NSError)
{
log("Failed to start browsing for peers with service type \(browseServiceType). Error: \(error)")
}
}
// MCSessionDelegate.
extension TSNPeerNetworking: MCSessionDelegate
{
// Nearby peer changed state.
public func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState)
{
// Log.
switch state
{
case .NotConnected:
log("Peer \(peerID.displayName) is not connected.")
case .Connecting:
log("Peer \(peerID.displayName) is connecting.")
case .Connected:
log("Peer \(peerID.displayName) is connected.")
}
// Notify the delegate.
if let delegate = delegate
{
delegate.peerNetworkingPeersChanged(self)
}
}
// Received data from nearby peer.
public func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID)
{
// Log.
log("Peer \(peerID.displayName) sent \(data.length) bytes.")
// Notify.
if let delegate = delegate
{
delegate.peerNetworking(self, didReceiveData: data)
}
}
// Received a byte stream from nearby peer.
public func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID)
{
}
// Start receiving a resource from nearby peer.
public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress)
{
}
// Finished receiving a resource from nearby peer and saved the content in a temporary location - the app is responsible for moving the file
// to a permanent location within its sandbox.
public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?)
{
}
// Made first contact with peer and have identity information about the nearby peer (certificate may be nil).
public func session(session: MCSession, didReceiveCertificate certificate: [AnyObject]?, fromPeer peerID: MCPeerID, certificateHandler: (Bool) -> Void)
{
certificateHandler(true);
log("Peer \(peerID.displayName) sent certificate and it was accepted.");
}
}
// Privates.
extension TSNPeerNetworking
{
// Log.
private func log(string: String)
{
print("TSNPeerNetworking: \(localPeerDisplayName) - \(string)")
}
}
| 90f54c65f62207142b5ce005bd3b6d8e | 32.898246 | 188 | 0.645585 | false | false | false | false |
keitaito/HackuponApp | refs/heads/master | HackuponApp/ViewControllers/MainTableViewController.swift | mit | 1 | //
// MainTableViewController.swift
// HackuponApp
//
// Created by Keita Ito on 3/14/16.
// Copyright © 2016 Keita Ito. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
// MARK: - Properties
let url = NSURL(string: "http://localhost:3000/foos.json")!
var peopleArray = [Person]()
override func viewDidLoad() {
super.viewDidLoad()
// Download data from the server.
NetworkClient.downloadDataWithURL(url) { (resultArray) -> Void in
// resultsArray is of type Array<Person>.
resultArray.forEach {
self.peopleArray.append($0)
}
// Update UI from the main queue.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return peopleArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MainTableViewCell
// Configure the cell...
let person = peopleArray[indexPath.row]
cell.nameLabel.text = person.name
cell.idLabel.text = String(person.id)
return cell
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| ffa48be30b4cea97c8c00d1dbd35a2a2 | 30.820225 | 126 | 0.641243 | false | false | false | false |
IngmarStein/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00085-swift-typechecker-typecheckpattern.swift | apache-2.0 | 11 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func fe<on>() -> (on, on -> on) -> on {
cb w cb.gf = {
}
{
on) {
> ji) -> ji in
dc ih(on, s)
}
}
func w(ed: (((ji, ji) -> ji) -> ji)) -> ji {
dc ed({
(x: ji, h:ji) -> ji in
dc x
})
}
w(fe(hg, fe(kj, lk)))
t l {
ml b
}
y ih<cb> {
nm <l: l q l.b == cb>(x: l.b) {
}
}
func fe<po : n>(w: po) {
}
fe(r qp n)
x o = u rq: Int -> Int = {
dc $sr
}
let k: Int = { (on: Int, fe: Int in
dc fe(on)
}(o, rq)
let w: Int = { on, fe in
dc fe(on)
}(o, rq)
func c(fe: v) -> <po>(() -> po) -> gf
| bb620c41899359587664a8710edecee6 | 20.340909 | 78 | 0.529286 | false | false | false | false |
EZ-NET/CodePiece | refs/heads/Rev2 | ESTwitter/API/APIError.swift | gpl-3.0 | 1 | //
// APIError.swift
// ESTwitter
//
// Created by Tomohiro Kumagai on 2020/01/27.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import Swifter
public enum APIError : Error {
case notReady
case responseError(code: Int, message: String)
case operationError(String)
case offline(String)
case unexpected(Error)
}
internal extension APIError {
init(from error: SwifterError) {
if case .urlResponseError = error.kind, let response = SwifterError.Response(fromMessage: error.message) {
self = .responseError(code: response.code, message: response.message)
}
else {
self = .unexpected(error)
}
}
init(from error: NSError) {
switch error.code {
case -1009:
self = .offline(error.localizedDescription)
default:
self = .unexpected(error)
}
}
}
extension APIError : CustomStringConvertible {
public var description: String {
switch self {
case .notReady:
return "API is not ready."
case .responseError(_, let message):
return message
case .operationError(let message):
return message
case .offline(let message):
return message
case .unexpected(let error):
return "Unexpected error: \(error)"
}
}
}
| 0f515163ce69211ac728f391e32cdc9e | 16.753623 | 108 | 0.680816 | false | false | false | false |
SearchDream/iOS-9-Sampler | refs/heads/master | iOS9Sampler/SampleViewControllers/QuickActionsViewController.swift | mit | 2 | //
// QuickActionsViewController.swift
// iOS9Sampler
//
// Created by Shuichi Tsutsumi on 9/28/15.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
class QuickActionsViewController: UIViewController {
@IBOutlet weak fileprivate var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if traitCollection.forceTouchCapability == UIForceTouchCapability.available {
label.text = "Your device supports 3D Touch!"
label.textColor = UIColor.green
} else {
label.text = "Your device does NOT support 3D Touch!"
label.textColor = UIColor.red
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 621d59b18b2c0f552beecab123396ec8 | 25.029412 | 85 | 0.651977 | false | false | false | false |
inamiy/VTree | refs/heads/master | Sources/Message.swift | mit | 1 | /// Message protocol that `VTree` generates from Cocoa's events,
/// then it dispatches corresponding **`AnyMsg`** via `Messenger`.
///
/// - Note:
/// Implementing `Message` will be a tedious work,
/// so use https://github.com/krzysztofzablocki/Sourcery
/// to assist code-generation for **`enum Msg` with associated values**.
///
/// 1. Conform to `AutoMessage` protocol (instead of `Message`).
/// 2. Run below script to automatically generate `extension Msg: Message`.
///
/// ```
/// enum Msg: AutoMessage { case tap(GestureContext), longPress(GestureContext), ... }
///
/// // Run script:
/// // $ <VTree-root>/Scripts/generate-message.sh <source-dir> <code-generated-dir>
/// ```
public protocol Message: MessageContext
{
init?(rawMessage: RawMessage)
var rawMessage: RawMessage { get }
}
extension Message
{
public init?(rawArguments: [Any])
{
var rawArguments = rawArguments
guard let funcName = rawArguments.popLast() as? String else { return nil }
self.init(rawMessage: RawMessage(funcName: funcName, arguments: rawArguments))
}
public var rawArguments: [Any]
{
var arguments = self.rawMessage.arguments
arguments.append(self.rawMessage.funcName)
return arguments
}
}
// MARK: RawMessage
public struct RawMessage
{
public let funcName: String
public let arguments: [Any]
public init(funcName: String, arguments: [Any])
{
self.funcName = funcName
self.arguments = arguments
}
}
// MARK: NoMsg
/// "No message" type that conforms to `Message` protocol.
public enum NoMsg: Message
{
public init?(rawMessage: RawMessage)
{
return nil
}
public var rawMessage: RawMessage
{
return RawMessage(funcName: "", arguments: [])
}
}
// MARK: AnyMsg
/// Type-erased `Message`.
public struct AnyMsg: Message
{
private let _rawMessage: RawMessage
public init<Msg: Message>(_ base: Msg)
{
self._rawMessage = base.rawMessage
}
public init?(rawMessage: RawMessage)
{
return nil
}
public var rawMessage: RawMessage
{
return self._rawMessage
}
}
extension Message
{
/// Converts from `AnyMsg`.
public init?(_ anyMsg: AnyMsg)
{
self.init(rawMessage: anyMsg.rawMessage)
}
}
| 473f64a7634f3626fd9352573f19e710 | 21.754902 | 86 | 0.64455 | false | false | false | false |
luanlzsn/pos | refs/heads/master | pos/pos_iphone/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// pos_iphone
//
// Created by luan on 2017/5/14.
// Copyright © 2017年 luan. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = .lightContent
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor.init(rgb: 0xe60a16)
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
IQKeyboardManager.sharedManager().enable = true
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
LanguageManager.setupCurrentLanguage()
AntManage.iphonePostRequest(path: "route=feed/rest_api/gettoken&grant_type=client_credentials", params: nil, successResult: { (response) in
if let data = response["data"] as? [String : Any] {
if let accseeToken = data["access_token"] as? String {
AntManage.iphoneToken = accseeToken
}
}
}, failureResult: {})
Thread.detachNewThreadSelector(#selector(runOnNewThread), toTarget: self, with: nil)
while AntManage.iphoneToken.isEmpty {
RunLoop.current.run(mode: .defaultRunLoopMode, before: Date.distantFuture)
}
return true
}
func runOnNewThread() {
sleep(1)
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 7b46a49700e731cabeb58d42dddf6ca2 | 44.364865 | 285 | 0.711349 | false | false | false | false |
KieranWynn/piccolo | refs/heads/master | Piccolo/StatusItemView.swift | mit | 1 | //
// StatusItemView.swift
// Piccolo
//
// Created by Kieran Wynn on 14/11/2014.
// Copyright (c) 2014 Kieran Wynn. All rights reserved.
//
//import Foundation
//import AppKit
//
//class StatusItemView: NSControl {
//
// var _statusItem: NSStatusItem
//
// var _image: NSImage
// var _alternateImage: NSImage
//
// var _rightAction = 0
//
// var _leftMenu: NSMenu
// var _rightMenu: NSMenu
//
// var _isMouseDown = false;
// var _isMenuVisible = false;
//
// init()
// {
// _image = NSImage()
// }
//
// init?(coder: NSCoder) {
// code = coder
// }
//
//}
| a40cce687a0b944f9c751ed184a05978 | 17 | 56 | 0.535494 | false | false | false | false |
tiagomartinho/webhose-cocoa | refs/heads/master | webhose-cocoa/Webhose/WebhosePost+SwiftyJSON.swift | mit | 1 | import SwiftyJSON
extension WebhosePost {
init(json: JSON) {
self.uuid = json["uuid"].stringValue
self.url = URL(string: json["url"].stringValue)!
self.published = Date.dateFromString(json["published"].stringValue)
self.title = json["title"].stringValue
self.orderInThread = json["ord_in_thread"].intValue
self.author = json["author"].stringValue
self.text = json["text"].stringValue
self.highlightText = json["highlightText"].stringValue
self.highlightTitle = json["highlightTitle"].stringValue
self.language = json["language"].stringValue
self.externalLinks = json["external_links"].arrayValue.map { $0.stringValue }
self.persons = json["persons"].arrayValue.map { $0.stringValue }
self.locations = json["locations"].arrayValue.map { $0.stringValue }
self.organizations = json["organizations"].arrayValue.map { $0.stringValue }
self.crawled = Date.dateFromString(json["crawled"].stringValue)
self.thread = WebhoseThread(json: json["thread"])
}
}
extension WebhosePost {
static func collection(_ json: JSON) -> [WebhosePost] {
return json.map { WebhosePost(json: $1) }
}
}
| 2de66c3c8f0ea8d2a0a0faf0d0df2d43 | 42.857143 | 85 | 0.659609 | false | false | false | false |
pawel-sp/PSZCircularPicker | refs/heads/master | PSZCircularPicker/CollectionViewDragAndDropController.swift | mit | 1 | //
// CollectionViewDragAndDropController.swift
// PSZCircularPicker
//
// Created by Paweł Sporysz on 30.10.2014.
// Copyright (c) 2014 Paweł Sporysz. All rights reserved.
//
import UIKit
public class CollectionViewDragAndDropController:NSObject {
// MARK: - Public properties
public var delegate:CollectionViewDragAndDropControllerDelegate?
// MARK: - Private properties
private let pickerCollectionView:UICollectionView
private let presenterCollectionView:UICollectionView
private let containerView:UIView
private struct Dragger {
static var pickedView:UIView?
static var locationInPickedView:CGPoint?
static var pickedIndexPath:NSIndexPath?
static func setupCell(cell:UICollectionViewCell, fromCollectionView collectionView:UICollectionView, toFrame frame:CGRect) {
self.pickedIndexPath = collectionView.indexPathForCell(cell)
cell.alpha = 1.0
self.pickedView = cell.snapshotViewAfterScreenUpdates(true)
self.pickedView?.frame = frame
}
static func updatePickedViewOrigin(origin:CGPoint) {
if let _pickedView = pickedView {
if let _locationInPickedView = locationInPickedView {
_pickedView.frame.origin = CGPointMake(
origin.x - _locationInPickedView.x,
origin.y - _locationInPickedView.y)
}
}
}
static func resetData() {
pickedView = nil
pickedIndexPath = nil
locationInPickedView = nil
}
}
// MARK: - Init
public init(pickerCollectionView:UICollectionView, presenterCollectionView:UICollectionView, containerView:UIView) {
self.pickerCollectionView = pickerCollectionView
self.presenterCollectionView = presenterCollectionView
self.containerView = containerView
super.init()
}
// MARK: - Gestures
public var dragAndDropLongPressGestureRecognizer:UILongPressGestureRecognizer {
return UILongPressGestureRecognizer(target:self, action:Selector("dragAndDropGestureAction:"))
}
public func dragAndDropGestureAction(gestureRecognizer:UILongPressGestureRecognizer) {
var gestureLocation = gestureRecognizer.locationInView(self.containerView)
if let cell = gestureRecognizer.view as? UICollectionViewCell {
switch gestureRecognizer.state {
case .Began:
Dragger.setupCell(
cell,
fromCollectionView: self.pickerCollectionView,
toFrame: self.pickerCollectionView.convertRect(cell.frame, toView: self.containerView)
)
Dragger.locationInPickedView = gestureRecognizer.locationInView(cell)
self.containerView.addSubview(Dragger.pickedView!)
self.delegate?.collectionViewDragAndDropController(self, pickingUpView: Dragger.pickedView!, fromCollectionViewIndexPath: Dragger.pickedIndexPath!)
case .Changed:
Dragger.updatePickedViewOrigin(gestureLocation)
self.delegate?.collectionViewDragAndDropController(self, dragginView: Dragger.pickedView!, pickedInLocation: Dragger.locationInPickedView!)
case .Ended:
let targetLocation = self.containerView.convertPoint(gestureLocation, toView: self.presenterCollectionView)
var targetIndexPath = self.presenterCollectionView.indexPathForItemAtPoint(targetLocation)
if let delegate = self.delegate {
delegate.collectionViewDragAndDropController(
self,
droppedView: Dragger.pickedView!,
fromCollectionViewIndexPath: Dragger.pickedIndexPath!,
toCollectionViewIndexPath: targetIndexPath!,
isCanceled: !CGRectContainsPoint(self.presenterCollectionView.frame, gestureLocation))
} else {
Dragger.pickedView?.removeFromSuperview()
}
default: break
}
}
}
}
| 68f7a55ed7922ab92a3ecc59dce217b9 | 41.798077 | 167 | 0.620085 | false | false | false | false |
uwinkler/commons | refs/heads/master | commons/NSData.swift | mit | 1 | //
// NSData.swift
//
// Created by Ulrich Winkler on 19/01/2015.
// Copyright (c) 2015 Ulrich Winkler. All rights reserved.
//
import Foundation
public extension NSData {
///
/// Converts "size" bytes at given location into an Int
///
public func toInt (location:Int, size:Int) -> Int {
let bytes = self.subdataWithRange(NSMakeRange(location,size)).bytes
return UnsafePointer<Int>(bytes).memory
}
//
// Converts the bytes to UInt8 Array
//
public func toUInt8Array () -> [UInt8] {
var byteArray = [UInt8](count: self.length, repeatedValue: 0x0)
self.getBytes(&byteArray, length:self.length)
return byteArray
}
///
/// Returns a data object in 'nono' notation
///
public var nono : String {
get {
return self.toUInt8Array().nono
}
}
public func subdata(length:Int, andFill:UInt8) -> NSData {
let l = min(self.length, length)
var ret = self.subdataWithRange(NSMakeRange(0, l)).mutableCopy() as! NSMutableData
var andFillRef = andFill
let data = NSData(bytes: &andFillRef, length: sizeof(UInt8))
for var i = l; i < length; i = i + sizeof(UInt8) {
ret.appendData(data)
}
return ret
}
}
| b1417311cefe6ae181798fcb7e049796 | 22.2 | 90 | 0.557471 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/ChatModule/CWChatClient/MessageHandle/CWChatMessageHandle.swift | mit | 2 | //
// CWChatMessageHandle.swift
// CWWeChat
//
// Created by chenwei on 2017/3/30.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
import XMPPFramework
class CWChatMessageHandle: CWMessageHandle {
override func handleMessage(message: XMPPMessage) -> Bool {
if message.isChatMessageWithBody() {
// 内容 来源 目标人 消息id
guard let body = message.body(),
let from = message.from().user,
let to = message.to().user,
let messageId = message.elementID() else {
return false
}
//默认是文字
let bodyType = message.forName("body")?.attribute(forName: "msgtype")?.stringValue ?? "1"
let bodyValue = Int(bodyType) ?? 1
var messageDate = Date()
if message.wasDelayed() {
messageDate = message.delayedDeliveryDate()
}
let type = CWMessageType(rawValue: bodyValue) ?? CWMessageType.none
var messageBody: CWMessageBody!
switch type {
case .text:
messageBody = CWTextMessageBody(text: body)
case .image:
messageBody = CWImageMessageBody()
messageBody.messageDecode(string: body)
default: break
}
let chatMessage = CWMessage(targetId: from,
messageID: messageId,
direction: .receive,
timestamp: messageDate.timeIntervalSince1970,
messageBody: messageBody)
chatMessage.senderId = to
self.delegate?.handMessageComplete(message: chatMessage)
return true
}
return false
}
}
| 5759cbbb39e30944aa6a1a67a3fd030e | 31.59322 | 101 | 0.50286 | false | false | false | false |
zhenghuadong11/firstGitHub | refs/heads/master | 旅游app_useSwift/旅游app_useSwift/MYEvaluationViewController.swift | apache-2.0 | 1 | //
// MYEvaluationViewController.swift
// 旅游app_useSwift
//
// Created by zhenghuadong on 16/4/27.
// Copyright © 2016年 zhenghuadong. All rights reserved.
//
import UIKit
class MYEvaluationViewController: UIViewController,MYImageEvvaluationViewControllerDelegate {
weak var _viewController:UIViewController?
var _num:String?
var _evalutionIndex:Int?
var _myPickerHaveModel:MYMYticketHaveModel?
var _buttons:Array<UIButton> = Array<UIButton>()
@IBOutlet weak var textView: UITextView!
var _star:Int = 0
var imageNum = 0
override func viewDidLoad() {
super.viewDidLoad()
for var i1 in 0..<5
{
var button = UIButton.init(type: UIButtonType.Custom)
button.frame = CGRectMake(CGFloat(i1)*30+100, 80, 30, 30)
button.setImage(UIImage.init(named: "hightLightStar"), forState: UIControlState.Selected)
button.setImage(UIImage.init(named: "star_none"), forState: UIControlState.Normal)
button.addTarget(self, action: #selector(buttonClick), forControlEvents: UIControlEvents.TouchUpInside)
button.tag = i1
_buttons.append(button)
self.view.addSubview(button)
}
}
@IBAction func cancelButtonClick(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func buttonClick(sender:UIButton) -> Void {
for i1 in 0...sender.tag {
_buttons[i1].selected = true
}
_star = sender.tag+1
if sender.tag+1 > 4
{
return
}
for i1 in sender.tag+1...4 {
_buttons[i1].selected = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func evaluationButotnClick(sender: AnyObject) {
let path = NSBundle.mainBundle().pathForResource("myPickerHave", ofType: "plist")
if let _ = path
{
var array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]>
var dict = array![_evalutionIndex!]
array?.removeAtIndex(_evalutionIndex!)
dict["isEvaluation"] = "true"
array?.append(dict)
(array! as NSArray).writeToFile(path!, atomically: true)
}
let pathEvaluetion = NSBundle.mainBundle().pathForResource("evaluetion", ofType: "plist")
if let _ = pathEvaluetion
{
var array = NSArray.init(contentsOfFile: pathEvaluetion!) as? Array<[String:AnyObject]>
var index = 0
var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
path = path?.stringByAppendingString("/ImageFile/")
var imageNames = Array<String>()
for var view in self.textView.subviews
{
if view.isKindOfClass(MYImageView)
{ var imagePath = path
let imageName = getCurrentTime()+index.description+rand().description
imageNames.append(imageName)
imagePath = imagePath?.stringByAppendingString(imageName)
let imageView = (view as! UIImageView)
print(imagePath)
try? UIImagePNGRepresentation(imageView.image!)?.writeToFile(imagePath!, options: NSDataWritingOptions.AtomicWrite)
index += 1
}
}
print(imageNames)
let dict:[String:AnyObject] = ["num":_num!,"evalution":textView.text,"star":_star.description,"user":MYMineModel._shareMineModel.name!,"evalutionNum":(array?.count)!.description,"images":imageNames]
array?.append(dict)
(array! as NSArray).writeToFile(pathEvaluetion!, atomically: true)
}
self.dismissViewControllerAnimated(true) {
(self._viewController as! MYMineShowTicketViewController).setUpmyTicketHaveModels()
(self._viewController as! MYMineShowTicketViewController)._tableView?.reloadData()
}
}
@IBAction func addPicktureClick(sender: AnyObject) {
let headImageController = MYImageEvvaluationViewController()
headImageController.delegate = self
self.presentViewController(headImageController, animated: true, completion: nil)
}
@IBAction func cancelImageClick(sender: AnyObject) {
if self.imageNum == 0
{
return
}
self.textView.subviews.last?.removeFromSuperview()
self.imageNum -= 1
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
textView.resignFirstResponder()
}
func imageEvvaluationViewController(viewController: MYImageEvvaluationViewController, image: UIImage) {
if self.imageNum == 8
{
return
}
let imageView = MYImageView.init(image: image)
self.textView.addSubview(imageView)
self.imageNum += 1
}
override func viewDidLayoutSubviews() {
var index = 0
for var view in self.textView.subviews
{
if view.isKindOfClass(MYImageView)
{
let width = self.textView.frame.width/4
let height = self.textView.frame.height/4
view.frame = CGRectMake(CGFloat(index%4)*width,CGFloat(index/4+2)*height,width,height)
index += 1
}
}
}
}
| a13794a5a5334c565db3a423fef23b65 | 35.451807 | 210 | 0.57098 | false | false | false | false |
LY-Coder/LYPlayer | refs/heads/master | LYPlayerExample/LYPlayer/LYProgressSlider.swift | mit | 1 | //
// LYProgressSlider.swift
//
// Copyright © 2017年 ly_coder. All rights reserved.
//
// GitHub地址:https://github.com/LY-Coder/LYPlayer
//
import UIKit
class LYProgressSlider: UIControl {
// 判断是否触摸中
private var isTouching: Bool = false
// 0 - 1
public var thumbImageValue: CGFloat = 0.0
// MARK: - life cycle
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupUIFrame()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/** 缓冲条的颜色 */
public var bufferedProgressColor: UIColor! {
willSet {
bufferedView.backgroundColor = newValue
}
}
/** 播放进度条的颜色 */
public var playProgressColor: UIColor! {
willSet {
playProgressView.backgroundColor = newValue
}
}
/** 未缓冲出来的颜色 */
public var noBufferProgressColor: UIColor! {
willSet {
noBufferView.backgroundColor = newValue
}
}
/** 视频缓冲进度 */
public var bufferedProgress: CGFloat = 0.0 {
didSet {
bufferedView.snp.updateConstraints { (make) in
make.width.equalTo(bufferedProgress * frame.size.width)
}
}
}
/** 播放进度 */
public var playProgress: CGFloat = 0.0 {
didSet {
// 在拖动时停止赋值
if playProgress.isNaN || playProgress > 1.0
|| isTouching {
return
}
dragImageView.snp.updateConstraints({ (make) in
make.centerX.equalTo(playProgress * frame.size.width)
})
}
}
// MARK: - setter and getter
// 播放进度视图
private lazy var playProgressView: UIView = {
let playProgressView = UIView()
playProgressView.backgroundColor = UIColor.red
return playProgressView
}()
// 缓冲进度视图
private lazy var bufferedView: UIView = {
let bufferedView = UIView()
bufferedView.backgroundColor = UIColor.clear
return bufferedView
}()
// 没有缓冲出来的部分
private lazy var noBufferView: UIView = {
let noBufferView = UIView()
noBufferView.backgroundColor = UIColor.white
return noBufferView
}()
// 拖动的小圆点
lazy var dragImageView: UIImageView = {
let dragImageView = UIImageView()
dragImageView.image = UIImage(named: "dot")
dragImageView.isUserInteractionEnabled = true
dragImageView.backgroundColor = UIColor.white
dragImageView.layer.cornerRadius = 7
return dragImageView
}()
// MARK: - private method
fileprivate func setupUI() {
addSubview(bufferedView)
addSubview(noBufferView)
addSubview(playProgressView)
addSubview(dragImageView)
}
fileprivate func setupUIFrame() {
dragImageView.snp.makeConstraints { (make) in
make.centerY.equalTo(self)
make.centerX.equalTo(0)
make.size.equalTo(CGSize(width: 14, height: 14))
}
playProgressView.snp.makeConstraints { (make) in
make.left.centerY.equalTo(self)
make.right.equalTo(dragImageView.snp.centerX)
make.height.equalTo(2)
}
bufferedView.snp.makeConstraints { (make) in
make.left.centerY.equalTo(self)
make.height.equalTo(2)
make.width.equalTo(0)
}
noBufferView.snp.makeConstraints { (make) in
make.centerY.right.equalTo(self)
make.left.equalTo(dragImageView.snp.centerX)
make.height.equalTo(2)
}
}
// MARK: - event response
// 开始点击
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
isTouching = true
// for touch in touches {
// let point = touch.location(in: self)
// }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
isTouching = false
}
// 手指在移动
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
for touch in touches {
// 获取当前位置
let point = touch.location(in: self)
// 在小圆点内并且在self内时,设置当前进度
if point.x > 0 && point.x < frame.width {
dragImageView.snp.updateConstraints({ (make) in
make.centerX.equalTo(point.x)
})
thumbImageValue = point.x / frame.width
}
}
}
}
| c93befba511baab637133bb329c19761 | 26.293785 | 79 | 0.559925 | false | false | false | false |
debugsquad/nubecero | refs/heads/master | nubecero/Tests/Firebase/Database/Model/TFDatabaseModelUserSession.swift | mit | 1 | import XCTest
@testable import nubecero
class TFDatabaseModelUserSession:XCTestCase
{
private let kToken:String? = "ddsfkjfsjksd3324fd"
private let kVersion:String = "312"
private let kTtl:Int? = 134398765
private let kTimestamp:TimeInterval = 1344556
private let kEmpty:String = ""
private let kNoTime:TimeInterval = 0
private let kNoTtl:Int = 0
func testInitTokenVersionTtl()
{
let initialStatus:MSession.Status = MSession.Status.active
let currentTime:TimeInterval = NSDate().timeIntervalSince1970
let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue
let keyToken:String = FDatabaseModelUserSession.Property.token.rawValue
let keyVersion:String = FDatabaseModelUserSession.Property.version.rawValue
let keyTimestamp:String = FDatabaseModelUserSession.Property.timestamp.rawValue
let keyTtl:String = FDatabaseModelUserSession.Property.ttl.rawValue
let model:FDatabaseModelUserSession = FDatabaseModelUserSession(
token:kToken,
version:kVersion,
ttl:kTtl)
XCTAssertEqual(
model.token,
kToken,
"Error storing token")
XCTAssertEqual(
model.version,
kVersion,
"Error storing version")
XCTAssertEqual(
model.ttl,
kTtl,
"Error storing ttl")
XCTAssertGreaterThanOrEqual(
model.timestamp,
currentTime,
"Error timestamp should be greater or equal to starting time")
XCTAssertEqual(
model.status,
initialStatus,
"Error user should be acitve on creation")
let modelJson:[String:Any]? = model.modelJson() as? [String:Any]
XCTAssertNotNil(
modelJson,
"Error creating model json")
let jsonStatusInt:Int? = modelJson?[keyStatus] as? Int
let jsonToken:String? = modelJson?[keyToken] as? String
let jsonVersion:String? = modelJson?[keyVersion] as? String
let jsonTimeStamp:TimeInterval? = modelJson?[keyTimestamp] as? TimeInterval
let jsonTtl:Int? = modelJson?[keyTtl] as? Int
XCTAssertNotNil(
jsonStatusInt,
"Error with status on json")
let jsonStatus:MSession.Status? = MSession.Status(rawValue:jsonStatusInt!)
XCTAssertEqual(
initialStatus,
jsonStatus,
"Error with initial status on json")
XCTAssertEqual(
kToken,
jsonToken,
"Error with token on json")
XCTAssertEqual(
kVersion,
jsonVersion,
"Error with version on json")
XCTAssertNotNil(
jsonTimeStamp,
"Error timestamp is nil")
XCTAssertGreaterThanOrEqual(
jsonTimeStamp!,
currentTime,
"Error with timestamp on json")
XCTAssertEqual(
kTtl,
jsonTtl,
"Error with ttl on json")
}
func testInitTokenNil()
{
let model:FDatabaseModelUserSession = FDatabaseModelUserSession(
token:nil,
version:kVersion,
ttl:kTtl)
XCTAssertEqual(
model.token,
kEmpty,
"Error token should be empty")
}
func testInitTtlNil()
{
let model:FDatabaseModelUserSession = FDatabaseModelUserSession(
token:kToken,
version:kVersion,
ttl:nil)
XCTAssertEqual(
model.ttl,
kNoTtl,
"Error ttl should be zero")
}
func testInitSnapshot()
{
let initialStatus:MSession.Status = MSession.Status.active
let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue
let keyToken:String = FDatabaseModelUserSession.Property.token.rawValue
let keyVersion:String = FDatabaseModelUserSession.Property.version.rawValue
let keyTimestamp:String = FDatabaseModelUserSession.Property.timestamp.rawValue
let keyTtl:String = FDatabaseModelUserSession.Property.ttl.rawValue
let snapshot:[String:Any] = [
keyStatus:initialStatus.rawValue,
keyToken:kToken,
keyVersion:kVersion,
keyTimestamp:kTimestamp,
keyTtl:kTtl
]
let model:FDatabaseModelUserSession = FDatabaseModelUserSession(
snapshot:snapshot)
XCTAssertEqual(
model.status,
initialStatus,
"Error storing status")
XCTAssertEqual(
model.token,
kToken,
"Error storing token")
XCTAssertEqual(
model.version,
kVersion,
"Error storing version")
XCTAssertEqual(
model.timestamp,
kTimestamp,
"Error storing timestamp")
XCTAssertEqual(
model.ttl,
kTtl,
"Error storing ttl")
}
func testInitSnapshotNil()
{
let snapshot:Any? = nil
let model:FDatabaseModelUserSession = FDatabaseModelUserSession(
snapshot:snapshot)
XCTAssertEqual(
model.status,
MSession.Status.unknown,
"Error default status")
XCTAssertEqual(
model.token,
kEmpty,
"Error default token")
XCTAssertEqual(
model.version,
kEmpty,
"Error default version")
XCTAssertEqual(
model.timestamp,
kNoTime,
"Error default timestamp")
XCTAssertEqual(
model.ttl,
kNoTtl,
"Error default ttl")
}
func testInitStatusActive()
{
let status:MSession.Status = MSession.Status.active
let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue
let snapshot:[String:Any] = [
keyStatus:status.rawValue,
]
let model:FDatabaseModelUserSession = FDatabaseModelUserSession(
snapshot:snapshot)
XCTAssertEqual(
model.status,
status,
"Error status active")
let modelJson:[String:AnyObject]? = model.modelJson() as? [String:AnyObject]
let jsonStatusInt:Int? = modelJson?[keyStatus] as? Int
let jsonStatus:MSession.Status? = MSession.Status(rawValue:jsonStatusInt!)
XCTAssertEqual(
jsonStatus,
status,
"Error json status")
}
func testInitStatusBanned()
{
let status:MSession.Status = MSession.Status.banned
let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue
let snapshot:[String:Any] = [
keyStatus:status.rawValue,
]
let model:FDatabaseModelUserSession = FDatabaseModelUserSession(
snapshot:snapshot)
XCTAssertEqual(
model.status,
status,
"Error status banned")
let modelJson:[String:AnyObject]? = model.modelJson() as? [String:AnyObject]
let jsonStatusInt:Int? = modelJson?[keyStatus] as? Int
let jsonStatus:MSession.Status? = MSession.Status(rawValue:jsonStatusInt!)
XCTAssertEqual(
jsonStatus,
status,
"Error json status")
}
}
| 2e3325ef863ae48956153a455fcf6549 | 28.753788 | 87 | 0.565627 | false | false | false | false |
mikina/SwiftNews | refs/heads/develop | SwiftNews/SwiftNews/Utils/Constants.swift | mit | 1 | //
// Constants.swift
// SwiftNews
//
// Created by Mike Mikina on 11/5/16.
// Copyright © 2016 SwiftCookies.com. All rights reserved.
//
import Foundation
struct Constants {
struct TabBar {
static let Height = 45
static let TopBorderColor = "#CECFD0"
static let TopBorderHeight = 1
static let DefaultButtonColor = "#ABA5A6"
static let DefaultSelectedButtonColor = "#4A4A4A"
static let SpikeButtonColor = "#FFFFFF"
static let SpikeSelectedButtonColor = "#F8E71C"
}
}
| 2a6e3b4a3bb07bb56e9d1b94f44ea62e | 23.047619 | 59 | 0.69703 | false | false | false | false |
pseudomuto/Retired | refs/heads/master | Examples/Retired iOS Demo/Retired iOS Demo/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Retired iOS Demo
//
// Created by David Muto on 2016-04-01.
// Copyright © 2016 pseudomuto. All rights reserved.
//
import Retired
import UIKit
// GET LINK FROM: https://linkmaker.itunes.apple.com/
let iTunesURL = NSURL(string: "itms-apps://geo.itunes.apple.com/us/app/popup-amazing-products-gift/id1057634612?mt=8")!
let versionURL = NSURL(string: "http://localhost:8000/Versions.json")!
let intervalBetweenRequests: NSTimeInterval = 60 * 60 * 24 // wait a day between requests (i.e. don't pester the user)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Retired.configure(versionURL, suppressionInterval: intervalBetweenRequests)
return true
}
func applicationDidBecomeActive(application: UIApplication) {
try! Retired.check() { updateRequired, message, error in
guard updateRequired else { return }
// handle error (non 200 status or network issue)
if let message = message {
message.presentInController(application.keyWindow?.rootViewController)
}
}
}
}
extension Message {
func presentInController(controller: UIViewController?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: continueButtonText, style: .Default, handler: goToAppStore))
if cancelButtonText != nil {
alert.addAction(UIAlertAction(title: cancelButtonText, style: .Cancel, handler: nil))
}
controller?.presentViewController(alert, animated: true, completion: nil)
}
private func goToAppStore(action: UIAlertAction) {
UIApplication.sharedApplication().openURL(iTunesURL)
}
}
| 6c07c2c3878db8e81100db5a7ee9e46d | 31.767857 | 125 | 0.73842 | false | false | false | false |
kumabook/FeedlyKit | refs/heads/master | Source/StreamsAPI.swift | mit | 1 | //
// StreamsAPI.swift
// FeedlyKit
//
// Created by Hiroki Kumamoto on 1/20/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
open class PaginationParams: ParameterEncodable {
open var count: Int?
open var ranked: String?
open var unreadOnly: Bool?
open var newerThan: Int64?
open var continuation: String?
public init() {}
open func toParameters() -> [String : Any] {
var params: [String:AnyObject] = [:]
if let c = count { params["count"] = c as AnyObject? }
if let r = ranked { params["ranked"] = r as AnyObject? }
if let u = unreadOnly { params["unreadOnly"] = u ? "true" as AnyObject? : "false" as AnyObject? }
if let n = newerThan { params["newerThan"] = NSNumber(value: n as Int64) }
if let co = continuation { params["continuation"] = co as AnyObject? }
return params
}
}
open class PaginatedEntryCollection: ResponseObjectSerializable {
open fileprivate(set) var id: String
open fileprivate(set) var updated: Int64?
open fileprivate(set) var continuation: String?
open fileprivate(set) var title: String?
open fileprivate(set) var direction: String?
open fileprivate(set) var alternate: Link?
open fileprivate(set) var items: [Entry]
required public convenience init?(response: HTTPURLResponse, representation: Any) {
self.init(json: JSON(representation))
}
public init(json: JSON) {
id = json["id"].stringValue
updated = json["updated"].int64
continuation = json["continuation"].string
title = json["title"].string
direction = json["direction"].string
alternate = json["alternate"].isEmpty ? nil : Link(json: json["alternate"])
items = json["items"].arrayValue.map({Entry(json: $0)})
}
public init(id: String, updated: Int64?, continuation: String?, title: String?, direction: String?, alternate: Link?, items: [Entry]) {
self.id = id
self.updated = updated
self.continuation = continuation
self.title = title
self.direction = direction
self.alternate = alternate
self.items = items
}
}
open class PaginatedIdCollection: ResponseObjectSerializable {
public let continuation: String?
public let ids: [String]
required public init?(response: HTTPURLResponse, representation: Any) {
let json = JSON(representation)
continuation = json["continuation"].string
ids = json["ids"].arrayValue.map({ $0.stringValue })
}
}
extension CloudAPIClient {
/**
Get a list of entry ids for a specific stream
GET /v3/streams/:streamId/ids
or
GET /v3/streams/ids?streamId=:streamId
(Authorization is optional; it is required for category and tag streams)
*/
public func fetchEntryIds(_ streamId: String, paginationParams: PaginationParams, completionHandler: @escaping (DataResponse<PaginatedIdCollection>) -> Void) -> Request {
return manager.request(Router.fetchEntryIds(target, streamId, paginationParams))
.validate()
.responseObject(completionHandler: completionHandler)
}
/**
Get the content of a stream
GET /v3/streams/:streamId/contents
or
GET /v3/streams/contents?streamId=:streamId
(Authorization is optional; it is required for category and tag streams)
*/
public func fetchContents(_ streamId: String, paginationParams: PaginationParams, completionHandler: @escaping (DataResponse<PaginatedEntryCollection>) -> Void) -> Request {
return manager.request(Router.fetchContents(target, streamId, paginationParams))
.validate()
.responseObject(completionHandler: completionHandler)
}
}
| 389b89c117fbbae0eff025c7443cd10d | 39.316832 | 177 | 0.626228 | false | false | false | false |
icoderRo/SMAnimation | refs/heads/master | SMDemo/iOS-MVX/MVVM/TableView/MVVMController.swift | mit | 2 | //
// MVVMController.swift
// iOS-MVX
//
// Created by simon on 2017/3/2.
// Copyright © 2017年 simon. All rights reserved.
//
import UIKit
class MVVMController: UIViewController {
fileprivate lazy var mvvmVM: MVVMVM = {return $0}(MVVMVM())
fileprivate lazy var tableView: UITableView = {[unowned self] in
let tableView = UITableView(frame: self.view.bounds)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .yellow
tableView.rowHeight = 70
tableView.register(UINib(nibName: "MVVMCell", bundle: nil), forCellReuseIdentifier: "cellId")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "MVVMTableView"
view.addSubview(tableView)
mvvmVM.loadData()
mvvmVM.reloadData = {[weak self] in
self?.tableView.reloadData()
}
}
}
extension MVVMController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mvvmVM.models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
mvvmVM.setCell(cell!, indexPath.row)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
| d34266c7ebbd0e0670d9e708f91061c7 | 27.203704 | 101 | 0.644123 | false | false | false | false |
fabiomassimo/eidolon | refs/heads/master | KioskTests/App/SwiftExtensionsTests.swift | mit | 1 | import Quick
import Nimble
import Kiosk
import ReactiveCocoa
class SwiftExtensionsTests: QuickSpec {
override func spec() {
describe("String") {
it("converts to UInt") {
let input = "4"
expect(input.toUInt()) == 4
}
it("returns nil if no conversion is available") {
let input = "not a number"
expect(input.toUInt()).to( beNil() )
}
it("uses a default if no conversion is available") {
let input = "not a number"
expect(input.toUInt(defaultValue: 4)) == 4
}
}
}
}
| a7fc0fd1d6e3925ee143ba4028b34a2b | 25.32 | 64 | 0.49696 | false | false | false | false |
algolia/algoliasearch-client-swift | refs/heads/master | Sources/AlgoliaSearchClient/Models/Search/MultipleIndex/BatchesResponse.swift | mit | 1 | //
// BatchesResponse.swift
//
//
// Created by Vladislav Fitc on 04/04/2020.
//
import Foundation
public struct BatchesResponse {
/// A list of TaskIndex to use with .waitAll.
public let tasks: [IndexedTask]
/// List of ObjectID affected by .multipleBatchObjects.
public let objectIDs: [ObjectID?]
}
extension BatchesResponse {
init(indexName: IndexName, responses: [BatchResponse]) {
let tasks: [IndexedTask] = responses.map { .init(indexName: indexName, taskID: $0.taskID) }
let objectIDs = responses.map(\.objectIDs).flatMap { $0 }
self.init(tasks: tasks, objectIDs: objectIDs)
}
}
extension BatchesResponse: Codable {
enum CodingKeys: String, CodingKey {
case tasks = "taskID"
case objectIDs
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let rawTasks: [String: Int] = try container.decode(forKey: .tasks)
self.tasks = rawTasks.map { rawIndexName, rawTaskID in IndexedTask(indexName: .init(rawValue: rawIndexName), taskID: .init(rawValue: String(rawTaskID))) }
self.objectIDs = try container.decode(forKey: .objectIDs)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
let rawTasks = [String: String](uniqueKeysWithValues: tasks.map { ($0.indexName.rawValue, $0.taskID.rawValue) })
try container.encode(rawTasks, forKey: .tasks)
try container.encode(objectIDs, forKey: .objectIDs)
}
}
| eabf3611f8dcce75c3ada35317510209 | 28.54902 | 158 | 0.711347 | false | false | false | false |
codwam/NPB | refs/heads/master | Demos/NPBDemo/NPB/Private/NPBConstant.swift | mit | 1 | //
// NPBConstant.swift
// NPBDemo
//
// Created by 李辉 on 2017/4/8.
// Copyright © 2017年 codwam. All rights reserved.
//
import Foundation
/*
系统私有属性
*/
// MARK: - UINavigationInteractiveTransition
let _UINavigationInteractiveTransition = "_UINavigationInteractiveTransition"
// 实际上就是 UINavigationController
let _UINavigationInteractiveTransition_Parent = "__parent"
// MARK: - UINavigationController
let _UINavigationController_IsTransitioning = "_isTransitioning"
let _UINavigationController_IsInteractiveTransition = "isInteractiveTransition"
let _UINavigationController_IsBuiltinTransition = "isBuiltinTransition"
// MARK: - interactivePopGestureRecognizer
let _InteractivePopGestureRecognizer_Targets = "_targets"
let _InteractivePopGestureRecognizer_HandleNavigationTransition = "handleNavigationTransition:"
let _InteractivePopGestureRecognizer_CanPanVertically = "canPanVertically"
// MARK: - UINavigationBar
let _UINavigationBar_PopForTouchAtPoint = "_popForTouchAtPoint"
let _UINavigationBar_BackgroundView = "_backgroundView"
let NPB_NavigationBarHeight = 44.0
// MARK: - UIToolbar
let _UIToolbar_ShadowView = "_shadowView"
// MARK: - CALayer
let kSnapshotLayerNameForTransition = "NPBNavigationExtensionSnapshotLayerName"
| 7a44925bb9c86dc6ca7f61881d99f436 | 23.230769 | 95 | 0.8 | false | false | false | false |
Adlai-Holler/BondPlusCoreData | refs/heads/master | BondPlusCoreDataTests/BondPlusCoreDataTests.swift | mit | 2 |
import CoreData
import Nimble
import Quick
import BondPlusCoreData
import Bond
import AlecrimCoreData
class DataContext: Context {
var stores: Table<Store> { return Table<Store>(context: self) }
var items: Table<Item> { return Table<Item>(context: self) }
}
class NSFetchedResultsDynamicArraySpec: QuickSpec {
override func spec() {
var context: DataContext!
var store: Store!
var importMore: (() -> ())!
beforeEach {
let bundle = NSBundle(forClass: self.classForCoder)
// create DB
AlecrimCoreData.Config.modelBundle = bundle
context = DataContext(stackType: .InMemory, managedObjectModelName: "BondPlusCoreDataTests", storeOptions: nil)
// load seed
let url = bundle.URLForResource("SeedData", withExtension: "json")!
let file = NSInputStream(URL: url)!
file.open()
var parseError: NSError?
let seedData = NSJSONSerialization.JSONObjectWithStream(file, options: .allZeros, error: &parseError)! as! [String: AnyObject]
file.close()
store = EKManagedObjectMapper.objectFromExternalRepresentation(seedData["store"]! as! [NSObject: AnyObject], withMapping: Store.objectMapping(), inManagedObjectContext: context.managedObjectContext) as! Store
context.managedObjectContext.processPendingChanges()
importMore = {
let url = bundle.URLForResource("MoreData", withExtension: "json")!
let file = NSInputStream(URL: url)!
file.open()
var parseError: NSError?
let moreData = NSJSONSerialization.JSONObjectWithStream(file, options: .allZeros, error: &parseError)! as! [String: AnyObject]
file.close()
let newItems = EKManagedObjectMapper.arrayOfObjectsFromExternalRepresentation(moreData["items"]! as! [[String: AnyObject]], withMapping: Item.objectMapping(), inManagedObjectContext: context.managedObjectContext) as! [Item]
store.mutableSetValueForKey("items").addObjectsFromArray(newItems)
context.managedObjectContext.processPendingChanges()
}
}
describe("Test Import") {
it("should load the store correctly") {
expect(store.name).to(equal("Adlai's Grocery"))
}
it("should load store.items correctly") {
expect(store.items.count).to(equal(6))
}
it("should load item attributes correctly") {
let anyItem = store.items.anyObject()! as! Item
let expectedItemNames = Set(["Apple", "Banana", "Cherry", "Asparagus", "Broccoli", "Celery"])
let actualItemNames = Set(context.items.toArray().map { $0.name })
expect(actualItemNames).to(equal(expectedItemNames))
}
}
describe("Fetched Results Array") {
var array: NSFetchedResultsDynamicArray<Item>!
var sectionBond: ArrayBond<NSFetchedResultsSectionDynamicArray<Item>>!
beforeEach {
let importantStore = context.stores.filterBy(attribute: "uuid", value: "2AB5041B-EF80-4910-8105-EC06B978C5DE").first()!
let fr = context.items
.filterBy(attribute: "store", value: importantStore)
.sortBy("itemType", ascending: true)
.thenByAscending("name")
.toFetchRequest()
let frc = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: context.managedObjectContext, sectionNameKeyPath: "itemType", cacheName: nil)
array = NSFetchedResultsDynamicArray(fetchedResultsController: frc)
sectionBond = ArrayBond()
array ->> sectionBond
}
it("should report correct number of sections") {
expect(array.count).to(equal(2))
}
it("should handle deleting the last section correctly") {
var removedSections = [Int]()
sectionBond.willRemoveListener = {array, indices in
removedSections += indices
}
context.items.filterBy(attribute: "itemType", value: "veggie").delete()
context.managedObjectContext.processPendingChanges()
expect(removedSections).to(equal([1]))
expect(array.count).to(equal(1))
}
it("should handle deleting all items correctly") {
var removedSections = [Int]()
sectionBond.willRemoveListener = {array, indices in
removedSections += indices
}
context.items.delete()
context.managedObjectContext.processPendingChanges()
for item in context.items {
println("item: \(item)")
}
expect(Set(removedSections)).to(equal(Set([0,1])))
expect(array.count).to(equal(0))
}
it("should handle delete at 0,0 correctly") {
let firstSectionBond = ArrayBond<Item>()
var removedIndices = [Int]()
firstSectionBond.willRemoveListener = { array, indices in
removedIndices += indices
}
array[0] ->> firstSectionBond
context.managedObjectContext.deleteObject(array[0][0])
context.managedObjectContext.processPendingChanges()
expect(removedIndices).to(equal([0]))
expect(array.count).to(equal(2))
expect(array[0].count).to(equal(2))
expect(array[0].first!.name).to(equal("Banana"))
}
it("should handle inserting many items (potentially out-of-order) correctly") {
let firstSectionBond = ArrayBond<Item>()
var insertedIndices = [Int]()
println("Items: \(array[0].value)")
firstSectionBond.willInsertListener = { array, indices in
insertedIndices += indices
}
array[0] ->> firstSectionBond
importMore()
println("Items: \(array[0].value)")
expect(insertedIndices).to(equal(Array(3...8)))
}
it("should handle update at 1,1 correctly") {
let lastSectionBond = ArrayBond<Item>()
var updatedIndices = [Int]()
lastSectionBond.willUpdateListener = { array, indices in
updatedIndices = indices
}
array[1] ->> lastSectionBond
let item = array[1][1]
item.count--
context.managedObjectContext.processPendingChanges()
expect(updatedIndices).to(equal([1]))
}
it("should handle inserting a section at index 1 correctly") {
let sectionsBond = ArrayBond<NSFetchedResultsSectionDynamicArray<Item>>()
var insertedSections = [Int]()
sectionsBond.willInsertListener = { array, indices in
insertedSections += indices
}
array ->> sectionsBond
let newItem = context.items.createEntity()
newItem.uuid = NSUUID().UUIDString
newItem.name = "Ground beef"
newItem.count = 10
newItem.itemType = "meat"
newItem.store = store
context.managedObjectContext.processPendingChanges()
expect(insertedSections).to(equal([1]))
}
}
}
}
| f15369ea19d2db73a71652f44d985050 | 37.335196 | 231 | 0.644273 | false | false | false | false |
bananafish911/SmartReceiptsiOS | refs/heads/master | SmartReceipts/Utils/ReportAssetsGenerator.swift | agpl-3.0 | 1 | //
// ReportAssetsGenerator.swift
// SmartReceipts
//
// Created by Jaanus Siim on 06/06/16.
// Copyright © 2016 Will Baumann. All rights reserved.
//
import Foundation
private struct Generation {
let fullPDF: Bool
let imagesPDF: Bool
let csv: Bool
let imagesZip: Bool
}
class ReportAssetsGenerator: NSObject {
// Generator's error representation
enum GeneratorError {
case fullPdfFailed // error in general
case fullPdfTooManyColumns // can't place all PDF columns
case imagesPdf
case csvFailed
case zipImagesFailed
}
fileprivate let trip: WBTrip
fileprivate var generate: Generation!
init(trip: WBTrip) {
self.trip = trip
}
func setGenerated(_ fullPDF: Bool, imagesPDF: Bool, csv: Bool, imagesZip: Bool) {
generate = Generation(fullPDF: fullPDF, imagesPDF: imagesPDF, csv: csv, imagesZip: imagesZip)
Logger.info("setGenerated: \(generate)")
}
/// Generate reports
///
/// - Parameter completion: [String] - array of resulting files (paths), GeneratorError - optional error
func generate(onSuccessHandler: ([String]) -> (), onErrorHandler: (GeneratorError) -> ()) {
var files = [String]()
let db = Database.sharedInstance()
trip.createDirectoryIfNotExists()
let tripName = trip.name ?? "Report"
let pdfPath = trip.file(inDirectoryPath: "\(tripName).pdf")
let pdfImagesPath = trip.file(inDirectoryPath: "\(tripName)Images.pdf")
let csvPath = trip.file(inDirectoryPath: "\(tripName).csv")
let zipPath = trip.file(inDirectoryPath: "\(tripName).zip")
if generate.fullPDF {
Logger.info("generate.fullPDF")
clearPath(pdfPath!)
guard let generator = TripFullPDFGenerator(trip: trip, database: db) else {
onErrorHandler(.fullPdfFailed)
return
}
if generator.generate(toPath: pdfPath) {
files.append(pdfPath!)
} else {
if generator.pdfRender.tableHasTooManyColumns {
onErrorHandler(.fullPdfTooManyColumns)
} else {
onErrorHandler(.fullPdfFailed)
}
return
}
}
if generate.imagesPDF {
Logger.info("generate.imagesPDF")
clearPath(pdfImagesPath!)
guard let generator = TripImagesPDFGenerator(trip: trip, database:db) else {
onErrorHandler(.imagesPdf)
return
}
if generator.generate(toPath: pdfImagesPath) {
files.append(pdfImagesPath!)
} else {
onErrorHandler(.imagesPdf)
return
}
}
if generate.csv {
Logger.info("generate.csv")
clearPath(csvPath!)
guard let generator = TripCSVGenerator(trip: trip, database: db) else {
onErrorHandler(.csvFailed)
return
}
if generator.generate(toPath: csvPath) {
files.append(csvPath!)
} else {
onErrorHandler(.csvFailed)
return
}
}
if generate.imagesZip {
Logger.info("generate.imagesZip")
clearPath(zipPath!)
let rai = WBReceiptAndIndex.receiptsAndIndices(fromReceipts: db?.allReceipts(for: trip), filteredWith: { receipt in
return WBReportUtils.filterOutReceipt(receipt)
})
let stamper = WBImageStampler()
if stamper.zip(toFile: zipPath, stampedImagesForReceiptsAndIndexes: rai, in: trip) {
files.append(zipPath!)
} else {
onErrorHandler(.zipImagesFailed)
return
}
}
onSuccessHandler(files)
}
fileprivate func clearPath(_ path: String) {
if !FileManager.default.fileExists(atPath: path) {
return
}
do {
try FileManager.default.removeItem(atPath: path)
} catch let error as NSError {
let errorEvent = ErrorEvent(error: error)
AnalyticsManager.sharedManager.record(event: errorEvent)
Logger.error("Remove file error \(error)")
}
}
}
| dd6667b5c56d62c37c79fd5ac4bd3c13 | 31.12766 | 128 | 0.553422 | false | false | false | false |
entotsu/TKSwarmAlert | refs/heads/master | TKSwarmAlert/Examples/SimplestExample.swift | mit | 1 | //
// ViewController.swift
// test
//
// Created by Takuya Okamoto on 2015/08/25.
// Copyright (c) 2015年 Uniface. All rights reserved.
//
import UIKit
import TKSwarmAlert
class SimpleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("view did load of simple view controller")
view.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
let testView = UIView()
testView.backgroundColor = UIColor.orange
testView.frame = CGRect(x: 40, y: 40, width: 40, height: 40)
view.addSubview(testView)
let fallView = UIView()
fallView.backgroundColor = UIColor.red
fallView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
fallView.center = view.center
let staticView = UIView()
staticView.backgroundColor = UIColor.blue
staticView.frame = CGRect(x: 250, y: 250, width: 50, height: 50)
Timer.schedule(delay: 1) { timer in
let alert = TKSwarmAlert(backgroundType: .brightBlur)
alert.durationOfPreventingTapBackgroundArea = 3
alert.addSubStaticView(staticView)
alert.show([fallView])
alert.didDissmissAllViews = {
print("didDissmissAllViews")
}
}
}
}
| dc87a5fcdc2d66c0beaa303bc97c96b8 | 26.48 | 72 | 0.605531 | false | true | false | false |
Vienta/kuafu | refs/heads/master | kuafu/kuafu/src/Controller/KFLisenceDetailViewController.swift | mit | 1 | //
// KFLisenceDetailViewController.swift
// kuafu
//
// Created by Vienta on 15/7/18.
// Copyright (c) 2015年 www.vienta.me. All rights reserved.
//
import UIKit
class KFLisenceDetailViewController: UIViewController {
@IBOutlet weak var txvLisence: UITextView!
var lisenceName: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = self.lisenceName
var lisenceFileName: String = self.lisenceName + "_LICENSE"
let path = NSBundle.mainBundle().pathForResource(lisenceFileName, ofType: "txt")
var lisenceContent: String! = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)
self.txvLisence.text = lisenceContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 1b309a839db64fcb64b0fb919651be63 | 28.4375 | 111 | 0.68896 | false | false | false | false |
coderZsq/coderZsq.target.swift | refs/heads/master | StudyNotes/Swift Note/PhotoBrowser/PhotoBrowser/Classes/Home/FlowLayout/HomeFlowLayout.swift | mit | 1 | //
// HomeFlowLayout.swift
// PhotoBrowser
//
// Created by 朱双泉 on 2018/10/30.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
class HomeFlowLayout: UICollectionViewFlowLayout {
override func prepare() {
let itemCountInRow: CGFloat = 3
let margin: CGFloat = 10
let itemW = (kScreenW - (itemCountInRow + 1) * margin) / itemCountInRow
let itemH = itemW * 1.3
itemSize = CGSize(width: itemW, height: itemH)
minimumLineSpacing = margin
minimumInteritemSpacing = margin
collectionView?.contentInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
}
}
| b1c3bfa2d36e619125df8e9fe8068fec | 28.043478 | 109 | 0.66018 | false | false | false | false |
thisfin/HostsManager | refs/heads/develop | HostsManager/WYVerticalCenterTextField.swift | mit | 1 | //
// WYVerticalCenterTextField.swift
// EmptyProject
//
// Created by wenyou on 2017/6/16.
// Copyright © 2017年 fin. All rights reserved.
//
import AppKit
// https://stackoverflow.com/questions/11775128/set-text-vertical-center-in-nstextfield
// NSTextField().cell = WYVerticalCenterTextFieldCell()
class WYVerticalCenterTextFieldCell: NSTextFieldCell {
override func titleRect(forBounds rect: NSRect) -> NSRect {
var titleRect = super.titleRect(forBounds: rect)
let minimumHeight = cellSize(forBounds: rect).height
titleRect.origin.y += (titleRect.height - minimumHeight) / 2
titleRect.size.height = minimumHeight
return titleRect
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
super.drawInterior(withFrame: titleRect(forBounds: cellFrame), in: controlView)
}
override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
super.select(withFrame: titleRect(forBounds: rect), in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
}
}
| 3d0af5d793ef336c453201a5d9f44b1f | 39.965517 | 158 | 0.725589 | false | false | false | false |
erusso1/ERNiftyFoundation | refs/heads/master | ERNiftyFoundation/Source/Classes/ERModelType.swift | mit | 1 | //
// ERModelType.swift
// Pods
//
// Created by Ephraim Russo on 8/31/17.
//
//
import Unbox
import Wrap
public protocol ERModelType: Equatable, Unboxable, WrapCustomizable, CustomDebugStringConvertible {
/// Returns the unique identifier of the model object.
var id: String { get }
/// Returns the JSON dictionary representation of the model object. May return `nil` due to Wrap errors.
var JSON: JSONObject? { get }
/// Creates a new model object given the passed JSON argument. Call can throw Unbox errors.
init(JSON: JSONObject) throws
}
extension ERModelType {
/// Returns the JSON dictionary computed by the `Wrap` framework. The encoded keys are determined by the `wrapKeyStyle` property, with a default set to `matchPropertyName`.
public var JSON: JSONObject? {
do { return try Wrap.wrap(self) }
catch { printPretty("Cannot return JSON for model with id: \(id) - error: \(error.localizedDescription)"); return nil }
}
/// Creates a new model object by unboxing the passed `JSON` dictionary.
public init(JSON: JSONObject) throws { try self.init(unboxer: Unboxer(dictionary: JSON)) }
}
public func ==<T: ERModelType>(lhs: T, rhs: T) -> Bool { return lhs.id == rhs.id }
extension ERModelType {
public var debugDescription: String {
if let json = self.JSON {
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)!
return string as String
}
else { return "\(self)" }
}
}
extension ERModelType {
/// The key style encoding type used by the `Wrap` framework. Default is set to `.matchPropertyName`.
public var wrapKeyStyle: WrapKeyStyle { return .matchPropertyName }
public func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
guard let date = originalValue as? Date else {return nil}
return ERDateIntervalFormatter.formatterType == .milliseconds ? Double(Int(date.timeIntervalSince1970*1000.0.rounded())) : (Int(date.timeIntervalSince1970.rounded()))
}
}
| e848c83c58228bca0e6a9312634e5b74 | 32.166667 | 174 | 0.702604 | false | false | false | false |
AnneBlair/YYGRegular | refs/heads/master | YYGRegular/YYGText.swift | mit | 1 | //
// YYGText.swift
// 24demo
//
// Created by 区块国际-yin on 17/2/10.
// Copyright © 2017年 区块国际-yin. All rights reserved.
//
import UIKit
/// Seting AttributedString
///
/// - Parameters:
/// - color: 颜色 Arry [[RGB,RGB,RGB],[RGB,RGB,RGB]]
/// - content: 内容 Arry ["第一个","第二个"]
/// - size: 字体 Arry [size1,size2]
/// - Returns: 富文本
public func setAttribute(color: [[Int]],content:[String],size: [CGFloat])-> NSMutableAttributedString {
let str = NSMutableAttributedString()
for i in 0..<color.count {
str.append(NSAttributedString(string: content[i], attributes: [NSForegroundColorAttributeName: UIColor(hex: color[i][0]), NSFontAttributeName:UIFont.systemFont(ofSize: size[i])]))
}
return str
}
/// scientific Notation Transition Normal String
/// 9.0006e+07 Transition 90,006,000
/// - Parameter f_loat: Input
/// - Returns: Output
public func inputFOutputS(f_loat: Double) -> String {
let numFormat = NumberFormatter()
numFormat.numberStyle = NumberFormatter.Style.decimal
let num = NSNumber.init(value: f_loat)
return numFormat.string(from: num)!
}
// MARK: - 数字转换成字符串金额 11121.01 -> "11,121.01" 三位一个逗号
extension NSNumber {
var dollars: String {
let formatter: NumberFormatter = NumberFormatter()
var result: String?
formatter.numberStyle = NumberFormatter.Style.decimal
result = formatter.string(from: self)
if result == nil {
return "error"
}
return result!
}
}
extension String {
/// 截取第一个到第任意位置
///
/// - Parameter end: 结束的位值
/// - Returns: 截取后的字符串
func stringCut(end: Int) ->String{
printLogDebug(self.characters.count)
if !(end < characters.count) { return "截取超出范围" }
let sInde = index(startIndex, offsetBy: end)
return substring(to: sInde)
}
/// 截取人任意位置到结束
///
/// - Parameter end:
/// - Returns: 截取后的字符串
func stringCutToEnd(star: Int) -> String {
if !(star < characters.count) { return "截取超出范围" }
let sRang = index(startIndex, offsetBy: star)..<endIndex
return substring(with: sRang)
}
/// 字符串任意位置插入
///
/// - Parameters:
/// - content: 插入内容
/// - locat: 插入的位置
/// - Returns: 添加后的字符串
func stringInsert(content: String,locat: Int) -> String {
if !(locat < characters.count) { return "截取超出范围" }
let str1 = stringCut(end: locat)
let str2 = stringCutToEnd(star: locat)
return str1 + content + str2
}
/// 计算字符串宽高
///
/// - Parameter size: size
/// - Returns: CGSize
func getStringSzie(size: CGFloat = 10) -> CGSize {
let baseFont = UIFont.systemFont(ofSize: size)
let size = self.size(attributes: [NSFontAttributeName: baseFont])
let width = ceil(size.width) + 5
let height = ceil(size.height)
return CGSize(width: width, height: height)
}
/// 输入字符串 输出数组
/// e.g "qwert" -> ["q","w","e","r","t"]
/// - Returns: ["q","w","e","r","t"]
func stringToArr() -> [String] {
let num = characters.count
if !(num > 0) { return [""] }
var arr: [String] = []
for i in 0..<num {
let tempStr: String = self[self.index(self.startIndex, offsetBy: i)].description
arr.append(tempStr)
}
return arr
}
/// 字符串截取 3 6
/// e.g let aaa = "abcdefghijklmnopqrstuvwxyz" -> "cdef"
/// - Parameters:
/// - start: 开始位置 3
/// - end: 结束位置 6
/// - Returns: 截取后的字符串 "cdef"
func startToEnd(start: Int,end: Int) -> String {
if !(end < characters.count) || start > end { return "取值范围错误" }
var tempStr: String = ""
for i in start...end {
let temp: String = self[self.index(self.startIndex, offsetBy: i - 1)].description
tempStr += temp
}
return tempStr
}
/// 字符URL格式化
///
/// - Returns: 格式化的 url
func stringEncoding() -> String {
let url = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
return url!
}
}
| efc136c313594f727aa82131b4ef5a06 | 29.072464 | 187 | 0.580482 | false | false | false | false |
slmcmahon/Coins2 | refs/heads/master | Coins2/CoinViewModel.swift | mit | 1 | //
// CoinViewModel.swift
// Coins2
//
// Created by Stephen McMahon on 6/20/17.
// Copyright © 2017 Stephen McMahon. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class CoinViewModel {
func recognizeImage(onSuccess:@escaping (String) -> Void, onFailure:@escaping (String) -> Void, image : UIImage) {
let resized = self.resizeImage(image: image, size: CGSize(width: image.size.width / 4.0, height: image.size.height / 4.0))
let imgData = UIImagePNGRepresentation(resized)
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData!, withName: "image",fileName: "png", mimeType: "image/png")
}, to:Constants.RecognizerUrl, headers: ["Prediction-Key" : Constants.PredictionKey])
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value ?? "")
let json = JSON(response.result.value ?? "")
let predictions = json["Predictions"].array!
onSuccess(self.readPredictions(predictions: predictions))
}
case .failure(let encodingError):
onFailure(encodingError as! String)
}
}
}
func readPredictions(predictions : [JSON]) -> String {
var allCoinsProbability = 0
var coinName = "unknown"
var coinProbability = 0.00000001
for dic in predictions {
let tag = dic["Tag"].string!
let pb = dic["Probability"].doubleValue
let percent = pb * 100
if tag == "All Coins" {
if Int(percent) < Constants.MinimumProbability {
return "We didn't recognize any coins in this photo"
} else {
allCoinsProbability = Int(percent)
continue
}
}
if (pb > coinProbability) {
coinProbability = pb
// all of the tags are pluralized, but we want to refer to the singular form in the response.
coinName = tag == "Pennies" ? "Penny" : tag.substring(to: tag.index(before: tag.endIndex))
}
}
return "We are \(allCoinsProbability) certain that the photo contains a \(coinName)."
}
private func resizeImage(image : UIImage, size : CGSize) -> UIImage {
UIGraphicsBeginImageContext(size)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
image.draw(in: rect)
let destImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return destImage!
}
}
| 72a1da4fc949645fbdd7ede1534a56fc | 37.602564 | 130 | 0.564264 | false | false | false | false |
szk-atmosphere/MartyJunior | refs/heads/master | MartyJunior/MJViewController.swift | mit | 1 | //
// MJSlideViewController.swift
// MartyJunior
//
// Created by 鈴木大貴 on 2015/11/26.
// Copyright © 2015年 Taiki Suzuki. All rights reserved.
//
import UIKit
import MisterFusion
open class MJViewController: UIViewController {
//MARK: - Inner class
private class RegisterCellContainer {
struct NibAndIdentifierContainer {
let nib: UINib?
let reuseIdentifier: String
}
struct ClassAndIdentifierContainer {
let aClass: AnyClass?
let reuseIdentifier: String
}
var cellNib: [NibAndIdentifierContainer] = []
var cellClass: [ClassAndIdentifierContainer] = []
var headerFooterNib: [NibAndIdentifierContainer] = []
var headerFooterClass: [ClassAndIdentifierContainer] = []
}
//MAKR: - Properties
public weak var delegate: MJViewControllerDelegate?
public weak var dataSource: MJViewControllerDataSource?
private let scrollView: UIScrollView = UIScrollView()
private let scrollContainerView: UIView = UIView()
private var scrollContainerViewWidthConstraint: NSLayoutConstraint?
fileprivate let contentView: MJContentView = MJContentView()
fileprivate let contentEscapeView: UIView = UIView()
fileprivate var contentEscapeViewTopConstraint: NSLayoutConstraint?
public private(set) var navigationView: MJNavigationView?
private let navigationContainerView = UIView()
private var containerViews: [UIView] = []
fileprivate var viewControllers: [MJTableViewController] = []
private let registerCellContainer: RegisterCellContainer = RegisterCellContainer()
public var hiddenNavigationView: Bool = false
public var tableViews: [UITableView] {
return viewControllers.map { $0.tableView }
}
public private(set) var titles: [String]?
public private(set) var numberOfTabs: Int = 0
private var _selectedIndex: Int = 0 {
didSet {
delegate?.mjViewController?(self, didChangeSelectedIndex: _selectedIndex)
}
}
public var selectedIndex: Int {
get {
let index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
if _selectedIndex != index {
_selectedIndex = index
viewControllers.enumerated().forEach { $0.element.tableView.scrollsToTop = $0.offset == index }
}
return index
}
set {
_selectedIndex = newValue
addContentViewToEscapeView()
UIView.animate(withDuration: 0.25, animations: {
self.scrollView.setContentOffset(CGPoint(x: self.scrollView.bounds.size.width * CGFloat(newValue), y: 0), animated: false)
}) { _ in
if let superview = self.contentView.superview, let constant = self.contentEscapeViewTopConstraint?.constant,
superview == self.contentEscapeView && self.scrollView.contentOffset.y < constant {
self.addContentViewToCell()
}
}
}
}
public var headerHeight: CGFloat {
return contentView.tabContainerView.frame.size.height + navigationContainerViewHeight
}
public var selectedViewController: MJTableViewController {
return viewControllers[selectedIndex]
}
private var navigationContainerViewHeight: CGFloat {
let sharedApplication = UIApplication.shared
let statusBarHeight = sharedApplication.isStatusBarHidden ? 0 : sharedApplication.statusBarFrame.size.height
let navigationViewHeight: CGFloat = hiddenNavigationView ? 0 : 44
return statusBarHeight + navigationViewHeight
}
fileprivate func indexOfViewController(_ viewController: MJTableViewController) -> Int {
return viewControllers.index(of: viewController) ?? 0
}
//MARK: - Life cycle
open func viewWillSetupForMartyJunior() {}
open func viewDidSetupForMartyJunior() {}
open override func viewDidLoad() {
super.viewDidLoad()
viewWillSetupForMartyJunior()
guard let dataSource = dataSource else { return }
titles = dataSource.mjViewControllerTitlesForTab?(self)
numberOfTabs = dataSource.mjViewControllerNumberOfTabs(self)
setupContentView(dataSource)
setupScrollView()
setupScrollContainerView()
setupContainerViews()
setupTableViewControllers()
registerNibAndClassForTableViews()
setupContentEscapeView()
setNavigationView()
viewDidSetupForMartyJunior()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewControllers.forEach { $0.tableView.reloadData() }
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.setNeedsDisplay()
view.layoutIfNeeded()
}
open override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Setup views
private func setupContentView(_ dataSource: MJViewControllerDataSource) {
contentView.titles = titles
contentView.segmentedControl.selectedSegmentIndex = 0
contentView.userDefinedView = dataSource.mjViewControllerContentViewForTop(self)
contentView.userDefinedTabView = dataSource.mjViewControllerTabViewForTop?(self)
contentView.setupTabView()
}
private func setupScrollView() {
scrollView.scrollsToTop = false
scrollView.isPagingEnabled = true
scrollView.delegate = self
scrollView.showsHorizontalScrollIndicator = false
view.addLayoutSubview(scrollView, andConstraints:
scrollView.top,
scrollView.left,
scrollView.right,
scrollView.bottom
)
}
private func setupScrollContainerView() {
scrollContainerViewWidthConstraint = scrollView.addLayoutSubview(scrollContainerView, andConstraints:
scrollContainerView.top,
scrollContainerView.left,
scrollContainerView.right,
scrollContainerView.bottom,
scrollContainerView.height |==| scrollView.height,
scrollContainerView.width |==| scrollView.width |*| CGFloat(numberOfTabs)
).firstAttribute(.width).first
}
private func setupContentEscapeView() {
contentEscapeViewTopConstraint = view.addLayoutSubview(contentEscapeView, andConstraints:
contentEscapeView.top,
contentEscapeView.left,
contentEscapeView.right,
contentEscapeView.height |==| contentView.currentHeight
).firstAttribute(.top).first
view.layoutIfNeeded()
contentEscapeView.backgroundColor = .clear
contentEscapeView.isUserInteractionEnabled = false
contentEscapeView.isHidden = true
}
private func setNavigationView() {
view.addLayoutSubview(navigationContainerView, andConstraints:
navigationContainerView.top,
navigationContainerView.left,
navigationContainerView.right,
navigationContainerView.height |==| navigationContainerViewHeight
)
if hiddenNavigationView { return }
let navigationView = MJNavigationView()
navigationContainerView.addLayoutSubview(navigationView, andConstraints:
navigationView.height |==| MJNavigationView.Height,
navigationView.left,
navigationView.bottom,
navigationView.right
)
navigationView.titleLabel.text = title
self.navigationView = navigationView
}
private func setupContainerViews() {
(0..<numberOfTabs).forEach {
let containerView = UIView()
let misterFusions: [MisterFusion]
switch $0 {
case 0:
misterFusions = [
containerView.left,
]
case (numberOfTabs - 1):
guard let previousContainerView = containerViews.last else { return }
misterFusions = [
containerView.right,
containerView.left |==| previousContainerView.right,
]
default:
guard let previousContainerView = containerViews.last else { return }
misterFusions = [
containerView.left |==| previousContainerView.right,
]
}
let commomMisterFusions = [
containerView.top,
containerView.bottom,
containerView.width |/| CGFloat(numberOfTabs)
]
scrollContainerView.addLayoutSubview(containerView, andConstraints: misterFusions + commomMisterFusions)
containerViews += [containerView]
}
contentView.delegate = self
}
private func setupTableViewControllers() {
containerViews.forEach {
let viewController = MJTableViewController()
viewController.delegate = self
viewController.dataSource = self
viewController.contentView = self.contentView
$0.addLayoutSubview(viewController.view, andConstraints:
viewController.view.top,
viewController.view.left,
viewController.view.right,
viewController.view.bottom
)
addChildViewController(viewController)
viewController.didMove(toParentViewController: self)
viewControllers += [viewController]
}
}
private func registerNibAndClassForTableViews() {
tableViews.forEach { tableView in
registerCellContainer.cellNib.forEach { tableView.register($0.nib, forCellReuseIdentifier: $0.reuseIdentifier) }
registerCellContainer.headerFooterNib.forEach { tableView.register($0.nib, forHeaderFooterViewReuseIdentifier: $0.reuseIdentifier) }
registerCellContainer.cellClass.forEach { tableView.register($0.aClass, forCellReuseIdentifier: $0.reuseIdentifier) }
registerCellContainer.headerFooterClass.forEach { tableView.register($0.aClass, forHeaderFooterViewReuseIdentifier: $0.reuseIdentifier) }
}
}
//MARK: - ContentView moving
fileprivate func addContentViewToCell() {
if contentView.superview != contentEscapeView { return }
contentEscapeView.isHidden = true
contentEscapeView.isUserInteractionEnabled = false
let cells = selectedViewController.tableView.visibleCells.filter { $0.isKind(of: MJTableViewTopCell.self) }
let cell = cells.first as? MJTableViewTopCell
cell?.mainContentView = contentView
}
fileprivate func addContentViewToEscapeView() {
if contentView.superview == contentEscapeView { return }
contentEscapeView.isHidden = false
contentEscapeView.isUserInteractionEnabled = true
contentEscapeView.addLayoutSubview(contentView, andConstraints:
contentView.top,
contentView.left,
contentView.right,
contentView.bottom
)
let topConstant = max(0, min(contentView.frame.size.height - headerHeight, selectedViewController.tableView.contentOffset.y))
contentEscapeViewTopConstraint?.constant = -topConstant
contentEscapeView.layoutIfNeeded()
}
//MARK: - Private
fileprivate func setTableViewControllersContentOffsetBasedOnScrollView(_ scrollView: UIScrollView, withoutSelectedViewController: Bool) {
let viewControllers = self.viewControllers.filter { $0 != selectedViewController }
let contentHeight = contentView.frame.size.height - headerHeight
viewControllers.forEach {
let tableView = $0.tableView
let contentOffset: CGPoint
if scrollView.contentOffset.y <= contentHeight {
contentOffset = scrollView.contentOffset
} else {
contentOffset = tableView.contentOffset.y >= contentHeight ? tableView.contentOffset : CGPoint(x: 0, y: contentHeight)
}
tableView.setContentOffset(contentOffset, animated: false)
}
}
//MARK: - Public
public func registerNibToAllTableViews(_ nib: UINib?, forCellReuseIdentifier reuseIdentifier: String) {
registerCellContainer.cellNib += [RegisterCellContainer.NibAndIdentifierContainer(nib: nib, reuseIdentifier: reuseIdentifier)]
}
public func registerNibToAllTableViews(_ nib: UINib?, forHeaderFooterViewReuseIdentifier reuseIdentifier: String) {
registerCellContainer.headerFooterNib += [RegisterCellContainer.NibAndIdentifierContainer(nib: nib, reuseIdentifier: reuseIdentifier)]
}
public func registerClassToAllTableViews(_ aClass: AnyClass?, forCellReuseIdentifier reuseIdentifier: String) {
registerCellContainer.cellClass += [RegisterCellContainer.ClassAndIdentifierContainer(aClass: aClass, reuseIdentifier: reuseIdentifier)]
}
public func registerClassToAllTableViews(_ aClass: AnyClass?, forHeaderFooterViewReuseIdentifier reuseIdentifier: String) {
registerCellContainer.headerFooterClass += [RegisterCellContainer.ClassAndIdentifierContainer(aClass: aClass, reuseIdentifier: reuseIdentifier)]
}
}
//MARK: - UIScrollViewDelegate
extension MJViewController: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
delegate?.mjViewController?(self, contentScrollViewDidScroll: scrollView)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if let constant = contentEscapeViewTopConstraint?.constant, !decelerate && scrollView.contentOffset.y < constant {
addContentViewToCell()
}
contentView.segmentedControl.selectedSegmentIndex = selectedIndex
delegate?.mjViewController?(self, contentScrollViewDidEndDragging: scrollView, willDecelerate: decelerate)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if let constant = contentEscapeViewTopConstraint?.constant, scrollView.contentOffset.y < constant {
addContentViewToCell()
}
contentView.segmentedControl.selectedSegmentIndex = selectedIndex
delegate?.mjViewController?(self, contentScrollViewDidEndDecelerating: scrollView)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
addContentViewToEscapeView()
delegate?.mjViewController?(self, contentScrollViewWillBeginDragging: scrollView)
}
}
//MARK: - MJTableViewControllerDataSource
extension MJViewController: MJTableViewControllerDataSource {
func tableViewControllerHeaderHeight(_ viewController: MJTableViewController) -> CGFloat {
return headerHeight
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell? {
return dataSource?.mjViewController(self, targetIndex: indexOfViewController(viewController), tableView: tableView, cellForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, numberOfRowsInSection section: Int) -> Int? {
return dataSource?.mjViewController(self, targetIndex: indexOfViewController(viewController), tableView: tableView, numberOfRowsInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, numberOfSectionsInTableView tableView: UITableView) -> Int? {
return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), numberOfSectionsInTableView: tableView)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, titleForHeaderInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, titleForFooterInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool? {
return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canEditRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canMoveRowAtIndexPath indexPath: IndexPath) -> Bool? {
return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canMoveRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, sectionIndexTitlesForTableView tableView: UITableView) -> [String]? {
return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), sectionIndexTitlesForTableView: tableView)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int? {
return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, sectionForSectionIndexTitle: title, atIndex: index)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) {
dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) {
dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath)
}
}
//MARK: - MJTableViewControllerDelegate
extension MJViewController: MJTableViewControllerDelegate {
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForTopCellAtIndexPath indexPath: IndexPath) -> CGFloat {
return contentView.currentHeight
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForTopCellAtIndexPath indexPath: IndexPath) -> CGFloat {
return contentView.currentHeight
}
func tableViewController(_ viewController: MJTableViewController, tableViewTopCell cell: MJTableViewTopCell) {
if viewController != selectedViewController { return }
if contentView.superview != contentEscapeView {
cell.mainContentView = contentView
}
}
func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndDecelerating scrollView: UIScrollView) {
if viewController != selectedViewController { return }
setTableViewControllersContentOffsetBasedOnScrollView(scrollView, withoutSelectedViewController: true)
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndDecelerating: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewDidScroll scrollView: UIScrollView) {
if viewController != selectedViewController { return }
if scrollView.contentOffset.y > contentView.frame.size.height - headerHeight {
addContentViewToEscapeView()
} else {
addContentViewToCell()
}
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidScroll: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndDragging scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if viewController != selectedViewController { return }
setTableViewControllersContentOffsetBasedOnScrollView(scrollView, withoutSelectedViewController: true)
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndDragging: scrollView, willDecelerate: decelerate)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewDidZoom scrollView: UIScrollView) {
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidZoom: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewWillBeginDragging scrollView: UIScrollView) {
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillBeginDragging: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewWillEndDragging scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillEndDragging: scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewWillBeginDecelerating scrollView: UIScrollView) {
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillBeginDecelerating: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndScrollingAnimation scrollView: UIScrollView) {
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndScrollingAnimation: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, viewForZoomingInScrollView scrollView: UIScrollView) -> UIView? {
if viewController != selectedViewController { return nil }
return delegate?.mjViewController?(self, selectedIndex: selectedIndex, viewForZoomingInScrollView: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewWillBeginZooming scrollView: UIScrollView, withView view: UIView?) {
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillBeginZooming: scrollView, withView: view)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndZooming scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndZooming: scrollView, withView: view, atScale: scale)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewShouldScrollToTop scrollView: UIScrollView) -> Bool? {
if viewController != selectedViewController { return false }
return delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewShouldScrollToTop: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, scrollViewDidScrollToTop scrollView: UIScrollView) {
viewControllers.filter { $0 != self.selectedViewController }.forEach { $0.tableView.setContentOffset(.zero, animated: false) }
if viewController != selectedViewController { return }
delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidScrollToTop: scrollView)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDisplayHeaderView: view, forSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDisplayFooterView: view, forSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndDisplayingCell: cell, forRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndDisplayingHeaderView: view, forSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndDisplayingFooterView: view, forSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, heightForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, heightForHeaderInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, heightForFooterInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: IndexPath) -> CGFloat? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, estimatedHeightForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, estimatedHeightForHeaderInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, estimatedHeightForFooterInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, viewForHeaderInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, viewForFooterInSection: section)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, accessoryButtonTappedForRowWithIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: IndexPath) -> Bool? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldHighlightRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didHighlightRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didHighlightRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didUnhighlightRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willSelectRowAtIndexPath indexPath: IndexPath) -> IndexPath? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willSelectRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDeselectRowAtIndexPath indexPath: IndexPath) -> IndexPath? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDeselectRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didSelectRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didDeselectRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didDeselectRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, editingStyleForRowAtIndexPath indexPath: IndexPath) -> UITableViewCellEditingStyle? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, editingStyleForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: IndexPath) -> String? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, titleForDeleteConfirmationButtonForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [UITableViewRowAction]? {
return delegate?.mjViewController?(self, selectedIndex: indexOfViewController(viewController), tableView: tableView, editActionsForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: IndexPath) -> Bool? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldIndentWhileEditingRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willBeginEditingRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndEditingRowAtIndexPath indexPath: IndexPath) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndEditingRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, targetIndexPathForMoveFromRowAtIndexPath: sourceIndexPath, toProposedIndexPath: proposedDestinationIndexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: IndexPath) -> Int? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, indentationLevelForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: IndexPath) -> Bool? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldShowMenuForRowAtIndexPath: indexPath)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: IndexPath, withSender sender: AnyObject?) -> Bool? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canPerformAction: action, forRowAtIndexPath: indexPath, withSender: sender)
}
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: IndexPath, withSender sender: AnyObject?) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, performAction: action, forRowAtIndexPath: indexPath, withSender: sender)
}
@available(iOS 9.0, *)
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canFocusRowAtIndexPath indexPath: IndexPath) -> Bool? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canFocusRowAtIndexPath: indexPath)
}
@available(iOS 9.0, *)
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldUpdateFocusInContext context: UITableViewFocusUpdateContext) -> Bool? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldUpdateFocusInContext: context)
}
@available(iOS 9.0, *)
func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didUpdateFocusInContext context: UITableViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didUpdateFocusInContext: context, withAnimationCoordinator: coordinator)
}
@available(iOS 9.0, *)
func tableViewController(_ viewController: MJTableViewController, indexPathForPreferredFocusedViewInTableView tableView: UITableView) -> IndexPath? {
return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), indexPathForPreferredFocusedViewInTableView: tableView)
}
}
//MARK: - MJContentViewDelegate
extension MJViewController: MJContentViewDelegate {
func contentView(_ contentView: MJContentView, didChangeValueOfSegmentedControl segmentedControl: UISegmentedControl) {
selectedIndex = segmentedControl.selectedSegmentIndex
}
}
| 68740447ec392b182c26dc18592effaa | 55.473763 | 239 | 0.741956 | false | false | false | false |
phimage/Prephirences | refs/heads/master | Xcodes/Mac/PreferencesTabViewController.swift | mit | 1 | //
// PreferencesTabViewController.swift
// Prephirences
/*
The MIT License (MIT)
Copyright (c) 2017 Eric Marchand (phimage)
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 Cocoa
/* Controller of tab view item can give prefered size by implementing this protocol */
@objc public protocol PreferencesTabViewItemControllerType {
var preferencesTabViewSize: NSSize {get}
}
/* Key for event on property preferencesTabViewSize */
public let kPreferencesTabViewSize = "preferencesTabViewSize"
/* Controller which resize parent window according to tab view items, useful for preferences */
@available(OSX 10.10, *)
public class PreferencesTabViewController: NSTabViewController {
private var observe = false
// Keep size of subview
private var cacheSize = [NSView: NSSize]()
// MARK: overrides
override public func viewDidLoad() {
super.viewDidLoad()
self.transitionOptions = []
}
override public func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) {
// remove listener on previous selected tab view
if let selectedTabViewItem = self.selectedTabViewItem as? NSTabViewItem,
let viewController = selectedTabViewItem.viewController as? PreferencesTabViewItemControllerType, observe {
(viewController as! NSViewController).removeObserver(self, forKeyPath: kPreferencesTabViewSize, context: nil)
observe = false
}
super.tabView(tabView, willSelect: tabViewItem)
// get size and listen to change on futur selected tab view item
if let view = tabViewItem?.view {
let currentSize = view.frame.size // Expect size from storyboard constraints or previous size
if let viewController = tabViewItem?.viewController as? PreferencesTabViewItemControllerType {
cacheSize[view] = getPreferencesTabViewSize(viewController, currentSize)
// Observe kPreferencesTabViewSize
let options = NSKeyValueObservingOptions.new.union(.old)
(viewController as! NSViewController).addObserver(self, forKeyPath: kPreferencesTabViewSize, options: options, context: nil)
observe = true
}
else {
cacheSize[view] = cacheSize[view] ?? currentSize
}
}
}
override public func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
super.tabView(tabView, didSelect: tabViewItem)
if let view = tabViewItem?.view, let window = self.view.window, let contentSize = cacheSize[view] {
self.setFrameSize(size: contentSize, forWindow: window)
}
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let kp = keyPath, kp == kPreferencesTabViewSize {
if let window = self.view.window, let viewController = object as? PreferencesTabViewItemControllerType,
let view = (viewController as? NSViewController)?.view, let currentSize = cacheSize[view] {
let contentSize = self.getPreferencesTabViewSize(viewController, currentSize)
cacheSize[view] = contentSize
DispatchQueue.main.async {
self.setFrameSize(size: contentSize, forWindow: window)
}
}
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
override public func removeTabViewItem(_ tabViewItem: NSTabViewItem) {
if let _ = tabViewItem.view {
if let viewController = tabViewItem.viewController as? PreferencesTabViewItemControllerType {
tabViewItem.removeObserver(viewController as! NSViewController, forKeyPath: kPreferencesTabViewSize)
}
}
}
func _removeAllToolbarItems(){
// Maybe fix a bug with toolbar style
}
deinit {
if let selectedTabViewItem = self.selectedTabViewItem as? NSTabViewItem,
let viewController = selectedTabViewItem.viewController as? PreferencesTabViewItemControllerType, observe {
(viewController as! NSViewController).removeObserver(self, forKeyPath: kPreferencesTabViewSize, context: nil)
}
}
// MARK: public
public var selectedTabViewItem: AnyObject? {
return selectedTabViewItemIndex<0 ? nil : tabViewItems[selectedTabViewItemIndex]
}
// MARK: privates
private func getPreferencesTabViewSize(_ viewController: PreferencesTabViewItemControllerType,_ referenceSize: NSSize) -> NSSize {
var controllerProposedSize = viewController.preferencesTabViewSize
if controllerProposedSize.width <= 0 { // 0 means keep size
controllerProposedSize.width = referenceSize.width
}
if controllerProposedSize.height <= 0 {
controllerProposedSize.height = referenceSize.height
}
return controllerProposedSize
}
private func setFrameSize(size: NSSize, forWindow window: NSWindow) {
let newWindowSize = window.frameRect(forContentRect: NSRect(origin: CGPoint.zero, size: size)).size
var frame = window.frame
frame.origin.y += frame.size.height
frame.origin.y -= newWindowSize.height
frame.size = newWindowSize
window.setFrame(frame, display:true, animate:true)
}
}
#endif
| a16dd2f92dd26bbf2cbaf781bf20850b | 41.006452 | 158 | 0.699585 | false | false | false | false |
ljshj/actor-platform | refs/heads/master | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AACountryViewController.swift | agpl-3.0 | 2 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
public protocol AACountryViewControllerDelegate {
func countriesController(countriesController: AACountryViewController, didChangeCurrentIso currentIso: String)
}
public class AACountryViewController: AATableViewController {
private var _countries: NSDictionary!
private var _letters: NSArray!
public var delegate: AACountryViewControllerDelegate?
public init() {
super.init(style: UITableViewStyle.Plain)
self.title = AALocalized("AuthCountryTitle")
let cancelButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss"))
self.navigationItem.setLeftBarButtonItem(cancelButtonItem, animated: false)
self.content = ACAllEvents_Auth.AUTH_PICK_COUNTRY()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 44.0
tableView.sectionIndexBackgroundColor = UIColor.clearColor()
}
private func countries() -> NSDictionary {
if (_countries == nil) {
let countries = NSMutableDictionary()
for (_, iso) in ABPhoneField.sortedIsoCodes().enumerate() {
let countryName = ABPhoneField.countryNameByCountryCode()[iso as! String] as! String
let phoneCode = ABPhoneField.callingCodeByCountryCode()[iso as! String] as! String
// if (self.searchBar.text.length == 0 || [countryName rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch].location != NSNotFound)
let countryLetter = countryName.substringToIndex(countryName.startIndex.advancedBy(1))
if (countries[countryLetter] == nil) {
countries[countryLetter] = NSMutableArray()
}
countries[countryLetter]!.addObject([countryName, iso, phoneCode])
}
_countries = countries;
}
return _countries;
}
private func letters() -> NSArray {
if (_letters == nil) {
_letters = (countries().allKeys as NSArray).sortedArrayUsingSelector(#selector(YYTextPosition.compare(_:)))
}
return _letters;
}
public func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
return letters() as [AnyObject]
}
public func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return index
}
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return letters().count;
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (countries()[letters()[section] as! String] as! NSArray).count
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: AAAuthCountryCell = tableView.dequeueCell(indexPath)
let letter = letters()[indexPath.section] as! String
let countryData = (countries().objectForKey(letter) as! NSArray)[indexPath.row] as! [String]
cell.setTitle(countryData[0])
cell.setCode("+\(countryData[2])")
cell.setSearchMode(false)
return cell
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let letter = letters()[indexPath.section] as! String
let countryData = (countries().objectForKey(letter) as! NSArray)[indexPath.row] as! [String]
delegate?.countriesController(self, didChangeCurrentIso: countryData[1])
dismiss()
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 25.0
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return letters()[section] as? String
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: true)
}
} | 6eaf5933abfde6e36d707a242c203dc8 | 37.672269 | 172 | 0.653988 | false | false | false | false |
chaoyang805/DoubanMovie | refs/heads/master | DoubanMovie/Snackbar.swift | apache-2.0 | 1 | /*
* Copyright 2016 chaoyang805 zhangchaoyang805@gmail.com
*
* 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
let SnackbarShouldShowNotification = Notification.Name("show snackbar")
let SnackbarShouldDismissNotification = Notification.Name("dismiss snackbar")
let SnackbarUserInfoKey = "targetSnackbar"
@objc protocol SnackbarDelegate: NSObjectProtocol {
@objc optional func snackbarWillAppear(_ snackbar: Snackbar)
@objc optional func snackbarDidAppear(_ snackbar: Snackbar)
@objc optional func snackbarWillDisappear(_ snackbar: Snackbar)
@objc optional func snackbarDidDisappear(_ snackbar: Snackbar)
}
enum SnackbarDuration: TimeInterval {
case Short = 1.5
case Long = 3
}
class Snackbar: NSObject {
private(set) lazy var view: SnackbarView = {
let _barView = SnackbarView()
// 为了Snackbar不被销毁
_barView.snackbar = self
return _barView
}()
private var showing: Bool = false
private var dismissHandler: (() -> Void)?
var duration: TimeInterval!
private weak var delegate: SnackbarDelegate?
class func make(text: String, duration: SnackbarDuration) -> Snackbar {
return make(text, duration: duration.rawValue)
}
private class func make(_ text: String, duration: TimeInterval) -> Snackbar {
let snackbar = Snackbar()
snackbar.setSnackbarText(text: text)
snackbar.duration = duration
snackbar.registerNotification()
snackbar.delegate = SnackbarManager.defaultManager()
return snackbar
}
func show() {
let record = SnackbarRecord(duration: duration, identifier: hash)
SnackbarManager.defaultManager().show(record)
}
func dispatchDismiss() {
let record = SnackbarRecord(duration: duration, identifier: hash)
SnackbarManager.defaultManager().dismiss(record)
}
// MARK: - Notification
func registerNotification() {
let manager = SnackbarManager.defaultManager()
NotificationCenter.default.addObserver(self, selector: #selector(Snackbar.handleNotification(_:)), name: SnackbarShouldShowNotification, object: manager)
NotificationCenter.default.addObserver(self, selector: #selector(Snackbar.handleNotification(_:)), name: SnackbarShouldDismissNotification, object: manager)
}
func unregisterNotification() {
NotificationCenter.default.removeObserver(self)
}
deinit {
NSLog("deinit")
}
func handleNotification(_ notification: NSNotification) {
guard let identifier = notification.userInfo?[SnackbarUserInfoKey] as? Int else {
NSLog("not found snackbar in notification's userInfo")
return
}
guard identifier == self.hash else {
NSLog("not found specified snackbar:\(identifier)")
return
}
switch notification.name {
case SnackbarShouldShowNotification:
handleShowNotification()
case SnackbarShouldDismissNotification:
handleDismissNotification()
default:
break
}
}
func handleShowNotification() {
self.showView()
}
func handleDismissNotification() {
self.dismissView()
}
// MARK: - Configure Snackbar
func setSnackbarText(text: String) {
view.messageView.text = text
view.messageView.sizeToFit()
}
// MARK: - Warning Retain cycle(solved)
func setAction(title: String, action: @escaping ((_ sender: AnyObject) -> Void)) -> Snackbar {
view.setAction(title: title) { (sender) in
action(sender)
self.dispatchDismiss()
}
return self
}
func dismissHandler(block: @escaping (() -> Void)) -> Snackbar {
self.dismissHandler = block
return self
}
// MARK: - Snackbar View show & dismiss
private func showView() {
guard let window = UIApplication.shared.keyWindow else { return }
self.delegate?.snackbarWillAppear?(self)
window.addSubview(view)
UIView.animate(
withDuration: 0.25,
delay: 0,
options: .curveEaseIn,
animations: { [weak self] in
guard let `self` = self else { return }
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: -40)
},
completion: { (done ) in
self.delegate?.snackbarDidAppear?(self)
self.showing = true
})
}
func dismissView() {
guard self.showing else { return }
self.delegate?.snackbarWillDisappear?(self)
UIView.animate(
withDuration: 0.25,
delay: 0,
options: UIViewAnimationOptions.curveEaseIn,
animations: { [weak self] in
guard let `self` = self else { return }
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 40)
},
completion: { (done) in
self.showing = false
self.view.snackbar = nil
self.view.removeFromSuperview()
self.dismissHandler?()
self.delegate?.snackbarDidDisappear?(self)
self.delegate = nil
self.unregisterNotification()
} )
}
}
| 96d8aa7f717a45976459d384d002f611 | 29.796117 | 164 | 0.583859 | false | false | false | false |
proxyco/RxBluetoothKit | refs/heads/master | Source/RestoredState.swift | mit | 1 | //
// RestoredState.swift
// RxBluetoothKit
//
// Created by Kacper Harasim on 21.05.2016.
// Copyright © 2016 Polidea. All rights reserved.
//
import Foundation
import CoreBluetooth
/**
Convenience class which helps reading state of restored BluetoothManager
*/
#if os(iOS)
public struct RestoredState {
/**
Restored state dictionary
*/
public let restoredStateData: [String:AnyObject]
public unowned let bluetoothManager: BluetoothManager
/**
Creates restored state information based on CoreBluetooth's dictionary
- parameter restoredState: Core Bluetooth's restored state data
- parameter bluetoothManager: `BluetoothManager` instance of which state has been restored.
*/
init(restoredStateDictionary: [String:AnyObject], bluetoothManager: BluetoothManager) {
self.restoredStateData = restoredStateDictionary
self.bluetoothManager = bluetoothManager
}
/**
Array of `Peripheral` objects which have been restored. These are peripherals that were connected to the central manager (or had a connection pending) at the time the app was terminated by the system.
*/
public var peripherals: [Peripheral] {
let objects = restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [AnyObject]
guard let arrayOfAnyObjects = objects else { return [] }
return arrayOfAnyObjects.flatMap { $0 as? CBPeripheral }
.map { RxCBPeripheral(peripheral: $0) }
.map { Peripheral(manager: bluetoothManager, peripheral: $0) }
}
/**
Dictionary that contains all of the peripheral scan options that were being used by the central manager at the time the app was terminated by the system.
*/
public var scanOptions: [String : AnyObject]? {
return restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [String : AnyObject]
}
/**
Array of `Service` objects which have been restored. These are all the services the central manager was scanning for at the time the app was terminated by the system.
*/
public var services: [Service] {
let objects = restoredStateData[CBCentralManagerRestoredStateScanServicesKey] as? [AnyObject]
guard let arrayOfAnyObjects = objects else { return [] }
return arrayOfAnyObjects.flatMap { $0 as? CBService }
.map { RxCBService(service: $0) }
.map { Service(peripheral: Peripheral(manager: bluetoothManager,
peripheral: RxCBPeripheral(peripheral: $0.service.peripheral)), service: $0) }
}
}
#endif
| 8530218d4e33480c4e15bf7bffcb6823 | 39.421875 | 205 | 0.708156 | false | false | false | false |
yangyouyong0/SwiftLearnLog | refs/heads/master | CiChang/CiChang/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// CiChang
//
// Created by yangyouyong on 15/7/8.
// Copyright © 2015年 yangyouyong. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource{
var bookArray = Array<CCBook>()
var tableView:UITableView?
// tableView
// @IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.setupView()
self.requestData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
internal func setupView() {
self.tableView = UITableView(frame: CGRectMake(0, 0, CGRectGetHeight(self.view.bounds), CGRectGetHeight(self.view.bounds)), style: .Plain)
self.view.addSubview(self.tableView!)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "bookCell")
}
internal func requestData() {
let urlStr = "http://cichang.hjapi.com/v2/book/?pageIndex=0&pageSize=100&sort=popular"
// let url = NSURL(string: urlStr)
// let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
// (data, response, error) in
// if data != nil {
// do {
// let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
// print("jsonData \(jsonData)")
//
// } catch {
// // report error
// print("noData,\(error)")
// }//
// }else{
// print("noData,\(error)")
// }
// }
// task!.resume()
// do {
// let jsonData = try NSJSONSerialization.JSONObjectWithData(data as! NSData, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
// print("jsonData \(jsonData)")
// } catch {
// // report error
// print("noData,\(error)")
// }//
Alamofire.request(.GET, URLString: urlStr).response {
(_, _, data, error) in
if data != nil {
if (JSON(data: data as! NSData) != nil){
let json = JSON(data: data as! NSData)
let items = json["data"]["items"]
for value in items{
let (_ , dict) = value as (String,JSON)
let book = CCBook().initWithDict(dict.object as! [String : AnyObject])
print(dict.object)
print("value is \(book)")
self.bookArray.append(book)
}
print("bookArray")
print(self.bookArray)
self.tableView!.reloadData()
}
}else{
print("noData,\(error)")
}
}
}
/*
// 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.
}
*/
// MARK: - TableViewDelegate&DataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("bookCell", forIndexPath: indexPath)
let book:CCBook = self.bookArray[indexPath.row]
cell.textLabel?.text = book.name
// Alamofire.request(.GET, URLString: book.coverImageUrl!).response {
// (_, _, data, error) in
// if data != nil {
// let image = UIImage(data: data as! NSData)
// cell.imageView?.image = image
// }
// }
// let imageUrl :NSURL = NSURL()
// let imageData :NSData = NSData(contentsOfURL: )
// cell.coverImage.image = UIImage(data: NSData(contentsOfURL:NSURL.URLWithString(book.coverImageUrl!)!)!)!)!
// var nsd = NSData(contentsOfURL:NSURL.URLWithString("http://ww2.sinaimg.cn/bmiddle/632dab64jw1ehgcjf2rd5j20ak07w767.jpg"))
// Configure the cell...
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.bookArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 68
}
}
| cd8c9a6e3bdbc2466a20a52a1dd0becc | 37.847328 | 162 | 0.57025 | false | false | false | false |
macemmi/HBCI4Swift | refs/heads/master | HBCI4Swift/HBCI4Swift/Source/Orders/HBCIAccountStatementOrder.swift | gpl-2.0 | 1 | //
// HBCIAccountStatementOrder.swift
// HBCI4Swift
//
// Created by Frank Emminghaus on 22.03.16.
// Copyright © 2016 Frank Emminghaus. All rights reserved.
//
import Foundation
public struct HBCIAccountStatementOrderPar {
public var supportsNumber:Bool;
public var needsReceipt:Bool;
public var supportsLimit:Bool;
public var formats:Array<HBCIAccountStatementFormat>;
}
open class HBCIAccountStatementOrder: HBCIOrder {
public let account:HBCIAccount;
open var number:Int?
open var year:Int?
open var format:HBCIAccountStatementFormat?
// result
open var statements = Array<HBCIAccountStatement>();
public init?(message: HBCICustomMessage, account:HBCIAccount) {
self.account = account;
super.init(name: "AccountStatement", message: message);
//adjustNeedsTanForPSD2();
if self.segment == nil {
return nil;
}
}
open func enqueue() ->Bool {
// check if order is supported
if !user.parameters.isOrderSupportedForAccount(self, number: account.number, subNumber: account.subNumber) {
logInfo(self.name + " is not supported for account " + account.number);
return false;
}
var values = Dictionary<String,Any>();
// check if SEPA version is supported (only globally for bank -
// later we check if account supports this as well
if segment.version >= 7 {
// we have the SEPA version
if account.iban == nil || account.bic == nil {
logInfo("Account has no IBAN or BIC information");
return false;
}
values = ["KTV.bic":account.bic!, "KTV.iban":account.iban!];
} else {
values = ["KTV.number":account.number, "KTV.KIK.country":"280", "KTV.KIK.blz":account.bankCode];
if account.subNumber != nil {
values["KTV.subnumber"] = account.subNumber!
}
}
if let idx = self.number {
values["idx"] = idx;
}
if let year = self.year {
values["year"] = year;
}
if let format = self.format {
values["format"] = String(format.rawValue);
}
if !segment.setElementValues(values) {
logInfo("AccountStatementOrder values could not be set");
return false;
}
// add to message
return msg.addOrder(self);
}
override open func updateResult(_ result:HBCIResultMessage) {
super.updateResult(result);
for seg in resultSegments {
if let statement = HBCIAccountStatement(segment: seg) {
statements.append(statement);
}
}
}
open class func getParameters(_ user:HBCIUser) ->HBCIAccountStatementOrderPar? {
guard let (elem, seg) = self.getParameterElement(user, orderName: "AccountStatement") else {
return nil;
}
guard let supportsNumber = elem.elementValueForPath("canindex") as? Bool else {
logInfo("AccountStatementParameters: mandatory parameter canindex missing");
logInfo(seg.description);
return nil;
}
guard let needsReceipt = elem.elementValueForPath("needreceipt") as? Bool else {
logInfo("AccountStatementParameters: mandatory parameter needreceipt missing");
logInfo(seg.description);
return nil;
}
guard let supportsLimit = elem.elementValueForPath("canmaxentries") as? Bool else {
logInfo("AccountStatementParameters: mandatory parameter supportsLimit missing");
logInfo(seg.description);
return nil;
}
var formats = Array<HBCIAccountStatementFormat>();
if let fm = elem.elementValuesForPath("format") as? [String] {
for formatString in fm {
if let format = convertAccountStatementFormat(formatString) {
formats.append(format);
}
}
}
return HBCIAccountStatementOrderPar(supportsNumber: supportsNumber, needsReceipt: needsReceipt, supportsLimit: supportsLimit, formats: formats);
}
}
| d2631abafa732ef01fc518e1009c3bcf | 33.416 | 152 | 0.598791 | false | false | false | false |
TENDIGI/Obsidian-UI-iOS | refs/heads/master | src/BasicTabBar.swift | mit | 1 | //
// BasicTabBar.swift
// Alfredo
//
// Created by Nick Lee on 8/21/15.
// Copyright (c) 2015 TENDIGI, LLC. All rights reserved.
//
// I'm not very proud of this class...
import UIKit
public final class BasicTabBar: BaseTabBar {
// MARK: Initialization
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
backgroundColor = backgroundColor ?? UIColor.white
}
/// The accent color, used for the selected tab text and indicator
public override var tintColor: UIColor! {
didSet {
layoutButtons()
setNeedsDisplay()
}
}
/// The text color used for non-selected tabs
public var textColor: UIColor = UIColor(red:0.14, green:0.14, blue:0.15, alpha:1) {
didSet {
layoutButtons()
setNeedsDisplay()
}
}
/// The height of the selected tab indicator
public var indicatorHeight: CGFloat = 3 {
didSet {
setNeedsDisplay()
}
}
/// The font used for the tab text
public var tabFont = UIFont.systemFont(ofSize: UIFont.systemFontSize) {
didSet {
layoutButtons()
}
}
// MARK: Layout
fileprivate func layoutButtons() {
guard delegate != nil else {
return
}
subviews.forEach { $0.removeFromSuperview() }
let tabNames = delegate.tabNames
let buttons = tabNames.map { (title) -> UIButton in
let b = UIButton(type: .custom)
b.setTitle(title, for: UIControlState())
b.addTarget(self, action: #selector(BasicTabBar.selectTabButton(_:)), for: .touchUpInside)
b.titleLabel?.font = self.tabFont
b.setTitleColor(self.textColor, for: UIControlState())
b.setTitleColor(self.tintColor, for: .selected)
b.setTitleColor(self.tintColor, for: .highlighted)
return b
}
let buttonSize = ceil(width / CGFloat(tabNames.count))
var x: CGFloat = 0
for (i, b) in buttons.enumerated() {
b.x = x
b.y = 0
b.width = buttonSize
b.height = height
b.tag = i
x += buttonSize
}
buttons.forEach { self.addSubview($0) }
selectTab(delegate.selectedTabIndex)
}
// MARK: BaseTabBar overrides
/// :nodoc:
public override func layout() {
super.layout()
layoutButtons()
}
/// :nodoc:
public override func selectTab(_ index: Int) {
if let buttons = (subviews as? [UIButton])?.sorted(by: { $0.x < $1.x }) {
for (i, b) in buttons.enumerated() {
b.isSelected = (i == index)
}
}
setNeedsDisplay()
}
public override func frameForTab(_ index: Int) -> CGRect {
if let buttons = (subviews as? [UIButton])?.sorted(by: { $0.x < $1.x }) {
for (i, b) in buttons.enumerated() {
if i == index {
return b.frame
}
}
}
return super.frameForTab(index)
}
// MARK: Actions
@objc private func selectTabButton(_ button: UIButton) {
delegate.selectTab(button.tag)
}
// MARK: UIView Overrides
/// :nodoc:
public override func draw(_ rect: CGRect) {
super.draw(rect)
let buttonWidth = rect.width / CGFloat(delegate.tabNames.count)
tintColor.setFill()
let fillRect = CGRect(x: buttonWidth * CGFloat(delegate.selectedTabIndex), y: rect.height - indicatorHeight, width: buttonWidth, height: indicatorHeight)
UIRectFill(fillRect)
}
/// :nodoc:
public override func layoutSubviews() {
super.layoutSubviews()
layoutButtons()
}
}
| 0c254eca7f5ed79c4f91cc580d5c46b0 | 24.844156 | 161 | 0.561558 | false | false | false | false |
Eliothu/WordPress-iOS | refs/heads/buildAndLearn5.5 | WordPress/Classes/Extensions/UIViewController+Helpers.swift | gpl-2.0 | 18 | import Foundation
extension UIViewController
{
public func isViewOnScreen() -> Bool {
let visibleAsRoot = view.window?.rootViewController == self
let visibleAsTopOnStack = navigationController?.topViewController == self && view.window != nil
let visibleAsPresented = view.window?.rootViewController?.presentedViewController == self
return visibleAsRoot || visibleAsTopOnStack || visibleAsPresented
}
}
| 1213626184d62f88d7ae1c63e612ce5b | 34.384615 | 103 | 0.706522 | false | false | false | false |
kentaiwami/FiNote | refs/heads/master | ios/FiNote/FiNote/Social/ByAge/SocialByAgeViewController.swift | mit | 1 | //
// SocialByAgeViewController.swift
// FiNote
//
// Created by 岩見建汰 on 2018/01/29.
// Copyright © 2018年 Kenta. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import SwiftyJSON
import Alamofire
import AlamofireImage
import StatusProvider
import KeychainAccess
class SocialByAgeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITabBarControllerDelegate, StatusController {
var contentView: UIView!
var latestView: UIView!
var scrollView = UIScrollView()
var refresh_controll = UIRefreshControl()
var movies: [[MovieByAge.Data]] = [[]]
var preViewName = "Social"
fileprivate let utility = Utility()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clear
let keychain = Keychain()
if (try! keychain.get("birthyear"))! == "" {
let status = Status(title: "No View", description: "誕生年を登録していないため閲覧することができません。\nユーザ情報画面にて誕生年を登録すると閲覧することができます。")
show(status: status)
}else {
CallGetByAgeAPI()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.navigationItem.title = "年代別ランキング"
self.tabBarController?.delegate = self
}
@objc func refresh(sender: UIRefreshControl) {
refresh_controll.beginRefreshing()
CallGetByAgeAPI()
}
func CallGetByAgeAPI() {
let urlString = API.base.rawValue+API.v1.rawValue+API.movie.rawValue+API.byage.rawValue
let activityData = ActivityData(message: "Get Data", type: .lineScaleParty)
NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData, nil)
DispatchQueue(label: "get-byage").async {
Alamofire.request(urlString, method: .get).responseJSON { (response) in
self.refresh_controll.endRefreshing()
NVActivityIndicatorPresenter.sharedInstance.stopAnimating(nil)
guard let res = response.result.value else{return}
let obj = JSON(res)
print("***** API results *****")
print(obj)
print("***** API results *****")
self.movies.removeAll()
if self.utility.isHTTPStatus(statusCode: response.response?.statusCode) {
// 結果をパース
let dictionaryValue = obj["results"].dictionaryValue
for key in stride(from: 10, to: 60, by: 10) {
// 10,20...ごとに配列を取得
let arrayValue = dictionaryValue[String(key)]?.arrayValue
// title, overview, poster, countごとにまとめた配列を取得
let data_array = MovieByAge().GetDataArray(json: arrayValue!)
self.movies.append(data_array)
}
self.DrawViews()
}else {
self.utility.showStandardAlert(title: "Error", msg: obj.arrayValue[0].stringValue, vc: self)
}
}
}
}
func DrawViews() {
InitScrollView()
CreateSection(text: "10代", isTop: true)
CreateCollectionView(tag: 1)
for i in 2...5 {
CreateSection(text: "\(i)0代", isTop: false)
CreateCollectionView(tag: i)
}
contentView.bottom(to: latestView, offset: 20)
}
func InitScrollView() {
scrollView.removeFromSuperview()
refresh_controll = UIRefreshControl()
scrollView = UIScrollView()
scrollView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
scrollView.refreshControl = refresh_controll
refresh_controll.addTarget(self, action: #selector(self.refresh(sender:)), for: .valueChanged)
self.view.addSubview(scrollView)
scrollView.top(to: self.view)
scrollView.leading(to: self.view)
scrollView.trailing(to: self.view)
scrollView.bottom(to: self.view)
contentView = UIView()
scrollView.addSubview(contentView)
contentView.top(to: scrollView)
contentView.leading(to: scrollView)
contentView.trailing(to: scrollView)
contentView.bottom(to: scrollView)
contentView.width(to: scrollView)
latestView = contentView
}
func CreateSection(text: String, isTop: Bool) {
let label = UILabel(frame: CGRect.zero)
label.text = text
label.font = UIFont(name: Font.helveticaneue_B.rawValue, size: 20)
contentView.addSubview(label)
label.leading(to: contentView, offset: 20)
if isTop {
label.top(to: latestView, offset: 20)
}else {
label.topToBottom(of: latestView, offset: 20)
}
latestView = label
}
func CreateCollectionView(tag: Int) {
let count_space = 35 as CGFloat
let w = 150 as CGFloat
let h = w*1.5 + count_space
let margin = 16 as CGFloat
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: w, height: h)
layout.minimumInteritemSpacing = margin
layout.minimumLineSpacing = margin
layout.sectionInset = UIEdgeInsets(top: 0, left: margin, bottom: 0, right: margin)
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.register(SocialByAgeCell.self, forCellWithReuseIdentifier: "MyCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.tag = tag
collectionView.backgroundColor = UIColor.clear
contentView.addSubview(collectionView)
collectionView.topToBottom(of: latestView, offset: 10)
collectionView.leading(to: contentView, offset: 20 - margin)
collectionView.width(to: contentView)
collectionView.height(h)
latestView = collectionView
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let index = collectionView.tag - 1
let title = "\(collectionView.tag*10)代 \(indexPath.row+1)位\n\(movies[index][indexPath.row].title)"
var release_date = ""
if movies[index][indexPath.row].release_date != "" {
release_date = "公開日:\(movies[index][indexPath.row].release_date)\n\n"
}
utility.showStandardAlert(title: title, msg: release_date + movies[index][indexPath.row].overview, vc: self)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let index = collectionView.tag - 1
return movies[index].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : SocialByAgeCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath) as! SocialByAgeCell
let index = collectionView.tag - 1
cell.poster.af_setImage(
withURL: URL(string: API.poster_base.rawValue+movies[index][indexPath.row].poster)!,
placeholderImage: UIImage(named: "no_image")
)
cell.user_count?.text = String(movies[index][indexPath.row].count)
return cell
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if viewController.restorationIdentifier! == "Social" && preViewName == "Social" {
scrollView.scroll(to: .top, animated: true)
}
preViewName = "Social"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| ac5ce854afadd15ecdca15f998fae4c8 | 36.855814 | 151 | 0.612483 | false | false | false | false |
buyiyang/iosstar | refs/heads/master | iOSStar/Scenes/Discover/CustomView/SellingIntroCell.swift | gpl-3.0 | 3 | //
// SellingIntroCell.swift
// iOSStar
//
// Created by J-bb on 17/7/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class SellingIntroCell: SellingBaseCell {
@IBOutlet weak var jobLabel: UILabel!
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var doDetail: UIButton!
@IBOutlet weak var backImageView: UIImageView!
@IBOutlet weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
backImageView.contentMode = .scaleAspectFill
backImageView.clipsToBounds = true
}
override func setPanicModel(model: PanicBuyInfoModel?) {
guard model != nil else {
return
}
nickNameLabel.text = model?.star_name
backImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model!.back_pic_url_tail), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model!.head_url_tail), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
jobLabel.text = model?.work
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| f4d4f69681c2b285bf65f5741501ecc0 | 33.552632 | 190 | 0.693069 | false | false | false | false |
AnarchyTools/atfoundation | refs/heads/master | src/filesystem/path.swift | apache-2.0 | 1 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if os(Linux)
import Glibc
#else
import Darwin
#endif
/// Abstraction for filesystem paths
public struct Path {
/// split path components
public let components: [String]
/// is this an absolute or relative path
public let isAbsolute: Bool
/// delimiter between path components
public var delimiter: Character
/// Initialize with a string, the string is split
/// into components by the rules of the current platform
///
/// - Parameter string: The string to parse
public init(_ string: String, delimiter: Character = "/") {
self.delimiter = delimiter
var components = string.split(character: self.delimiter)
if components[0] == "" {
self.isAbsolute = true
components.remove(at: 0)
} else {
self.isAbsolute = false
}
self.components = components
}
/// Initialize with path components
///
/// - Parameter components: Array of path component strings
/// - Parameter absolute: Boolean, defines if the path is absolute
public init(components: [String], absolute: Bool = false) {
self.components = components
self.isAbsolute = absolute
self.delimiter = "/"
}
/// Initialize empty path
///
/// - Parameter absolute: If set to true the empty path is equal to
/// the root path, else it equals the current path
public init(absolute: Bool = false) {
self.components = []
self.isAbsolute = absolute
self.delimiter = "/"
}
/// Create a new path instance by appending a component
///
/// - Parameter component: path component to append
/// - Returns: new Path instance
public func appending(_ component: String) -> Path {
var components = self.components
components.append(component)
return Path(components: components, absolute: self.isAbsolute)
}
/// Create a new path instance by removing the last path component
///
/// - Returns: New path instance cropped by the last path component
public func removingLastComponent() -> Path {
var components = self.components
components.removeLast()
return Path(components: components, absolute: self.isAbsolute)
}
/// Create a new path instance by removing the first path component
///
/// - Returns: New path instance cropped by the first path component,
/// implies conversion to relative path
public func removingFirstComponent() -> Path {
var components = self.components
components.remove(at: 0)
return Path(components: components, absolute: false)
}
/// Create a new path instance by joining two paths
///
/// - Parameter path: other path to append to this instance.
/// If the other path is absolute the result
/// is the other path without this instance.
public func join(_ path: Path) -> Path {
if path.isAbsolute {
return Path(components: path.components, absolute: true)
} else {
var myComponents = self.components
myComponents += path.components
return Path(components: myComponents, absolute: self.isAbsolute)
}
}
/// Create a path instance that defines a relative path to another path
///
/// - Parameter path: the path to calculate a relative path to
/// - Returns: new path instance that is a relative path to `path`.
/// If this instance is not absolute the result will be `nil`
public func relativeTo(path: Path) -> Path? {
if !self.isAbsolute || !path.isAbsolute {
return nil
}
let maxCount = min(self.components.count, path.components.count)
var up = 0
var same = 0
for idx in 0..<maxCount {
let c1 = self.components[idx]
let c2 = path.components[idx]
if c1 != c2 {
up = maxCount - idx
break
} else {
same = idx
}
}
var newComponents = [String]()
if same < up {
for _ in 0..<(up - same + 1) {
newComponents.append("..")
}
}
for idx in (same + 1)..<self.components.count {
newComponents.append(self.components[idx])
}
return Path(components:newComponents, absolute: false)
}
/// Return the dirname of a path
///
/// - Returns: new path instance with only the dir name
public func dirname() -> Path {
return self.removingLastComponent()
}
/// Return the file name of a path
///
/// - Returns: file name string
public func basename() -> String {
return self.components.last!
}
/// Return absolute path to the user's home directory
///
/// - Returns: absolute path to user's homee directory or `nil` if
/// that's not available
public static func homeDirectory() -> Path? {
let home = getenv("HOME")
if let h = home {
if let s = String(validatingUTF8: h) {
return Path(s)
}
}
return nil
}
/// Return path to the temp directory
///
/// - Returns: path instance with temp directory
public static func tempDirectory() -> Path {
// TODO: temp dirs for other platforms
return Path("/tmp")
}
}
public func ==(lhs: Path, rhs: Path) -> Bool {
if lhs.components.count != rhs.components.count || lhs.isAbsolute != rhs.isAbsolute {
return false
}
for i in 0..<lhs.components.count {
if lhs.components[i] != rhs.components[i] {
return false
}
}
return true
}
public func +(lhs: Path, rhs: String) -> Path {
return lhs.join(Path(rhs))
}
public func +(lhs: Path, rhs: Path) -> Path {
return lhs.join(rhs)
}
public func +=(lhs: inout Path, rhs: String) {
lhs = lhs.join(Path(rhs))
}
public func +=(lhs: inout Path, rhs: Path) {
lhs = lhs.join(rhs)
}
extension Path: CustomStringConvertible {
/// Convert path back to a String
public var description: String {
if self.components.count == 0 {
if self.isAbsolute {
return "\(self.delimiter)"
} else {
return "."
}
}
var result = String.join(parts: components, delimiter: self.delimiter)
if self.isAbsolute {
result = "\(self.delimiter)" + result
}
return result
}
} | 0e519abf6d8ae9c7c9e62193963ca69a | 30.465217 | 89 | 0.594113 | false | false | false | false |
daviwiki/Gourmet_Swift | refs/heads/master | Gourmet/GourmetModel/Interactors/GetBalance.swift | mit | 1 | //
// GetAccountInfo.swift
// Gourmet
//
// Created by David Martinez on 08/12/2016.
// Copyright © 2016 Atenea. All rights reserved.
//
import Foundation
public protocol GetBalanceListener : NSObjectProtocol {
func onSuccess (balance : Balance)
func onError ()
}
public class GetBalance : NSObject, GetBalanceOfflineListener, GetBalanceOnlineListener {
private var getBalanceOffline : GetBalanceOffline!
private var getBalanceOnline : GetBalanceOnline!
private var storeBalance : StoreBalance!
private weak var listener : GetBalanceListener?
private var account : Account!
public init(getBalanceOffline : GetBalanceOffline,
getBalanceOnline : GetBalanceOnline,
storeBalance : StoreBalance) {
super.init()
self.getBalanceOffline = getBalanceOffline
self.getBalanceOnline = getBalanceOnline
self.storeBalance = storeBalance
getBalanceOffline.setListener(listener: self)
getBalanceOnline.setListener(listener: self)
}
public func setListener (listener : GetBalanceListener) {
self.listener = listener
}
public func execute (account : Account) {
self.account = account
getBalanceOffline.execute()
}
// MARK: GetBalanceOfflineListener
public func onFinish(getBalanceOffline: GetBalanceOffline, balance: Balance?) {
guard listener != nil else { return }
if (balance != nil) {
listener!.onSuccess(balance: balance!)
}
getBalanceOnline.execute(account: account)
}
// MARK: GetBalanceOnlineListener
public func onFinish(getBalanceOnline: GetBalanceOnline, balance: Balance?) {
guard listener != nil else { return }
if (balance != nil) {
DispatchQueue.main.async {
self.listener!.onSuccess(balance: balance!)
}
storeBalance.execute(balance: balance!)
} else {
DispatchQueue.main.async {
self.listener!.onError()
}
}
}
}
| ac3b5c2f91da2b5bb9706aef1906d27a | 27.051948 | 89 | 0.626852 | false | false | false | false |
hilen/TSWeChat | refs/heads/master | JJA_Swift/Pods/TimedSilver/Sources/UIKit/UICollectionView+TSExtension.swift | mit | 3 | //
// UICollectionView+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/5/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
public extension UICollectionView {
/**
Last indexPath in section
- parameter section: section
- returns: NSIndexPath
*/
func ts_lastIndexPathInSection(_ section: Int) -> IndexPath? {
return IndexPath(row: self.numberOfItems(inSection: section)-1, section: section)
}
/// Last indexPath in UICollectionView
var ts_lastIndexPath: IndexPath? {
if (self.ts_totalItems - 1) > 0 {
return IndexPath(row: self.ts_totalItems-1, section: self.numberOfSections)
} else {
return nil
}
}
/// Total items in UICollectionView
var ts_totalItems: Int {
var i = 0
var rowCount = 0
while i < self.numberOfSections {
rowCount += self.numberOfItems(inSection: i)
i += 1
}
return rowCount
}
/**
Scroll to the bottom
- parameter animated: animated
*/
func ts_scrollToBottom(_ animated: Bool) {
let section = self.numberOfSections - 1
let row = self.numberOfItems(inSection: section) - 1
if section < 0 || row < 0 {
return
}
let path = IndexPath(row: row, section: section)
let offset = contentOffset.y
self.scrollToItem(at: path, at: .top, animated: animated)
let delay = (animated ? 0.1 : 0.0) * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: { () -> Void in
if self.contentOffset.y != offset {
self.ts_scrollToBottom(false)
}
})
}
/**
Reload data without flashing
*/
func ts_reloadWithoutFlashing() {
UIView.setAnimationsEnabled(false)
CATransaction.begin()
CATransaction.setDisableActions(true)
self.reloadData()
CATransaction.commit()
UIView.setAnimationsEnabled(true)
}
/**
Fetch indexPaths of UICollectionView's visibleCells
- returns: NSIndexPath Array
*/
func ts_visibleIndexPaths() -> [IndexPath] {
var list = [IndexPath]()
for cell in self.visibleCells {
if let indexPath = self.indexPath(for: cell) {
list.append(indexPath)
}
}
return list
}
/**
Fetch indexPaths of UICollectionView's rect
- returns: NSIndexPath Array
*/
func ts_indexPathsForElementsInRect(_ rect: CGRect) -> [IndexPath] {
let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect)
if (allLayoutAttributes?.count ?? 0) == 0 {return []}
var indexPaths: [IndexPath] = []
indexPaths.reserveCapacity(allLayoutAttributes!.count)
for layoutAttributes in allLayoutAttributes! {
let indexPath = layoutAttributes.indexPath
indexPaths.append(indexPath)
}
return indexPaths
}
/**
Reload data with completion block
- parameter completion: completion block
*/
func ts_reloadData(_ completion: @escaping ()->()) {
UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() })
}
}
| 06f47f13ca2150b34593a7963fe42f49 | 27.293651 | 109 | 0.591304 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | iOS/Account/NewsBlurAccountViewController.swift | mit | 1 | //
// NewsBlurAccountViewController.swift
// NetNewsWire
//
// Created by Anh-Quang Do on 3/9/20.
// Copyright (c) 2020 Ranchero Software. All rights reserved.
//
import UIKit
import Account
import Secrets
import RSWeb
import SafariServices
class NewsBlurAccountViewController: UITableViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var showHideButton: UIButton!
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var footerLabel: UILabel!
weak var account: Account?
weak var delegate: AddAccountDismissDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setupFooter()
activityIndicator.isHidden = true
usernameTextField.delegate = self
passwordTextField.delegate = self
if let account = account, let credentials = try? account.retrieveCredentials(type: .newsBlurBasic) {
actionButton.setTitle(NSLocalizedString("Update Credentials", comment: "Update Credentials"), for: .normal)
actionButton.isEnabled = true
usernameTextField.text = credentials.username
passwordTextField.text = credentials.secret
} else {
actionButton.setTitle(NSLocalizedString("Add Account", comment: "Add Account"), for: .normal)
}
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: usernameTextField)
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: passwordTextField)
tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
}
private func setupFooter() {
footerLabel.text = NSLocalizedString("Sign in to your NewsBlur account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a NewsBlur account?", comment: "NewsBlur")
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView
headerView.imageView.image = AppAssets.image(for: .newsBlur)
return headerView
} else {
return super.tableView(tableView, viewForHeaderInSection: section)
}
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func showHidePassword(_ sender: Any) {
if passwordTextField.isSecureTextEntry {
passwordTextField.isSecureTextEntry = false
showHideButton.setTitle("Hide", for: .normal)
} else {
passwordTextField.isSecureTextEntry = true
showHideButton.setTitle("Show", for: .normal)
}
}
@IBAction func action(_ sender: Any) {
guard let username = usernameTextField.text else {
showError(NSLocalizedString("Username required.", comment: "Credentials Error"))
return
}
// When you fill in the email address via auto-complete it adds extra whitespace
let trimmedUsername = username.trimmingCharacters(in: .whitespaces)
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .newsBlur, username: trimmedUsername) else {
showError(NSLocalizedString("There is already a NewsBlur account with that username created.", comment: "Duplicate Error"))
return
}
let password = passwordTextField.text ?? ""
startAnimatingActivityIndicator()
disableNavigation()
let basicCredentials = Credentials(type: .newsBlurBasic, username: trimmedUsername, secret: password)
Account.validateCredentials(type: .newsBlur, credentials: basicCredentials) { result in
self.stopAnimatingActivityIndicator()
self.enableNavigation()
switch result {
case .success(let sessionCredentials):
if let sessionCredentials = sessionCredentials {
if self.account == nil {
self.account = AccountManager.shared.createAccount(type: .newsBlur)
}
do {
do {
try self.account?.removeCredentials(type: .newsBlurBasic)
try self.account?.removeCredentials(type: .newsBlurSessionId)
} catch {}
try self.account?.storeCredentials(basicCredentials)
try self.account?.storeCredentials(sessionCredentials)
self.account?.refreshAll() { result in
switch result {
case .success:
break
case .failure(let error):
self.presentError(error)
}
}
self.dismiss(animated: true, completion: nil)
self.delegate?.dismiss()
} catch {
self.showError(NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error"))
}
} else {
self.showError(NSLocalizedString("Invalid username/password combination.", comment: "Credentials Error"))
}
case .failure(let error):
self.showError(error.localizedDescription)
}
}
}
@IBAction func signUpWithProvider(_ sender: Any) {
let url = URL(string: "https://newsblur.com")!
let safari = SFSafariViewController(url: url)
safari.modalPresentationStyle = .currentContext
self.present(safari, animated: true, completion: nil)
}
@objc func textDidChange(_ note: Notification) {
actionButton.isEnabled = !(usernameTextField.text?.isEmpty ?? false)
}
private func showError(_ message: String) {
presentError(title: "Error", message: message)
}
private func enableNavigation() {
self.cancelBarButtonItem.isEnabled = true
self.actionButton.isEnabled = true
}
private func disableNavigation() {
cancelBarButtonItem.isEnabled = false
actionButton.isEnabled = false
}
private func startAnimatingActivityIndicator() {
activityIndicator.isHidden = false
activityIndicator.startAnimating()
}
private func stopAnimatingActivityIndicator() {
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
}
}
extension NewsBlurAccountViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 928f8b44467f74e08afc2b730a8fe654 | 32.119171 | 239 | 0.751252 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | refs/heads/main | Buy/Generated/Storefront/UnitPriceMeasurementMeasuredType.swift | mit | 1 | //
// UnitPriceMeasurementMeasuredType.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The accepted types of unit of measurement.
public enum UnitPriceMeasurementMeasuredType: String {
/// Unit of measurements representing areas.
case area = "AREA"
/// Unit of measurements representing lengths.
case length = "LENGTH"
/// Unit of measurements representing volumes.
case volume = "VOLUME"
/// Unit of measurements representing weights.
case weight = "WEIGHT"
case unknownValue = ""
}
}
| 35b2c29c3af2cd1e1418dd5e918003ca | 36.108696 | 81 | 0.739895 | false | false | false | false |
moozzyk/SignalR-Client-Swift | refs/heads/master | Tests/SignalRClientTests/Constants.swift | mit | 1 | //
// Constants.swift
// SignalRClientTests
//
// Created by Pawel Kadluczka on 10/1/18.
// Copyright © 2018 Pawel Kadluczka. All rights reserved.
//
import Foundation
let BASE_URL = "http://localhost:5000"
let ECHO_URL = URL(string: "\(BASE_URL)/echo")!
let ECHO_WEBSOCKETS_URL = URL(string: "\(BASE_URL)/echoWebSockets")!
let ECHO_LONGPOLLING_URL = URL(string: "\(BASE_URL)/echoLongPolling")!
let ECHO_NOTRANSPORTS_URL = URL(string: "\(BASE_URL)/echoNoTransports")!
let TESTHUB_URL = URL(string: "\(BASE_URL)/testhub")!
let TESTHUB_WEBSOCKETS_URL = URL(string: "\(BASE_URL)/testhubWebSockets")!
let TESTHUB_LONGPOLLING_URL = URL(string: "\(BASE_URL)/testhubLongPolling")!
// Used by most tests that don't depend on a specific transport directly
let TARGET_ECHO_URL = ECHO_URL // ECHO_URL or ECHO_WEBSOCKETS_URL or ECHO_LONGPOLLING_URL
let TARGET_TESTHUB_URL = TESTHUB_URL // TESTHUB_URL or TESTHUB_WEBSOCKETS_URL or TESTHUB_LONGPOLLING_URL
| bf0af786c14fae38a58465a7653c081a | 38.625 | 104 | 0.73081 | false | true | false | false |
watson-developer-cloud/ios-sdk | refs/heads/master | Sources/AssistantV2/Models/LogMessageSource.swift | apache-2.0 | 1 | /**
* (C) Copyright IBM Corp. 2021.
*
* 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
/**
An object that identifies the dialog element that generated the error message.
*/
public enum LogMessageSource: Codable, Equatable {
case dialogNode(LogMessageSourceDialogNode)
case action(LogMessageSourceAction)
case step(LogMessageSourceStep)
case handler(LogMessageSourceHandler)
private struct GenericLogMessageSource: Codable, Equatable {
var type: String
private enum CodingKeys: String, CodingKey {
case type = "type"
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let genericInstance = try? container.decode(GenericLogMessageSource.self) {
switch genericInstance.type {
case "dialog_node":
if let val = try? container.decode(LogMessageSourceDialogNode.self) {
self = .dialogNode(val)
return
}
case "action":
if let val = try? container.decode(LogMessageSourceAction.self) {
self = .action(val)
return
}
case "step":
if let val = try? container.decode(LogMessageSourceStep.self) {
self = .step(val)
return
}
case "handler":
if let val = try? container.decode(LogMessageSourceHandler.self) {
self = .handler(val)
return
}
default:
// falling through to throw decoding error
break
}
}
throw DecodingError.typeMismatch(LogMessageSource.self,
DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Decoding failed for all associated types"))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .dialogNode(let dialog_node):
try container.encode(dialog_node)
case .action(let action):
try container.encode(action)
case .step(let step):
try container.encode(step)
case .handler(let handler):
try container.encode(handler)
}
}
}
| 9108439ee50d2f8db5c3ae9873ed3aa2 | 33.348837 | 157 | 0.598849 | false | false | false | false |
aojet/Aojet | refs/heads/master | Sources/Aojet/function/Identifiable.swift | mit | 1 | //
// Identifiable.swift
// Aojet
//
// Created by Qihe Bian on 8/29/16.
// Copyright © 2016 Qihe Bian. All rights reserved.
//
import Foundation
public typealias Identifier = NSUUID
public protocol Identifiable {
var objectId: Identifier { get }
}
public protocol IdentifierHashable: Identifiable, Hashable {
}
public extension Identifiable {
static func generateObjectId() -> Identifier {
return Identifier()
}
}
public extension IdentifierHashable {
var hashValue: Int {
get {
return objectId.hashValue
}
}
}
public func ==<T>(lhs: T, rhs: T) -> Bool where T:IdentifierHashable {
return lhs.objectId == rhs.objectId
}
| db2546712f84a36c14a2eec342208bff | 16.918919 | 70 | 0.695324 | false | false | false | false |
noxytrux/RescueKopter | refs/heads/master | RescueKopter/Utilities.swift | mit | 1 | //
// Utilities.swift
// RescueKopter
//
// Created by Marcin Pędzimąż on 15.11.2014.
// Copyright (c) 2014 Marcin Pedzimaz. All rights reserved.
//
import UIKit
import QuartzCore
let kKPTDomain:String! = "KPTDomain"
struct imageStruct
{
var width : Int = 0
var height : Int = 0
var bitsPerPixel : Int = 0
var hasAlpha : Bool = false
var bitmapData : UnsafeMutablePointer<Void>? = nil
}
func createImageData(name: String!,inout texInfo: imageStruct) {
let baseImage = UIImage(named: name)
let image: CGImageRef? = baseImage?.CGImage
if let image = image {
texInfo.width = CGImageGetWidth(image)
texInfo.height = CGImageGetHeight(image)
texInfo.bitsPerPixel = CGImageGetBitsPerPixel(image)
texInfo.hasAlpha = CGImageGetAlphaInfo(image) != .None
let sizeInBytes = texInfo.width * texInfo.height * texInfo.bitsPerPixel / 8
let bytesPerRow = texInfo.width * texInfo.bitsPerPixel / 8
texInfo.bitmapData = malloc(Int(sizeInBytes))
let context: CGContextRef? = CGBitmapContextCreate(
texInfo.bitmapData!,
texInfo.width,
texInfo.height, 8,
bytesPerRow,
CGImageGetColorSpace(image),
CGImageGetBitmapInfo(image).rawValue)
if let context = context {
CGContextDrawImage(
context,
CGRectMake(0, 0, CGFloat(texInfo.width), CGFloat(texInfo.height)),
image)
}
}
}
func convertToRGBA(inout texInfo: imageStruct) {
assert(texInfo.bitsPerPixel == 24, "Wrong image format")
let stride = texInfo.width * 4
let newPixels = malloc(stride * texInfo.height)
var dstPixels = UnsafeMutablePointer<UInt32>(newPixels)
var r: UInt8,
g: UInt8,
b: UInt8,
a: UInt8
a = 255
let sourceStride = texInfo.width * texInfo.bitsPerPixel / 8
let pointer = texInfo.bitmapData!
for var j : Int = 0; j < texInfo.height; j++
{
for var i : Int = 0; i < sourceStride; i+=3 {
let position : Int = Int(i + (sourceStride * j))
var srcPixel = UnsafeMutablePointer<UInt8>(pointer + position)
r = srcPixel.memory
srcPixel++
g = srcPixel.memory
srcPixel++
b = srcPixel.memory
srcPixel++
dstPixels.memory = (UInt32(a) << 24 | UInt32(b) << 16 | UInt32(g) << 8 | UInt32(r) )
dstPixels++
}
}
if let _ = texInfo.bitmapData {
free(texInfo.bitmapData!)
}
texInfo.bitmapData = newPixels
texInfo.bitsPerPixel = 32
texInfo.hasAlpha = true
}
struct mapDataStruct {
var object: UInt32 //BGRA!
var playerSpawn: UInt8 {
return UInt8(object & 0x000000FF)
}
var ground: UInt8 {
return UInt8((object & 0x0000FF00) >> 8)
}
var grass: UInt8 {
return UInt8((object & 0x00FF0000) >> 16)
}
var wall: UInt8 {
return UInt8((object & 0xFF000000) >> 24)
}
var desc : String {
return "(\(self.ground),\(self.grass),\(self.wall),\(self.playerSpawn))"
}
}
func makeNormal(x1:Float32, y1:Float32, z1:Float32,
x2:Float32, y2:Float32, z2:Float32,
x3:Float32, y3:Float32, z3:Float32,
inout rx:Float32, inout ry:Float32, inout rz:Float32 )
{
let ax:Float32 = x3-x1,
ay:Float32 = y3-y1,
az:Float32 = z3-z1,
bx:Float32 = x2-x1,
by:Float32 = y2-y1,
bz:Float32 = z2-z1
rx = ay*bz - by*az
ry = bx*az - ax*bz
rz = ax*by - bx*ay
}
func createARGBBitmapContext(inImage: CGImage) -> CGContext! {
var bitmapByteCount = 0
var bitmapBytesPerRow = 0
let pixelsWide = CGImageGetWidth(inImage)
let pixelsHigh = CGImageGetHeight(inImage)
bitmapBytesPerRow = Int(pixelsWide) * 4
bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapData = malloc(Int(bitmapByteCount))
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
let context = CGBitmapContextCreate(bitmapData,
pixelsWide,
pixelsHigh,
Int(8),
Int(bitmapBytesPerRow),
colorSpace,
bitmapInfo.rawValue)
return context
}
func loadMapData(mapName: String) -> (data: UnsafeMutablePointer<Void>, width: Int, height: Int) {
let image = UIImage(named: mapName)
let inImage = image?.CGImage
let cgContext = createARGBBitmapContext(inImage!)
let imageWidth = CGImageGetWidth(inImage)
let imageHeight = CGImageGetHeight(inImage)
var rect = CGRectZero
rect.size.width = CGFloat(imageWidth)
rect.size.height = CGFloat(imageHeight)
CGContextDrawImage(cgContext, rect, inImage)
let dataPointer = CGBitmapContextGetData(cgContext)
return (dataPointer, imageWidth, imageHeight)
}
| 566a6a76967c723c543c13fabc3a258d | 24.726368 | 98 | 0.598143 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | refs/heads/master | Swift/LeetCode/Binary Search/69_Sqrt(x).swift | mit | 1 | // 69_Sqrt(x)
// https://leetcode.com/problems/sqrtx/submissions/
//
// Created by Honghao Zhang on 9/15/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Implement int sqrt(int x).
//
//Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
//
//Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
//
//Example 1:
//
//Input: 4
//Output: 2
//Example 2:
//
//Input: 8
//Output: 2
//Explanation: The square root of 8 is 2.82842..., and since
// the decimal part is truncated, 2 is returned.
//
// Tag: Binary search
// 求sqrt(x)
import Foundation
class Num69 {
// Use binary search to find the result in the range 1...x - 1
func mySqrt(_ x: Int) -> Int {
guard x > 1 else {
return x
}
var start = 1
var end = x - 1
while start + 1 < end {
let mid = start + (end - start) / 2
if mid * mid < x {
start = mid
}
else if mid * mid > x {
end = mid
}
else {
return mid
}
}
return start
}
}
| 3a0a45d8b6225134821b99c976cdfc8f | 20.471698 | 124 | 0.591388 | false | false | false | false |
blomma/gameoflife | refs/heads/master | gameoflife/Cell.swift | mit | 1 | enum CellState {
case alive, dead
}
class Cell {
let x: Int
let y: Int
var state: CellState
var neighbours: [Cell] = [Cell]()
init(state: CellState, x: Int, y: Int) {
self.state = state
self.x = x
self.y = y
}
}
extension Cell: Hashable {
var hashValue: Int {
return x.hashValue ^ y.hashValue
}
static func ==(lhs: Cell, rhs: Cell) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
| 2ba5ccfa4a95b287711b092a615598f9 | 14.5 | 50 | 0.578341 | false | false | false | false |
Yurssoft/QuickFile | refs/heads/master | QuickFile/Additional_Classes/Extensions/YSTabBarControllerExtension.swift | mit | 1 | //
// YSTabBarController.swift
// YSGGP
//
// Created by Yurii Boiko on 9/28/16.
// Copyright © 2016 Yurii Boiko. All rights reserved.
//
import UIKit
extension UITabBarController {
func setTabBarVisible(isVisible: Bool, animated: Bool, completion: (() -> Swift.Void)? = nil) {
let tabBarFrame = tabBar.frame
let tabBarHeight = tabBarFrame.size.height
let offsetY = (isVisible ? -tabBarHeight : tabBarHeight)
let duration: TimeInterval = (animated ? 0.3 : 0.0)
UIView.animate(withDuration: duration,
animations: {
[weak self] in self?.tabBar.frame = tabBarFrame.offsetBy(dx: 0, dy: offsetY)
},
completion: { (isFinished) in
if isFinished && completion != nil {
completion!()
}
})
}
func tabBarIsVisible() -> Bool {
return tabBar.frame.origin.y < UIScreen.main.bounds.height
}
open override func viewDidLayoutSubviews() {
print("")//seems to have fixed bug with resetting frame of UITabBarController's tabBar
}
}
| 44484cf6a86d9763b8ad883ddbcf2805 | 32.314286 | 100 | 0.575472 | false | false | false | false |
toshiapp/toshi-ios-client | refs/heads/master | Toshi/Controllers/Settings/Passphrase/Views/PassphraseView.swift | gpl-3.0 | 1 | // 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
import SweetUIKit
struct Word {
let index: Int
let text: String
init(_ index: Int, _ text: String) {
self.index = index
self.text = text
}
}
typealias Phrase = [Word]
typealias Layout = [NSLayoutConstraint]
protocol AddDelegate: class {
func add(_ wordView: PassphraseWordView)
}
protocol RemoveDelegate: class {
func remove(_ wordView: PassphraseWordView)
}
protocol VerificationDelegate: class {
func verify(_ phrase: Phrase) -> VerificationStatus
}
enum PassphraseType {
case original
case shuffled
case verification
}
enum VerificationStatus {
case unverified
case tooShort
case correct
case incorrect
}
class PassphraseView: UIView {
private var type: PassphraseType = .original
var verificationStatus: VerificationStatus = .unverified {
didSet {
if self.verificationStatus == .incorrect {
DispatchQueue.main.asyncAfter(seconds: 0.5) {
self.shake()
}
} else {
Profile.current?.updateVerificationState(self.verificationStatus == .correct)
}
}
}
private var originalPhrase: Phrase = []
private var currentPhrase: Phrase = []
private var layout: Layout = []
let margin: CGFloat = 10
let maxWidth = UIScreen.main.bounds.width - 30
weak var addDelegate: AddDelegate?
weak var removeDelegate: RemoveDelegate?
weak var verificationDelegate: VerificationDelegate?
var wordViews: [PassphraseWordView] = []
var containers: [UILayoutGuide] = []
convenience init(with originalPhrase: [String], for type: PassphraseType) {
self.init(withAutoLayout: true)
self.type = type
assert(originalPhrase.count <= 12, "Too large")
self.originalPhrase = originalPhrase.enumerated().map { index, text in Word(index, text) }
wordViews = wordViews(for: self.originalPhrase)
for wordView in wordViews {
addSubview(wordView)
}
switch self.type {
case .original:
isUserInteractionEnabled = false
currentPhrase.append(contentsOf: self.originalPhrase)
activateNewLayout()
case .shuffled:
self.originalPhrase.shuffle()
currentPhrase.append(contentsOf: self.originalPhrase)
activateNewLayout()
case .verification:
backgroundColor = Theme.lightGrayBackgroundColor
layer.cornerRadius = 4
clipsToBounds = true
activateNewLayout()
}
}
func add(_ word: Word) {
currentPhrase.append(word)
deactivateLayout()
activateNewLayout()
animateLayout()
wordViews.filter { wordView in
if let index = wordView.word?.index {
return self.currentPhrase.map { word in word.index }.contains(index)
} else {
return false
}
}.forEach { wordView in
if word.index == wordView.word?.index {
self.sendSubview(toBack: wordView)
wordView.alpha = 0
}
UIView.animate(withDuration: 0.4, delay: 0.1, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .easeOutFromCurrentStateWithUserInteraction, animations: {
wordView.alpha = 1
}, completion: nil)
}
verificationStatus = verificationDelegate?.verify(currentPhrase) ?? .unverified
}
func remove(_ word: Word) {
currentPhrase = currentPhrase.filter { currentWord in
currentWord.index != word.index
}
deactivateLayout()
activateNewLayout()
animateLayout()
wordViews.filter { wordView in
if let index = wordView.word?.index {
return !self.currentPhrase.map { word in word.index }.contains(index)
} else {
return false
}
}.forEach { wordView in
wordView.alpha = 0
}
}
func reset(_ word: Word) {
wordViews.filter { wordView in
wordView.word?.index == word.index
}.forEach { wordView in
wordView.isAddedForVerification = false
wordView.isEnabled = true
wordView.bounce()
}
}
func animateLayout(completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .easeOutFromCurrentStateWithUserInteraction, animations: {
self.superview?.layoutIfNeeded()
}, completion: completion)
}
func deactivateLayout() {
NSLayoutConstraint.deactivate(layout)
for container in containers {
removeLayoutGuide(container)
}
layout.removeAll()
}
func wordViews(for phrase: Phrase) -> [PassphraseWordView] {
return phrase.map { word -> PassphraseWordView in
let wordView = PassphraseWordView(with: word)
wordView.isAddedForVerification = false
wordView.addTarget(self, action: #selector(toggleAddedState(for:)), for: .touchUpInside)
return wordView
}
}
func newContainer(withOffset offset: CGFloat) -> UILayoutGuide {
let container = UILayoutGuide()
containers.append(container)
addLayoutGuide(container)
layout.append(container.centerXAnchor.constraint(equalTo: centerXAnchor))
layout.append(container.topAnchor.constraint(equalTo: topAnchor, constant: offset))
return container
}
func currentWordViews() -> [PassphraseWordView] {
var views: [PassphraseWordView] = []
for currentWord in currentPhrase {
for wordView in wordViews {
if let word = wordView.word, word.index == currentWord.index {
views.append(wordView)
if case .verification = type {
wordView.isAddedForVerification = false
}
}
}
}
return views
}
private func activateNewLayout() {
var origin = CGPoint(x: 0, y: margin)
var container = newContainer(withOffset: origin.y)
let currentWordViews = self.currentWordViews()
var previousWordView: UIView?
for wordView in currentWordViews {
let size = wordView.getSize()
let newWidth = origin.x + size.width + margin
if newWidth > maxWidth {
origin.y += PassphraseWordView.height + margin
origin.x = 0
if let previousWordView = previousWordView {
layout.append(previousWordView.rightAnchor.constraint(equalTo: container.rightAnchor, constant: -margin))
}
container = newContainer(withOffset: origin.y)
previousWordView = nil
}
layout.append(wordView.topAnchor.constraint(equalTo: container.topAnchor))
layout.append(wordView.leftAnchor.constraint(equalTo: previousWordView?.rightAnchor ?? container.leftAnchor, constant: margin))
layout.append(wordView.bottomAnchor.constraint(equalTo: container.bottomAnchor))
if let lastWordView = currentWordViews.last, lastWordView == wordView {
layout.append(wordView.rightAnchor.constraint(equalTo: container.rightAnchor, constant: -margin))
}
previousWordView = wordView
origin.x += size.width + margin
}
prepareHiddenViews(for: origin)
layout.append(container.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -margin))
NSLayoutConstraint.activate(layout)
}
func prepareHiddenViews(for origin: CGPoint) {
guard let lastContainer = containers.last else { return }
wordViews.filter { wordView in
if let index = wordView.word?.index {
return !self.currentPhrase.map { word in word.index }.contains(index)
} else {
return false
}
}.forEach { wordView in
wordView.alpha = 0
let size = wordView.getSize()
let newWidth = origin.x + size.width + self.margin
self.layout.append(wordView.topAnchor.constraint(equalTo: lastContainer.topAnchor, constant: newWidth > self.maxWidth ? PassphraseWordView.height + self.margin : 0))
self.layout.append(wordView.centerXAnchor.constraint(equalTo: lastContainer.centerXAnchor))
}
}
@objc func toggleAddedState(for wordView: PassphraseWordView) {
wordView.isAddedForVerification = !wordView.isAddedForVerification
if wordView.isAddedForVerification {
addDelegate?.add(wordView)
removeDelegate?.remove(wordView)
}
}
}
| 41941fd4b1cc8e509dcc0b99f70b2b1d | 30.555556 | 178 | 0.622618 | false | false | false | false |
duongsonthong/waveFormLibrary | refs/heads/master | waveFormLibrary-Example/Example/Pods/waveFormLibrary/waveFormLibrary/ControllerWaveForm.swift | mit | 2 | //
// ControllerWaveForm.swift
//
// Created by SSd on 10/30/16.
//
import UIKit
import AVFoundation
import MediaPlayer
@IBDesignable
public class ControllerWaveForm: UIView{
var urlLocal = URL(fileURLWithPath: "")
var mWaveformView : WaveFormView?
var mTouchDragging : Bool = false
var mTouchStart : Int = 0
var mTouchInitialOffset : Int = 0
var mOffset : Int = 0
var mMaxPos : Int = 0
var mStartPos : Int = 0
var mEndPos : Int = 0
let buttonWidth : Int = 100
var mTouchInitialStartPos : Int = 0
var mTouchInitialEndPos : Int = 0
var mWidth : Int = 0
var mOffsetGoal : Int = 0
var mFlingVelocity : Int = 0
var playButton : PlayButtonView?
var zoomInButton : UIButton?
var zoomOutButton : UIButton?
var audioPlayer : AVAudioPlayer!
var mPlayStartOffset : Int = 0
var mPlayStartMsec : Int = 0
var mPlayEndMsec : Int = 0
var mTimer : Timer?
var mButtonStart : CustomButtom?
var mButtonEnd : CustomButtom?
var waveFormBackgroundColorPrivate : UIColor = UIColor.white
var currentPlayColorPrivate : UIColor = UIColor.blue
var mediaPlayer:MPMusicPlayerController = MPMusicPlayerController.applicationMusicPlayer()
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func setMp3Url(mp3Url : URL){
urlLocal = mp3Url
let rectFrame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height*6/10)
mWidth = Int(frame.size.width)
mWaveformView = WaveFormView(frame: rectFrame,deletgate: self,waveFormBackgroundColor: waveFormBackground,currentPlayLineColor: currentPlayColor)
do {
try mWaveformView?.setFileUrl(url: urlLocal)
} catch let error as NSError{
print(error)
}
//controll player
let controllerViewWidth = frame.width*2/10
let controllerViewFrame = CGRect(x: 0, y: (mWaveformView?.frame.height)!+8, width: frame.width, height: controllerViewWidth)
let controllerView = UIView(frame: controllerViewFrame)
controllerView.backgroundColor = UIColor.clear
let playButtonWidth = controllerView.frame.height
let playButtonRect = CGRect(x: controllerView.frame.width/2-playButtonWidth/2, y: 0, width: playButtonWidth, height: playButtonWidth)
playButton = PlayButtonView(frame: playButtonRect)
playButton?.backgroundColor = UIColor.clear
let zoomInRect = CGRect(x: 0, y: 0, width: controllerView.frame.height, height: controllerView.frame.height)
let zoomOutRect = CGRect(x: controllerView.frame.width-controllerView.frame.height, y: 0, width: controllerView.frame.height, height: controllerView.frame.height)
zoomInButton = UIButton(frame: zoomInRect)
zoomInButton?.backgroundColor = UIColor.clear
zoomInButton?.setTitle("+", for: .normal)
zoomOutButton = UIButton(frame: zoomOutRect)
zoomOutButton?.backgroundColor = UIColor.clear
zoomOutButton?.setTitle("-", for: .normal)
playButton?.addTarget(self, action: #selector(self.clickPlay), for: .touchUpInside)
zoomOutButton?.addTarget(self, action: #selector(self.waveformZoomOut), for: .touchUpInside)
zoomInButton?.addTarget(self, action: #selector(self.waveformZoomIn), for: .touchUpInside)
//add subview
controllerView.addSubview(playButton!)
controllerView.addSubview(zoomInButton!)
controllerView.addSubview(zoomOutButton!)
let buttonWidth = CGFloat(100)
let buttonHeigh = CGFloat(50)
mButtonStart = CustomButtom(frame: CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeigh),parentViewParam : self,isLeft : true,delegate: self)
mButtonStart?.setBackgroundImage(UIImage(named : "HandleLeftBig"), for: .normal)
mButtonEnd = CustomButtom(frame: CGRect(x: frame.size.width-buttonWidth, y: mWaveformView!.frame.height-buttonHeigh, width: buttonWidth, height: buttonHeigh),parentViewParam : self,isLeft : false,delegate: self)
mButtonEnd?.setBackgroundImage(UIImage(named: "buttonHandle"), for: .normal)
finishOpeningSoundFile()
addSubview(mWaveformView!)
mWaveformView!.addSubview(mButtonEnd!)
mWaveformView!.addSubview(mButtonStart!)
addSubview(controllerView)
}
func finishOpeningSoundFile() {
if let waveFormUnWrap = mWaveformView {
mMaxPos = waveFormUnWrap.maxPos()
mTouchDragging = false;
mOffset = 0;
mOffsetGoal = 0;
mFlingVelocity = 0;
resetPositions();
updateDisplay();
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: urlLocal)
audioPlayer.delegate = self
} catch let error as NSError {
print(error)
}
}
func waveformZoomIn(){
mWaveformView?.zoomIn();
mStartPos = (mWaveformView?.getStart())!;
mEndPos = (mWaveformView?.getEnd())!;
mMaxPos = (mWaveformView?.maxPos())!;
mOffset = (mWaveformView?.getOffset())!;
mOffsetGoal = mOffset;
updateDisplay();
}
func waveformZoomOut() {
mWaveformView?.zoomOut();
mStartPos = (mWaveformView?.getStart())!;
mEndPos = (mWaveformView?.getEnd())!;
mMaxPos = (mWaveformView?.maxPos())!;
mOffset = (mWaveformView?.getOffset())!;
mOffsetGoal = mOffset;
updateDisplay();
}
func clickPlay(){
onPlay(startPosition: mStartPos)
}
func trap(pos : Int) -> Int {
if (pos < 0){
return 0
}
if (pos > mMaxPos ){
return mMaxPos
}
return pos;
}
func onPlay(startPosition : Int){
if isPlaying() {
if let audioPlayerUW = audioPlayer {
audioPlayerUW.pause()
mTimer?.invalidate()
mTimer = nil
updateButton()
}
return
}
mPlayStartMsec = mWaveformView!.pixelsToMillisecs(pixels: startPosition)
mPlayEndMsec = mWaveformView!.pixelsToMillisecs(pixels: mEndPos)
if let audioPlayerUW = audioPlayer {
audioPlayerUW.currentTime = TimeInterval(exactly: Float(mPlayStartMsec)/1000)!
audioPlayerUW.play()
}
updateButton()
mTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.updateDisplay), userInfo: nil, repeats: true)
mTimer?.fire()
}
func updateButton(){
if isPlaying() {
playButton?.setPlayStatus(isPlay: true)
}else {
playButton?.setPlayStatus(isPlay: false)
}
}
func updateDisplay() {
if isPlaying() {
let now : Int = Int(round(Double(audioPlayer.currentTime)*1000) + Double(mPlayStartOffset))
let frames : Int = mWaveformView!.millisecsToPixels(msecs: now)
mWaveformView?.setPlayback(pos: frames)
setOffsetGoalNoUpdate(offset: frames - mWidth / 2)
if now > mPlayEndMsec {
if let audioPlayerUW = audioPlayer {
audioPlayerUW.currentTime = TimeInterval(exactly: Float(mPlayStartMsec)/1000)!
audioPlayerUW.play()
}
}
}
var offsetDelta : Int = 0
if (!mTouchDragging) {
if (mFlingVelocity != 0) {
offsetDelta = mFlingVelocity / 30
if (mFlingVelocity > 80) {
mFlingVelocity -= 80
} else if (mFlingVelocity < -80) {
mFlingVelocity += 80
} else {
mFlingVelocity = 0
}
mOffset += offsetDelta;
if (mOffset + mWidth / 2 > mMaxPos) {
mOffset = mMaxPos - mWidth / 2
mFlingVelocity = 0
}
if (mOffset < 0) {
mOffset = 0;
mFlingVelocity = 0
}
mOffsetGoal = mOffset
} else {
offsetDelta = mOffsetGoal - mOffset
if (offsetDelta > 10){
offsetDelta = offsetDelta / 10
}
else if (offsetDelta > 0){
offsetDelta = 1
}
else if (offsetDelta < -10){
offsetDelta = offsetDelta / 10
}
else if (offsetDelta < 0){
offsetDelta = -1
}
else{
offsetDelta = 0
}
mOffset += offsetDelta
}
}
if let waveFormUW = mWaveformView {
waveFormUW.setParameters(start: mStartPos, end: mEndPos, offset: mOffset)
waveFormUW.setNeedsDisplay()
}
if let buttonEndUW = mButtonEnd {
let endX : Int = mEndPos - mOffset - Int(buttonEndUW.getWidth()-buttonEndUW.getWidth()/2)
buttonEndUW.updateFramePostion(position: endX)
}
if let buttonStartUW = mButtonStart {
let startX : Int = mStartPos - mOffset - Int (buttonStartUW.getWidth()/2)
buttonStartUW.updateFramePostion(position: startX)
}
}
func setOffsetGoalStart() {
setOffsetGoal(offset: mStartPos - mWidth / 2)
}
func setOffsetGoalEnd() {
setOffsetGoal(offset: mEndPos - mWidth / 2)
}
func setOffsetGoal(offset : Int) {
setOffsetGoalNoUpdate(offset: offset);
updateDisplay()
}
func setOffsetGoalNoUpdate(offset : Int) {
if (mTouchDragging) {
return;
}
mOffsetGoal = offset;
if (mOffsetGoal + mWidth / 2 > mMaxPos){
mOffsetGoal = mMaxPos - mWidth / 2
}
if (mOffsetGoal < 0){
mOffsetGoal = 0
}
}
func resetPositions() {
mStartPos = 0;
mEndPos = mMaxPos;
}
// Play state
func pause(){
if let audioPlayerUW = audioPlayer {
audioPlayerUW.pause()
}
}
func isPlaying() -> Bool {
if let audioPlayerUW = audioPlayer {
if audioPlayerUW.isPlaying {
return true
}
return false
}
return false
}
}
extension ControllerWaveForm : AVAudioPlayerDelegate {
}
extension ControllerWaveForm : WaveFormMoveProtocol {
// waveForm touch
func touchesBegan(position : Int){
mTouchDragging = true
mTouchStart = position
mTouchInitialOffset = mOffset
}
func touchesMoved(position : Int){
mOffset = trap(pos: Int(mTouchInitialOffset + (mTouchStart - position)));
updateDisplay()
}
func touchesEnded(position : Int){
mTouchDragging = false;
mOffsetGoal = mOffset;
}
}
extension ControllerWaveForm : ButtonMoveProtocol{
// Button touch
func buttonTouchesBegan(position : Int,isLeft : Bool){
mTouchDragging = true;
mTouchStart = position;
mTouchInitialStartPos = mStartPos;
mTouchInitialEndPos = mEndPos;
}
func buttonTouchesMoved(position : Int,isLeft : Bool){
let delta = position - mTouchStart;
if isLeft {
mStartPos = trap(pos: Int (mTouchInitialStartPos + delta));
if mStartPos > mEndPos {
mStartPos = mEndPos
}
}else {
mEndPos = trap(pos: Int(mTouchInitialEndPos + delta));
if mEndPos < mStartPos {
mEndPos = mStartPos
}
//waveFormView.updateEnd(x: Float(position))
}
mPlayStartMsec = mWaveformView!.pixelsToMillisecs(pixels: mStartPos)
mPlayEndMsec = mWaveformView!.pixelsToMillisecs(pixels: mEndPos)
updateDisplay()
}
func buttonTouchesEnded(position : Int,isLeft : Bool){
//print("buttonTouchesEnded")
mTouchDragging = false
if isLeft {
setOffsetGoalStart()
}else {
setOffsetGoalEnd()
}
}
}
extension ControllerWaveForm{
@IBInspectable public
var waveFormBackground : UIColor{
get {
return waveFormBackgroundColorPrivate
}
set(newValue){
waveFormBackgroundColorPrivate = newValue
}
}
@IBInspectable public
var currentPlayColor : UIColor {
get{
return currentPlayColorPrivate
}
set(newValue){
currentPlayColorPrivate = newValue
}
}
}
| af9d44214715ca1e3ce172c1d077d52c | 32.40665 | 219 | 0.577859 | false | false | false | false |
CrazyZhangSanFeng/BanTang | refs/heads/master | BanTang/BanTang/Classes/Home/View/BTCoverView.swift | apache-2.0 | 1 | //
// BTCoverView.swift
// BanTang
//
// Created by 张灿 on 16/6/13.
// Copyright © 2016年 张灿. All rights reserved.
// 遮盖
import UIKit
class BTCoverView: UIView {
//闭包作为属性
var click: () -> Void = {
}
class func show() -> BTCoverView {
let cover = BTCoverView()
cover.frame = UIScreen.mainScreen().bounds
cover.backgroundColor = UIColor.blackColor()
cover.alpha = 0.4
UIApplication.sharedApplication().keyWindow?.addSubview(cover)
return cover
}
/** popShow, */
class func popShow() -> BTCoverView {
let cover = BTCoverView()
cover.frame = CGRect(x: 0, y: 64, width: BTscreenW, height: BTscreenH - 64 - 49)
cover.backgroundColor = UIColor.blackColor()
cover.alpha = 0.4
UIApplication.sharedApplication().keyWindow?.addSubview(cover)
return cover
}
//点击屏幕调用闭包,类似代理
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.click()
}
}
| eb2a47c394ec8e6f19b1860d7b93c858 | 23.666667 | 88 | 0.600386 | false | false | false | false |
shirai/SwiftLearning | refs/heads/master | playground/オプショナル型.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
/*オプショナル型とは、変数の型がもつ通常の値に加えて、空の(値が無い)状態を保持できる変数です。空の状態はnilで表現します。*/
/*
*
*宣言
変数の宣言時に、型の後ろに「?」をつけて宣言
*
*/
var name: String?
//name = nil //nilを入れなくても最初に入っている
name = "Saki"
print(name) //"?"のオプショナル型の変数は出力したときにOptionalという記述が含まれる
name = "Saki"
print(name!) // 変数名の後ろに!をつけてアンラップ
// オプショナル型でない変数にはnilを代入できない。
//var name1: String
//name1 = nil // エラーになる。
/*
*
*オプショナルバインディング
値が空(nil)の場合はfalse、それ以外はtrue
アンラップをする場合には、必ずラッピングの中身が存在する(=nilではない)ことが保証されていなければいけません。
nilかどうかわからない場合は後述するオプショナルチェイニングかオプショナルバインディングを使いましょう。
*
*/
var price: Int? = 100
if let p = price {
print("価格:\(p)円")
}else{
print("価格:未定")
}
price = nil
if let p = price {
print("価格:\(p)円")
}else{
print("価格:未定")
}
/*
*
*アンラップ
オプショナル型を計算で使用したり、通常の型を受け取る関数の引数に渡したりする場合は、値が空でないことを明示するために、アンラップする必要があります。アンラップはラップ(包装)の反対で、オプションという包装紙に包まれた変数の包装を解くイメージです。
*アンラップするには、オプショナル型の変数名の後ろに「!」をつけます。
*
*/
var diameter: Double?
diameter = 4
print("円の周りの長さは\(Double(Double(diameter!) * 3.14))センチです。")// 変数名の後ろに!をつけてアンラップ
var diameter2: Int?
diameter2 = 4
print("円の周りの長さは\(Int(Double(diameter2!) * 3.14))センチです。")// 変数名の後ろに!をつけてアンラップ
/*3.14はDouble型。自動変換されないので、Double型*Double型しかできない。(Int*Double->エラー)一番外側で計算結果の型を指定する。*/
//中身が空(nil)のオプショナル型の変数をアンラップすると実行時エラーが発生
//diameter = nil
//print("円の直径は\(Double(Double(diameter!)*3.14))㎠です。")
//非オプショナル型を受けとるには関数の呼び出し側でアンラップが必要
func calculateTax(p: Int) -> Int { //func <関数>(<引数名>:<型>){<処理>}
return Int(Double(p) * 1.08)
}
var price2: Int?
price2 = 300
let priceWithTax = calculateTax(p:price2!)//変数名の後ろに!をつけてアンラップ
print(priceWithTax)
//if文を使うと、値が空かどうかの判定とアンラップされた別変数への代入を同時に行うことができる。
diameter = 4
if let unwrappedDiameter = diameter{
// unwrappedPriceはアンラップされているので後ろに!は不要
print("円の周りの長さは \(unwrappedDiameter*3.14) センチです。")
}
diameter = nil
if let unwrappedDiameter = diameter{
// unwrappedPriceはアンラップされているので後ろに!は不要
print("円の周りの長さは \(unwrappedDiameter*3.14) センチです。")
}else{
print("円の直径がわかりません。")
}
//定数でも変数でも同様に書ける
//配列やディクショナリも同様にオプショナル型として宣言できる
var party: Array<String>?
party = ["戦士", "魔法使い"]
party!.append("nil") // 変数名の後ろに!をつけてアンラップ
party!.append("僧侶") // 変数名の後ろに!をつけてアンラップ
print(party)
/*
*
*暗黙的なオプショナル型
宣言時に?ではなく!をつけて宣言
暗黙的なオプショナル型は、空値(nil)をとり得るという意味では、上で説明したオプショナル型と同じですが、使用時にアンラップする必要がありません。
アンラップの必要がないので、初期値がnilでも使用時までには必ず値が入っていると想定されるケースでは、暗黙的なオプショナル型の方が便利です。
但し、アンラップが必要な状況で、暗黙的なオプショナル型を空のまま使用すると実行時エラーが発生します。
*
*/
var うまい棒: Double!
うまい棒 = 10
print("税込み価格は\(Int(うまい棒 * 1.08))円") // 変数名の後ろに!をつける必要がない
//うまい棒 = nil
//print("税込み価格は\(Int(うまい棒 * 1.08))円") // エラー
/*暗黙的なオプショナル型の宣言に使用する!と、アンラップに使用する!を混同しないようにしてください。同じ記号が使われていますが意味は異なります。*/
//暗黙的なオプショナル型をif文の中で条件として使用
var ガリガリ君: Double!
ガリガリ君 = 60
if let unwrappedPrice = ガリガリ君 {
print("税込み価格は\(Int(unwrappedPrice * 1.08))円")
} else {
print("価格は未定")
}
/*
*
*nil結合演算子
??という演算子を使うと、オプショナル型がnilでなければその値を、nilの場合は指定した値を与えることができる。
*
*/
var a: Int?
let b = a ?? 10 //aはnilなので、10が代入される
let c = b ?? 20 //bはnilではないので、20が代入される
| bbbf61e02398cd1ebbfdcf54ea3806a9 | 21.058394 | 124 | 0.724686 | false | false | false | false |
isohrab/gpkey | refs/heads/master | GPKeyboard/KeyboardViewController.swift | mit | 1 | //
// KeyboardViewController.swift
// Gachpazh Keyboard
//
// Created by sohrab on 09/09/16.
// Copyright © 2016 ark.sohrab. All rights reserved.
//
import UIKit
import AudioToolbox
class KeyboardViewController: UIInputViewController, GPButtonEventsDelegate {
// 1396 - 1397 - 1306:char - 1155:delete - 1156:space+number+shift+return
let delSound: SystemSoundID = 1155
let charSound: SystemSoundID = 1104
let utilSound: SystemSoundID = 1156
let vibSound: SystemSoundID = 1520
var soundState: Int = 0
/****************************
* define alphabet value *
****************************/
// [layer][row][column]
let characters :[[[Harf]]]=[[
// first layer: first row:
[Harf.init(name: "zad", face: "ض", output: "ض", returnable: false, spaceReturnable: false),
Harf.init(name: "sad", face: "ص", output: "ص", returnable: false, spaceReturnable: false),
Harf.init(name: "ghaf", face: "ق", output: "ق", returnable: false, spaceReturnable: false),
Harf.init(name: "fe", face: "ف", output: "ف", returnable: false, spaceReturnable: false),
Harf.init(name: "ghein",face: "غ", output: "غ", returnable: false, spaceReturnable: false),
Harf.init(name: "ein", face: "ع", output: "ع", returnable: false, spaceReturnable: false),
Harf.init(name: "ha", face: "ه", output: "ه", returnable: false, spaceReturnable: false),
Harf.init(name: "khe", face: "خ", output: "خ", returnable: false, spaceReturnable: false),
Harf.init(name: "he", face: "ح", output: "ح", returnable: false, spaceReturnable: false),
Harf.init(name: "je", face: "ج", output: "ج", returnable: false, spaceReturnable: false),
Harf.init(name: "che", face: "چ", output: "چ", returnable: false, spaceReturnable: false)],
//first Layer, Second Row:
[Harf.init(name: "she", face: "ش", output: "ش", returnable: false, spaceReturnable: false),
Harf.init(name: "se", face: "س", output: "س", returnable: false, spaceReturnable: false),
Harf.init(name: "ye", face: "ی", output: "ی", returnable: false, spaceReturnable: false),
Harf.init(name: "be", face: "ب", output: "ب", returnable: false, spaceReturnable: false),
Harf.init(name: "lam", face: "ل", output: "ل", returnable: false, spaceReturnable: false),
Harf.init(name: "alef",face: "ا", output: "ا", returnable: false, spaceReturnable: false),
Harf.init(name: "te", face: "ت", output: "ت", returnable: false, spaceReturnable: false),
Harf.init(name: "non", face: "ن", output: "ن", returnable: false, spaceReturnable: false),
Harf.init(name: "mim", face: "م", output: "م", returnable: false, spaceReturnable: false),
Harf.init(name: "ke", face: "ک", output: "ک", returnable: false, spaceReturnable: false),
Harf.init(name: "ge", face: "گ", output: "گ", returnable: false, spaceReturnable: false)],
//first Layer, Third Row:
[Harf.init(name: "za", face: "ظ", output: "ظ", returnable: false, spaceReturnable: false),
Harf.init(name: "ta", face: "ط", output: "ط", returnable: false, spaceReturnable: false),
Harf.init(name: "ze", face: "ز", output: "ز", returnable: false, spaceReturnable: false),
Harf.init(name: "re", face: "ر", output: "ر", returnable: false, spaceReturnable: false),
Harf.init(name: "zal", face: "ذ", output: "ذ", returnable: false, spaceReturnable: false),
Harf.init(name: "dal", face: "د", output: "د", returnable: false, spaceReturnable: false),
Harf.init(name: "pe", face: "پ", output: "پ", returnable: false, spaceReturnable: false),
Harf.init(name: "ve", face: "و", output: "و", returnable: false, spaceReturnable: false)],
// first Layer, Fourth Row:
[Harf.init(name: "se3noghte",face: "ث", output: "ث", returnable: false, spaceReturnable: false),
Harf.init(name: "zhe", face: "ژ", output: "ژ", returnable: false, spaceReturnable: false)]],
// Shift LAYER
// Second Layer: first Row:
[[Harf.init(name: "saken", face: "ْ", output: "ْ", returnable: true, spaceReturnable: false),
Harf.init(name: "o", face: "ُ", output: "ُ", returnable: true, spaceReturnable: false),
Harf.init(name: "e", face: "ِ", output: "ِ", returnable: true, spaceReturnable: false),
Harf.init(name: "a", face: "َ", output: "َ", returnable: true, spaceReturnable: false),
Harf.init(name: "an", face: "ً", output: "ً", returnable: true, spaceReturnable: false),
Harf.init(name: "parantezL", face: "\u{0028}", output: "\u{0029}", returnable: false, spaceReturnable: true),
Harf.init(name: "parantezR", face: "\u{0029}", output: "\u{0028}", returnable: false, spaceReturnable: true),
Harf.init(name: "akoladL", face: "\u{007B}", output: "\u{007D}", returnable: false, spaceReturnable: true),
Harf.init(name: "akoladR", face: "\u{007D}", output: "\u{007B}", returnable: false, spaceReturnable: true),
Harf.init(name: "beraketL", face: "\u{005b}", output: "\u{005d}", returnable: false, spaceReturnable: true),
Harf.init(name: "beraketR", face: "\u{005d}", output: "\u{005b}", returnable: false, spaceReturnable: true)],
// second Layer, Second Row:
[Harf.init(name: "bullet", face: "•", output: "•", returnable: false, spaceReturnable: true),
Harf.init(name: "underline",face: "_", output: "_", returnable: false, spaceReturnable: true),
Harf.init(name: "yeHamze", face: "ئ", output: "ئ", returnable: true, spaceReturnable: false),
Harf.init(name: "tashdid", face: "\u{0651}", output: "\u{0651}", returnable: true, spaceReturnable: false),
Harf.init(name: "hamze", face: "ء", output: "ء", returnable: true, spaceReturnable: false),
Harf.init(name: "abakola", face: "آ", output: "آ", returnable: true, spaceReturnable: false),
Harf.init(name: "keshidan",face: "ـ", output: "ـ", returnable: false, spaceReturnable: true),
Harf.init(name: "2fleshL", face: "\u{00ab}", output: "\u{00bb}", returnable: false, spaceReturnable: true),
Harf.init(name: "2fleshR", face: "\u{00bb}", output: "\u{00ab}", returnable: false, spaceReturnable: true),
Harf.init(name: "apostroph",face: "'", output: "'", returnable: true, spaceReturnable: false),
Harf.init(name: "quotation",face: "\"", output: "\"", returnable: false, spaceReturnable: true)],
//second layer, third Row:
[Harf.init(name: "noghte", face: ".", output: ".", returnable: false, spaceReturnable: true),
Harf.init(name: "virgol", face: "،", output: "،", returnable: false, spaceReturnable: true),
Harf.init(name: "3noghte", face: "\u{2026}", output: "\u{2026}", returnable: false, spaceReturnable: true),
Harf.init(name: "donoghte", face: ":", output: ":", returnable: false, spaceReturnable: true),
Harf.init(name: "semicolon", face: "؛", output: "؛", returnable: false, spaceReturnable: true),
Harf.init(name: "centigrad", face: "°", output: "°", returnable: false, spaceReturnable: true),
Harf.init(name: "soal", face: "؟", output: "؟", returnable: false, spaceReturnable: true),
Harf.init(name: "tajob", face: "!", output: "!", returnable: false, spaceReturnable: true)],
// second layer, fourth Row:
[Harf.init(name: "atsign", face: "@", output: "@", returnable: false, spaceReturnable: true),
Harf.init(name: "sharp", face: "#", output: "#", returnable: false, spaceReturnable: true)]],
//Number layer
// first Row:
[[Harf.init(name: "yek",face: "۱", output: "۱", returnable: false, spaceReturnable: false),
Harf.init(name: "do",face: "۲", output: "۲", returnable: false, spaceReturnable: false),
Harf.init(name: "se",face: "۳", output: "۳", returnable: false, spaceReturnable: false),
Harf.init(name: "char",face: "۴", output: "۴", returnable: false, spaceReturnable: false),
Harf.init(name: "panj",face: "۵", output: "۵", returnable: false, spaceReturnable: false),
Harf.init(name: "shesh",face: "۶", output: "۶", returnable: false, spaceReturnable: false),
Harf.init(name: "haft",face: "۷", output: "۷", returnable: false, spaceReturnable: false),
Harf.init(name: "hasht",face: "۸", output: "۸", returnable: false, spaceReturnable: false),
Harf.init(name: "noh",face: "۹", output: "۹", returnable: false, spaceReturnable: false),
Harf.init(name: "sefr",face: "۰", output: "۰", returnable: false, spaceReturnable: false),
Harf.init(name: "mosbat",face: "=", output: "=", returnable: false, spaceReturnable: false)],
//second Row:
[Harf.init(name: "prime",face: "`", output: "`", returnable: false, spaceReturnable: false),
Harf.init(name: "mad",face: "~", output: "~", returnable: false, spaceReturnable: false),
Harf.init(name: "bala",face: "^", output: "^", returnable: false, spaceReturnable: false),
Harf.init(name: "dollar",face: "$", output: "$", returnable: false, spaceReturnable: false),
Harf.init(name: "euro",face: "€", output: "€", returnable: false, spaceReturnable: false),
Harf.init(name: "star",face: "*", output: "*", returnable: false, spaceReturnable: false),
Harf.init(name: "darsad",face: "٪", output: "٪", returnable: false, spaceReturnable: false),
Harf.init(name: "mosbat",face: "+", output: "+", returnable: false, spaceReturnable: false),
Harf.init(name: "menha", face: "-",output: "-", returnable: false, spaceReturnable: false),
Harf.init(name: "zarb",face: "×", output: "×", returnable: false, spaceReturnable: false),
Harf.init(name: "taghsim",face: "÷", output: "÷", returnable: false, spaceReturnable: false)],
//third Row:
[Harf.init(name: "number-seperator",face: ",", output: ",", returnable: false, spaceReturnable: false),
Harf.init(name: "register",face: ".", output: ".", returnable: false, spaceReturnable: false),
Harf.init(name: "Copyright",face: ":", output: ":", returnable: false, spaceReturnable: false),
Harf.init(name: "kama",face: "،", output: "،", returnable: false, spaceReturnable: false),
Harf.init(name: "small",face: "<", output: ">", returnable: false, spaceReturnable: false),
Harf.init(name: "great",face: ">", output: "<", returnable: false, spaceReturnable: false),
Harf.init(name: "pipe",face: "|", output: "|", returnable: false, spaceReturnable: false),
Harf.init(name: "parantezL", face: "\u{0028}", output: "\u{0028}", returnable: false, spaceReturnable: false),
Harf.init(name: "parantezR", face: "\u{0029}", output: "\u{0029}", returnable: false, spaceReturnable: false),],
// fourht row:
[Harf.init(name: "back-slash",face: "\\", output: "\\", returnable: false, spaceReturnable: false),
Harf.init(name: "slash",face: "/", output: "/", returnable: false, spaceReturnable: false),]]]
// the smiles are changable in main App
var smile:[String] = ["\u{1F600}", // 😀
"\u{1F601}", // 😁
"\u{1F602}", // 😂
"\u{1F60F}", // 😏
"\u{0263A}", // 😘☺
"\u{1F917}", // 🤗
"\u{1F60D}", // 😍
"\u{1F618}", // 😘
"\u{1F61C}", // 😜
"\u{1F339}", // 🌹
"\u{02764}", // 🌹❤
"\u{1f614}", // 😔
"\u{1F622}", // 😢
"\u{1F62D}", // 😭
"\u{1F612}", // 😒
"\u{1F620}", // 😠
"\u{1F624}", // 😤
"\u{1F633}", // 😳
"\u{1F631}", // 😱
"\u{1F60B}", // 😋
"\u{1F38A}", // 🎊
"\u{1F494}", // 💔
"\u{1F610}", // 😐
"\u{1F62C}", // 😬
"\u{1F644}", // 🙄
"\u{1F60E}", // 😎
"\u{1F615}", // 😕
"\u{1F925}", // 🤥
"\u{1F914}", // 🤔
"\u{1F922}", // 🤢
"\u{1F44C}", // 👌
"\u{1F44D}", // 👍
"\u{1F64F}"] // 🙏
/*************************************
* *
* Define Global Value *
* - keyboards layers *
* - keyboard dimension and points *
* *
*************************************/
var gapHorizontal: CGFloat = 6 // in iPad screens should be multiply by 2
var gapVertical: CGFloat = 10 // in iPad Screen should be multiply by 2
var buttonHeight: CGFloat = 52
var dmpPatriot: CGFloat = 1
var shift: Bool = false // show state of shift button
{
didSet {
doShift(shifting: shift)
}
}
var returnAfterSpace = false {
didSet {
if returnAfterSpace == true
{
alefbaButtons[4][3].label?.text = "فاصله"
alefbaButtons[4][3].type = .SPACE
}
}
}
var deleting: Bool = false // when it is true, continuing deleting characters
var deleteTimer: TimeInterval = 0.3 // it will accelerate deleting upto 500 milisecond
var timer:Timer!
// colors
var buttonBackground = UIColor.white // color of button in noraml state
var viewBackground = UIColor(red:0.82, green:0.84, blue:0.86, alpha:1.0) // main background color
var utilBackgroundColor = UIColor(red:0.67, green:0.70, blue:0.73, alpha:1.0) // color of util button in normal state
var textColorNormal = UIColor.black
var textColorHighlighted = UIColor.black
var makeButtonBiggerTextColor = UIColor.black
var buttonShadowColor = UIColor.gray.cgColor
var utilButtonTouchDownColor = UIColor.white
var buttonBorderColor = UIColor.gray.cgColor
var makeButtonBiggerBackground = UIColor(red:0.90, green:0.89, blue:0.89, alpha:1.0)
/******* Layout variabels *********/
var alefbaLayout: UIView!
var numberLayout: UIView!
var alefbaButtons: [[GPButton]]!
var numberButtons: [[GPButton]]!
var portraitConstraints:[NSLayoutConstraint]!
var landscapeConstraints:[NSLayoutConstraint]!
/******************************************
* *
* initial Alefba Layout *
* *
*****************************************/
func initAlefbaLayout(){
alefbaButtons = [[GPButton]]()
// Add emojies
var rowButtons = [GPButton]()
for i in 0...10
{
let btn = GPButton(with: .EMOJI)
btn.label?.text = smile[i]
rowButtons.append(btn)
btn.backLayerInsetX = 0
btn.backLayerInsetY = 0
btn.addTarget(self, action: #selector(self.emojiTouched(_:)), for: .touchUpInside)
alefbaLayout.addSubview(btn)
}
alefbaButtons.append(rowButtons)
// Add character buttons
for i in 0..<characters[0].count
{
var rowButtons = [GPButton]()
for j in 0..<characters[0][i].count
{
let btn = GPButton(with: .CHAR)
btn.harf = characters[0][i][j]
rowButtons.append(btn)
btn.backLayerInsetX = gapHorizontal / 2
btn.backLayerInsetY = gapVertical / 2
// btn.isExclusiveTouch = true
btn.addTarget(self, action: #selector(self.charTouched(_:)), for: .touchUpInside)
alefbaLayout.addSubview(btn)
}
alefbaButtons.append(rowButtons)
}
// add all util function
let shiftButton = GPButton(with: .SHIFT)
shiftButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside)
shiftButton.label?.text = ".؟!"
shiftButton.backLayerInsetX = gapHorizontal / 2
shiftButton.backLayerInsetY = gapVertical / 2
alefbaButtons[3].insert(shiftButton, at: 0)
alefbaLayout.addSubview(shiftButton)
let deleteButton = GPButton(with: .DELETE)
deleteButton.addTarget(self, action: #selector(self.deleteTouchDown(sender:)), for: .touchDown)
deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpInside)
deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpOutside)
deleteButton.label?.text = ""
deleteButton.backLayerInsetX = gapHorizontal / 2
deleteButton.backLayerInsetY = gapVertical / 2
alefbaButtons[3].insert(deleteButton, at: alefbaButtons[3].count)
alefbaLayout.addSubview(deleteButton)
let numberButton = GPButton(with: .NUMBER)
numberButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside)
numberButton.label?.text = "۱۲۳"
numberButton.backLayerInsetX = gapHorizontal / 2
numberButton.backLayerInsetY = gapVertical / 2
alefbaButtons[4].insert(numberButton, at: 0)
alefbaLayout.addSubview(numberButton)
let globeButton = GPButton(with: .GLOBE)
globeButton.backLayerInsetX = gapHorizontal / 2
globeButton.backLayerInsetY = gapVertical / 2
globeButton.label?.text = ""
alefbaButtons[4].insert(globeButton, at: 1)
alefbaLayout.addSubview(globeButton)
globeButton.addTarget(self, action: #selector(advanceToNextInputMode), for: .touchUpInside)
let spaceButton = GPButton(with: .SPACE)
spaceButton.label?.text = "فاصله"
spaceButton.backLayerInsetX = gapHorizontal / 2
spaceButton.backLayerInsetY = gapVertical / 2
spaceButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside)
alefbaButtons[4].insert(spaceButton, at: 3)
alefbaLayout.addSubview(spaceButton)
let enterButton = GPButton(with: .ENTER)
enterButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside)
enterButton.label?.text = ""
enterButton.backLayerInsetX = gapHorizontal / 2
enterButton.backLayerInsetY = gapVertical / 2
alefbaButtons[4].insert(enterButton, at: 5)
alefbaLayout.addSubview(enterButton)
// calculate constraints
sizeConstraints(buttons: alefbaButtons, kbLayout: alefbaLayout)
positionConstraints(buttons: alefbaButtons, kbLayout: alefbaLayout)
}
/******************************************
* *
* initial Number Layout *
* *
*****************************************/
func initNumberLayout(){
// TODO: background should be checked here
numberLayout.backgroundColor = viewBackground
numberButtons = [[GPButton]]()
// Add emojies
var rowButtons = [GPButton]()
for i in 0...10
{
let btn = GPButton(with: .EMOJI)
btn.label?.text = smile[i+22]
rowButtons.append(btn)
btn.backLayerInsetX = 0
btn.backLayerInsetY = 0
btn.addTarget(self, action: #selector(self.emojiTouched(_:)), for: .touchUpInside)
numberLayout.addSubview(btn)
}
numberButtons.append(rowButtons)
for i in 0..<characters[2].count
{
var rowButtons = [GPButton]()
for j in 0..<characters[2][i].count
{
let btn = GPButton(with: .CHAR)
btn.harf = characters[2][i][j]
rowButtons.append(btn)
btn.backLayerInsetX = gapHorizontal / 2
btn.backLayerInsetY = gapVertical / 2
btn.isExclusiveTouch = true
btn.addTarget(self, action: #selector(self.charTouched(_:)), for: .touchUpInside)
numberLayout.addSubview(btn)
}
numberButtons.append(rowButtons)
}
// add all util function
let deleteButton = GPButton(with: .DELETE)
deleteButton.addTarget(self, action: #selector(self.deleteTouchDown(sender:)), for: .touchDown)
deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpInside)
deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpOutside)
deleteButton.label?.text = ""
deleteButton.backLayerInsetX = gapHorizontal / 2
deleteButton.backLayerInsetY = gapVertical / 2
numberButtons[3].insert(deleteButton, at: numberButtons[3].count)
numberLayout.addSubview(deleteButton)
let numberButton = GPButton(with: .NUMBER)
numberButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside)
numberButton.label?.text = "الفبا"
numberButton.backLayerInsetX = gapHorizontal / 2
numberButton.backLayerInsetY = gapVertical / 2
numberButtons[4].insert(numberButton, at: 0)
numberLayout.addSubview(numberButton)
let globeButton = GPButton(with: .GLOBE)
globeButton.backLayerInsetX = gapHorizontal / 2
globeButton.backLayerInsetY = gapVertical / 2
globeButton.label?.text = ""
numberButtons[4].insert(globeButton, at: 1)
numberLayout.addSubview(globeButton)
globeButton.addTarget(self, action: #selector(advanceToNextInputMode), for: .touchUpInside)
let spaceButton = GPButton(with: .SPACE)
spaceButton.label?.text = "فاصله"
spaceButton.backLayerInsetX = gapHorizontal / 2
spaceButton.backLayerInsetY = gapVertical / 2
spaceButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside)
numberButtons[4].insert(spaceButton, at: 3)
numberLayout.addSubview(spaceButton)
let enterButton = GPButton(with: .ENTER)
enterButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside)
enterButton.label?.text = ""
enterButton.backLayerInsetX = gapHorizontal / 2
enterButton.backLayerInsetY = gapVertical / 2
numberButtons[4].insert(enterButton, at: 5)
numberLayout.addSubview(enterButton)
// Calculate constraint
sizeConstraints(buttons: numberButtons, kbLayout: numberLayout)
positionConstraints(buttons: numberButtons, kbLayout: numberLayout)
}
/************************************
* DELETE FUNCTION *
************************************/
// delete touching
func deleteTouchDown(sender: GPButton)
{
playSound(for: delSound)
let proxy = textDocumentProxy as UITextDocumentProxy
proxy.deleteBackward()
deleting = true
timer = Timer.scheduledTimer(timeInterval: deleteTimer, target: self, selector: #selector(doDeleting), userInfo: nil, repeats: false)
}
func doDeleting()
{
if deleting
{
let proxy = textDocumentProxy as UITextDocumentProxy
proxy.deleteBackward()
if deleteTimer > 0.1
{
deleteTimer -= 0.08
}
if proxy.documentContextBeforeInput != nil
{
timer = Timer.scheduledTimer(timeInterval: deleteTimer, target: self, selector: #selector(doDeleting), userInfo: nil, repeats: false)
playSound(for: delSound)
}
else
{
proxy.deleteBackward()
timer = Timer.scheduledTimer(timeInterval: deleteTimer, target: self, selector: #selector(doDeleting), userInfo: nil, repeats: false)
}
}
}
// set deleting boolean value to false with this event
func deleteTouchUp(_ sender: GPButton)
{
deleting = false
deleteTimer = 0.3
timer.invalidate()
}
/************************************
* UTIL FUNCTION *
************************************/
func utilTouched(sender: GPButton)
{
let proxy = textDocumentProxy as UITextDocumentProxy
let type = sender.type!
switch type
{
case .SPACE:
playSound(for: utilSound)
proxy.insertText(" ")
if shift == true
{
if returnAfterSpace == true
{
shift = false
returnAfterSpace = false
}
}
break
case .GLOBE:
self.advanceToNextInputMode()
break
case .SHIFT:
playSound(for: utilSound)
shift = !shift
break
case .NUMBER:
playSound(for: utilSound)
if alefbaLayout.layer.opacity == 0
{
numberLayout.layer.opacity = 0
alefbaLayout.layer.opacity = 1
}
else
{
alefbaLayout.layer.opacity = 0
numberLayout.layer.opacity = 1
}
if shift == true
{
shift = false
}
break
case .ENTER:
playSound(for: utilSound)
proxy.insertText("\n")
break
case .HALBSPACE:
playSound(for: utilSound)
proxy.insertText("\u{200C}")
shift = false
break
default:
break
}
}
/************************************
* SHIFT FUNCTION *
************************************/
func doShift(shifting:Bool)
{
if shifting
{
for i in 0...10
{
alefbaButtons[0][i].label?.text = smile[i+11]
}
// first two row in characters array
for i in 0...1
{
for j in 0...10
{
// i+1 because buttons have one more row for emojies
alefbaButtons[i+1][j].harf = characters[1][i][j]
}
}
// row 3 is include shift and delete button
for j in 1...8
{
alefbaButtons[3][j].harf = characters[1][2][j-1]
}
// 4th row, the buttons beside the space
alefbaButtons[4][2].harf = characters[1][3][0]
alefbaButtons[4][4].harf = characters[1][3][1]
// half space
alefbaButtons[4][3].label?.text = "نیمفاصله"
alefbaButtons[4][3].type = .HALBSPACE
}
else
{
for i in 0...10
{
alefbaButtons[0][i].label?.text = smile[i]
}
// row 1 and 2
for i in 0...1
{
for j in 0...10
{
alefbaButtons[i+1][j].harf = characters[0][i][j]
}
}
// row 3 is include shift and delete button
for j in 1...8
{
alefbaButtons[3][j].harf = characters[0][2][j-1]
}
// 4th row, the buttons beside the space
alefbaButtons[4][2].harf = characters[0][3][0]
alefbaButtons[4][4].harf = characters[0][3][1]
// half space
alefbaButtons[4][3].label?.text = "فاصله"
alefbaButtons[4][3].type = .SPACE
}
}
func shiftManager(sender: GPButton)
{
if shift == true {
let type = sender.type!
if type == .CHAR
{
if let h = sender.harf
{
if h.returnable == true
{
sender.Highlighting(state: false)
shift = false
return
}
if h.spaceReturnable == true
{
returnAfterSpace = true
}
}
}
}
}
/************************************
* OTHER FUNCTION *
************************************/
// add character into textfield
func charTouched(_ sender: GPButton)
{
playSound(for: charSound)
let proxy = textDocumentProxy as UITextDocumentProxy
guard let char = sender.harf?.output else {return}
proxy.insertText(char)
shiftManager(sender: sender)
}
func emojiTouched(_ sender: GPButton)
{
playSound(for: charSound)
let proxy = textDocumentProxy as UITextDocumentProxy
guard let char = sender.label?.text else {return}
proxy.insertText(char)
if shift == true
{
returnAfterSpace = true
}
}
func playSound(for type:UInt32)
{
// mute mode
if soundState == 1
{
return // hisssss! >:/
}
// vibrate mode
if soundState == 2
{
AudioServicesPlaySystemSound(vibSound)
return
}
AudioServicesPlaySystemSound(type)
}
//////////// constraints functions: ///////////
func positionConstraints(buttons: [[GPButton]], kbLayout: UIView)
{
// chaining all first column to top and botton of each other vertically.
for row in 0..<buttons.count-1
{
NSLayoutConstraint(item: buttons[row][0], attribute: .bottom, relatedBy: .equal, toItem: buttons[row+1][0], attribute: .top, multiplier: 1, constant: 0).isActive = true
}
// chain first button to top of the keyboard layer
NSLayoutConstraint(item: buttons[0][0], attribute: .top, relatedBy: .equal, toItem: kbLayout, attribute: .top, multiplier: 1, constant: 0).isActive = true
// chain the last button to top of the keyboard layer
NSLayoutConstraint(item: buttons[buttons.count-1][0], attribute: .bottom, relatedBy: .equal, toItem: kbLayout, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
// chaining all buttons in a row from left to right of each other horizontally.
for row in 0..<buttons.count
{
for col in 1..<buttons[row].count
{
NSLayoutConstraint(item: buttons[row][col-1], attribute: .right, relatedBy: .equal, toItem: buttons[row][col], attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: buttons[row][col-1], attribute: .centerY, relatedBy: .equal, toItem: buttons[row][col], attribute: .centerY, multiplier: 1, constant: 0).isActive = true
}
}
for row in 0..<buttons.count
{
NSLayoutConstraint(item: buttons[row][0], attribute: .left, relatedBy: .equal, toItem: kbLayout, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: buttons[row][buttons[row].count-1], attribute: .right, relatedBy: .equal, toItem: kbLayout, attribute: .right, multiplier: 1, constant: 0).isActive = true
}
}
func sizeConstraints(buttons: [[GPButton]], kbLayout: UIView)
{
let muster = buttons[1][1]
let np = NSLayoutConstraint(item: muster, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: buttonHeight)
np.priority = 999
portraitConstraints.append(np)
let nl = NSLayoutConstraint(item: muster, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: buttonHeight * 0.8)
nl.priority = 999
landscapeConstraints.append(nl)
for row in 0..<buttons.count
{
for col in 0..<buttons[row].count
{
let type = buttons[row][col].type!
// all buttons should have same height (except emoji buttons)
if type != .EMOJI
{
NSLayoutConstraint(item: buttons[row][col], attribute: .height, relatedBy: .equal, toItem: muster, attribute: .height, multiplier: 1, constant: 0).isActive = true
}
// assign width constraint to buttons according to its characteristic
switch type
{
case .CHAR:
NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1, constant: 0).isActive = true
break
case .EMOJI:
// the width is always equal to muster
// Portrait
portraitConstraints.append(NSLayoutConstraint(item: buttons[row][col], attribute: .height, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1.3, constant: 0))
// Landscape
landscapeConstraints.append(NSLayoutConstraint(item: buttons[row][col], attribute: .height, relatedBy: .equal, toItem: muster, attribute: .height, multiplier: 0.8, constant: 0))
NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1, constant: 0).isActive = true
break
case .SHIFT, .DELETE:
NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .greaterThanOrEqual, toItem: muster, attribute: .width, multiplier: 1.5, constant: 0).isActive = true
break
case .ENTER:
NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1.75, constant: 0).isActive = true
break
case .SPACE, .HALBSPACE:
NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .greaterThanOrEqual, toItem: muster, attribute: .width, multiplier: 3.5, constant: 0).isActive = true
break
case .GLOBE, .NUMBER:
NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1.25, constant: 0).isActive = true
break
}
}
}
}
/****************************************
* *
* System default function *
* *
****************************************/
override func updateViewConstraints()
{
super.updateViewConstraints()
// Activate constraints according device orientation
if UIScreen.main.bounds.size.height > UIScreen.main.bounds.size.width
{
NSLayoutConstraint.deactivate(landscapeConstraints)
NSLayoutConstraint.activate(portraitConstraints)
}
else
{
NSLayoutConstraint.deactivate(portraitConstraints)
NSLayoutConstraint.activate(landscapeConstraints)
}
self.view.layoutSubviews()
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
updateViewConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
let prefs = UserDefaults(suiteName: "group.me.alirezak.gachpazh")
// retreive user Sound settings
if let s = prefs?.integer(forKey: "sound") {
if s != 0
{
soundState = s
}
else
{
soundState = 3 // default sound is On
}
}
for i in 0..<33
{
if let emojiInt = prefs?.integer(forKey: String(i)){
if emojiInt != 0
{
smile [i] = String(Character(UnicodeScalar(emojiInt)!))
}
}
}
// get all variable according current device state
calculateVariables()
}
override func viewWillAppear(_ animated: Bool) {
print("viewWillAppear")
super.viewWillAppear(animated)
setTheme()
// initial landscape and portrait constraints
landscapeConstraints = [NSLayoutConstraint]()
portraitConstraints = [NSLayoutConstraint]()
/**** initial Alefba layer ****/
alefbaLayout = UIView()
alefbaLayout.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(alefbaLayout)
alefbaLayout.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
alefbaLayout.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
alefbaLayout.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
alefbaLayout.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
initAlefbaLayout()
alefbaLayout.layer.opacity = 0
/*** Initial Number Layer ***/
numberLayout = UIView()
numberLayout.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(numberLayout)
numberLayout.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
numberLayout.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
numberLayout.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
numberLayout.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
initNumberLayout()
numberLayout.layer.opacity = 0
}
override func viewDidAppear(_ animated: Bool) {
UIView.animate(withDuration: 0.4) {
self.alefbaLayout.layer.opacity = 1
}
}
func calculateVariables()
{
// define a default multiplier based iphone 6/6s/7 (width = 375) screen size.
if UIScreen.main.bounds.size.height > UIScreen.main.bounds.size.width
{
dmpPatriot = UIScreen.main.bounds.size.width / 375
}
else
{
dmpPatriot = UIScreen.main.bounds.size.width / 667
}
gapHorizontal = gapHorizontal * dmpPatriot
if dmpPatriot < 1
{
gapVertical = gapVertical / dmpPatriot
}
else
{
gapVertical = gapVertical * dmpPatriot
buttonHeight = buttonHeight * dmpPatriot
}
}
override func textDidChange(_ textInput: UITextInput?) {
//The app has just changed the document's contents, the document context has been updated.
setTheme()
// check if user "SEND" the message!
let proxy = self.textDocumentProxy
if proxy.documentContextAfterInput == nil && proxy.documentContextBeforeInput == nil
{
guard (alefbaLayout != nil) else {
return
}
shift = false
}
}
// GPButtonEventsDelegate
func moveCursor(numberOfMovement: Int) {
let proxy = textDocumentProxy as UITextDocumentProxy
proxy.adjustTextPosition(byCharacterOffset: numberOfMovement)
}
func setTheme()
{
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
viewBackground = UIColor(red:0.08, green:0.08, blue:0.08, alpha:1.0)
GPButton.buttonColor = UIColor(red:0.35, green:0.35, blue:0.35, alpha:1.0)
GPButton.buttonHighlighted = UIColor(red:0.35, green:0.35, blue:0.35, alpha:1.0)
GPButton.utilBackgroundColor = UIColor(red:0.22, green:0.22, blue:0.22, alpha:1.0)
GPButton.charColor = UIColor.white
GPButton.shadowColor = UIColor(red:0.08, green:0.08, blue:0.08, alpha:1.0)
GPButton.layoutColor = UIColor(red:0.08, green:0.08, blue:0.08, alpha:1.0)
} else {
viewBackground = UIColor(red:0.84, green:0.84, blue:0.84, alpha:1.0)
GPButton.buttonColor = UIColor.white
GPButton.buttonHighlighted = UIColor.white
GPButton.utilBackgroundColor = UIColor(red:0.67, green:0.70, blue:0.73, alpha:1.0)
GPButton.charColor = UIColor.black
GPButton.shadowColor = UIColor(red:0.54, green:0.55, blue:0.56, alpha:1.0)
GPButton.layoutColor = UIColor(red:0.84, green:0.84, blue:0.84, alpha:1.0)
}
}
}
| 8fe7225f68f027925b54e73ff737a2a8 | 43.39135 | 197 | 0.546705 | false | false | false | false |
filograno/Moya | refs/heads/master | Demo/Tests/SignalProducer+MoyaSpec.swift | mit | 1 |
import Quick
import Moya
import ReactiveSwift
import Nimble
#if os(iOS) || os(watchOS) || os(tvOS)
private func ImageJPEGRepresentation(_ image: Image, _ compression: CGFloat) -> Data? {
return UIImageJPEGRepresentation(image, compression) as Data?
}
#elseif os(OSX)
private func ImageJPEGRepresentation(_ image: Image, _ compression: CGFloat) -> Data? {
var imageRect: CGRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let imageRep = NSBitmapImageRep(cgImage: image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)!)
return imageRep.representation(using: .JPEG, properties: [:])
}
#endif
// Necessary since Image(named:) doesn't work correctly in the test bundle
private extension ImageType {
class func testPNGImage(named name: String) -> ImageType {
class TestClass { }
let bundle = Bundle(for: type(of: TestClass()))
let path = bundle.path(forResource: name, ofType: "png")
return Image(contentsOfFile: path!)!
}
}
private func signalSendingData(_ data: Data, statusCode: Int = 200) -> SignalProducer<Response, Moya.Error> {
return SignalProducer(value: Response(statusCode: statusCode, data: data as Data, response: nil))
}
class SignalProducerMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filterStatusCodes(range: 0...9).startWithResult { event -> Void in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusCodes().startWithResult { result -> Void in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusCodes().startWithResult({ _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { result -> Void in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult({ _ in
called = true
})
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 304)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult({ _ in
called = true
})
expect(called).to(beTruthy())
}
it("knows how to filter individual status codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 42)
var called = false
signal.filterStatusCode(code: 42).startWithResult({ _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = Data()
let signal = signalSendingData(data, statusCode: 43)
var errored = false
signal.filterStatusCode(code: 42).startWithResult { result -> Void in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testPNGImage(named: "testImage")
let data = ImageJPEGRepresentation(image, 0.75)
let signal = signalSendingData(data!)
var size: CGSize?
signal.mapImage().startWithResult({ _ in
size = image.size
})
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = Data()
let signal = signalSendingData(data)
var receivedError: Moya.Error?
signal.mapImage().startWithResult { result -> Void in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
let expectedError = Moya.Error.imageMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let signal = signalSendingData(data)
var receivedJSON: [String: String]?
signal.mapJSON().startWithResult { result -> Void in
if case .success(let _json) = result,
let json = _json as? [String: String] {
receivedJSON = json
}
}
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
let data = json.data(using: String.Encoding.utf8)
let signal = signalSendingData(data!)
var receivedError: Moya.Error?
signal.mapJSON().startWithResult { result -> Void in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
switch receivedError {
case .some(.jsonMapping):
break
default:
fail("expected NSError with \(NSCocoaErrorDomain) domain")
}
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
let data = string.data(using: String.Encoding.utf8)
let signal = signalSendingData(data!)
var receivedString: String?
signal.mapString().startWithResult({ _ in
receivedString = string
})
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = NSData(bytes: [0x11FFFF] as [UInt32], length: 1) //Byte exceeding UTF8
let signal = signalSendingData(data as Data)
var receivedError: Moya.Error?
signal.mapString().startWithResult { result -> Void in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
let expectedError = Moya.Error.stringMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
}
}
| ad89aa43ac5da5bfe2e9e2c46b0061a8 | 38.791667 | 119 | 0.474631 | false | false | false | false |
SwiftORM/StORM | refs/heads/master | Sources/StORM/StORMtResultSet.swift | apache-2.0 | 2 | //
// StORMResultSet.swift
// StORM
//
// Created by Jonathan Guthrie on 2016-09-23.
//
//
/// Result Set container class.
/// Collects the Restltset, and the cursor data.
/// Datasurce specific properties can also be set, such as those required for MySQL ResultSet parsing.
open class StORMResultSet {
/// A container for the ResultSet Rows.
public var rows: [StORMRow] = [StORMRow]()
/// The ResultSet's cursor.
public var cursorData: StORMCursor = StORMCursor()
/// An array of strings which are the field/column names.
/// Used exclusively for MySQL datasources at this time.
public var fieldNames = [String]() // explicitly for MySQL, but should be adopted globally
/// A [String:String] which are is the field property information.
/// Used exclusively for MySQL datasources at this time.
open var fieldInfo = [String:String]() // explicitly for MySQL, but should be adopted globally
/// The foundSetCount property.
/// Used exclusively for MySQL datasources at this time.
public var foundSetCount = 0 // explicityly for MySQL, but should be adopted globally
/// The inserted ID value.
/// Used exclusively for MySQL datasources at this time.
public var insertedID = 0 // explicityly for MySQL, but should be adopted globally
/// Public initializer.
public init() {}
}
| ea76a94ab441f6b9ddbcb6dcf827a73c | 33.421053 | 102 | 0.727829 | false | false | false | false |
zcrome/taxi-app-client-end-point | refs/heads/master | taxi-app-client-end-point/taxi-app-client-end-point/Model/Client.swift | mit | 1 | //
// Client.swift
// taxi-app-client-end-point
//
// Created by zcrome on 10/16/17.
// Copyright © 2017 zcrome. All rights reserved.
//
import Foundation
import SwiftyJSON
class Client: TypeOfUserProtocol{
var id: String
var name: String
var lastName: String
var phone: String
var email: String
let typeUseIs: TypeOfUser = .client
var isValid: Bool{
if id.isEmpty{
return false
}
return true
}
init(name: String,
lastName: String,
phone: String,
email: String) {
self.name = name
self.lastName = lastName
self.phone = phone
self.email = email
self.id = ""
}
init(TaxiJSON json: JSON) {
if let id = json["userId"].string{
self.id = id
}else{
self.id = ""
}
if let name = json["name"].string{
self.name = name
}else{
self.name = ""
}
if let lastName = json["lastName"].string{
self.lastName = lastName
}else{
self.lastName = ""
}
if let phone = json["phone"].string{
self.phone = phone
}else{
self.phone = ""
}
if let email = json["email"].string{
self.email = email
}else{
self.email = ""
}
}
}
| 3f5f468a6393b684b17042a4a90db998 | 16.054795 | 49 | 0.554217 | false | false | false | false |
toggl/superday | refs/heads/develop | teferi/Interactors/GetActivitiesGroupedByDaysInRange.swift | bsd-3-clause | 1 | import Foundation
import RxSwift
class GetActivitiesGroupedByDaysInRange: Interactor
{
private let repositoryService: RepositoryService
private let timeService: TimeService
private let startDay: Date
private let endDay: Date
init(repositoryService: RepositoryService, timeService: TimeService, startDay: Date, endDay: Date)
{
self.repositoryService = repositoryService
self.timeService = timeService
self.startDay = startDay
self.endDay = endDay
}
func execute() -> Observable<[Date: [Activity]]>
{
return repositoryService.getTimeSlots(fromDate: startDay.ignoreTimeComponents(), toDate: endDay.tomorrow.ignoreTimeComponents())
.map(toDictionary)
}
func toDictionary(timeSlots: [TimeSlotEntity]) -> [Date: [Activity]]
{
return timeSlots
.groupBy({ $0.startTime.ignoreTimeComponents() })
.reduce([Date:[Activity]]()) { dict, timeSlotsForDay in
guard let date = timeSlotsForDay.first?.startTime else { return dict }
var dictCopy = dict
dictCopy[date] = timeSlotsForDay
.groupBy({ $0.category })
.map { timeSlotsGroup in
let totalDuration = timeSlotsGroup.map { [unowned self] timeSlot in
timeSlot.duration ?? self.timeService.now.timeIntervalSince(timeSlot.startTime)
}
.reduce(0, +)
return Activity(category: timeSlotsGroup.first!.category, duration: totalDuration)
}
return dictCopy
}
}
}
| b74d114409d7eb8f7351adbb6c6709c6 | 32.698113 | 136 | 0.572788 | false | false | false | false |
PezHead/tiny-tennis-scoreboard | refs/heads/master | Tiny Tennis/ChampionStore.swift | mit | 1 | //
// ChampionStore.swift
// Tiny Tennis
//
// Created by David Bireta on 10/20/16.
// Copyright © 2016 David Bireta. All rights reserved.
//
import TableTennisAPI
/// Provides access to available `Champion`s.
class ChampionStore {
/// Returns all of the `Champion`s.
/// This will make a API call to fetch champion data. Results will be cached for offline usage.
///
/// - parameter completion: Closure to be called when the final list of champions is compiled.
static func all(_ completion: @escaping ([Champion]) -> Void) {
var championList = [Champion]()
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent("combinedPlayers.json")
if let jsonData = try? Data(contentsOf: path) {
let json = try? JSONSerialization.jsonObject(with: jsonData, options: [])
if let peeps = json as? [Any] {
for case let playerObj as [String: Any] in peeps {
if let champ = Champion(jsonData: playerObj) {
championList.append(champ)
}
}
// FIXME: Not a huge fan of calling the completion twice (once for cache, once for network).
completion(championList)
}
}
}
// Request players from API
API.shared.getPlayers { champions in
champions.forEach { champ in
// Merge updated players with exisitng players
// Simple approach: Just add players that don't already exist
if championList.contains(champ) {
let index = championList.index(of: champ)!
championList.remove(at: index)
}
championList.append(champ)
}
// Send completion result
completion(championList)
// Write updated player list to disk
do {
let jsonFriendlyChamps = championList.map({ (champion) -> [String: Any] in
return champion.dictionaryRep()
})
if JSONSerialization.isValidJSONObject(jsonFriendlyChamps) {
let jsonified = try JSONSerialization.data(withJSONObject: jsonFriendlyChamps, options: .prettyPrinted)
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent("combinedPlayers.json")
do {
try jsonified.write(to: path, options: .atomic)
} catch let error {
print("Error writing player file: \(error)")
}
}
}
} catch let error {
print("Error serializing to json: \(error)")
}
}
}
}
| c379226392cfb7928a290e872d7836ae | 39.139241 | 123 | 0.51561 | false | false | false | false |
adolfrank/Swift_practise | refs/heads/master | 08-day/08-day/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// 08-day
//
// Created by Adolfrank on 3/21/16.
// Copyright © 2016 FrankAdol. All rights reserved.
//
import UIKit
class HomeViewController: UITableViewController {
let cellIdentifer = "NewCellIdentifier"
let favoriteEmoji = ["🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆"]
let newFavoriteEmoji = ["🏃🏃🏃🏃🏃", "💩💩💩💩💩", "👸👸👸👸👸", "🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆" ]
var emojiData = [String]()
// var tableViewController = UITableViewController(style: .Plain)
// var refreshControl = UIRefreshControl()
@IBAction func showNav(sender: AnyObject) {
print("yyy")
}
override func viewDidLoad() {
super.viewDidLoad()
emojiData = favoriteEmoji
let emojiTableView = self.tableView
emojiTableView.backgroundColor = UIColor(red:0.092, green:0.096, blue:0.116, alpha:1)
emojiTableView.dataSource = self
emojiTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifer)
emojiTableView.tableFooterView = UIView(frame: CGRectZero)
emojiTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: "didRoadEmoji", forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl!.backgroundColor = UIColor(red:100/255/0
, green:0.113, blue:0.145, alpha:1)
let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.refreshControl!.attributedTitle = NSAttributedString(string: "Last updated on \(NSDate())", attributes: attributes)
self.refreshControl!.tintColor = UIColor.whiteColor()
// self.title = "emoji"
let titleLabel = UILabel(frame: CGRectMake(0, 0, 0 , 44))
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.text = "下拉刷新"
titleLabel.textColor = UIColor.whiteColor()
self.navigationItem.titleView = titleLabel
self.navigationController?.hidesBarsOnSwipe
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "bg"), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage(named: "bg")
emojiTableView.rowHeight = UITableViewAutomaticDimension
emojiTableView.estimatedRowHeight = 60.0
}
func didRoadEmoji() {
print("ttt")
self.emojiData = newFavoriteEmoji
self.tableView.reloadData()
self.refreshControl!.endRefreshing()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return emojiData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer, forIndexPath: indexPath)
// let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer)! as UITableViewCell
// Configure the cell...
cell.textLabel!.text = self.emojiData[indexPath.row]
cell.textLabel!.textAlignment = NSTextAlignment.Center
cell.textLabel!.font = UIFont.systemFontOfSize(50)
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
| fe7359a0051f867b4380e4d9ff0c13b5 | 37.8125 | 128 | 0.676329 | false | false | false | false |
jhaigler94/cs4720-iOS | refs/heads/master | Pensieve/Pensieve/MemoryViewController.swift | apache-2.0 | 1 | //
// MemoryViewController.swift
// Pensieve
//
// Created by Jennifer Ruth Haigler on 10/26/15.
// Copyright © 2015 University of Virginia. All rights reserved.
//
import UIKit
import CoreData
class MemoryViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var passedMemName: UILabel!
@IBOutlet weak var passedMemDate: UILabel!
@IBOutlet weak var passedMemTime: UILabel!
@IBOutlet weak var MemPointTable: UITableView!
var memName = String()
var memDate = String()
var memTime = String()
var memLoc = String()
var memId = String()
var note = String()
//var picFileLoc = String()
var passName:String!
var passDate:String!
var passTime:String!
var names = [String]()
// MARK: Properties
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
passedMemName.text = passName;
passedMemDate.text = passDate;
passedMemTime.text = passTime;
title = "Pensieve"
/*populateNames()
MemPointTable.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
*/
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
print("VIEWDIDAPPEAR: MEMORYVIEW")
names = []
populateNames()
MemPointTable.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
//MemPointTable.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
NSLog("You selected cell number: \(indexPath.row)!")
let fetchRequest = NSFetchRequest(entityName: "Memory")
/* And execute the fetch request on the context */
do {
let mems = try managedObjectContext.executeFetchRequest(fetchRequest)
for memory in mems{
if((memory.valueForKey("memname")as? String!)==((passedMemName.text)as?String!)){
if((memory.valueForKey("pointid")as? String!)==(names[indexPath.row])){
memName = ((memory.valueForKey("memname")as? String)!)
memDate = ((memory.valueForKey("memdate")as? String)!)
memTime = ((memory.valueForKey("memtime")as? String)!)
memLoc = ((memory.valueForKey("memloc")as? String)!)
memId = ((memory.valueForKey("pointid")as? String)!)
//picFileLoc = ((memory.valueForKey("picfileloc")as? String)!)
note = ((memory.valueForKey("note")as? String)!)
}
}
}
}catch let error as NSError{
print(error)
}
NSLog(memName)
NSLog(memDate)
NSLog(memTime)
self.performSegueWithIdentifier("ToViewMemPt", sender: self)
}
// MARK: Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ToCreateMemPtSeg") {
var cMemVC = segue.destinationViewController as! CreateMemPtViewController;
cMemVC.passFromMemName = passedMemName.text
}
else if (segue.identifier == "ToViewMemPt") {
var memVC = segue.destinationViewController as! ViewMemPt;
memVC.passedName = memName
memVC.passedDate = memDate
memVC.passedTime = memTime
memVC.passedLoc = memLoc
memVC.passedId = memId
memVC.passedNote = note
//memVC.passedFileLoc = picFileLoc
}
}
@IBAction func unwindToMemView(unwindSegue: UIStoryboardSegue) {
if let memViewController = unwindSegue.sourceViewController as? CreateMemPtViewController {
print("Coming from CreateMemPtViewController")
}
}
func populateNames(){
/* Create the fetch request first */
let fetchRequest = NSFetchRequest(entityName: "Memory")
/* And execute the fetch request on the context */
do {
let mems = try managedObjectContext.executeFetchRequest(fetchRequest)
for memory in mems{
if(!((memory.valueForKey("memloc")as? String!)==("MainNotPoint"))){
if((memory.valueForKey("memname")as? String!)==(passName)){
names.append(((memory.valueForKey("pointid")as? String)!))
}
}
}
}catch let error as NSError{
print(error)
}
}
func tableView(MemPointTable: UITableView,
numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(MemPointTable: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell =
MemPointTable.dequeueReusableCellWithIdentifier("Cell")
cell!.textLabel!.text = names[indexPath.row]
return cell!
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| b54fae6aa9381c2665e2c602d20819b8 | 31.747253 | 112 | 0.580034 | false | false | false | false |
caamorales/JTSplashView | refs/heads/master | JTSplashView/JTSplashView.swift | mit | 3 | //
// JTSplashView.swift
// JTSplashView Example
//
// Created by Jakub Truhlar on 25.07.15.
// Copyright (c) 2015 Jakub Truhlar. All rights reserved.
//
import UIKit
class JTSplashView: UIView {
// MARK: Properties
static let sharedInstance = JTSplashView()
static let screenSize = UIScreen.mainScreen().bounds.size
let duration = 0.3
let borderWidth : CGFloat = 10.0
var bgColor = UIColor(red: 45.0 / 255.0, green: 61.0 / 255.0, blue: 81.0 / 255.0, alpha: 1.0)
var circleColor = UIColor(red: 110.0 / 255.0, green: 180.0 / 255.0, blue: 240.0 / 255.0, alpha: 1.0)
var vibrateAgain = true
var completionBlock:(() -> Void)?
var circlePathInitial = UIBezierPath(ovalInRect: CGRect(x: screenSize.width / 2, y: screenSize.height / 2, width: 0.0, height: 0.0))
var circlePathFinal = UIBezierPath(ovalInRect: CGRect(x: (screenSize.width / 2) - 35.0, y: (screenSize.height / 2) - 35.0, width: 70.0, height: 70.0))
var circlePathShrinked = UIBezierPath(ovalInRect: CGRect(x: screenSize.width / 2 - 5.0, y: screenSize.height / 2 - 5.0, width: 10.0, height: 10.0))
var circlePathSqueezeVertical = UIBezierPath(ovalInRect: CGRect(x: (screenSize.width / 2) - 34.0, y: (screenSize.height / 2) - 36.0, width: 68.0, height: 72.0))
var circlePathSqueezeHorizontal = UIBezierPath(ovalInRect: CGRect(x: (screenSize.width / 2) - 36.0, y: (screenSize.height / 2) - 34.0, width: 72.0, height: 68.0))
var baseCircleLayer = CAShapeLayer()
var bgWithMask = UIView()
var bgWithoutMask = UIView()
// MARK: Initializers
init() {
super.init(frame:CGRectZero)
self.alpha = 0.0
UIApplication.sharedApplication().delegate?.window??.makeKeyAndVisible()
}
override init(frame: CGRect) {
super.init(frame: frame)
doInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
doInit()
}
func doInit() {
// 1x with mask and above 1x without mask BG
bgWithMask = createBackgroundWithMask(createMaskCircleLayer())
bgWithoutMask = createBackgroundWithMask(nil)
addSubview(bgWithMask)
addSubview(bgWithoutMask)
createBaseCircle()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("addToWindow"), name: UIWindowDidBecomeVisibleNotification, object: nil)
}
/**
Class function to create the splash view.
This function takes three optional arguments and generate splash view above everything in keyWindow. StatusBar is hidden during the process, so you should make it visible in finish function block.
:param: backgroundColor Background color of the splash view. Default is asphalt color.
:param: circleColor Color of the animated circle. Default is blue color.
:param: circleSize Size of the animated circle. 10pt border will be added, but the size remains the same. Width should be same as height. Default is CGSize(70, 70).
*/
class func splashViewWithBackgroundColor(backgroundColor: UIColor?, circleColor: UIColor?, circleSize: CGSize?) {
if isVisible() {
return
}
UIApplication.sharedApplication().statusBarHidden = true
sharedInstance.alpha = 1.0
// Redefine properties
if (backgroundColor != nil) {
sharedInstance.bgColor = backgroundColor!
}
if (circleColor != nil) {
sharedInstance.circleColor = circleColor!
}
if (circleSize != nil) {
var sizeWithoutBorder = CGSizeMake(circleSize!.width - sharedInstance.borderWidth, circleSize!.height - sharedInstance.borderWidth)
sharedInstance.circlePathFinal = UIBezierPath(ovalInRect: CGRect(x: (JTSplashView.screenSize.width / 2) - (sizeWithoutBorder.width / 2), y: (JTSplashView.screenSize.height / 2) - (sizeWithoutBorder.height / 2), width: sizeWithoutBorder.width, height: sizeWithoutBorder.height))
sharedInstance.circlePathSqueezeVertical = UIBezierPath(ovalInRect: CGRect(x: (JTSplashView.screenSize.width / 2) - ((sizeWithoutBorder.width / 2) * 0.96), y: (JTSplashView.screenSize.height / 2) - ((sizeWithoutBorder.height / 2) * 1.04), width: sizeWithoutBorder.width * 0.96, height: sizeWithoutBorder.height * 1.04))
sharedInstance.circlePathSqueezeHorizontal = UIBezierPath(ovalInRect: CGRect(x: (JTSplashView.screenSize.width / 2) - ((sizeWithoutBorder.width / 2) * 1.04), y: (JTSplashView.screenSize.height / 2) - ((sizeWithoutBorder.height / 2) * 0.96), width: sizeWithoutBorder.width * 1.04, height: sizeWithoutBorder.height * 0.96))
}
sharedInstance.doInit()
}
// MARK: Public functions
/**
Class function to hide the splash view.
This function hide the splash view. Should be called in the right time after the app is ready.
*/
class func finish() {
finishWithCompletion(nil)
}
/**
Class function to hide the splash view with completion handler.
This function hide the splash view and call the completion block afterward. Should be called in the right time after the app is ready.
:param: completion The completion block
*/
class func finishWithCompletion(completion: (() -> Void)?) {
if !isVisible() {
return
}
if (completion != nil) {
sharedInstance.completionBlock = completion
}
sharedInstance.vibrateAgain = false;
}
/**
Class function obtains the splashView visibility state.
This function will tell you if the splashView is visible or not.
:returns: Bool Tells us if is the splashView visible.
*/
class func isVisible() -> Bool {
return (sharedInstance.alpha != 0.0)
}
// MARK: Private functions
@objc private func addToWindow() {
UIApplication.sharedApplication().keyWindow?.addSubview(JTSplashView.sharedInstance)
}
private func finalAnimation() {
zoomOut()
}
private func createMaskCircleLayer() -> CAShapeLayer {
var circleLayer = CAShapeLayer()
var maskPath = CGPathCreateMutable()
CGPathAddPath(maskPath, nil, circlePathShrinked.CGPath)
CGPathAddRect(maskPath, nil, CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
circleLayer.path = maskPath
circleLayer.fillRule = kCAFillRuleEvenOdd
circleLayer.fillColor = circleColor.CGColor
return circleLayer
}
private func createBaseCircle() {
baseCircleLayer.path = circlePathInitial.CGPath
baseCircleLayer.fillRule = kCAFillRuleEvenOdd
baseCircleLayer.fillColor = UIColor.clearColor().CGColor
baseCircleLayer.strokeColor = circleColor.CGColor
baseCircleLayer.lineWidth = borderWidth
enlarge()
NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("vibration"), userInfo: nil, repeats: false)
layer.addSublayer(baseCircleLayer)
}
private func createBackgroundWithMask(mask: CAShapeLayer?) -> UIView {
var backgroundView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
backgroundView.backgroundColor = bgColor
backgroundView.userInteractionEnabled = false
if (mask != nil) {
backgroundView.layer.mask = createMaskCircleLayer()
}
return backgroundView
}
// Animations
@objc private func zoomIn() {
UIView.animateWithDuration(NSTimeInterval(self.duration * 0.5), delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
// The rest of the transformation will not be visible due completion block alpha = 0 part. But it will look like it just continued faster
var cornerCorrection : CGFloat = 1.25
var multiplier = (JTSplashView.screenSize.height / self.borderWidth) * cornerCorrection
self.bgWithMask.transform = CGAffineTransformMakeScale(multiplier, multiplier)
self.bgWithMask.center = CGPointMake(JTSplashView.screenSize.width / 2, JTSplashView.screenSize.height / 2)
}) { (Bool) -> Void in
// Run optional block if exists
if (self.completionBlock != nil) {
self.completionBlock!()
}
self.alpha = 0.0
self.bgWithMask.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.bgWithMask.center = CGPointMake(JTSplashView.screenSize.width / 2, JTSplashView.screenSize.height / 2)
}
}
private func zoomOut() {
// Shrink
var shrinkAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
shrinkAnimation.fromValue = circlePathFinal.CGPath
shrinkAnimation.toValue = circlePathShrinked.CGPath
shrinkAnimation.duration = duration;
shrinkAnimation.fillMode = kCAFillModeForwards
shrinkAnimation.removedOnCompletion = false
shrinkAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
baseCircleLayer.addAnimation(shrinkAnimation, forKey: nil)
NSTimer.scheduledTimerWithTimeInterval(shrinkAnimation.duration, target: self, selector: Selector("fadeOut"), userInfo: nil, repeats: false)
NSTimer.scheduledTimerWithTimeInterval(shrinkAnimation.duration, target: self, selector: Selector("zoomIn"), userInfo: nil, repeats: false)
}
private func enlarge() {
var enlargeAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
enlargeAnimation.fromValue = circlePathInitial.CGPath
enlargeAnimation.toValue = circlePathFinal.CGPath
enlargeAnimation.duration = duration;
enlargeAnimation.fillMode = kCAFillModeForwards
enlargeAnimation.removedOnCompletion = false
baseCircleLayer.addAnimation(enlargeAnimation, forKey: nil)
}
@objc private func vibration() {
var vibration1: CABasicAnimation = CABasicAnimation(keyPath: "path")
vibration1.fromValue = circlePathFinal.CGPath
vibration1.toValue = circlePathSqueezeVertical.CGPath
vibration1.beginTime = 0.0
vibration1.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
vibration1.duration = duration
var vibration2: CABasicAnimation = CABasicAnimation(keyPath: "path")
vibration2.fromValue = circlePathSqueezeVertical.CGPath
vibration2.toValue = circlePathSqueezeHorizontal.CGPath
vibration2.beginTime = duration
vibration2.duration = duration
vibration2.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
var vibration3: CABasicAnimation = CABasicAnimation(keyPath: "path")
vibration3.fromValue = circlePathSqueezeHorizontal.CGPath
vibration3.toValue = circlePathSqueezeVertical.CGPath
vibration3.beginTime = duration * 2
vibration3.duration = duration
vibration3.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
var vibration4: CABasicAnimation = CABasicAnimation(keyPath: "path")
vibration4.fromValue = circlePathSqueezeVertical.CGPath
vibration4.toValue = circlePathFinal.CGPath
vibration4.beginTime = duration * 3
vibration4.duration = duration
vibration4.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
var vibrations: CAAnimationGroup = CAAnimationGroup()
vibrations.animations = [vibration1, vibration2, vibration3, vibration4]
vibrations.duration = duration * 4
vibrations.repeatCount = 1
baseCircleLayer.addAnimation(vibrations, forKey: nil)
// Vibrate one more time or trigger final animation
if vibrateAgain {
NSTimer.scheduledTimerWithTimeInterval(duration * 4, target: self, selector: Selector("vibration"), userInfo: nil, repeats: false)
} else {
finalAnimation()
}
}
@objc private func fadeOut() {
self.bgWithoutMask.alpha = 0.0
self.baseCircleLayer.opacity = 0.0
}
} | 4b089cb4c284a284eb7799b8ce361b5b | 43.307692 | 333 | 0.668061 | false | false | false | false |
apple/swift-tools-support-core | refs/heads/main | Sources/TSCUtility/Platform.swift | apache-2.0 | 1 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import TSCBasic
import Foundation
/// Recognized Platform types.
public enum Platform: Equatable {
case android
case darwin
case linux(LinuxFlavor)
case windows
/// Recognized flavors of linux.
public enum LinuxFlavor: Equatable {
case debian
case fedora
}
/// Lazily checked current platform.
public static var currentPlatform = Platform.findCurrentPlatform(localFileSystem)
/// Returns the cache directories used in Darwin.
private static var darwinCacheDirectoriesLock = NSLock()
private static var _darwinCacheDirectories: [AbsolutePath]? = .none
/// Attempt to match `uname` with recognized platforms.
internal static func findCurrentPlatform(_ fileSystem: FileSystem) -> Platform? {
#if os(Windows)
return .windows
#else
guard let uname = try? Process.checkNonZeroExit(args: "uname").spm_chomp().lowercased() else { return nil }
switch uname {
case "darwin":
return .darwin
case "linux":
return Platform.findCurrentPlatformLinux(fileSystem)
default:
return nil
}
#endif
}
internal static func findCurrentPlatformLinux(_ fileSystem: FileSystem) -> Platform? {
do {
if try fileSystem.isFile(AbsolutePath(validating: "/etc/debian_version")) {
return .linux(.debian)
}
if try fileSystem.isFile(AbsolutePath(validating: "/system/bin/toolbox")) ||
fileSystem.isFile(AbsolutePath(validating: "/system/bin/toybox")) {
return .android
}
if try fileSystem.isFile(AbsolutePath(validating: "/etc/redhat-release")) ||
fileSystem.isFile(AbsolutePath(validating: "/etc/centos-release")) ||
fileSystem.isFile(AbsolutePath(validating: "/etc/fedora-release")) ||
Platform.isAmazonLinux2(fileSystem) {
return .linux(.fedora)
}
} catch {}
return nil
}
private static func isAmazonLinux2(_ fileSystem: FileSystem) -> Bool {
do {
let release = try fileSystem.readFileContents(AbsolutePath(validating: "/etc/system-release")).cString
return release.hasPrefix("Amazon Linux release 2")
} catch {
return false
}
}
/// Returns the cache directories used in Darwin.
public static func darwinCacheDirectories() throws -> [AbsolutePath] {
try Self.darwinCacheDirectoriesLock.withLock {
if let darwinCacheDirectories = Self._darwinCacheDirectories {
return darwinCacheDirectories
}
var directories = [AbsolutePath]()
// Compute the directories.
try directories.append(AbsolutePath(validating: "/private/var/tmp"))
(try? TSCBasic.determineTempDirectory()).map{ directories.append($0) }
#if canImport(Darwin)
getConfstr(_CS_DARWIN_USER_TEMP_DIR).map({ directories.append($0) })
getConfstr(_CS_DARWIN_USER_CACHE_DIR).map({ directories.append($0) })
#endif
Self._darwinCacheDirectories = directories
return directories
}
}
#if canImport(Darwin)
/// Returns the value of given path variable using `getconf` utility.
///
/// - Note: This method returns `nil` if the value is an invalid path.
private static func getConfstr(_ name: Int32) -> AbsolutePath? {
let len = confstr(name, nil, 0)
let tmp = UnsafeMutableBufferPointer(start: UnsafeMutablePointer<Int8>.allocate(capacity: len), count:len)
defer { tmp.deallocate() }
guard confstr(name, tmp.baseAddress, len) == len else { return nil }
let value = String(cString: tmp.baseAddress!)
guard value.hasSuffix(AbsolutePath.root.pathString) else { return nil }
return try? resolveSymlinks(AbsolutePath(validating: value))
}
#endif
}
| 5699103acc8aa2aa137e0f29c38d212b | 37.087719 | 115 | 0.637494 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/WordPressTest/BlogTests.swift | gpl-2.0 | 1 | import CoreData
import XCTest
@testable import WordPress
final class BlogTests: XCTestCase {
private var context: NSManagedObjectContext!
override func setUp() {
super.setUp()
context = TestContextManager().mainContext
}
override func tearDown() {
super.tearDown()
}
// MARK: - Atomic Tests
func testIsAtomic() {
let blog = BlogBuilder(context)
.with(atomic: true)
.build()
XCTAssertTrue(blog.isAtomic())
}
func testIsNotAtomic() {
let blog = BlogBuilder(context)
.with(atomic: false)
.build()
XCTAssertFalse(blog.isAtomic())
}
// MARK: - Blog Lookup
func testThatLookupByBlogIDWorks() throws {
let blog = BlogBuilder(context).build()
XCTAssertNotNil(blog.dotComID)
XCTAssertNotNil(Blog.lookup(withID: blog.dotComID!, in: context))
}
func testThatLookupByBlogIDFailsForInvalidBlogID() throws {
XCTAssertNil(Blog.lookup(withID: NSNumber(integerLiteral: 1), in: context))
}
func testThatLookupByBlogIDWorksForIntegerBlogID() throws {
let blog = BlogBuilder(context).build()
XCTAssertNotNil(blog.dotComID)
XCTAssertNotNil(try Blog.lookup(withID: blog.dotComID!.intValue, in: context))
}
func testThatLookupByBlogIDFailsForInvalidIntegerBlogID() throws {
XCTAssertNil(try Blog.lookup(withID: 1, in: context))
}
func testThatLookupBlogIDWorksForInt64BlogID() throws {
let blog = BlogBuilder(context).build()
XCTAssertNotNil(blog.dotComID)
XCTAssertNotNil(try Blog.lookup(withID: blog.dotComID!.int64Value, in: context))
}
func testThatLookupByBlogIDFailsForInvalidInt64BlogID() throws {
XCTAssertNil(try Blog.lookup(withID: Int64(1), in: context))
}
// MARK: - Plugin Management
func testThatPluginManagementIsDisabledForSimpleSites() {
let blog = BlogBuilder(context)
.with(atomic: true)
.build()
XCTAssertFalse(blog.supports(.pluginManagement))
}
func testThatPluginManagementIsEnabledForBusinessPlans() {
let blog = BlogBuilder(context)
.with(isHostedAtWPCom: true)
.with(planID: 1008) // Business plan
.with(isAdmin: true)
.build()
XCTAssertTrue(blog.supports(.pluginManagement))
}
func testThatPluginManagementIsDisabledForPrivateSites() {
let blog = BlogBuilder(context)
.with(isHostedAtWPCom: true)
.with(planID: 1008) // Business plan
.with(isAdmin: true)
.with(siteVisibility: .private)
.build()
XCTAssertTrue(blog.supports(.pluginManagement))
}
func testThatPluginManagementIsEnabledForJetpack() {
let blog = BlogBuilder(context)
.withAnAccount()
.withJetpack(version: "5.6", username: "test_user", email: "user@example.com")
.with(isHostedAtWPCom: false)
.with(isAdmin: true)
.build()
XCTAssertTrue(blog.supports(.pluginManagement))
}
func testThatPluginManagementIsDisabledForWordPress54AndBelow() {
let blog = BlogBuilder(context)
.with(wordPressVersion: "5.4")
.with(username: "test_username")
.with(password: "test_password")
.with(isAdmin: true)
.build()
XCTAssertFalse(blog.supports(.pluginManagement))
}
func testThatPluginManagementIsEnabledForWordPress55AndAbove() {
let blog = BlogBuilder(context)
.with(wordPressVersion: "5.5")
.with(username: "test_username")
.with(password: "test_password")
.with(isAdmin: true)
.build()
XCTAssertTrue(blog.supports(.pluginManagement))
}
func testThatPluginManagementIsDisabledForNonAdmins() {
let blog = BlogBuilder(context)
.with(wordPressVersion: "5.5")
.with(username: "test_username")
.with(password: "test_password")
.with(isAdmin: false)
.build()
XCTAssertFalse(blog.supports(.pluginManagement))
}
func testStatsActiveForSitesHostedAtWPCom() {
let blog = BlogBuilder(context)
.isHostedAtWPcom()
.with(modules: [""])
.build()
XCTAssertTrue(blog.isStatsActive())
}
func testStatsActiveForSitesNotHotedAtWPCom() {
let blog = BlogBuilder(context)
.isNotHostedAtWPcom()
.with(modules: ["stats"])
.build()
XCTAssertTrue(blog.isStatsActive())
}
func testStatsNotActiveForSitesNotHotedAtWPCom() {
let blog = BlogBuilder(context)
.isNotHostedAtWPcom()
.with(modules: [""])
.build()
XCTAssertFalse(blog.isStatsActive())
}
// MARK: - Blog.version string conversion testing
func testTheVersionIsAStringWhenGivenANumber() {
let blog = BlogBuilder(context)
.set(blogOption: "software_version", value: 13.37)
.build()
XCTAssertTrue((blog.version as Any) is String)
XCTAssertEqual(blog.version, "13.37")
}
func testTheVersionIsAStringWhenGivenAString() {
let blog = BlogBuilder(context)
.set(blogOption: "software_version", value: "5.5")
.build()
XCTAssertTrue((blog.version as Any) is String)
XCTAssertEqual(blog.version, "5.5")
}
func testTheVersionDefaultsToAnEmptyStringWhenTheValueIsNotConvertible() {
let blog = BlogBuilder(context)
.set(blogOption: "software_version", value: NSObject())
.build()
XCTAssertTrue((blog.version as Any) is String)
XCTAssertEqual(blog.version, "")
}
}
| 36b914203789c07ebbf8b5b16348aef3 | 29.05641 | 90 | 0.620031 | false | true | false | false |
laurentVeliscek/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Effects/Delay/Simple Delay/AKDelayPresets.swift | mit | 2 | //
// AKDelayPresets.swift
// AudioKit
//
// Created by Nicholas Arner, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
/// Preset for the AKDelay
public extension AKDelay {
/// Short Delay
public func presetShortDelay() {
time = 0.125
feedback = 0.204
lowPassCutoff = 5077.644
dryWetMix = 0.100
}
/// Long, dense delay
public func presetDenseLongDelay() {
time = 0.795
feedback = 0.900
lowPassCutoff = 5453.823
dryWetMix = 0.924
}
/// Electrical Circuits, Robotic Delay Effect
public func presetElectricCircuitsDelay() {
time = 0.025
feedback = 0.797
lowPassCutoff = 13960.832
dryWetMix = 0.747
}
/// Print out current values in case you want to save it as a preset
public func printCurrentValuesAsPreset() {
print("public func presetSomeNewDelay() {")
print(" time = \(String(format: "%0.3f", time))")
print(" feedback = \(String(format: "%0.3f", feedback))")
print(" lowPassCutoff = \(String(format: "%0.3f", lowPassCutoff))")
print(" dryWetMix = \(String(format: "%0.3f", dryWetMix))")
print("}\n")
}
} | 912431999375c3307e81a7b892065683 | 25.895833 | 78 | 0.584496 | false | false | false | false |
USAssignmentWarehouse/EnglishNow | refs/heads/master | EnglishNow/Controller/Auth/SignUpVC.swift | apache-2.0 | 1 | //
// SignUpVC.swift
// EnglishNow
//
// Created by Nha T.Tran on 5/20/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
class SignUpVC: UIViewController {
// MARK: -declare
@IBAction func btnDismiss(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBOutlet weak var registerView: UIView!
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var txtConfirmPassword: UITextField!
@IBOutlet var txtUsername: UITextField!
@IBOutlet var txtError: UILabel!
@IBOutlet var btnSignUp: UIButton!
@IBAction func btnSignUp(_ sender: Any) {
ProgressHUD.show(view: view)
if txtPassword.text != txtConfirmPassword.text{
txtError.text = WSString.passwordNotMatch
ProgressHUD.hide(view: self.view)
}
else{
if let email = txtEmail.text, let password = txtPassword.text {
FirebaseClient.shared.signUp(email: email, password: password, userName: txtUsername.text!, skills: skills, completion: {(user, error) in
if let firebaseError = error{
MessageBox.warning(body: firebaseError.localizedDescription)
ProgressHUD.hide(view: self.view)
return
}
if let user = user {
ProgressHUD.hide(view: self.view)
MessageBox.show(body: "Sign Up successfully!")
self.dismiss(animated: true, completion: nil)
}
})
}
else {
self.txtError.text = WSString.invalidEmailPassword
ProgressHUD.hide(view: self.view)
}
}
}
var skills: [Skill] = [Skill]()
override func viewDidLoad() {
super.viewDidLoad()
skills.append(Listening())
skills.append(Speaking())
skills.append(Pronunciation())
initShow()
// Do any additional setup after loading the view.
}
// MARK: -init to show
func initShow(){
registerView.layer.cornerRadius = 5
txtEmail.layer.cornerRadius = 5
txtEmail.layer.borderWidth = 1
txtEmail.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
txtPassword.layer.cornerRadius = 5
txtPassword.layer.borderWidth = 1
txtPassword.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
txtPassword.isSecureTextEntry = true
txtUsername.layer.cornerRadius = 5
txtUsername.layer.borderWidth = 1
txtUsername.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
txtConfirmPassword.layer.cornerRadius = 5
txtConfirmPassword.layer.borderWidth = 1
txtConfirmPassword.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
txtConfirmPassword.isSecureTextEntry = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//disappear keyboard when click on anywhere in screen
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
| b2680cdae7f83b524a526c4434a9234c | 30.535088 | 153 | 0.600556 | false | false | false | false |
xmartlabs/XLMediaZoom | refs/heads/master | Sources/MediaZoom.swift | mit | 1 | //
// MediaZoom.swift
// MediaZoom (https://github.com/xmartlabs/XLMediaZoom)
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.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
public class MediaZoom: UIView, UIScrollViewDelegate {
public lazy var imageView: UIImageView = {
let image = UIImageView(frame: self.mediaFrame())
image.clipsToBounds = true
image.autoresizingMask = [.flexibleWidth, .flexibleHeight]
image.contentMode = .scaleAspectFill
return image
}()
public var maxAlpha: CGFloat = 1
public var hideHandler: (() -> ())?
public var useBlurEffect = false
public var animationTime: Double
public var originalImageView: UIImageView
public var backgroundView: UIView
public lazy var contentView: UIScrollView = {
let contentView = UIScrollView(frame: MediaZoom.currentFrame())
contentView.contentSize = self.mediaFrame().size
contentView.backgroundColor = .clear
contentView.maximumZoomScale = 1.5
return contentView
}()
public init(with image: UIImageView, animationTime: Double, useBlur: Bool = false) {
let frame = MediaZoom.currentFrame()
self.animationTime = animationTime
useBlurEffect = useBlur
originalImageView = image
backgroundView = MediaZoom.backgroundView(with: frame, useBlur: useBlur)
super.init(frame: frame)
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceOrientationDidChange(notification:)),
name: .UIDeviceOrientationDidChange,
object: nil
)
imageView.image = image.image
addGestureRecognizer(
UITapGestureRecognizer(
target: self,
action: #selector(handleSingleTap(sender:))
)
)
contentView.addSubview(imageView)
contentView.delegate = self
addSubview(backgroundView)
addSubview(contentView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func show(onHide callback: (() -> ())? = nil) {
let frame = MediaZoom.currentFrame()
self.frame = frame
backgroundView.frame = frame
imageView.frame = mediaFrame()
hideHandler = callback
UIView.animate(
withDuration: animationTime,
animations: { [weak self] in
guard let `self` = self else { return }
self.imageView.frame = self.imageFrame()
self.backgroundView.alpha = self.maxAlpha
},
completion: { [weak self] finished in
if finished {
self?.showAnimationDidFinish()
}
}
)
}
private static func backgroundView(with frame: CGRect, useBlur: Bool) -> UIView {
if useBlur {
let blurView = UIVisualEffectView(frame: frame)
blurView.effect = UIBlurEffect(style: .dark)
blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
blurView.alpha = 0
return blurView
} else {
let bgView = UIView(frame: frame)
bgView.backgroundColor = .black
bgView.alpha = 0
return bgView
}
}
private static func currentFrame() -> CGRect {
let screenSize = UIScreen.main.bounds
return CGRect(
x: CGFloat(0),
y: CGFloat(0),
width: screenSize.width,
height: screenSize.height
)
}
private func imageFrame() -> CGRect {
let size = bounds
guard let imageSize = imageView.image?.size else { return CGRect.zero }
let ratio = min(size.height / imageSize.height, size.width / imageSize.width)
let imageWidth = imageSize.width * ratio
let imageHeight = imageSize.height * ratio
let imageX = (frame.size.width - imageWidth) * 0.5
let imageY = (frame.size.height - imageHeight) * 0.5
return CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
}
private func mediaFrame() -> CGRect {
return originalImageView.frame
}
func deviceOrientationDidChange(notification: NSNotification) {
let orientation = UIDevice.current.orientation
switch orientation {
case .landscapeLeft, .landscapeRight, .portrait:
let newFrame = MediaZoom.currentFrame()
frame = newFrame
backgroundView.frame = newFrame
imageView.frame = imageFrame()
default:
break
}
}
public func handleSingleTap(sender: UITapGestureRecognizer) {
willHandleSingleTap()
UIView.animate(
withDuration: animationTime,
animations: { [weak self] in
guard let `self` = self else { return }
self.contentView.zoomScale = 1
self.imageView.frame = self.mediaFrame()
self.backgroundView.alpha = 0
},
completion: { [weak self] finished in
if finished {
self?.removeFromSuperview()
self?.contentView.zoomScale = 1
self?.hideHandler?()
}
}
)
}
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
let yOffset = (scrollView.frame.height - imageView.frame.height) / 2.0
let xOffset = (scrollView.frame.width - imageView.frame.width) / 2.0
let x = xOffset > 0 ? xOffset : scrollView.frame.origin.x
let y = yOffset > 0 ? yOffset : scrollView.frame.origin.y
UIView.animate(withDuration: 0.3) { [weak self] in
self?.imageView.frame.origin = CGPoint(x: x, y: y)
}
return imageView
}
open func willHandleSingleTap() {
}
open func showAnimationDidFinish() {
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| caf18462c42b7896622a7a425c43d1a3 | 34.77 | 88 | 0.619793 | false | false | false | false |
renzifeng/ZFZhiHuDaily | refs/heads/master | ZFZhiHuDaily/NewsComments/Model/ZFComments.swift | apache-2.0 | 1 | //
// ZFComments.swift
//
// Created by 任子丰 on 16/1/30
// Copyright (c) 任子丰. All rights reserved.
//
import Foundation
import SwiftyJSON
public class ZFComments: NSObject {
// MARK: Declaration for string constants to be used to decode and also serialize.
internal let kZFCommentsAuthorKey: String = "author"
internal let kZFCommentsContentKey: String = "content"
internal let kZFCommentsInternalIdentifierKey: String = "id"
internal let kZFCommentsAvatarKey: String = "avatar"
internal let kZFCommentsLikesKey: String = "likes"
internal let kZFCommentsTimeKey: String = "time"
// MARK: Properties
public var author: String?
public var content: String?
public var internalIdentifier: Int?
public var avatar: String?
public var likes: Int?
public var time: Int?
// MARK: SwiftyJSON Initalizers
/**
Initates the class based on the object
- parameter object: The object of either Dictionary or Array kind that was passed.
- returns: An initalized instance of the class.
*/
convenience public init(object: AnyObject) {
self.init(json: JSON(object))
}
/**
Initates the class based on the JSON that was passed.
- parameter json: JSON object from SwiftyJSON.
- returns: An initalized instance of the class.
*/
public init(json: JSON) {
author = json[kZFCommentsAuthorKey].string
content = json[kZFCommentsContentKey].string
internalIdentifier = json[kZFCommentsInternalIdentifierKey].int
avatar = json[kZFCommentsAvatarKey].string
likes = json[kZFCommentsLikesKey].int
time = json[kZFCommentsTimeKey].int
}
/**
Generates description of the object in the form of a NSDictionary.
- returns: A Key value pair containing all valid values in the object.
*/
public func dictionaryRepresentation() -> [String : AnyObject ] {
var dictionary: [String : AnyObject ] = [ : ]
if author != nil {
dictionary.updateValue(author!, forKey: kZFCommentsAuthorKey)
}
if content != nil {
dictionary.updateValue(content!, forKey: kZFCommentsContentKey)
}
if internalIdentifier != nil {
dictionary.updateValue(internalIdentifier!, forKey: kZFCommentsInternalIdentifierKey)
}
if avatar != nil {
dictionary.updateValue(avatar!, forKey: kZFCommentsAvatarKey)
}
if likes != nil {
dictionary.updateValue(likes!, forKey: kZFCommentsLikesKey)
}
if time != nil {
dictionary.updateValue(time!, forKey: kZFCommentsTimeKey)
}
return dictionary
}
}
| 7135497116a160925ca7c1d19e815fee | 28.139535 | 88 | 0.714286 | false | false | false | false |
Frainbow/ShaRead.frb-swift | refs/heads/master | ShaRead/ShaRead/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ShaRead
//
// Created by martin on 2016/4/13.
// Copyright © 2016年 Frainbow. All rights reserved.
//
import UIKit
import CoreData
import Firebase
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.fbTokenChangeNoti(_:)), name: FBSDKAccessTokenDidChangeNotification, object: nil)
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
FIRApp.configure()
return true
}
func fbTokenChangeNoti(noti: NSNotification) {
}
func toggleUserMode() {
toggleRootView("Main", controllerIdentifier: "MainController")
}
func toggleAdminMode() {
toggleRootView("StoreAdmin", controllerIdentifier: "StoreAdminMainController")
}
func toggleRootView(storyboardName: String, controllerIdentifier: String) {
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let rootController = storyboard.instantiateViewControllerWithIdentifier(controllerIdentifier)
self.window!.rootViewController = rootController
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "tw.frb.ShaRead" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("ShaRead", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| f391fa58a8c6e379852a914205c02188 | 50.811189 | 291 | 0.722905 | false | false | false | false |
FredericJacobs/AsyncMessagesViewController | refs/heads/master | Source/Views/MessageCellNode.swift | mit | 1 | //
// MessageCellNode.swift
// AsyncMessagesViewController
//
// Created by Huy Nguyen on 12/02/15.
// Copyright (c) 2015 Huy Nguyen. All rights reserved.
//
import Foundation
let kAMMessageCellNodeTopTextAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(),
NSFontAttributeName: UIFont.boldSystemFontOfSize(12)]
let kAMMessageCellNodeContentTopTextAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(),
NSFontAttributeName: UIFont.systemFontOfSize(12)]
let kAMMessageCellNodeBottomTextAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(),
NSFontAttributeName: UIFont.systemFontOfSize(11)]
private let kContentHorizontalInset: CGFloat = 4
private let kContentVerticalInset: CGFloat = 1
class MessageCellNode: ASCellNode {
private let isOutgoing: Bool
private let topTextNode: ASTextNode?
private let contentTopTextNode: ASTextNode?
private let bottomTextNode: ASTextNode?
private let contentNode: MessageContentNode
private var contentTopTextNodeXOffset: CGFloat {
return contentNode.avatarImageSize > 0 ? 56 : 11
}
init(isOutgoing: Bool, topText: NSAttributedString?, contentTopText: NSAttributedString?, bottomText: NSAttributedString?, senderAvatarURL: NSURL?, senderAvatarImageSize: CGFloat, bubbleNode: ASDisplayNode) {
self.isOutgoing = isOutgoing
topTextNode = topText != nil ? ASTextNode() : nil
topTextNode?.layerBacked = true
topTextNode?.attributedString = topText
contentTopTextNode = contentTopText != nil ? ASTextNode() : nil
contentTopTextNode?.layerBacked = true
contentTopTextNode?.attributedString = contentTopText
contentNode = MessageContentNode(isOutgoing: isOutgoing, avatarURL: senderAvatarURL,
avatarImageSize: senderAvatarImageSize, bubbleNode: bubbleNode)
bottomTextNode = bottomText != nil ? ASTextNode() : nil
bottomTextNode?.layerBacked = true
bottomTextNode?.attributedString = bottomText
super.init()
if let node = topTextNode { addSubnode(node) }
if let node = contentTopTextNode { addSubnode(node) }
addSubnode(contentNode)
if let node = bottomTextNode { addSubnode(node) }
selectionStyle = .None
}
override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
let pairs: [(ASDisplayNode?, CGFloat)] = [(topTextNode, 0), (contentTopTextNode, contentTopTextNodeXOffset), (contentNode, 0), (bottomTextNode, 0)]
var requiredHeight: CGFloat = 0
for (optionalNode, xOffset) in pairs {
if let node = optionalNode {
let measuredSize = node.measure(CGSizeMake(constrainedSize.width - xOffset - 2 * kContentHorizontalInset, constrainedSize.height))
requiredHeight += measuredSize.height
}
}
return CGSizeMake(constrainedSize.width, requiredHeight + 2 * kContentVerticalInset)
}
override func layout() {
let topTextNodeXOffset = (self.calculatedSize.width - (topTextNode?.calculatedSize.width ?? 0)) / 2 - kContentHorizontalInset // topTextNode is center-aligned
let pairs: [(ASDisplayNode?, CGFloat)] = [(topTextNode, topTextNodeXOffset), (contentTopTextNode, contentTopTextNodeXOffset), (contentNode, 0), (bottomTextNode, 0)]
var y: CGFloat = kContentVerticalInset
for (optionalNode, xOffset) in pairs {
if let node = optionalNode {
var x = kContentHorizontalInset + xOffset
if isOutgoing {
x = self.calculatedSize.width - node.calculatedSize.width - x // Right-aligned
}
node.frame = CGRectMake(x, y, node.calculatedSize.width, node.calculatedSize.height)
y = node.frame.maxY
}
}
}
} | 4d3cdef00f3c69513549b58d828f5d90 | 42.94382 | 212 | 0.693095 | false | false | false | false |
csound/csound | refs/heads/develop | iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/HarmonizerTestViewController.swift | lgpl-2.1 | 3 | /*
HarmonizerTestViewController.swift
Nikhil Singh, Dr. Richard Boulanger
Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini
This file is part of Csound iOS SwiftExamples.
The Csound for iOS Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
import UIKit
class HarmonizerTestViewController: BaseCsoundViewController {
@IBOutlet var mHarmPitchSlider: UISlider!
@IBOutlet var mGainSlider: UISlider!
@IBOutlet var mSwitch: UISwitch!
override func viewDidLoad() {
title = "12. Mic: Harmonizer"
super.viewDidLoad()
}
@IBAction func toggleOnOff(_ sender: UISwitch) {
if sender.isOn {
let tempFile = Bundle.main.path(forResource: "harmonizer", ofType: "csd")
csound.stop()
csound = CsoundObj()
csound.useAudioInput = true
csound.add(self)
let csoundUI = CsoundUI(csoundObj: csound)
csoundUI?.add(mHarmPitchSlider, forChannelName: "slider")
csoundUI?.add(mGainSlider, forChannelName: "gain")
csound.play(tempFile)
} else {
csound.stop()
}
}
@IBAction func showInfo(_ sender: UIButton) {
infoVC.preferredContentSize = CGSize(width: 300, height: 120)
infoText = "This examples uses Csound's streaming phase vocoder to create a harmonizer effect. A dry/wet balance control is provided."
displayInfo(sender)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension HarmonizerTestViewController: CsoundObjListener {
func csoundObjCompleted(_ csoundObj: CsoundObj!) {
DispatchQueue.main.async { [unowned self] in
self.mSwitch.isOn = false
}
}
}
| f8d740f1716ec7a9ce259e1dfd9d2572 | 31.922078 | 142 | 0.675345 | false | false | false | false |
alobanov/Dribbble | refs/heads/master | Dribbble/services/NetworkService.swift | mit | 1 | //
// BaseNetworkService.swift
// Dribbble
//
// Created by Lobanov Aleksey on 17.02.17.
// Copyright © 2017 Lobanov Aleksey. All rights reserved.
//
import Foundation
import RxSwift
struct NetworkError {
let type: NetworkReqestType
let error: NSError
static func unknown() -> NetworkError {
return NetworkError(type: .unknown, error: AppError.dummyError.error)
}
}
struct NetworkState {
let type: NetworkReqestType
let state: LoadingState
static func unknown() -> NetworkState {
return NetworkState(type: .unknown, state: .unknown)
}
}
protocol NetworkServiceStateble {
var networkError: Observable<NetworkError> {get}
var commonNetworkState: Observable<NetworkState> {get}
}
class NetworkService {
let bag = DisposeBag()
var networkError: Observable<NetworkError> {
return _networkError.asObservable().skip(1)
}
var commonNetworkState: Observable<NetworkState> {
return _commonNetworkState.asObservable()
}
// Dependencies
var api: Networking!
private var requestInProcess = false
internal var _networkError = Variable<NetworkError>(NetworkError.unknown())
internal var _commonNetworkState = Variable<NetworkState>(NetworkState.unknown())
init(api: Networking) {
self.api = api
}
func isRequestInProcess(networkReqestType: NetworkReqestType = .unknown) -> Bool {
guard _commonNetworkState.value.state != .loading else { return true }
_commonNetworkState.value = NetworkState(type: networkReqestType, state: .loading)
return false
}
func handleResponse<E>(_ response: Observable<E>, networkReqestType: NetworkReqestType) -> Observable<E> {
return response.map {[weak self] event -> E in
self?._commonNetworkState.value = NetworkState(type: networkReqestType, state: .normal)
return event
}.do(onError: {[weak self] err in
self?.throwError(type: networkReqestType, error: err as NSError)
})
}
func throwError(type: NetworkReqestType, error: NSError) {
self._networkError.value = NetworkError(type: type, error: error)
self._commonNetworkState.value = NetworkState(type: type, state: .error)
}
}
| a435b9f6db0ac6967b31fdd025bdb05e | 27.526316 | 108 | 0.717251 | false | false | false | false |
SimpleApp/evc-swift | refs/heads/master | EVC/EVC/Engine/core/EVCEngine.swift | mit | 1 | //
// EVCEngine.swift
// EVC
//
// Created by Benjamin Garrigues on 04/09/2017.
import Foundation
class EVCEngine {
//MARK: - Context
fileprivate (set) var context: EVCEngineContext
//MARK: - Capabilities
//Replace and add your own capabilities
fileprivate let dataStore : FileDataStore
fileprivate let restAPI : SampleJSONRestAPI
//MARK: - Middlewares
//Add your own middleware here
//MARK: - Services
//Service are the only properties visible from the GUI Layer.
//Replace and add your own services
let sampleService: SampleService
//type of allComponents is array of nullable because a common scenario
//is to disable components when using the engine in an extension.
fileprivate var allComponents : [EVCEngineComponent?] {
return [
//Capabilities
dataStore,
restAPI,
//Middleware
//Service
sampleService]
}
//MARK: - Initialization
//init may become a big function if your engine has a lot of components.
//This function however should have very little logic beyond creating and injecting components
init(initialContext : EVCEngineContext,
//Mock injection for unit-testing purpose
mockedDatastore: FileDataStore? = nil,
mockedRestAPI : SampleJSONRestAPI? = nil,
mockedService : SampleService? = nil
) {
//Capabilities
dataStore = try! mockedDatastore ?? FileDataStore()
restAPI = try! mockedRestAPI ?? SampleJSONRestAPI(environment: initialContext.environment)
//Middlewares
//Services
if let mockedService = mockedService {
sampleService = mockedService
} else {
sampleService = SampleService(dataStore: dataStore,
restAPI: restAPI)
}
//Context
context = initialContext
propagateContext()
}
//MARK: - Internal flow
fileprivate func propagateContext() {
for o in allComponents { o?.onEngineContextUpdate(context: context) }
}
//MARK: - Public interface
//MARK: Application State
//Note : application state may not be available on all platforms (such as extensions)
//so we don't directly use UIApplication inside the engine, but let the outside provide us with the information
public func onApplicationDidEnterBackground() {
context.applicationForeground = false
propagateContext()
}
public func onApplicationDidBecomeActive() {
context.applicationForeground = true
propagateContext()
}
}
| 48e66eacad7c04e614a4528ddb94d5d2 | 29.079545 | 115 | 0.653948 | false | false | false | false |
nubbel/Cococapods-Xcode7GenericArchive | refs/heads/master | FluxKit/Dispatcher.swift | mit | 2 | //
// Dispatcher.swift
// FluxKit
//
// Created by Dominique d'Argent on 16/05/15.
// Copyright (c) 2015 Dominique d'Argent. All rights reserved.
//
import Foundation
public class Dispatcher<Action : ActionType> {
public typealias Token = String
public typealias Callback = Action -> Void
private var tokenGenerator : TokenStream.Generator
private var isDispatching : Bool = false
private var pendingAction : Action?
private var callbacks : [Token: Callback] = [:]
private var dispatchTokens : Set<Token> { return Set(callbacks.keys) }
private var pendingDispatchTokens : Set<Token> = []
private var handledDispatchTokens : Set<Token> = []
public init() {
tokenGenerator = TokenStream(prefix: "ID_").generate()
}
public func register(callback: Callback) -> Token {
if let token = tokenGenerator.next() {
callbacks[token] = callback
return token
}
preconditionFailure("FluxKit.Dispatcher: Failed to generate new dispatch token.")
}
public func unregister(dispatchToken: Token) {
precondition(isRegistered(dispatchToken), "FluxKit.Dispatcher: Unknown dispatch token \(dispatchToken).")
callbacks.removeValueForKey(dispatchToken)
}
public func dispatch(action: Action) {
precondition(!isDispatching, "FluxKit.Dispatcher: Cannot dispatch while dispatching.")
beginDispatching(action)
for dispatchToken in dispatchTokens {
if isPending(dispatchToken) {
continue
}
invokeCallback(dispatchToken)
}
endDispatching()
}
public func waitFor(dispatchTokens: Token...) {
waitFor(dispatchTokens)
}
public func waitFor(dispatchTokens: [Token]) {
for dispatchToken in dispatchTokens {
if isPending(dispatchToken) {
precondition(isHandled(dispatchToken), "FluxKit.Dispatcher: Circular dependency detected while waiting for \(dispatchToken).")
continue
}
invokeCallback(dispatchToken)
}
}
}
private extension Dispatcher {
func beginDispatching(action: Action) {
isDispatching = true
pendingAction = action
pendingDispatchTokens = []
handledDispatchTokens = []
}
func endDispatching() {
isDispatching = false
pendingAction = nil
}
func invokeCallback(dispatchToken: Token) {
precondition(isDispatching, "FluxKit.Dispatcher: Not dispatching.")
precondition(pendingAction != nil, "FluxKit.Dispatcher: Action missing.")
precondition(isRegistered(dispatchToken), "FluxKit.Dispatcher: Unknown dispatch token \(dispatchToken).")
if let action = pendingAction, callback = callbacks[dispatchToken] {
pendingDispatchTokens.insert(dispatchToken)
callback(action)
handledDispatchTokens.insert(dispatchToken)
}
}
func isRegistered(dispatchToken: Token) -> Bool {
return callbacks[dispatchToken] != nil
}
func isPending(dispatchToken: Token) -> Bool {
return pendingDispatchTokens.contains(dispatchToken)
}
func isHandled(dispatchToken: Token) -> Bool {
return handledDispatchTokens.contains(dispatchToken)
}
}
| c864e70e1c7f275cc0963bebce27d0a4 | 28.779661 | 142 | 0.623791 | false | false | false | false |
nyalix/shiro-obi-app | refs/heads/master | Todoapp3/EditViewController.swift | mit | 1 | //
// TodoItemViewController.swift
// Todoapp
//
// Created by Katsuya yamamoto on 2015/12/13.
// Copyright (c) 2015年 nyalix. All rights reserved.
//
import UIKit
class EditViewController: UIViewController {
var task: Todo? = nil
@IBOutlet weak var todoField: UITextView!
@IBAction func cancel(sender: UIBarButtonItem) {
navigationController!.popViewControllerAnimated(true)
}
@IBAction func save(sender: UIBarButtonItem) {
//
// let newTask: Todo = Todo.MR_createEntity() as Todo
// newTask.item = makeTodo.text
// newTask.managedObjectContext!.MR_saveToPersistentStoreAndWait()
// //self.dismissViewControllerAnimated(true, completion: nil)
// navigationController!.popViewControllerAnimated(true)
// }
// @IBAction func clickSave(sender: UIBarButtonItem) {
if task != nil {
editTask()
} else {
createTask()
}
navigationController!.popViewControllerAnimated(true)
}
func createTask() {
let newTask: Todo = Todo.MR_createEntity() as Todo
newTask.item = todoField.text
_ = NSDate()
let dateFormatter = NSDateFormatter() // フォーマットの取得
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") // JPロケール
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm" // フォーマットの指定
newTask.date = dateFormatter.stringFromDate(NSDate()) // 現在日時
newTask.managedObjectContext!.MR_saveToPersistentStoreAndWait()
}
func editTask() {
task?.item = todoField.text
task?.managedObjectContext!.MR_saveToPersistentStoreAndWait()
}
override func viewDidLoad() {
super.viewDidLoad()
if let taskTodo = task {
todoField.text = taskTodo.item
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 5c6b217cbe69a135e395e2c1e6b28e4e | 30.487805 | 106 | 0.605345 | false | false | false | false |
adauguet/ClusterMapView | refs/heads/master | Example/Example/ViewController.swift | mit | 1 | //
// ViewController.swift
// ClusterMapViewDemo
//
// Created by Antoine DAUGUET on 02/05/2017.
//
//
import UIKit
import MapKit
import ClusterMapView
class ViewController: UIViewController {
@IBOutlet weak var mapView: ClusterMapView!
override func viewDidLoad() {
super.viewDidLoad()
// let path = Bundle.main.path(forResource: "Toilets", ofType: "json")!
// let url = URL(fileURLWithPath: path)
// let data = try! Data(contentsOf: url)
// let json = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String : Any]]
// let toilets = Toilet.foo(json: json)
// mapView.delegate = mapView
// mapView.setAnnotations(toilets)
let path = Bundle.main.path(forResource: "Streetlights", ofType: "json")!
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
let json = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String : Any]]
let streetlights = Streetlight.foo(json: json)
mapView.delegate = self
mapView.setAnnotations(streetlights)
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if let mapView = mapView as? ClusterMapView {
mapView.updateNodes(animated: animated)
}
}
func mapViewDidFinishClustering(_ mapView: ClusterMapView) {
print(#function)
}
func mapViewDidFinishAnimating(_ mapView: ClusterMapView) {
print(#function)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let node = annotation as? Node {
var pin: MKPinAnnotationView!
if let dequeued = mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView {
pin = dequeued
pin.annotation = node
} else {
pin = MKPinAnnotationView(annotation: node, reuseIdentifier: "pin")
}
switch node.type {
case .leaf:
pin.pinTintColor = .green
case .node:
pin.pinTintColor = .blue
case .root:
pin.pinTintColor = .red
}
return pin
}
return nil
}
}
| b3cdf113889df439d8d0f31a6c7b8d3b | 32.459459 | 124 | 0.592892 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwallet/src/Views/TransactionCells/TxAmountCell.swift | mit | 1 | //
// TxAmountCell.swift
// breadwallet
//
// Created by Ehsan Rezaie on 2017-12-21.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class TxAmountCell: UITableViewCell, Subscriber {
// MARK: - Vars
private let container = UIView()
private lazy var tokenAmountLabel: UILabel = {
let label = UILabel(font: UIFont.customBody(size: 26.0))
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
return label
}()
private lazy var fiatAmountLabel: UILabel = {
let label = UILabel(font: UIFont.customBody(size: 14.0))
label.textAlignment = .center
return label
}()
private let separator = UIView(color: .clear)
// MARK: - Init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
private func setupViews() {
addSubviews()
addConstraints()
}
private func addSubviews() {
contentView.addSubview(container)
contentView.addSubview(separator)
container.addSubview(fiatAmountLabel)
container.addSubview(tokenAmountLabel)
}
private func addConstraints() {
container.constrain(toSuperviewEdges: UIEdgeInsets(top: C.padding[1],
left: C.padding[2],
bottom: -C.padding[2],
right: -C.padding[2]))
tokenAmountLabel.constrain([
tokenAmountLabel.constraint(.top, toView: container),
tokenAmountLabel.constraint(.leading, toView: container),
tokenAmountLabel.constraint(.trailing, toView: container)
])
fiatAmountLabel.constrain([
fiatAmountLabel.constraint(toBottom: tokenAmountLabel, constant: 0),
fiatAmountLabel.constraint(.leading, toView: container),
fiatAmountLabel.constraint(.trailing, toView: container),
fiatAmountLabel.constraint(.bottom, toView: container)
])
separator.constrainBottomCorners(height: 0.5)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func set(viewModel: TxDetailViewModel) {
let largeFont = UIFont.customBody(size: 26.0)
let smallFont = UIFont.customBody(size: 14.0)
let fiatColor = UIColor.mediumGray
let textColor = UIColor.lightGray
let tokenColor: UIColor = (viewModel.direction == .received) ? .receivedGreen : .darkGray
let amountText = NSMutableAttributedString(string: viewModel.amount,
attributes: [.font: largeFont,
.foregroundColor: tokenColor])
tokenAmountLabel.attributedText = amountText
// fiat amount label
let currentAmount = viewModel.fiatAmount
let originalAmount = viewModel.originalFiatAmount
if viewModel.status != .complete || originalAmount == nil {
fiatAmountLabel.attributedText = NSAttributedString(string: currentAmount,
attributes: [.font: smallFont,
.foregroundColor: fiatColor])
} else {
let format = (viewModel.direction == .sent) ? S.TransactionDetails.amountWhenSent : S.TransactionDetails.amountWhenReceived
let attributedText = NSMutableAttributedString(string: String(format: format, originalAmount!, currentAmount),
attributes: [.font: smallFont,
.foregroundColor: textColor])
attributedText.set(attributes: [.foregroundColor: fiatColor], forText: currentAmount)
attributedText.set(attributes: [.foregroundColor: fiatColor], forText: originalAmount!)
fiatAmountLabel.attributedText = attributedText
}
}
}
| 7a359e5be58bf2d9e57e32ecc0693b00 | 39.305556 | 135 | 0.572479 | false | false | false | false |
mleiv/IBStyler | refs/heads/master | IBStylerDemo/IBStylerDemo/IBStyles/IBGradient.swift | mit | 2 | //
// IBGradient.swift
//
// Created by Emily Ivie on 9/17/16.
//
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import UIKit
/// Just a helpful way to define background gradients.
/// See CAGradientLayer for more information on the properties used here.
///
/// - direction: .Vertical or .Horizontal
/// - colors
/// - locations
/// - createGradientView()
public struct IBGradient {
/// Quick enum to more clearly define IBGradient direction (Vertical or Horizontal).
public enum Direction {
case vertical, horizontal
}
public var direction: Direction = .vertical
public var colors: [UIColor] = []
public var locations: [Double] = []
init(direction: Direction, colors: [UIColor]) {
self.direction = direction
self.colors = colors
}
/// Generates a IBGradientView from the gradient values provided.
///
/// - parameter bounds: The size to use in creating the gradient view.
/// - returns: a UIView with a gradient background layer
public func createGradientView(_ bounds: CGRect) -> (IBGradientView) {
let gradientView = IBGradientView(frame: bounds)
gradientView.setLayerColors(colors)
if !locations.isEmpty {
gradientView.setLayerLocations(locations)
} else {
gradientView.setLayerEndPoint(direction == .vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0))
}
return gradientView
}
}
//MARK: IBGradientView
/// Allows for an auto-resizable CAGradientLayer (like, say, during device orientation changes).
///
/// IBStyles IBStylePropertyName.BackgroundGradient uses this.
final public class IBGradientView: UIView {
/// Built-in UIView function that responds to .layer requests.
/// Changes the .layer property of the view to be CAGradientLayer. But we still have to change all interactions with .layer to recognize this new type, hence the other functions.
///
/// returns: CAGradientLayer .layer reference
override public class var layerClass : (AnyClass) {
return CAGradientLayer.self
}
/// Sets the colors of the gradient. Can be more than two.
///
/// parameter colors: a list of UIColor elements.
public func setLayerColors(_ colors: [UIColor]) {
let layer = self.layer as? CAGradientLayer
layer?.colors = colors.map({ $0.cgColor })
}
/// Sets the locations of the gradient. See CAGradientLayer documentation for how this work, because I only used endPoint myself.
/// parameter locations: a list of Double location positions.
public func setLayerLocations(_ locations: [Double]) {
let layer = self.layer as? CAGradientLayer
layer?.locations = locations.map({ NSNumber(value: $0 as Double) })
}
/// Sets the start point of the gradient (this is the simplest way to define a gradient: setting the start or end point)
///
/// parameter startPoint: a CGPoint using 0.0 - 1.0 values
public func setLayerStartPoint(_ startPoint: CGPoint) {
let layer = self.layer as? CAGradientLayer
layer?.startPoint = startPoint
}
/// Sets the end point of the gradient (this is the simplest way to define a gradient: setting the start or end point)
///
/// parameter endPoint: a CGPoint using 0.0 - 1.0 values
public func setLayerEndPoint(_ endPoint: CGPoint) {
let layer = self.layer as? CAGradientLayer
layer?.endPoint = endPoint
}
}
| 1ab812e7dd821d8f3398c5ccc5ca8d09 | 39.808989 | 182 | 0.677863 | false | false | false | false |
SSU-CS-Department/ssumobile-ios | refs/heads/master | SSUMobile/Modules/Email/Views/SSUEmailPickerViewController.swift | apache-2.0 | 1 | //
// SSUEmailPickerViewController.swift
// SSUMobile
//
// Created by Eric Amorde on 7/26/15.
// Copyright (c) 2015 Sonoma State University Department of Computer Science. All rights reserved.
//
import UIKit
class SSUEmailPickerViewController: UITableViewController {
struct Segue {
static let google = "gdocs"
static let exchange = "exchange"
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SSUEmailViewController {
if segue.identifier == Segue.exchange {
destination.mode = .email
} else if segue.identifier == Segue.google {
destination.mode = .googleDocs
}
}
}
}
| ae2ced8f62c5590c32866d879fc9d04a | 26.068966 | 99 | 0.634395 | false | false | false | false |
mcjcloud/Show-And-Sell | refs/heads/master | Show And Sell/LoginViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Show And Sell
//
// Created by Brayden Cloud on 9/5/16.
// Copyright © 2016 Brayden Cloud. All rights reserved.
//
// UIViewController implementation to show a Login screen for accessing the server
//
import UIKit
import Google
import GoogleSignIn
protocol LoginViewControllerDelegate {
func login(didPressCreateButton createButton: UIButton)
}
class LoginViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate, UIGestureRecognizerDelegate {
// GUI properties
@IBOutlet var emailField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var messageLabel: UILabel!
@IBOutlet var loginButton: UIButton!
@IBOutlet var googleButton: GIDSignInButton!
@IBOutlet var createAccountButton: UIButton!
// delegate for switching between login and create
var delegate: LoginViewControllerDelegate?
var user: User!
var autoLogin: Bool = true
var loggingIn: Bool = false
var loadOverlay = OverlayView(type: .loading, text: nil)
override func viewDidLoad() {
super.viewDidLoad()
print("Login view did load")
// setup text fields
setupTextField(emailField, placeholder: "Email")
setupTextField(passwordField, placeholder: "Password")
// make textfields dismiss when uiview tapped
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
self.view.addGestureRecognizer(gestureRecognizer)
gestureRecognizer.cancelsTouchesInView = false // allow subviews to receive clicks.
// assign textField methods
emailField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
passwordField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
// configure google delegate
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
//assert(configureError == nil, "Error configuring Google services: \(configureError)")
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
// set gray color for disabled button
loginButton.setTitleColor(UIColor.gray, for: .disabled)
createAccountButton.setTitleColor(UIColor.gray, for: .disabled)
// adjust google button
googleButton.colorScheme = .dark
googleButton.addTarget(self, action: #selector(googleSignIn), for: .touchUpInside)
// Do any additional setup after loading the view, typically from a nib.
AppDelegate.loginVC = self // pass a reference to the AppDelegate
messageLabel.text = ""
// enable/disable login button
loginButton.isEnabled = shouldEnableLogin()
// auto login
if let email = AppData.save.email, let pword = AppData.save.password {
emailField.text = email
passwordField.text = HttpRequestManager.decrypt(pword)
if autoLogin {
logIn(loginButton)
}
}
}
override func viewWillAppear(_ animated: Bool) {
// enable/disable login button
loginButton.isEnabled = shouldEnableLogin()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Transition
@IBAction func unwindToLogin(segue: UIStoryboardSegue) {
print("unwind to login")
// save data from session
AppData.saveData()
// clear tab bar data
AppDelegate.tabVC?.clearTabData()
// clear fields
emailField.text = ""
passwordField.text = ""
messageLabel.text = ""
logout()
loginButton.isEnabled = true
createAccountButton.isEnabled = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// do nothing
}
// IBOutlet functions
@IBAction func logIn(_ sender: UIButton) {
// clear error message
messageLabel.text = ""
loggingIn = true
loadOverlay.showOverlay(view: self.view, position: .center)
// GET user data.
if let email = emailField.text, let password = passwordField.text {
let securePassword = HttpRequestManager.encrypt(password)
// disable login button and create account button (until login attempt is complete)
loginButton.isEnabled = false
createAccountButton.isEnabled = false
HttpRequestManager.user(withEmail: email, andPassword: securePassword) { user, response, error in
self.postLogin(user: user, response: response, error: error)
}
}
else {
messageLabel.text = "Please make sure all fields are filled."
}
}
@IBAction func createAccount(_ sender: UIButton) {
delegate?.login(didPressCreateButton: sender)
}
// MARK: Google Auth
func application(application: UIApplication, openURL url: URL, options: [String: Any]) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication.rawValue] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation.rawValue])
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if (error == nil) {
// Perform any operations on signed in user here.
let userId = user.userID // For client-side use only!
let email = user.profile.email
let name = user.profile.name?.components(separatedBy: " ")
let firstName = name?[0]
let lastName = name?[1]
// do sign in for google account
print("userId: \(userId)")
print("\(email) signed in")
print("name: \(name)")
if let email = email, let userId = userId, let firstName = firstName, let lastName = lastName {
loadOverlay.showOverlay(view: UIApplication.shared.keyWindow!, position: .center)
HttpRequestManager.googleUser(email: email, userId: HttpRequestManager.encrypt(userId), firstName: firstName, lastName: lastName) { user, response, error in
print("calling postlogin from google sign in")
// finish login
AppData.save.isGoogleSigned = true
AppData.saveData()
self.postLogin(user: user, response: response, error: error)
}
}
}
else {
print("signin error: \(error.localizedDescription)")
}
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
// disconnect
print("google disconnect")
}
func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {
// stop loading icon
print("stop loading")
loadOverlay.hideOverlayView()
}
func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
// present a sign in vc
print("should present VC")
self.present(viewController, animated: true, completion: nil)
}
func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) {
// dismiss the sign in vc
print("should dismissVC")
self.dismiss(animated: true, completion: nil)
}
// MARK: Helper
func textChanged(_ textField: UITextField) {
loginButton.isEnabled = shouldEnableLogin()
}
// dismiss a keyboard
func dismissKeyboard() {
emailField.resignFirstResponder()
passwordField.resignFirstResponder()
self.view.endEditing(true)
}
// MARK: Gesture Recognizer
// fix for google button not working - google button wouldn't get tap because the GestureRecognizer added to its superview got it.
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view is GIDSignInButton {
return false
}
else {
return true
}
}
// setup the custom TextField
func setupTextField(_ textfield: UITextField, placeholder: String) {
// edit password field
let width = CGFloat(1.5)
let border = CALayer()
border.borderColor = UIColor(colorLiteralRed: 0.298, green: 0.686, blue: 0.322, alpha: 1.0).cgColor // Green
border.frame = CGRect(x: 0, y: textfield.frame.size.height - width, width: textfield.frame.size.width, height: textfield.frame.size.height)
border.borderWidth = width
textfield.layer.addSublayer(border)
textfield.layer.masksToBounds = true
textfield.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
textfield.attributedPlaceholder = NSAttributedString(string: placeholder,
attributes: [NSForegroundColorAttributeName: UIColor.white])
}
// check if the login button should be enabled.
func shouldEnableLogin() -> Bool {
return (emailField.text?.characters.count ?? 0) > 0 && (passwordField.text?.characters.count ?? 0) > 0 && !loggingIn
}
func postLogin(user: User?, response: URLResponse?, error: Error?) {
print("postlogin response: \((response as? HTTPURLResponse)?.statusCode)")
// stop any loading
DispatchQueue.main.async {
self.loadOverlay.hideOverlayView()
self.loggingIn = false
}
// check error
if let e = error {
print("error logging in: \(e)")
// switch buttons and change message label in main thread
DispatchQueue.main.async {
self.messageLabel.text = "Error logging in."
self.loginButton.isEnabled = true
self.createAccountButton.isEnabled = true
}
}
else if let u = user {
print("user recieved: \(u.email)")
self.user = u
self.autoLogin = true
// if the signed in user is not the same as the saved user, reasign the "save user"
AppData.user = u
AppData.save.email = u.email
AppData.save.password = u.password
AppData.saveData()
// go to tabs segue from main thread
DispatchQueue.main.async(execute: {
print("Logging in, groupId: \(u.groupId)")
print("segue to tabs")
self.performSegue(withIdentifier: "loginToTabs", sender: self)
})
// save data
AppData.saveData()
}
else {
DispatchQueue.main.async {
if let status = (response as? HTTPURLResponse)?.statusCode {
// check error
switch(status) {
case 409:
self.messageLabel.text = "Account with gmail address already exists."
GIDSignIn.sharedInstance().signOut()
case 401:
self.messageLabel.text = "Incorrect username or password."
default:
self.messageLabel.text = "Error getting user."
}
}
else {
// generic error message
self.messageLabel.text = "Error getting user."
}
// re-enable buttons
self.loginButton.isEnabled = true
self.createAccountButton.isEnabled = true
}
}
}
// when the google button is clicked
func googleSignIn() {
// clear message label
messageLabel.text = ""
print("google button clicked")
loadOverlay.showOverlay(view: UIApplication.shared.keyWindow!, position: .center)
}
// log the user out
func logout() {
// clear non-persistant data.
AppData.myGroup = nil
AppData.user = nil
AppData.group = nil
AppData.bookmarks = nil
AppData.save.isGoogleSigned = false
AppData.saveData()
// logout google user
GIDSignIn.sharedInstance().signOut()
}
}
| 2350be98536b7d0abf2a336c31fa2b20 | 37.050595 | 224 | 0.597028 | false | false | false | false |
josve05a/wikipedia-ios | refs/heads/develop | Wikipedia/Code/DescriptionWelcomeImageViewController.swift | mit | 4 | class DescriptionWelcomeImageViewController: UIViewController {
var pageType:DescriptionWelcomePageType = .intro
private lazy var imageForWelcomePageType: UIImage? = {
switch pageType {
case .intro:
return UIImage(named: "description-cat")
case .exploration:
return UIImage(named: "description-planet")
}
}()
private var image: UIImage? {
return imageForWelcomePageType
}
override func viewDidLoad() {
super.viewDidLoad()
guard let image = image else {
return
}
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
view.wmf_addSubviewWithConstraintsToEdges(imageView)
}
}
| 4c32a7fb19b6f77ae1dd788f125135c4 | 28.230769 | 63 | 0.634211 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/CryptoAssets/Sources/StellarKit/Foundation/AccountResponse+Convenience.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import PlatformKit
import stellarsdk
// MARK: StellarSDK Convenience
extension AccountResponse {
var totalBalance: CryptoValue {
let value = balances
.lazy
.filter { $0.whichAssetType == .native }
.map(\.balance)
.compactMap { Decimal(string: $0) }
.reduce(0, +)
return CryptoValue.create(major: value, currency: .stellar)
}
func toAssetAccountDetails(minimumBalance: CryptoValue) -> StellarAccountDetails {
let account = StellarAssetAccount(
accountAddress: accountId,
name: CryptoCurrency.stellar.defaultWalletName,
description: CryptoCurrency.stellar.defaultWalletName,
sequence: Int(sequenceNumber),
subentryCount: subentryCount
)
var actionableBalance: CryptoValue = .zero(currency: .stellar)
if let balanceMinusReserve = try? totalBalance - minimumBalance, balanceMinusReserve.isPositive {
actionableBalance = balanceMinusReserve
}
return StellarAccountDetails(
account: account,
balance: totalBalance,
actionableBalance: actionableBalance
)
}
}
extension AccountBalanceResponse {
fileprivate enum WhichAssetType: String, Codable {
case native
case credit_alphanum4
case credit_alphanum12
}
fileprivate var whichAssetType: WhichAssetType? {
WhichAssetType(rawValue: assetType)
}
}
| 9d7f93aca3cddb592c2a84865618daf1 | 29.346154 | 105 | 0.651458 | false | false | false | false |
jngd/advanced-ios10-training | refs/heads/master | T2E02/T2E02/CustomSegue.swift | apache-2.0 | 1 | //
// CustomSegue.swift
// T2E02
//
// Created by jngd on 23/01/2017.
// Copyright © 2017 jngd. All rights reserved.
//
import UIKit
class CustomSegue: UIStoryboardSegue {
override func perform() {
let source : UIViewController = self.source as UIViewController
let destination : UIViewController = self.destination as
UIViewController
UIGraphicsBeginImageContext(source.view.bounds.size)
source.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let sourceImage : UIImage =
UIGraphicsGetImageFromCurrentImageContext()!
destination.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let destinationImage : UIImage =
UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let sourceImageView : UIImageView = UIImageView (image: sourceImage)
let destinationImageView : UIImageView = UIImageView (image: destinationImage)
source.view.addSubview(sourceImageView)
source.view.addSubview(destinationImageView)
destinationImageView.transform = CGAffineTransform(translationX: destinationImageView.frame.size.width, y: 0)
UIView.animate(withDuration: 1.0, animations: { () in
sourceImageView.transform = CGAffineTransform(translationX: -sourceImageView.frame.size.width, y: 0)
destinationImageView.transform = CGAffineTransform(translationX: 0, y: 0)
}, completion: { (finished) in
source.present(destination, animated: false, completion: {() -> Void in
sourceImageView.removeFromSuperview()
destinationImageView.removeFromSuperview()
})
})
}
}
| 7f767f2ad4121ff68ddb5e5748254f72 | 35.47619 | 111 | 0.772846 | false | false | false | false |
Moonsownner/DearFace | refs/heads/master | DearFace/Pods/SwiftIconFont/SwiftIconFont/Classes/FontLoader.swift | mit | 2 | //
// FontLoader.swift
// SwiftIconFont
//
// Created by Sedat Ciftci on 18/03/16.
// Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved.
//
import UIKit
import CoreText
class FontLoader: NSObject {
class func loadFont(_ fontName: String) {
let bundle = Bundle(for: FontLoader.self)
var fontURL = URL(string: "")
for filePath : String in bundle.paths(forResourcesOfType: "ttf", inDirectory: nil) {
let filename = NSURL(fileURLWithPath: filePath).lastPathComponent!
if filename.lowercased().range(of: fontName.lowercased()) != nil {
fontURL = NSURL(fileURLWithPath: filePath) as URL
}
}
do
{
let data = try Data(contentsOf: fontURL!)
let provider = CGDataProvider(data: data as CFData)
let font = CGFont.init(provider!)
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(font, &error) {
let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue())
let nsError = error!.takeUnretainedValue() as AnyObject as! NSError
NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
}
} catch {
}
}
}
| c98f071739200d7690e30781d1aafc25 | 32.790698 | 168 | 0.599449 | false | false | false | false |
superpeteblaze/BikeyProvider | refs/heads/master | Code/Location/LocationProvider.swift | mit | 1 | //
// Created by Pete Smith
// http://www.petethedeveloper.com
//
//
// License
// Copyright © 2016-present Pete Smith
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import CoreLocation
/**
### LocationProviderDelegate
Location Provider delegate protocol
*/
public protocol LocationProviderDelegate {
func retrieved(_ location: CLLocation)
func accessDenied()
#if os(iOS)
@available(iOS 9, *)
func retrieved(_ heading: CLHeading)
#endif
func locationAccess(_ isGranted: Bool)
}
/**
Empty extension to make some delegate methods optional
*/
public extension LocationProviderDelegate {
#if os(iOS)
func retrieved(_ heading: CLHeading) {}
#endif
func locationAccess(_ isGranted: Bool){}
}
/**
### LocationProvider
Provides location services such as current location, currect heading
Messages are sent to the specified delegate
*/
final public class LocationProvider: NSObject, CLLocationManagerDelegate {
// Singleton
public static let sharedInstance = LocationProvider()
// MARK: - Public properties
public var delegate: LocationProviderDelegate?
var requiredAccuracy: CLLocationAccuracy = 70
public var needsToRequestAccess: Bool {
return CLLocationManager.authorizationStatus() == .notDetermined
}
// MARK: - Private properties
fileprivate var locman = CLLocationManager()
fileprivate var startTime: Date!
fileprivate var trying = false
fileprivate var updatingHeading = false
// MARK: - Initialization
fileprivate override init() {
super.init()
locman.delegate = self
locman.desiredAccuracy = kCLLocationAccuracyBest
#if os(iOS)
locman.activityType = .fitness
locman.pausesLocationUpdatesAutomatically = true
#endif
}
// MARK: - Public Methods
/**
Request location access authorization
*/
public func requestAlwaysAuthorization() {
#if os(iOS)
locman.requestAlwaysAuthorization()
#endif
}
/**
Request location access authorization
*/
public func requestWhenInUseAuthorization() {
#if os(iOS)
locman.requestWhenInUseAuthorization()
#endif
}
/**
Get the current location
Location is passed back to caller using the delegate
*/
public func getLocation(withAuthScope authScope: CLAuthorizationStatus) {
if !determineStatus(withAuthScope: authScope) {
delegate?.accessDenied()
return
}
if trying {
return
}
trying = true
startTime = nil
locman.startUpdatingLocation()
}
/**
Stop all location based updates (location, heading)
*/
public func stopUpdates () {
locman.stopUpdatingLocation()
#if os(iOS)
locman.stopUpdatingHeading()
#endif
updatingHeading = false
trying = false
startTime = nil
}
/**
Get the current heading
*/
@available(iOS 9, *)
public func getHeading() {
#if os(iOS)
if !CLLocationManager.headingAvailable() {
return
}
if updatingHeading {
return
}
self.locman.headingFilter = 5
self.locman.headingOrientation = .portrait
self.locman.startUpdatingHeading()
#endif
updatingHeading = true
}
// MARK: - CLLocationManager Delegate
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
stopUpdates()
delegate?.accessDenied()
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last, location.horizontalAccuracy > 0 && location.horizontalAccuracy < requiredAccuracy else { return }
delegate?.retrieved(location)
}
#if os(iOS)
@available(iOS 9, *)
public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
self.delegate?.retrieved(newHeading)
}
#endif
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedAlways, .authorizedWhenInUse:
delegate?.locationAccess(true)
default:
delegate?.locationAccess(false)
}
}
// MARK: - Location helper methods
fileprivate func determineStatus(withAuthScope authScope: CLAuthorizationStatus) -> Bool {
let ok = CLLocationManager.locationServicesEnabled()
if !ok {
// System will display dialog prompting for location access
return true
}
let status = CLLocationManager.authorizationStatus()
switch status {
case .authorizedAlways, .authorizedWhenInUse:
return true
case .notDetermined:
#if os(iOS)
if authScope == .authorizedWhenInUse {
requestWhenInUseAuthorization()
} else {
requestAlwaysAuthorization()
}
#endif
requestAlwaysAuthorization()
return true
case .restricted:
delegate?.accessDenied()
return false
case .denied:
delegate?.accessDenied()
return false
}
}
}
| a07835e8be0f58ad1d6d26be5f94c0e7 | 25.313636 | 142 | 0.598549 | false | false | false | false |
alickbass/SweetRouter | refs/heads/master | SweetRouter/Router.swift | mit | 1 | //
// Router.swift
// SweetRouter
//
// Created by Oleksii on 17/03/2017.
// Copyright © 2017 ViolentOctopus. All rights reserved.
//
import Foundation
public struct Router<T: EndpointType>: URLRepresentable {
public let environment: T.Environment
public let route: T.Route
public init(_ environment: T.Environment = T.current, at route: T.Route) {
self.environment = environment
self.route = route
}
public var components: URLComponents {
var components = environment.components
let route = self.route.route
components.path = environment.value.defaultPath.with(route.path).pathValue
components.queryItems = route.query?.queryItems
components.fragment = route.fragment
return components
}
}
public protocol URLRepresentable {
var components: URLComponents { get }
var url: URL { get }
}
public extension URLRepresentable {
public var url: URL {
guard let url = components.url else { fatalError("URL components are not valid") }
return url
}
}
public protocol EndpointType {
associatedtype Environment: EnvironmentType
associatedtype Route: RouteType
static var current: Environment { get }
}
public protocol RouteType {
var route: URL.Route { get }
}
public protocol EnvironmentType: URLRepresentable {
var value: URL.Env { get }
}
public extension EnvironmentType {
public var components: URLComponents {
var components = URLComponents()
let environment = value
components.scheme = environment.scheme.rawValue
components.host = environment.host.hostString
components.port = environment.port
components.path = environment.defaultPath.pathValue
return components
}
}
| d5fa92121980aa235309be20fcd3cf53 | 24.816901 | 90 | 0.672122 | false | false | false | false |
tungvoduc/DTButtonMenuController | refs/heads/master | DTButtonMenuController/Classes/ButtonPositioningDriver.swift | mit | 1 | //
// ButtonPositioningDriver.swift
// Pods
//
// Created by Admin on 17/03/2017.
//
//
import UIKit
enum ButtonPositionDriverType {
case Satellite
case Arc
}
enum Position {
case left
case right
case top
case bottom
}
enum TouchPointPosition {
case topLeft
case topRight
case bottomLeft
case bottomRight
case center
}
class ButtonPositioningDriver: NSObject {
/// Automatically shrink the arc of buttons
var shouldShrinkArc = true
/// Number of buttons that will be displayed.
var numberOfItems: Int
var buttonAngle: Double
/// Radius of button.
var buttonRadius: CGFloat
/// Positioning type
var positioningType: ButtonPositionDriverType
/// Arc
var buttonsArc: Double = Double.pi / 2 + Double.pi / 6
/// Distance from touchPoint to a button
var distance: CGFloat = 80.0
/// Allow the buttons and the distance from touchPoint to the button center to be scaled
var scaleable: Bool = false
/// Margin to the edge to the screen or the defined view
var margin: CGFloat = 8.0
/// If not provide maxButtonsAngle, maxButtonsAngle will be automatically calculated by numberOfButtons, maxButtonsAngle = Pi/(numberOfButtons * 2)
init(numberOfButtons: Int = 1, buttonRadius radius: CGFloat, buttonsAngle angle: Double = Double.pi/6, positioningType type: ButtonPositionDriverType = .Arc) {
numberOfItems = numberOfButtons
buttonRadius = radius
buttonAngle = angle
positioningType = type;
super.init()
}
func positionsOfItemsInView(with size: CGSize, at touchPoint: CGPoint) -> [CGPoint] {
var points = [CGPoint]()
let fromAndToAngles = self.fromAngleAndToAngleInView(withSize: size, atPoint: touchPoint)
let fromAngle = fromAndToAngles[0]
let toAngle = fromAndToAngles[1]
var startingAngle = 0.0
let difference = toAngle - fromAngle
let sign = toAngle - fromAngle > 0 ? 1.0 : -1.0
var step = (buttonsArc * sign) / Double(numberOfItems - 1)
if fabs(difference) > buttonsArc {
startingAngle = difference > 0 ? (difference - buttonsArc) / 2 : (difference + buttonsArc) / 2
}
if fabs(difference) < buttonsArc {
if (shouldShrinkArc) {
step = fabs(difference) * sign / Double(numberOfItems - 1)
}
}
for i in 0 ..< numberOfItems {
let angle = step * Double(i) + fromAngle + startingAngle;
let x = touchPoint.x + (distance + buttonRadius) * CGFloat(cos(angle))
let y = touchPoint.y + (distance + buttonRadius) * CGFloat(sin(angle))
let point = CGPoint(x: x, y: y)
points.append(point)
}
return points
}
private func fromAngleAndToAngleInView(withSize size: CGSize, atPoint point: CGPoint) -> [Double] {
var fromAngle = 0.0;
var toAngle = 0.0;
if (positioningType == .Satellite) {
fromAngle = 0.0;
toAngle = Double.pi * 2;
} else {
if (buttonsArc > Double.pi * 2) {
fromAngle = (buttonsArc - Double.pi) / 2
toAngle = fromAngle - buttonsArc
} else {
fromAngle = -(Double.pi - buttonsArc) / 2
toAngle = -(Double.pi - abs(fromAngle))
}
}
let outerRadius: CGFloat = distance + buttonRadius * 2 + margin;
let touchPointInset = self.distanceOfTouchPointToEdges(touchPoint: point, inViewWithSize: size)
let touchPointPosition = self.touchPointPositionInView(withSize: size, touchPoint: point)
// This version prioritises to display the buttons to the TOP therefore it does not check touchPointInset.bottom > outerRadius
if (touchPointInset.top > outerRadius && touchPointInset.left > outerRadius && touchPointInset.right > outerRadius) {
return [fromAngle, toAngle]
}
if (touchPointInset.top < outerRadius && touchPointInset.left > outerRadius && touchPointInset.right > outerRadius) {
return [-fromAngle, -toAngle]
}
if (touchPointInset.top > outerRadius && touchPointInset.bottom > outerRadius && touchPointInset.left < touchPointInset.right) {
return [-(Double.pi / 2 + fromAngle), (Double.pi / 2 + fromAngle)]
}
if (touchPointInset.top > outerRadius && touchPointInset.bottom > outerRadius && touchPointInset.left > touchPointInset.right) {
return [(Double.pi / 2 + fromAngle) - Double.pi, (Double.pi / 2 + fromAngle) - Double.pi - buttonsArc]
}
let thresholdPoints = self.thresholdPointsOfButtonsArcInView(withSize: size, atTouchPoint: point);
let firstPoint = thresholdPoints[0];
let secondPoint = thresholdPoints[1];
var firstAngle: Double = (Double)(self.angleBetweenHorizontalLineAndLineHasCenterPointAndAnotherPoint(centerPoint: point, anotherPoint: firstPoint))
var secondAngle: Double = (Double)(self.angleBetweenHorizontalLineAndLineHasCenterPointAndAnotherPoint(centerPoint: point, anotherPoint: secondPoint))
if (firstAngle > secondAngle) {
let temp = secondAngle
secondAngle = firstAngle
firstAngle = temp
}
if touchPointPosition == .topLeft || touchPointPosition == .bottomLeft {
//secondAngle = secondAngle < 0 ? Double.pi + fabs(Double.pi - fabs(secondAngle)) : secondAngle
} else if touchPointPosition == .topRight || touchPointPosition == .bottomRight {
secondAngle = secondAngle > 0 ? -(Double.pi * 2 - secondAngle) : secondAngle;
}
return [firstAngle, secondAngle];
}
private func touchPointPositionInView(withSize size: CGSize, touchPoint:CGPoint) -> TouchPointPosition {
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
let centerPoint = CGPoint(x: size.width/2 + rect.origin.x, y: size.height/2 + rect.origin.y)
var touchPosition: TouchPointPosition = .center
if touchPoint.x <= centerPoint.x && touchPoint.y <= centerPoint.y {
touchPosition = .topLeft
}
if touchPoint.x >= centerPoint.x && touchPoint.y <= centerPoint.y {
touchPosition = .topRight
}
if touchPoint.x <= centerPoint.x && touchPoint.y >= centerPoint.y {
touchPosition = .bottomLeft
}
if touchPoint.x >= centerPoint.x && touchPoint.y >= centerPoint.y {
touchPosition = .bottomRight
}
return touchPosition
}
private func thresholdPointsOfButtonsArcInView(withSize size: CGSize, atTouchPoint point: CGPoint) -> [CGPoint] {
let marginX: CGFloat = margin;
let marginY: CGFloat = margin;
let arcRadius: CGFloat = distance + buttonRadius * 2 + margin;
let touchPointInset = self.distanceOfTouchPointToEdges(touchPoint: point, inViewWithSize: size)
let touchPointPosition = self.touchPointPositionInView(withSize: size, touchPoint: point)
var fromPointOffsetXSign: CGFloat = 1
var fromPointOffsetYSign: CGFloat = 1
var toPointOffsetXSign: CGFloat = 1
var toPointOffsetYSign: CGFloat = 1
switch touchPointPosition {
case .topLeft:
fromPointOffsetXSign = touchPointInset.top >= arcRadius ? -1 : 1
fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.top ? -1 : 1
toPointOffsetXSign = 1
toPointOffsetYSign = 1
case .topRight:
fromPointOffsetXSign = touchPointInset.top >= arcRadius ? 1 : -1
fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.top ? -1 : 1
toPointOffsetXSign = -1
toPointOffsetYSign = 1
case .bottomLeft:
fromPointOffsetXSign = touchPointInset.bottom >= arcRadius ? -1 : 1
fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.bottom ? 1 : -1
toPointOffsetXSign = 1
toPointOffsetYSign = -1
case .bottomRight:
fromPointOffsetXSign = touchPointInset.bottom >= arcRadius ? 1 : -1
fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.bottom ? 1 : -1
toPointOffsetXSign = -1
toPointOffsetYSign = -1
default:
fromPointOffsetXSign = -1
fromPointOffsetYSign = -1
toPointOffsetXSign = 1
toPointOffsetYSign = -1
}
let closestHorizontalDistanceToEdge = touchPointInset.left > touchPointInset.right ? touchPointInset.right : touchPointInset.left
let closestVerticalDistanceToEdge = touchPointInset.top > touchPointInset.bottom ? touchPointInset.bottom : touchPointInset.top
let offsetX: CGFloat = sqrt(pow(arcRadius, 2) - pow(max(abs((closestHorizontalDistanceToEdge - (marginX + buttonRadius))), (marginX + buttonRadius)), 2))
let offsetY: CGFloat = sqrt(pow(arcRadius, 2) - pow(max(abs((closestVerticalDistanceToEdge - (marginY + buttonRadius))), (marginY + buttonRadius)), 2))
let baseFromPointX = point.x;
let baseFromPointY = touchPointPosition == .topLeft || touchPointPosition == .topRight ? 0.0 : size.height;
let baseToPointX = touchPointPosition == .topLeft || touchPointPosition == .bottomLeft ? 0.0 : size.width;
let baseToPointY = point.y;
let fromPoint: CGPoint = CGPoint(x: baseFromPointX + fromPointOffsetXSign * offsetX, y: baseFromPointY + (marginY + buttonRadius) * fromPointOffsetYSign)
let toPoint: CGPoint = CGPoint(x:baseToPointX + (marginX + buttonRadius) * toPointOffsetXSign, y: baseToPointY + toPointOffsetYSign * offsetY)
return [fromPoint, toPoint]
}
private func distanceOfTouchPointToEdges(touchPoint point: CGPoint, inViewWithSize size: CGSize) -> UIEdgeInsets {
var edgeInsets : UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
edgeInsets.top = point.y
edgeInsets.bottom = size.height - edgeInsets.top
edgeInsets.left = point.x
edgeInsets.right = size.width - point.x
return edgeInsets
}
private func angleBetweenHorizontalLineAndLineHasCenterPointAndAnotherPoint(centerPoint: CGPoint, anotherPoint: CGPoint) -> CGFloat {
let sign: CGFloat = anotherPoint.y < centerPoint.y ? -1 : 1
let isObstubeAngle: Bool = anotherPoint.x < centerPoint.x ? true : false
let horizontalLength = fabs(centerPoint.x - anotherPoint.x)
let verticalLength = fabs(centerPoint.y - anotherPoint.y)
var angle = atan(verticalLength/horizontalLength)
if isObstubeAngle {
angle = ((CGFloat)(Double.pi) - angle) * sign
} else {
angle = angle * sign
}
return angle
}
}
| b7492071626659f3cfd0dcc56990c60f | 39.621429 | 163 | 0.620802 | false | false | false | false |
debugsquad/Hyperborea | refs/heads/master | Hyperborea/Model/Search/MSearchEntryNumber.swift | mit | 1 | import UIKit
class MSearchEntryNumber
{
private static let kBreak:String = "\n"
private static let kSeparator:String = ", "
private static let kKeyEntries:String = "entries"
private static let kKeyGrammaticalFeatures:String = "grammaticalFeatures"
private static let kKeyType:String = "type"
private static let kKeyText:String = "text"
private static let kTypeNumber:String = "Number"
private static let kNumberFontSize:CGFloat = 14
class func parse(json:Any) -> NSAttributedString?
{
guard
let jsonMap:[String:Any] = json as? [String:Any],
let jsonEntries:[Any] = jsonMap[kKeyEntries] as? [Any]
else
{
return nil
}
var numbers:[String] = []
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let attributes:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:kNumberFontSize),
NSForegroundColorAttributeName:UIColor.black]
let stringBreak:NSAttributedString = NSAttributedString(
string:kBreak,
attributes:attributes)
let stringSeparator:NSAttributedString = NSAttributedString(
string:kSeparator,
attributes:attributes)
for jsonEntry:Any in jsonEntries
{
guard
let jsonEntryMap:[String:Any] = jsonEntry as? [String:Any],
let jsonFeatures:[Any] = jsonEntryMap[
kKeyGrammaticalFeatures] as? [Any]
else
{
continue
}
for jsonFeature:Any in jsonFeatures
{
guard
let featureMap:[String:Any] = jsonFeature as? [String:Any],
let featureMapType:String = featureMap[kKeyType] as? String,
let featureMapText:String = featureMap[kKeyText] as? String
else
{
continue
}
if featureMapType == kTypeNumber
{
let numberLowerCase:String = featureMapText.lowercased()
var append:Bool = true
for number:String in numbers
{
if number == numberLowerCase
{
append = false
break
}
}
if append
{
numbers.append(numberLowerCase)
if mutableString.string.isEmpty
{
mutableString.append(stringBreak)
}
else
{
mutableString.append(stringSeparator)
}
let numberString:NSAttributedString = NSAttributedString(
string:numberLowerCase,
attributes:attributes)
mutableString.append(numberString)
}
}
}
}
return mutableString
}
}
| c8eb79c17117887594330e12a90d5b8e | 32.952381 | 81 | 0.453857 | false | false | false | false |