blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
4a027c42db33db80680ab9575706eed053e74404
|
Swift
|
naoyashiga/RP3DTransition
|
/RP3DTransition/NavigationController.swift
|
UTF-8
| 1,485
| 2.546875
| 3
|
[] |
no_license
|
//
// NavigationController.swift
// RP3DTransition
//
// Created by naoyashiga on 2015/09/26.
// Copyright © 2015年 naoyashiga. All rights reserved.
//
import UIKit
class NavigationController: UINavigationController, UINavigationControllerDelegate {
var interactiveTransition: RP3DInteractiveTransition?
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator = RP3DTransitionAnimator()
switch operation {
case .Push:
interactiveTransition = nil
animator.transitionType = .Push
return animator
case .Pop:
animator.transitionType = .Pop
return animator
default:
return nil
}
}
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactiveTransition
}
}
| true
|
48b7fb33213c0c60310c0b6b71b50a2811433193
|
Swift
|
sivaganeshsg/On-the-Map
|
/On the Map/UserUrlViewController.swift
|
UTF-8
| 7,354
| 2.609375
| 3
|
[] |
no_license
|
//
// UserUrlViewController.swift
// On the Map
//
// Created by Siva Ganesh on 21/09/15.
// Copyright (c) 2015 Siva Ganesh. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class UserUrlViewController: UIViewController {
var userAddress = ""
var userUrl = ""
var lat = ""
var long = ""
@IBOutlet weak var activityIndicatorIcon: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
startActivityIndicator()
// Reverse address to Co-ordinate
let address = userAddress
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
if let placemark = placemarks?[0]{
self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
self.lat = placemark.location!.coordinate.latitude.description
self.long = placemark.location!.coordinate.longitude.description
let initialLocation = CLLocation(latitude: placemark.location!.coordinate.latitude, longitude: placemark.location!.coordinate.longitude)
self.centerMapOnLocation(initialLocation)
self.stopActivityIndicator()
print(self.lat)
}else{
self.stopActivityIndicator()
let alertController = UIAlertController(title: "Error", message:
"Unable to find the given address. Please Enter a new Address", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
}
})
// Do any additional setup after loading the view.
}
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var userUrlField: UITextField!
@IBAction func submitPressed(sender: AnyObject) {
userUrl = userUrlField.text!
if(!userUrl.characters.isEmpty && UserFunctions.isValidUrl(userUrl)){
let accId = UserFunctions.user_id
UserFunctions.getUserDetails(accId){ (success, errorMessage) in
if success {
let fullDetails = ["uniqueKey" : UserFunctions.user_id,"firstName" : UserFunctions.firstName, "lastName" : UserFunctions.lastName,"mapString" : self.userAddress,"mediaURL" : self.userUrl,"latitude" : (self.lat as NSString).doubleValue,"longitude" : (self.long as NSString).doubleValue]
UserFunctions.updateUserLocationInParse(fullDetails){ (success, errorMessage) in
if success {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("newLocationToTabBarSegue", sender: nil)
}
}
}else{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let alertController = UIAlertController(title: "Error", message:
errorMessage, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
}else{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dispatch_async(dispatch_get_main_queue()) {
// let errorMsg = parsedResult["error"] as? String
let alertController = UIAlertController(title: "Error", message:
errorMessage, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
}
}else{
let alertController = UIAlertController(title: "Error", message:
"Enter a valid URL. Include http or https", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: false)
}
@IBAction func cancelButtonPressed(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func browseBtnPressed(sender: AnyObject) {
userUrl = userUrlField.text!
if(!userUrl.characters.isEmpty && UserFunctions.isValidUrl(userUrl)){
let givenURL = userUrl
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.urlString = givenURL
self.presentViewController(webVC, animated: true, completion: nil)
}else{
let alertController = UIAlertController(title: "Error", message:
"Unable to find the given address. Please Enter a new Address", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
func startActivityIndicator(){
activityIndicatorIcon.startAnimating()
activityIndicatorIcon.hidden = false
}
func stopActivityIndicator(){
activityIndicatorIcon.stopAnimating()
activityIndicatorIcon.hidden = true
}
@IBAction func resignKeyboard(sender: AnyObject) {
sender.resignFirstResponder()
}
}
| true
|
8ad4ee7a09f27552f8aa6a7d24c0d3474832c468
|
Swift
|
CodyAdcock/Stretch-Problems
|
/8:23 Stretch.playground/Contents.swift
|
UTF-8
| 3,059
| 3.984375
| 4
|
[] |
no_license
|
class Person{
//properties
let name: String?
let age: Int?
let favoriteMovie: String?
init(myDictionary: Dictionary<String, Any>){
var dictName: String?
var dictAge: Int?
var dictMovie: String?
for (key, value) in myDictionary{
switch key{
case "nameKey":
dictName = value as? String
case "ageKey":
dictAge = value as? Int
case "favMovieKey":
dictMovie = value as? String
default:
break
}
}
self.name = dictName
self.age = dictAge
self.favoriteMovie = dictMovie
}
}
let workingDictionary = ["nameKey" : "Derek", "ageKey": 28, "favMovieKey" : "Zoolander"] as [String : Any]
let brokenDictionary = ["nameKey" : "Steve", "ageKey": 2] as [String : Any]
let derek = Person.init(myDictionary: workingDictionary)
print("Name: \(derek.name ?? "Oops") \(derek.age ?? 123456789) \(derek.favoriteMovie ?? "Oops")")
let steve = Person.init(myDictionary: brokenDictionary)
print("Name: \(steve.name ?? "Missing Data") \(steve.age ?? 404) \(steve.favoriteMovie)")
//
///NEW CLASS FOR TREVOR'S EXAMPLE
//
class TrevPerson{
let name: String
let age: Int
let favoriteMovie: String
init?(dictionary: Dictionary<String, Any>){
guard let name = dictionary["nameKey"] as? String,
let age = dictionary["ageKey"] as? Int,
let favoriteMovie = dictionary["favMovieKey"] as? String else {return nil}
self.name = name
self.age = age
self.favoriteMovie = favoriteMovie
}
}
let TrevDerek = TrevPerson(dictionary: workingDictionary)
let TrevSteve = TrevPerson(dictionary: brokenDictionary)
print("Trev Name: \(TrevDerek?.name) \(TrevDerek?.age) \(TrevDerek?.favoriteMovie)")
print("Trev Name: \(TrevSteve?.name) \(TrevSteve?.age) \(TrevSteve?.favoriteMovie)")
//
//Making mine Failable
//
class FailablePerson{
let name: String?
let age: Int?
let favoriteMovie: String?
init?(myDictionary: Dictionary<String, Any>){
var dictName: String?
var dictAge: Int?
var dictMovie: String?
for (key, value) in myDictionary{
switch key{
case "nameKey":
dictName = value as? String
case "ageKey":
dictAge = value as? Int
case "favMovieKey":
dictMovie = value as? String
default:
break
}
}
self.name = dictName
self.age = dictAge
self.favoriteMovie = dictMovie
}
}
let failableDerek = FailablePerson.init(myDictionary: workingDictionary)
print("FailableName: \(failableDerek?.name) \(failableDerek?.age) \(failableDerek?.favoriteMovie)")
let failableSteve = FailablePerson.init(myDictionary: brokenDictionary)
print("FailableName: \(failableSteve?.name) \(failableSteve?.age) \(failableSteve?.favoriteMovie )")
| true
|
d90228ab5d37dc67ca77f6a958884cfc1ef50abc
|
Swift
|
FutureAndroidDeveloper/PhotoMap
|
/PhotoMap/PhotoMap/Library/Services/CategoriesService.swift
|
UTF-8
| 1,011
| 2.921875
| 3
|
[] |
no_license
|
//
// CategoriesService.swift
// PhotoMap
//
// Created by Kiryl Klimiankou on 8/6/19.
// Copyright © 2019 Kiryl Klimiankou. All rights reserved.
//
import Foundation
import RxSwift
class CategoriesService {
private let fileManager: FileManager!
private let resourcePath: URL!
private let folderName = "Categories"
init() {
fileManager = FileManager.default
resourcePath = URL(string: Bundle.main.resourcePath!)?.appendingPathComponent(folderName)
}
func getCategories() -> Observable<[String]> {
var categories = [String]()
let items = try! fileManager.contentsOfDirectory(atPath: resourcePath!.absoluteString)
for var item in items {
if let index = item.range(of: ".") {
let distance = item.distance(from: index.lowerBound, to: item.endIndex)
item.removeLast(distance)
categories.append(item)
}
}
return Observable.just(categories.reversed())
}
}
| true
|
d050902661d0a870d6912c342dbb2b4170ec0da8
|
Swift
|
zats/p5swift
|
/Sources/p5swift/Core/Configuration/Internal/BlendMode+CoreGraphics.swift
|
UTF-8
| 837
| 2.640625
| 3
|
[] |
no_license
|
// p5swift
import CoreGraphics
extension BlendMode {
var cgBlendMode: CGBlendMode {
switch self {
case .blend:
return .normal
case .add:
return .screen
case .darkest:
return .darken
case .lightest:
return .lighten
case .difference:
return .difference
case .exclusion:
return .exclusion
case .multiply:
return .multiply
case .screen:
return .screen
case .replace:
fatalError("Not implemented yet")
case .remove:
fatalError("Not implemented yet")
case .overlay:
return .overlay
case .hardLight:
return .hardLight
case .softLiht:
return .softLight
case .dodge:
return .colorDodge
case .burn:
return .colorBurn
case .subtract:
fatalError("Not implemented yet")
}
}
}
| true
|
d38334ed386a094f8ebd97433727e67699d83bea
|
Swift
|
persiogv/PokeClient
|
/Sources/PokeClient/Models/PokemonAbility.swift
|
UTF-8
| 818
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
//
// PokemonAbility.swift
// PokeClient
//
// Created by Pérsio on 20/04/20.
//
import Foundation
/// Pokemon ability model
public struct PokemonAbility: Decodable {
// MARK: Coding keys
private enum CodingKeys: String, CodingKey {
case ability
case isHidden = "is_hidden"
case slot
}
// MARK: Properties
public let ability: Ability?
public let isHidden: Bool?
public let slot: Int?
// MARK: Initializers
/// Initializer
/// - Parameters:
/// - ability: An Ability instance
/// - isHidden: Hidden boolean
/// - slot: Ability slot value
public init(ability: Ability?, isHidden: Bool?, slot: Int?) {
self.ability = ability
self.isHidden = isHidden
self.slot = slot
}
}
| true
|
879b58ab2e98ef4fcee788d3e5f24b8824175f5f
|
Swift
|
mokagio/yow-connected-2015
|
/Swift-Optionals-Func-Programming-And-You.playground/Pages/follow-the-types.xcplaygroundpage/Contents.swift
|
UTF-8
| 205
| 3.171875
| 3
|
[] |
no_license
|
//: ## Follow the types
func magicNumber(string: String) -> Int {
return string.characters.count * 100 + 42
}
let optString: Optional<String> = "abc"
let arrayStr: Array<String> = ["abc", "de", "f"]
| true
|
98393c65686c6c4af52a361c73f55ad511a7f9f3
|
Swift
|
farklf/KurtsSegmentControl
|
/KurtsSegmentControl/CollectionViewController.swift
|
UTF-8
| 3,309
| 2.71875
| 3
|
[] |
no_license
|
//
// CollectionViewController.swift
// KurtsSegmentControl
//
// Created by MAC Consultant on 7/20/19.
// Copyright © 2019 MAC Consultant. All rights reserved.
//
import UIKit
class CollectionViewController: UIViewController {
var books: [Book] = []
@IBOutlet weak var collectionView: UICollectionView!
let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
print("cvc")
viewModel.get(books: "Harry Potter")
NotificationCenter.default.addObserver(forName: Notification.Name("Object"), object: nil, queue: .main) { [unowned self] _ in
print(" in collections")
self.collectionView.reloadData()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension CollectionViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("in number of item")
print(viewModel.myBooks.count)
return viewModel.myBooks.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
let book = viewModel.myBooks[indexPath.row]
let url = URL(string: book.thumbnail)!
URLSession.shared.dataTask(with: url) { (dat, _, _) in
if let data = dat {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
cell.collectionImage.image = image
self.view.layoutIfNeeded()
print("Received Image")
}
}
}
}.resume()
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//Add this to un-highlight the row that was tapped
collectionView.deselectItem(at: indexPath, animated: true)
//Select the correct beer from the array
let book = viewModel.myBooks[indexPath.row]
viewModel.currentBook = book
let bkDetailVC = storyboard?.instantiateViewController(withIdentifier: "DetailedViewController") as! DetailedViewController
bkDetailVC.viewModel = viewModel
//present the detail VC
self.navigationController?.pushViewController(bkDetailVC, animated: true)
}
}
extension CollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: 131, height: 135)
}
}
| true
|
02d9086447844f3195ab70e03f7bd945922215ec
|
Swift
|
junguochen/ElegantUI
|
/Source/UIView/UIView+Convenient.swift
|
UTF-8
| 1,482
| 2.796875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
//
// UIView+Convenient.swift
// ElegantUI
//
// Created by John on 2019/7/25.
// Copyright © 2019 ElegantUI. All rights reserved.
//
import UIKit
public extension UIView {
/// removeFromSuperview 之前增加 superview == nil 的判断
func safeRemoveFromSuperview() {
if superview == nil { return }
removeFromSuperview()
}
convenience init(backgroundColor: UIColor?) {
self.init()
self.backgroundColor = backgroundColor
}
}
public extension CGRect {
init(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) {
self.init(x: x, y: y, width: w, height: h)
}
}
public extension UIView {
// TODO: 可封装 -> ElegantUI
/// 添加虚线边框
@discardableResult
func drawDottedLine(start point0: CGPoint,
end point1: CGPoint,
strokeColor: UIColor? = nil,
lineWidth: CGFloat? = nil,
lineDashPattern: [NSNumber]? = nil) -> CAShapeLayer {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = strokeColor?.cgColor ?? UIColor.lightGray.cgColor
shapeLayer.lineWidth = lineWidth ?? 1
// 4 虚线高, 3 间隔高.
shapeLayer.lineDashPattern = lineDashPattern ?? [4, 1]
let path = CGMutablePath()
path.addLines(between: [point0, point1])
shapeLayer.path = path
layer.addSublayer(shapeLayer)
return shapeLayer
}
}
| true
|
11690fdd078321f385a316111a9bc232e4354833
|
Swift
|
sajanshrestha/fresh_food
|
/GTracker/Views/Components/PickerView.swift
|
UTF-8
| 639
| 3.09375
| 3
|
[] |
no_license
|
//
// PickerView.swift
// GTracker
//
// Created by Sajan Shrestha on 1/20/20.
// Copyright © 2020 Sajan Shrestha. All rights reserved.
//
import SwiftUI
struct PickerView: View {
@Binding var selected: Int
var list: [Int]
var body: some View {
Picker(selection: $selected, label: Text("")) {
ForEach(list, id: \.self) { item in
Text("\(item)")
}
}
.foregroundColor(.black)
.font(.headline)
}
}
struct PickerView_Previews: PreviewProvider {
static var previews: some View {
PickerView(selected: .constant(0), list: [1,2,3])
}
}
| true
|
3f2e2c783165ee16e53369ef5456e5a8e6a55336
|
Swift
|
KeithGapusan/iOSCommonUI
|
/iOSCommonUI/Pod/Walkthrough/WalkThroughPageViewController.swift
|
UTF-8
| 6,374
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// WalkThroughPageViewController. swift
// StraightArrow
//
// Created by Belinda Natividad on 09/03/2018.
// Copyright © 2018 Keith Randell Gapusan. All rights reserved.
//
import UIKit
public protocol WalkThroughPageViewControllerDelegate {
func didUpdatePageView(sender: Int)
func getNumberOfViews(sender: Int)
}
class WalkThroughPageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
let pageControl: UIPageControl = {
let pageController = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 50,width: UIScreen.main.bounds.width,height: 50))
pageController.currentPage = 0
// pageController.tintColor = customColor.darkBlue
// pageController.pageIndicatorTintColor = UIColor.gray
// pageController.currentPageIndicatorTintColor = customColor.violet
return pageController
}()
lazy var orderedViewControllers: [UIViewController] = {
return [self.newVc(viewController: "wtVC1"),
self.newVc(viewController: "wtVC1"),
self.newVc(viewController: "wtVC1"),
self.newVc(viewController: "wtVC1")]
}()
var imageList = [String]()
var descList = [String]()
var pageDelegate : WalkThroughPageViewControllerDelegate!
var currentViewIndex : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
setCurrentView(index: currentViewIndex)
configurePageControl()
}
func setCurrentView(index : Int){
print("set curr = \(index)")
print("set curr = \(orderedViewControllers)")
let vc = orderedViewControllers[index] as! WalkThroughViewController
setViewControllers([vc],
direction: .forward,
animated: true,
completion:{(value:Bool) in
print("completed \(value)")
if value {
self.pageDelegate.didUpdatePageView(sender: index)
vc.setDesription(text: self.descList[index])
vc.setImageLogo(imageName: self.imageList[index])
}
})
}
func setCurrentIndex(index : Int){
self.currentViewIndex = index
}
func setImageList(images:[String]){
self.imageList = images
}
func setDescList(descriptions:[String]){
self.descList = descriptions
}
func nextPage(index:Int){
// let view = self.orderedViewControllers[index]
self.setViewControllers(self.orderedViewControllers,
direction: .forward,
animated: true,
completion: nil)
}
func getCurrentView() -> Int{
return self.pageControl.currentPage
}
func setViewController(views : [UIViewController]){
self.orderedViewControllers = views
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = orderedViewControllers.count
self.pageControl.currentPage = self.currentViewIndex
self.view.addSubview(pageControl)
}
func newVc(viewController: String) -> UIViewController {
let vc = UIStoryboard(name: "Walkthrough", bundle: nil).instantiateViewController(withIdentifier: viewController) as! WalkThroughViewController
return vc
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let pageContentViewController = pageViewController.viewControllers![0]
let vc = pageContentViewController as! WalkThroughViewController
vc.setImageLogo(imageName: self.imageList[orderedViewControllers.index(of: pageContentViewController)!])
vc.setDesription(text: descList[orderedViewControllers.index(of: pageContentViewController)!])
self.pageControl.currentPage = orderedViewControllers.index(of: pageContentViewController)!
self.pageDelegate.didUpdatePageView(sender: self.pageControl.currentPage)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
// User is on the first view controller and swiped left to loop to
// the last view controller.
guard previousIndex >= 0 else {
return orderedViewControllers.last
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
// User is on the last view controller and swiped right to loop to
// the first view controller.
guard orderedViewControllersCount != nextIndex else {
return orderedViewControllers.first
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
}
| true
|
ff379e8a041d46edbbe155ea6635f47bb286eba7
|
Swift
|
Genius-Systems-Nepal/Newsapp-demo-iOS
|
/Newsapp-demo-iOS/utils/CacheManager.swift
|
UTF-8
| 405
| 2.71875
| 3
|
[] |
no_license
|
//
// CacheManager.swift
// Newsapp-demo-iOS
//
// Created by Kapil Bhattarai on 7/29/20.
// Copyright © 2020 Kapil Bhattarai. All rights reserved.
//
import Foundation
struct CacheManager {
static var cache = [String: Data]()
static func setVideoCache (_ url: String, _ data: Data) {
cache[url] = data
}
static func getVideoCache (_ url: String ) -> Data? {
return cache[url]
}
}
| true
|
e7c0003b096bba949d9c18ed5e22212631152a98
|
Swift
|
CTChar/SampleWork
|
/OpenTrack/OpenTrack/NameViewController.swift
|
UTF-8
| 2,039
| 2.78125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// OpenTrack
//
// Created by Cole Herzog on 9/28/16.
// Copyright © 2016 Spensa. All rights reserved.
//
import UIKit
class NameViewController: UIViewController {
@IBOutlet var continueButton: UIButton!
@IBOutlet var disclaimer: UITextView!
@IBOutlet var firstName: UITextField!
@IBOutlet var lastName: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
if let first = defaults.object(forKey: "first") as? String,
let last = defaults.object(forKey: "last") as? String {
if first != "" {
firstName.text = first
}
if last != "" {
lastName.text = last
}
}
}
@IBAction func warningHit(_ sender: AnyObject) {
disclaimer.isHidden = !disclaimer.isHidden
view.endEditing(true)
}
@IBAction func continueHit(_ sender: AnyObject) {
if let first = firstName.text,
let last = lastName.text {
let defaults = UserDefaults.standard
defaults.set(first, forKey: "first")
defaults.set(last, forKey: "last")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextView = segue.destination as? TrackingViewController else {
fatalError("This isn't a tracking view controller, and you're not a nice person.")
}
if let first = firstName.text,
let last = lastName.text {
nextView.firstName = first
nextView.lastName = last
} else {
fatalError("How did you even perform a segue without these?")
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if firstName.text != "" && lastName.text != "" {
return true
} else {
return false
}
}
}
| true
|
e8b1dba68b88310d73f81cfd4314d3ce339e360b
|
Swift
|
ekuester/Swift-Slides-Transition
|
/Slides Transition/CollectionViewItem.swift
|
UTF-8
| 1,430
| 2.765625
| 3
|
[] |
no_license
|
//
// CollectionViewItem.swift
// Slides Transition
//
// Created by Erich Küster on December 16, 2016
// Copyright © 2016 Erich Küster. All rights reserved.
//
import Cocoa
class CollectionViewItem: NSCollectionViewItem {
// 1
var imageFile: ImageFile? {
didSet {
guard isViewLoaded
else { return }
imageView?.image = imageFile?.thumbnail
textField?.stringValue = (imageFile?.fileName)!
}
}
// 2
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.lightGray.cgColor
view.layer?.borderWidth = 0.0
view.layer?.borderColor = NSColor.red.cgColor
// If the set image view is a DoubleActionImageView, set the double click handler
if let imageView = imageView as? DoubleActionImageView {
imageView.doubleAction = #selector(CollectionViewItem.handleDoubleClickInImageView(_:))
imageView.target = self
}
}
// 3
func setHighlight(_ selected: Bool) {
view.layer?.borderWidth = selected ? 2.0 : 0.0
}
// MARK: IBActions
@IBAction func handleDoubleClickInImageView(_ sender: AnyObject?) {
// On double click, show the image in a new view
NotificationCenter.default.post(name: Notification.Name(rawValue: "com.image.doubleClicked"), object: self.imageFile)
}
}
| true
|
4bcd03e2a1ff0baa89f16dd9310e4c5565aa769a
|
Swift
|
mkll/Discoverable-Bonjour
|
/Sources/Discoverable/DiscoverableError.swift
|
UTF-8
| 2,250
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// DiscoverableError.swift
// Assistive Technology
//
// Created by Ben Mechen on 29/01/2020.
// Copyright © 2020 Team 30. All rights reserved.
//
import Foundation
import Network
/// Errors thrown by Discoverable.
/// Split into three categories, all with a set prefix:
/// * POSIX errors –> `connect` prefix, signify errors from the foundation level C library POSIX, used as a fundamental base for iOS connections
/// * Bonjour service discovery errors –> `discover` prefix, signify errors ran into whilst trying to discover the server advertising on the local network using the Bonjour protocol
/// * Service resolve errors –> `discoverResolve` prefix, signify errors ran into in the second component of the discovery process; resolving the server's IP address from the discovered services
public enum DiscoverableError: Error {
/// Other connection error
case connectOther
/// POSIX address not available
case connectAddressUnavailable
/// POSIX permission denied
case connectPermissionDenied
/// POSIX device busy
case connectDeviceBusy
/// POSIX operation canceled
case connectCanceled
/// POSIX connection refused
case connectRefused
/// POSIX host is down or unreachable
case connectHostDown
/// POSIX connection already exists
case connectAlreadyConnected
/// POSIX operation timed ouit
case connectTimeout
/// POSIX network is down, unreachable, or has been reset
case connectNetworkDown
/// Connection server discovery failed
case connectShakeNoResponse
/// Discovery search did not find service in time
case discoverTimeout
/// Service not found while resolving IP
case discoverResolveServiceNotFound
/// Resolve service activity in progress
case discoverResolveBusy
/// Resolve service not setup correctly or given bad argument (e.g. bad IP)
case discoverIncorrectConfiguration
/// Resolve service was canceled
case discoverResolveCanceled
/// Resolve service did not get IP in time
case discoverResolveTimeout
/// Unable to resolve IP address from sender
case discoverResolveFailed
/// Other, unknown error during IP resolve
case discoverResolveUnknown
}
| true
|
d956851e42b7686d79e417f2688f827f2c23cf3c
|
Swift
|
itggangpae/iOS
|
/CarCollection/ViewController.swift
|
UTF-8
| 3,002
| 3.203125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CarCollection
//
// Created by Adam on 2021/02/28.
//
import UIKit
class ViewController: UIViewController {
var images : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
for i in 0...24{
let imgName : String = String(format: "car%02i.jpg", i)
images.append(imgName)
}
}
}
extension ViewController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
//셀의 개수를 설정하는 메소드
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
//셀의 개수를 설정
return images.count
}
//셀 구성하기
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.imageView.image = UIImage(named: images[indexPath.row])
return cell
}
// 사이즈
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewCellWithd = collectionView.frame.width / 3 - 1
return CGSize(width: collectionViewCellWithd, height: collectionViewCellWithd)
}
//위아래 라인 간격
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
//옆 라인 간격
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath){
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderColor = UIColor.cyan.cgColor
cell?.layer.borderWidth = 3.0
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath){
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderColor = nil
cell?.layer.borderWidth = 0.0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderColor = UIColor.yellow.cgColor
cell?.layer.borderWidth = 5.0
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderColor = UIColor.yellow.cgColor
cell?.layer.borderWidth = 0.0
}
}
| true
|
3a9be96e3e3bd91235a1339770cb0e7c6caecb56
|
Swift
|
masato1252/gourmetPocket
|
/placeBook/PlaceListData.swift
|
UTF-8
| 866
| 2.53125
| 3
|
[] |
no_license
|
//
// PlaceListData.swift
// placeBook
//
// Created by 松浦 雅人 on 2017/03/08.
// Copyright © 2017年 松浦 雅人. All rights reserved.
//
import UIKit
class PlaceListData: NSObject {
var place_id:String = ""
var site_type:Int = 0
var site_id:String = ""
var name:String = ""
var area:String = ""
var station:String = ""
var comment:String = ""
var img:UIImage? = nil
init(place_id:String, site_type:Int, site_id:String, name:String, area:String, station:String, comment:String, img:UIImage?) {
self.place_id = place_id
self.site_type = site_type
self.site_id = site_id
self.name = name
self.area = area
self.station = station
self.comment = comment
self.img = img
super.init()
}
override init(){
}
}
| true
|
0795cf9d7e7c50cc62b6b0875bb02ae967927b06
|
Swift
|
igor-makarov/NetNewsWire
|
/Shared/Extensions/RSImage-Extensions.swift
|
UTF-8
| 2,657
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// RSImage-Extensions.swift
// RSCore
//
// Created by Maurice Parker on 4/11/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
import RSCore
extension RSImage {
static let avatarSize = 48
static func scaledForAvatar(_ data: Data, imageResultBlock: @escaping (RSImage?) -> Void) {
DispatchQueue.global().async {
let image = RSImage.scaledForAvatar(data)
DispatchQueue.main.async {
imageResultBlock(image)
}
}
}
static func scaledForAvatar(_ data: Data) -> RSImage? {
let scaledMaxPixelSize = Int(ceil(CGFloat(RSImage.avatarSize) * RSScreen.mainScreenScale))
guard var cgImage = RSImage.scaleImage(data, maxPixelSize: scaledMaxPixelSize) else {
return nil
}
if cgImage.width < avatarSize || cgImage.height < avatarSize {
cgImage = RSImage.compositeAvatar(cgImage)
}
#if os(iOS)
return RSImage(cgImage: cgImage)
#else
let size = NSSize(width: cgImage.width, height: cgImage.height)
return RSImage(cgImage: cgImage, size: size)
#endif
}
}
private extension RSImage {
#if os(iOS)
static func compositeAvatar(_ avatar: CGImage) -> CGImage {
let rect = CGRect(x: 0, y: 0, width: avatarSize, height: avatarSize)
UIGraphicsBeginImageContext(rect.size)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(AppAssets.avatarBackgroundColor.cgColor)
context.fill(rect)
context.translateBy(x: 0.0, y: CGFloat(integerLiteral: avatarSize));
context.scaleBy(x: 1.0, y: -1.0)
let avatarRect = CGRect(x: (avatarSize - avatar.width) / 2, y: (avatarSize - avatar.height) / 2, width: avatar.width, height: avatar.height)
context.draw(avatar, in: avatarRect)
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!.cgImage!
}
#else
static func compositeAvatar(_ avatar: CGImage) -> CGImage {
var resultRect = CGRect(x: 0, y: 0, width: avatarSize, height: avatarSize)
let resultImage = NSImage(size: resultRect.size)
resultImage.lockFocus()
if let context = NSGraphicsContext.current?.cgContext {
if NSApplication.shared.effectiveAppearance.isDarkMode {
context.setFillColor(AppAssets.avatarDarkBackgroundColor.cgColor)
} else {
context.setFillColor(AppAssets.avatarLightBackgroundColor.cgColor)
}
context.fill(resultRect)
let avatarRect = CGRect(x: (avatarSize - avatar.width) / 2, y: (avatarSize - avatar.height) / 2, width: avatar.width, height: avatar.height)
context.draw(avatar, in: avatarRect)
}
resultImage.unlockFocus()
return resultImage.cgImage(forProposedRect: &resultRect, context: nil, hints: nil)!
}
#endif
}
| true
|
eaaf542d852d2bcc73fb65c83d008af12c8b3fcd
|
Swift
|
DanielEdrisian/Billie
|
/Billie/Views/Now Playing/PlayPauseView.swift
|
UTF-8
| 466
| 2.703125
| 3
|
[] |
no_license
|
//
// PlayPauseView.swift
// Billie
//
// Created by Samuel Shi on 10/18/20.
//
import SwiftUI
struct PlayPauseView: View {
@ObservedObject var publisher = SpotifyPublisher.shared
var body: some View {
Button(action: {
if publisher.isPaused {
publisher.playerAPI?.resume(.none)
} else {
publisher.playerAPI?.pause(.none)
}
}) {
Image(systemName: publisher.isPaused ? "play.fill" : "pause.fill")
}
}
}
| true
|
405d0060b68b8e1f2c57c7687738286e9fa5958c
|
Swift
|
ranggasenatama/iOS-Mobile-Task
|
/FP/Attedance Class/Attedance Class/Scenes/Main/AttendanceClass/GetLocation/GetLocationViewModel.swift
|
UTF-8
| 1,176
| 2.703125
| 3
|
[] |
no_license
|
//
// GetQRCodeViewModel.swift
// Attedance Class
//
// Created by Rangga Senatama Putra on 28/11/18.
// Copyright © 2018 Rangga Senatama Putra. All rights reserved.
//
import UIKit
import Domain
import Device
class GetLocationViewModel {
var agenda: String!
var longtitude: String!
var latitude: String!
let getCoordinateUseCase: GetCoordinateGPSUseCase = GetCoordinateGPSUseCase(_coordinateRepository: CoordinateRepositoryDevice())
let getRangeTwoCoordinate: GetRangeTwoCoordinateInMetersUseCase = GetRangeTwoCoordinateInMetersUseCase(_coordinateRepository: CoordinateRepositoryDevice())
func transfrom(input: String) {
let output = input.split(separator: ",")
latitude = String(output[0])
longtitude = String(output[1])
agenda = String(output[2])
}
func isInRangeLocation() -> Bool {
let currentLocation = self.getCoordinateUseCase.invoke()
let agendaQRCode = CoordinateEntity(_longtitude: Double(longtitude)!, _latitude: Double(latitude)!)
let meters = self.getRangeTwoCoordinate.invoke(_coordinate1: currentLocation, _coordinate2: agendaQRCode)
print(meters)
return meters <= 30
}
}
| true
|
41755efa9171da8e5d322c40cb8589e58cfd3a1f
|
Swift
|
mewhite/BluetoothConnect
|
/BluetoothConnect/PostureSenseDriver.swift
|
UTF-8
| 15,755
| 2.71875
| 3
|
[] |
no_license
|
//
// PostureSenseDriver.swift
// BluetoothConnect
//
// Created by Monisha White on 9/2/14.
// Copyright (c) 2014 Monisha White. All rights reserved.
//
import Foundation
import CoreBluetooth
import UIKit // just for UIDevice in error description
enum PostureSenseStatus : Printable {
case PoweredOff
case Searching
case Connecting
case SettingUp // getting services and charecteristics before LiveUpdates
case Disconnected
case LiveUpdates
case Idle // connected but not receiving LiveUpdates
case Disengaging // turning off LiveUpdates
var description: String {
switch self {
case PoweredOff: return "Bluetooth is off"
case Searching: return "Searching Devices"
case Connecting: return "Connecting to device"
case SettingUp: return "Setting up live updates"
case Disconnected: return "Disconnected from device"
case LiveUpdates: return "Live update"
case Idle: return "Idle"
case Disengaging: return "Disengaging"
}
}
}
/// Bluutooth service UUIDs
enum ServiceUUID : String
{
case GenericAccessProfile = "1800"
case DeviceInformation = "180A"
case PostureSensor = "D6E8F230-1513-11E4-8C21-0800200C9A66"
}
/// Characteristic UUIDs for Device Information service
enum DeviceCharacteristicUUID : String
{
case SystemID = "0x2A23"
case ModelName = "0x2A24"
case SerialNumber = "0x2A25"
case FirmwareRevision = "0x2A26"
case Manufacturer = "0x2A29"
}
// TODO: (YS) read these on first time pairing
/// Characteristic UUIDs for Posture Sensor service
enum PostureCharacteristicUUID : String
{
case BatteryLevel = "2A19"
case SensorOffsets = "D6E8F233-1513-11E4-8C21-0800200C9A66"
case SensorCoeffs = "D6E8F234-1513-11E4-8C21-0800200C9A66"
case AccelOffsets = "D6E8F235-1513-11E4-8C21-0800200C9A66"
case UnixTimeStamp = "D6E91942-1513-11E4-8C21-0800200C9A66"
case RealTimeControl = "D6E91940-1513-11E4-8C21-0800200C9A66"
case RealTimeData = "D6E91941-1513-11E4-8C21-0800200C9A66"
}
/// Error Domains and Codes
enum ErrorDomain: String
{
case ConnectionError = "ConnectionError"
case SetupError = "SetupError"
case RuntimeError = "RuntimeError"
}
// TODO: (YS) I think we can safely use a single error domain for everything driver-related.
enum ConnectionErrorCodes: Int
{
case ErrorCodeConnectingToPeripheral = 1
case ErrorCodeUnexpectedDisconnect = 2
case ErrorCodeDiscoveringServices = 3
case ErrorCodeDiscoveringCharacteristics = 4
case ErrorCodeUnidentifiedCentralState = 5
case ErrorCodeResettingConnection = 6
case ErrorCodeBluetoothUnsupported = 7
case ErrorCodeBluetoothUnauthorized = 8
case ErrorCodeBluetoothPoweredOff = 9
}
enum SetupErrorCodes: Int
{
case ErrorCodeUpdatingNotificationState = 1
}
enum RuntimeErrorCodes: Int
{
case ErrorCodeReceivingRealTimeData = 1
case ErrorCodeUpdatingCharacteristicValue = 2
case ErrorCodeSettingRealTimeControl = 3
case ErrorCodeWritingCharacteristicValue = 4
}
protocol PostureSenseDriverDelegate
{
func didChangeStatus(status: PostureSenseStatus)
func didReceiveData(posture: Posture)
func didReceiveBatteryLevel(level: Int) // TODO: (YS) call this when reading battery level - both on connect, and in regular intervals
func didGetError(error: NSError)
}
class PostureSenseDriver: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
{
var myCentralManager: CBCentralManager? = nil
var myPeripheral: CBPeripheral? = nil
var myRealTimeControl: CBCharacteristic? = nil
var myUnixTimeStamp: CBCharacteristic? = nil
var myDelegate: PostureSenseDriverDelegate? = nil
var myDecoder = PostureSenseDecoder()
var myStatus : PostureSenseStatus = .PoweredOff {
didSet {
myDelegate?.didChangeStatus(oldValue)
}
}
init(delegate: PostureSenseDriverDelegate)
{
myDelegate = delegate
super.init()
myCentralManager = CBCentralManager(delegate:self, queue:dispatch_queue_create(nil, nil))
}
// MARK: - CBCentralManagerDelegate Functions
func centralManagerDidUpdateState(central: CBCentralManager!)
{
var nextStatus = PostureSenseStatus.PoweredOff
var error : NSError? = nil
switch central.state {
case .PoweredOn:
nextStatus = .Searching
central.scanForPeripheralsWithServices(
[CBUUID.UUIDWithString(ServiceUUID.PostureSensor.toRaw())],
options:nil)
case .Resetting, .Unknown: // temporary states
error = nil
case .Unsupported:
error = NSError(
domain: ErrorDomain.ConnectionError.toRaw(),
code: ConnectionErrorCodes.ErrorCodeBluetoothUnsupported.toRaw(),
userInfo: [NSLocalizedDescriptionKey: "The \(UIDevice.currentDevice().model) does not support Bluetooth low energy."]
)
case .Unauthorized:
error = NSError(
domain: ErrorDomain.ConnectionError.toRaw(),
code: ConnectionErrorCodes.ErrorCodeBluetoothUnauthorized.toRaw(),
userInfo: [NSLocalizedDescriptionKey: "The app is not authorized to use Bluetooth low energy",
NSLocalizedRecoverySuggestionErrorKey : "Please go to Settings > Privacy to change that."]
)
case .PoweredOff:
error = NSError(
domain: ErrorDomain.ConnectionError.toRaw(),
code: ConnectionErrorCodes.ErrorCodeBluetoothPoweredOff.toRaw(),
userInfo: [NSLocalizedDescriptionKey: "Bluetooth is currently powered off",
NSLocalizedRecoverySuggestionErrorKey : "Please go to Settings > Bluetooth to change that."]
)
}
myStatus = nextStatus
if let err = error {
myDelegate?.didGetError(err)
}
}
func centralManager(central: CBCentralManager!,
didDiscoverPeripheral peripheral: CBPeripheral!,
advertisementData: [NSObject : AnyObject]!,
RSSI: NSNumber!)
{
// TODO: (YS) ensure this is a PostureSense device by checking peripheral.name
central.stopScan()
self.myPeripheral = peripheral
// TODO: (YS) maybe should set self as delegate here? self.myPeripheral.delegate = self
myCentralManager!.connectPeripheral(peripheral, options: nil)
myStatus = .Connecting
// TODO: (YS) save the peripheral.identifier if this is the first time, and check against it in future activations - can use NSUserDefaults
}
func centralManager(central: CBCentralManager!,
didConnectPeripheral peripheral: CBPeripheral!)
{
peripheral.delegate = self
//TODO: specify which services to discover - not nil?
// TODO: (YS) in the first time, we need "Device Information" to decide which device to pair with. Afetr that we only need "Posture Sensor"
// todo: QUESTION (MW) we don't need the Generic Access Profile? Is the local name not the identifier for which posture sensor it is?
// (YS) Right, the generic access is standard, and we don't need to query it here.
peripheral.discoverServices(nil)
myStatus = .SettingUp // WORKAROUND: state not actually changed until next call!
myStatus = .SettingUp
}
func centralManager(central: CBCentralManager!,
didFailToConnectPeripheral peripheral: CBPeripheral!,
error: NSError!)
{
myDelegate?.didGetError(NSError(domain: ErrorDomain.ConnectionError.toRaw(), code: ConnectionErrorCodes.ErrorCodeConnectingToPeripheral.toRaw(), userInfo: error?.userInfo))
}
//TODO: Implement this function in case it find many sensors. OR implement didDiscover peripheral to check that it's the correct one.
// TODO: (YS) if this is the first time (no paired device yet) then we probably want this, since it gets called after all peripherals were discovered, not just the first. (I think...)
func centralManager(central: CBCentralManager!,
didRetrievePeripherals peripherals: [AnyObject]!)
{
//println("didRetrievePeripherals")
}
// MARK: - CBPeripheralDelegate Functions
func peripheral(peripheral: CBPeripheral!,
didDiscoverServices error: NSError!)
{
if let err = error {
myDelegate?.didGetError(error)
return
}
for service in peripheral.services as [CBService] {
peripheral.discoverCharacteristics(nil, forService: service)
}
}
func peripheral(peripheral: CBPeripheral!,
didDiscoverCharacteristicsForService service: CBService!,
error: NSError!)
{
if let err = error {
myDelegate?.didGetError(error)
return
}
if let serviceUUID = ServiceUUID.fromRaw(service.UUID.UUIDString)
{
switch serviceUUID {
case .GenericAccessProfile:
return
case .DeviceInformation:
setupDeviceInformation(peripheral, service: service)
case .PostureSensor:
setupPostureSensor(peripheral, service: service)
}
}
}
func setupPostureSensor(peripheral: CBPeripheral!, service: CBService!)
{
for characteristic in service.characteristics as [CBCharacteristic]
{
if let UUID = PostureCharacteristicUUID.fromRaw(characteristic.UUID.UUIDString)
{
switch UUID {
case .UnixTimeStamp: // save for writing into this characteristic
myUnixTimeStamp = characteristic
case .RealTimeControl: // save for writing into this characteristic
myRealTimeControl = characteristic
case .RealTimeData:
peripheral.setNotifyValue(true, forCharacteristic: characteristic)
default:
peripheral.readValueForCharacteristic(characteristic)
}
}
}
}
func setupDeviceInformation(peripheral: CBPeripheral!, service: CBService!)
{
for characteristic in service.characteristics as [CBCharacteristic]
{
if let UUID = DeviceCharacteristicUUID.fromRaw(characteristic.UUID.UUIDString)
{
switch UUID {
case .SystemID:
return
case .ModelName:
return
case .SerialNumber:
return
case .FirmwareRevision:
return
case .Manufacturer:
return
default: return
}
// TODO: (YS) pass the characteristic.data to the decoder and/or the delegate
}
}
}
func peripheral(peripheral: CBPeripheral!,
didUpdateValueForCharacteristic characteristic: CBCharacteristic!,
error: NSError!)
{
if let err = error {
myDelegate?.didGetError(error)
return
}
// TODO: (YS) switch(characteristic.service) and check DeviceCharacteristicUUID
if let UUID = PostureCharacteristicUUID.fromRaw(characteristic.UUID.UUIDString)
{
let data = characteristic.value
switch UUID {
case .BatteryLevel:
let level = myDecoder.decodeBatteryLevel(data)
myDelegate?.didReceiveBatteryLevel(level)
case .SensorOffsets:
myDecoder.setSensorOffsets(data)
case .SensorCoeffs:
myDecoder.setSensorCoefficients(data)
case .AccelOffsets:
myDecoder.setAccelerometerOffsets(data)
case .RealTimeData:
let posture = myDecoder.decodeRealTimeData(data)
myDelegate?.didReceiveData(posture)
default:
trace("Received Unexpected Posture Characteristic: \(UUID.toRaw())")
}
}
}
func turnOnRealTimeControl(peripheral: CBPeripheral!)
{
// TODO: (YS) ensure peripheral is not nil and is connected
var onByte = [UInt8] (count: 1, repeatedValue: 1)
let RealTimeControl_ON = NSData(bytes: &onByte, length: 1)
peripheral.writeValue(RealTimeControl_ON, forCharacteristic: myRealTimeControl, type: CBCharacteristicWriteType.WithResponse)
myStatus = .LiveUpdates
}
//Real Time Control turned off to stop receiving data from sensor.
// Notification State remains on, but no data is communicated because real time control is off.
func turnOffRealTimeControl(peripheral: CBPeripheral!)
{
// TODO: (YS) ensure peripheral is not nil and is connected
var offByte = [UInt8] (count: 1, repeatedValue: 0)
let RealTimeControl_OFF = NSData(bytes: &offByte, length: 1)
peripheral.writeValue(RealTimeControl_OFF, forCharacteristic: myRealTimeControl, type: CBCharacteristicWriteType.WithResponse)
}
//Only purpose of this function is for error checking
func peripheral(peripheral: CBPeripheral!,
didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic!,
error: NSError!)
{
if let err = error {
myDelegate?.didGetError(NSError(
domain: ErrorDomain.SetupError.toRaw(),
code: SetupErrorCodes.ErrorCodeUpdatingNotificationState.toRaw(),
userInfo: err.userInfo))
trace("Error changing notification state: \(err)")
}
}
func peripheral(peripheral: CBPeripheral!,
didWriteValueForCharacteristic characteristic: CBCharacteristic!,
error: NSError!)
{
if let err = error { // TODO: (YS) Should probably say "can't subscribe/unsucscribe to live updates" or something like that
myDelegate?.didGetError(NSError(domain: ErrorDomain.RuntimeError.toRaw(), code: RuntimeErrorCodes.ErrorCodeWritingCharacteristicValue.toRaw(), userInfo: err.userInfo))
}
else if myStatus == .Disengaging {
myStatus = .Idle
}
}
func disengagePostureSense()
{
myStatus = .Disengaging
turnOffRealTimeControl(myPeripheral)
}
func engagePostureSense()
{
turnOnRealTimeControl(myPeripheral)
}
//TODO: make a button to explicitly connect/search, not automatically
func connectToPostureSensor()
{
myCentralManager?.scanForPeripheralsWithServices(
[CBUUID.UUIDWithString(ServiceUUID.PostureSensor.toRaw())],
options:nil)
myStatus = .Searching
}
func disconnectFromPostureSensor()
{
myCentralManager?.cancelPeripheralConnection(myPeripheral)
}
func centralManager(central: CBCentralManager!,
didDisconnectPeripheral peripheral: CBPeripheral!,
error: NSError!)
{
if let err = error {
myDelegate?.didGetError(NSError(
domain: ErrorDomain.ConnectionError.toRaw(),
code: ConnectionErrorCodes.ErrorCodeUnexpectedDisconnect.toRaw(),
userInfo: err.userInfo))
}
else {
myStatus = .Disconnected
}
}
}
| true
|
189779f5553fa48795e42d70aed1822af8a0edbe
|
Swift
|
Eminhayal/TheRickandMortyApp
|
/TheRickandMortyApp/UI/Location/LocationTableView.swift
|
UTF-8
| 1,547
| 2.875
| 3
|
[] |
no_license
|
//
// LocationTableView.swift
// TheRickandMortyApp
//
// Created by Emin Hayal on 18.09.2021.
//
import UIKit
protocol LocationTableViewProtocol {
func update( items : [LocationResult] )
}
protocol LocationTableViewOutput : AnyObject {
func onSelect( item : LocationResult )
func getNewDatas()
}
final class LocationTableView: NSObject , UITableViewDelegate , UITableViewDataSource {
private lazy var items : [LocationResult] = []
weak var delegate: LocationTableViewOutput?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: LocationTableViewCell.identifier, for: indexPath) as! LocationTableViewCell
cell.configureLocationData(data: items[indexPath.row])
if (Double(indexPath.row) * 100) / (100 * Double(items.count)) > 0.8 {
delegate?.getNewDatas()
}
return cell //MyTableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.onSelect(item: items[indexPath.row])
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
extension LocationTableView : LocationTableViewProtocol{
func update(items: [LocationResult]) {
self.items = items
}
}
| true
|
a1079336f09598d6a45fa90fdd0170f8a351d063
|
Swift
|
vedem1192/polyPaint
|
/clientLegerSwift/DrawingPage/SettingDrawing/SettingDrawingSetter.swift
|
UTF-8
| 1,488
| 2.828125
| 3
|
[] |
no_license
|
//
// SettingDrawingSetter.swift
// clientLegerSwift
//
// Created by lea el hage on 2018-03-25.
// Copyright © 2018 log3900. All rights reserved.
//
import Foundation
class SettingDrawingSetter {
var needsSetting = true
var drawingMode = true
static let instance = SettingDrawingSetter()
let username = NetworkManager.instance.username
var password = ""
var passConf = ""
var visibility : Bool = true
var protected : Bool = true
var title : String = ""
var type : Int = 0
func passConfirmation() -> Bool {
if password == passConf && password != nil && passConf != nil {
return true
}
return false
}
func confirmSetting() -> Bool{
var confirmed = false
if !title.isEmpty {
if protected == false {
confirmed = true
}
else if protected && passConfirmation() {
confirmed = true
}
}
print(confirmed)
return confirmed
}
func checkOwner() -> Bool {
//verifies if allowed to change setting if owner
//only changes public, protected , passwords
return true
}
func createDrawing() {
//add mode
let drawing = DrawingObject(creator: username, title: title, visibility: visibility, password: password, drawingMode: drawingMode)
drawingManager.saveAsNewDrawing(newDrawing: drawing)
}
}
| true
|
08c5472b89f9285563ae55fce710a61e2121132c
|
Swift
|
bloodox/JWELLCFRAMER
|
/JWELLCFramer/SlideRevealViewController.swift
|
UTF-8
| 76,849
| 2.671875
| 3
|
[] |
no_license
|
//
// SlideRevealViewController.swift
//
// Created by William Thompson on 9/23/18.
// Copyright © 2018 William Thompson. 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.
Inspired by Joan Lluch's SWRevealViewController class
version 1.0
- Release notes
- Supports sliding the front view controller left or right to expose view controllers beneath
- Supports iOS 9.0 and later
- If SlideRevealViewControllerDelegate is implemented all transitions must be re created in delegate methods
*/
//
//
//
//
//TODO: Add more comments
import UIKit
import QuartzCore
import UIKit.UIGestureRecognizerSubclass
// MARK: - ViewPosition Enum
/*
Constants to hold the view position of the front view controller exposing view controllers beneath
*/
@objc public enum ViewPosition: Int {
case none = 0
case leftSideMostRemoved = 1
case leftSideMost = 2
case leftSide = 3
case left = 4
case right = 5
case rightMost = 6
case rightSideMostRemoved = 7
}
// MARK: - SlideRevealViewOperation Enum
/*
Constants to hold the current operation
*/
@objc enum SlideRevealViewOperation: Int {
case none = 0
case replaceLeftController = 1
case replaceFrontController = 2
case replaceRightController = 3
}
// MARK: - Animation type
@objc enum SlideRevealAnimationType: Int {
case spring
case easeout
}
@objc enum SlideRevealViewLocation: Int {
case above
case beneath
}
// MARK: - SlideRevealViewBlurEffect Enum
/*
Constants to hold the selected blur effect of the left and right view controller when exposed above the front(main) view controller
*/
@objc enum SlideRevealViewBlurEffect: Int {
case none = -1
case lightest
case light
case dark
}
// MARK: - SlideRevealViewControllerDelegate
@objc protocol SlideRevealViewControllerDelegate: NSObjectProtocol {
// All methods are optional. Delegate use is optional.
// The following delegate methods will be called before and after the front view moves to a position.
@objc optional func revealController(_ revealController: SlideRevealViewController, willMoveTo position: ViewPosition)
/*
Called right before the front(main) view controller moves to a new position to expose view controllers beneath
used mostly as a notification method.
-Parameters:
-revealController: The reveal view controller object typically passed as self
-position: The ViewPosition constant for the front(main) view controller to move to
*/
@objc optional func revealController(_ revealController: SlideRevealViewController, didMoveTo position: ViewPosition)
/*
Called after the front(main) view controller moved to a new position to expose view controllers beneath, used mostly as a notifcation method
-Parameters:
-revealController: The reveal controller object typically passed as self
-position: The ViewPosition constant for the front(main) view controller to move to
*/
// This will be called inside the reveal animation, thus you can use it to place your own code that will be animated in sync.
@objc optional func revealController(_ revealController: SlideRevealViewController, animateTo position: ViewPosition)
// Implement the following methods to return false when you want the gesture recognizers to be ignored.
@objc optional func panGestureRecognizerShouldBegin(_ revealController: SlideRevealViewController) -> Bool
@objc optional func tapGestureRecognizerShouldBegin(_ revealController: SlideRevealViewController) -> Bool
// Implement the following methods to return true if you want other gesture recognizer to share events with tap and pan gesture.
@objc optional func panGestureRecognizesSimutaneouslyWith(_ otherGesture: UIGestureRecognizer, revealController: SlideRevealViewController) -> Bool
@objc optional func tapGestureRecognizesSimutaneouslyWith(_ otherGesture: UIGestureRecognizer, revealController: SlideRevealViewController) -> Bool
// Notification methods called when the pan gesture begins and ends.
@objc optional func panGestureBegan(_ revealController: SlideRevealViewController?)
@objc optional func panGestureEnded(_ revealController: SlideRevealViewController?)
// The following methods provide a means to track the evolution of the gesture recognizer.
// The 'location' parameter is the X origin coordinate of the front view as the user drags it
// The 'progress' parameter is a number ranging from 0 to 1 indicating the front view location relative to the
// leftRevealWidth or rightRevealWidth. 1 is fully revealed, dragging ocurring in the overDraw region will result in values above 1.
// The 'overProgress' parameter is a number ranging from 0 to 1 indicating the front view location relative to the
// overdraw region. 0 is fully revealed, 1 is fully overdrawn. Negative values occur inside the normal reveal region
@objc optional func revealController(_ revealController: SlideRevealViewController, panGestureBeganFromLocation location: CGFloat, progress: CGFloat, overProgress: CGFloat)
@objc optional func revealController(_ revealController: SlideRevealViewController, panGestureMovedToLocation location: CGFloat, progress: CGFloat, overProgress: CGFloat)
@objc optional func revealController(_ revealController: SlideRevealViewController, panGestureEndedToLocation location: CGFloat, progress: CGFloat, overProgress: CGFloat)
// Notification methods called for child view controller replacement.
@objc optional func revealController(_ revealController: SlideRevealViewController, willAdd viewController: UIViewController?, forOperation: SlideRevealViewOperation, animated: Bool)
@objc optional func revealController(_ revealController: SlideRevealViewController, didAdd viewController: UIViewController?, forOperation: SlideRevealViewOperation, animated: Bool)
// Support for custom transition animations while replacing child view controllers. If Implemented, it will be called in response to calls to "setXXXXViewController" methods.
@objc optional func revealController(_ revealController: SlideRevealViewController, animationControllerFor operation: SlideRevealViewOperation, from fromVC: UIViewController?, to toVC: UIViewController?) -> UIViewControllerAnimatedTransitioning?
}
//MARK: StatusBar helper function
// computes the required offset adjustment due to the status bar for the passed in view,
// it will return the statusBar height if view fully overlaps the statusBar, otherwise returns 0.0
public func statusBarAdjustment(_ view: UIView) -> CGFloat {
var adjustment: CGFloat = 0.0
let app = UIApplication.shared
let viewFrame = view.convert(view.bounds, to: app.keyWindow)
let statusBarFrame = app.statusBarFrame
if viewFrame.intersects(statusBarFrame) {
adjustment = CGFloat(fminf(Float(statusBarFrame.size.width), Float(statusBarFrame.size.height)))
}
return adjustment
}
// MARK: - SlideRevealView class
class SlideRevealView: UIView {
weak var revealViewController: SlideRevealViewController!
private(set) var leftView: UIView?
private(set) var rightView: UIView?
private(set) var frontView: UIView?
var disableLayout = false
static func scaledValue(v1: CGFloat, min2: CGFloat, max2: CGFloat, min1: CGFloat, max1: CGFloat) -> CGFloat {
let result: CGFloat = min2 + (v1 - min1) * ((max2 - min2) / (max1 - min1))
if result != result {
return min2
}
if result < min2 {
return min2
}
if result > max2 {
return max2
}
return result
}
init(frame: CGRect, controller: SlideRevealViewController) {
super.init(frame: frame)
revealViewController = controller
let bounds: CGRect = self.bounds
frontView = UIView(frame: bounds)
frontView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
reloadShadow()
self.addSubview(self.frontView!)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func reloadShadow() {
let frontViewLayer: CALayer? = frontView?.layer
frontViewLayer?.shadowColor = revealViewController.frontViewShadowColor.cgColor
frontViewLayer?.shadowOpacity = Float(revealViewController.frontViewShadowOpacity)
frontViewLayer?.shadowOffset = revealViewController.frontViewShadowOffset
frontViewLayer?.shadowRadius = revealViewController.frontViewShadowRadius
}
func hierarchycalFrameAdjustment(_ frame: CGRect) -> CGRect {
var frame = frame
if revealViewController.isPresentFrontViewHierarchically {
let dummyBar = UINavigationBar()
let barHeight = dummyBar.sizeThatFits(CGSize(width: CGFloat(100), height: CGFloat(100))).height
let offset: CGFloat = barHeight + statusBarAdjustment(self)
frame.origin.y += offset
frame.size.height -= offset
}
return frame
}
func prepareLeftView(for newPosition: ViewPosition) {
if leftView == nil {
leftView = UIView(frame: bounds)
leftView?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
insertSubview(leftView!, belowSubview: frontView!)
}
let xLocation = frontLocation(for: revealViewController.frontViewPosition!)
layoutRearViews(for: xLocation)
prepareFor(newPosition: newPosition)
}
func prepareRightView(for newPosition: ViewPosition) {
//TODO: work on the presenting above front view
if rightView == nil {
rightView = UIView(frame: bounds)
rightView?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
insertSubview(rightView!, belowSubview: frontView!)
}
let xLocation = frontLocation(for: revealViewController.frontViewPosition!)
layoutRearViews(for: xLocation)
prepareFor(newPosition: newPosition)
}
func unloadLeftView() {
leftView?.removeFromSuperview()
leftView = nil
}
func unloadRightView() {
rightView?.removeFromSuperview()
rightView = nil
}
func frontLocation(for viewPosition: ViewPosition) -> CGFloat {
var revealWidth: CGFloat = 0.0
var revealOverdraw: CGFloat = 0.0
var location: CGFloat = 0.0
var frontViewPosition = viewPosition
let symetry: Int = frontViewPosition.rawValue < ViewPosition.left.rawValue ? -1 : 1
revealViewController.getRevealWidth(revealWidth: &revealWidth, revealOverdraw: &revealOverdraw, symetry: symetry)
revealViewController.getAdjusted(frontViewPosition: &frontViewPosition, symetry: symetry)
if frontViewPosition == .right {
location = revealWidth
} else if frontViewPosition.rawValue > ViewPosition.right.rawValue {
location = revealWidth + revealOverdraw
}
return location * CGFloat(symetry)
}
func dragFrontViewTo(xLocation: CGFloat) {
let bounds = self.bounds
var xLocation = xLocation
xLocation = adjustedDragLocation(location: xLocation)
layoutRearViews(for: xLocation)
let frame = CGRect(x: xLocation, y: CGFloat(0.0), width: bounds.size.width, height: bounds.size.height)
frontView?.frame = hierarchycalFrameAdjustment(frame)
}
func dragLeftViewTo(xLocation: CGFloat) {
let bounds = self.bounds
var xLocation = xLocation
xLocation = adjustedLeftDragLocation(location: -xLocation)
layoutRearViews(for: xLocation)
let frame = CGRect(x: xLocation, y: 0.0, width: bounds.size.width, height: bounds.size.height)
print(xLocation)
leftView?.frame = hierarchycalFrameAdjustment(frame)
}
//MARK: - Overrides
override func layoutSubviews() {
if disableLayout {
return
}
let bounds = self.bounds
let position = revealViewController.frontViewPosition
let location = frontLocation(for: position!)
layoutRearViews(for: location)
let frame = CGRect(x: location, y: 0.0, width: bounds.size.width, height: bounds.size.height)
frontView?.frame = hierarchycalFrameAdjustment(frame)
let frontViewController = revealViewController.frontViewController
let viewLoaded = frontViewController != nil && (frontViewController?.isViewLoaded)!
let viewNotRemoved = (position?.rawValue)! > ViewPosition.leftSideMostRemoved.rawValue && (position?.rawValue)! < ViewPosition.rightSideMostRemoved.rawValue
let shadowBounds = viewLoaded && viewNotRemoved ? frontView?.bounds : CGRect.zero
let shadowPath = UIBezierPath(rect: shadowBounds!)
frontView?.layer.shadowPath = shadowPath.cgPath
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
var isInside = super.point(inside: point, with: event)
if !isInside && revealViewController.isExtendsPointInsideHit {
let testViews = [leftView, rightView, frontView]
let testControllers = [revealViewController.leftViewController!, revealViewController.frontViewController!, revealViewController.rightViewController!]
for i in 0..<3 {
if testViews[i] != nil && testControllers[i].isViewLoaded {
let pt = convert(point, to: testViews[i])
isInside = (testViews[i]?.point(inside: pt, with: event))!
}
}
}
return isInside
}
func pointInside(point: CGPoint, with event: UIEvent?) -> Bool {
var isInside = super.point(inside: point, with: event)
if revealViewController.isExtendsPointInsideHit {
if !isInside && leftView != nil && (revealViewController.leftViewController?.isViewLoaded)! {
let pt = convert(point, to: leftView)
isInside = (leftView?.point(inside: pt, with: event))!
}
if !isInside && frontView != nil && (revealViewController.frontViewController?.isViewLoaded)! {
let pt = convert(point, to: frontView)
isInside = (frontView?.point(inside: pt, with: event))!
}
if !isInside && rightView != nil && (revealViewController.rightViewController?.isViewLoaded)! {
let pt = convert(point, to: rightView)
isInside = (rightView?.point(inside: pt, with: event))!
}
}
return isInside
}
//MARK: - Private Methods
private func layoutRearViews(for location: CGFloat) {
let bounds = self.bounds
var leftRevealWidth = revealViewController.leftViewRevealWidth
if leftRevealWidth < 0 {
leftRevealWidth = bounds.size.width + revealViewController.leftViewRevealWidth
}
let leftXLocation: CGFloat = SlideRevealView.scaledValue(v1: location, min2: -revealViewController.leftViewRevealDisplacement, max2: 0, min1: 0, max1: leftRevealWidth)
let leftWidth = leftRevealWidth + revealViewController.leftViewRevealOverdraw
leftView?.frame = CGRect(x: leftXLocation, y: 0.0, width: leftWidth, height: bounds.size.height)
var rightRevealWidth = revealViewController.rightViewRevealWidth
if rightRevealWidth < 0 {
rightRevealWidth = bounds.size.width + revealViewController.rightViewRevealWidth
}
let rightXLocation = SlideRevealView.scaledValue(v1: location, min2: 0, max2: revealViewController.rightViewRevealDisplacement, min1: -rightRevealWidth, max1: 0)
let rightWidth = (rightRevealWidth + revealViewController.rightViewRevealOverdraw)
rightView?.frame = CGRect(x: (bounds.size.width - rightWidth + rightXLocation), y: 0.0, width: rightWidth, height: bounds.size.height)
}
private func prepareFor(newPosition: ViewPosition) {
if leftView == nil || rightView == nil {
return
}
let symetry: Int = newPosition.rawValue < ViewPosition.left.rawValue ? -1 : 1
let subViews: [UIView] = self.subviews
let leftIndex: Int = subViews.firstIndex(of: leftView!)!
let rightIndex: Int = subViews.firstIndex(of: rightView!)!
if ((symetry < 0 && rightIndex < leftIndex) || (symetry > 0 && leftIndex < rightIndex)) {
exchangeSubview(at: rightIndex, withSubviewAt: leftIndex)
}
}
private func adjustedDragLocation(location: CGFloat) -> CGFloat {
var result: CGFloat = 0.0
var revealWidth: CGFloat = 0.0
var revealOverdraw: CGFloat = 0.0
var bouncesBack = false
var stableDrag = false
let position = revealViewController.frontViewPosition
let symetry: Int = location < 0 ? -1 : 1
revealViewController.getRevealWidth(revealWidth: &revealWidth, revealOverdraw: &revealOverdraw, symetry: symetry)
revealViewController.getBounceBack(bounceBack: &bouncesBack, stableDrag: &stableDrag, symetry: symetry)
if !bouncesBack || stableDrag || position == ViewPosition.rightSideMostRemoved || position == ViewPosition.leftSideMost {
revealWidth += revealOverdraw
revealOverdraw = 0.0
}
let x = (location * CGFloat(symetry))
if x <= revealWidth {
result = x
}
else if (x <= revealWidth + 2 * revealOverdraw) {
result = (revealWidth + (x - revealWidth) / 2)
}
else {
result = revealWidth + revealOverdraw
}
return result * CGFloat(symetry)
}
private func adjustedLeftDragLocation(location: CGFloat) -> CGFloat {
var result: CGFloat = 0.0
var revealWidth: CGFloat = 0.0
var revealOverdraw: CGFloat = 0.0
var bouncesBack = false
var stableDrag = false
let position = revealViewController.frontViewPosition
let symetry: Int = location < 0 ? -1 : 1
revealViewController.getRevealWidth(revealWidth: &revealWidth, revealOverdraw: &revealOverdraw, symetry: symetry)
revealViewController.getBounceBack(bounceBack: &bouncesBack, stableDrag: &stableDrag, symetry: symetry)
if !bouncesBack || stableDrag || position == ViewPosition.rightSideMostRemoved || position == ViewPosition.leftSideMost {
revealWidth += revealOverdraw
revealOverdraw = 0.0
}
let x = (location * CGFloat(symetry))
if x <= revealWidth {
result = x
}
else if (x <= revealWidth + 2 * revealOverdraw) {
result = (revealWidth + (x - revealWidth) / -2)
}
else {
result = revealWidth + revealOverdraw
}
return result * CGFloat(symetry)
}
}
// MARK: - SlideRevealContextTransitioningObject class
private class SlideRevealContextTransitioningObject: NSObject, UIViewControllerContextTransitioning {
weak internal var revealVC : SlideRevealViewController?
internal var view: UIView?
internal var toVC: UIViewController?
internal var fromVC: UIViewController?
internal var completion: (() -> Void)?
init(revealController revealVC: SlideRevealViewController, containerView view: UIView?, fromVC: UIViewController?, toVC: UIViewController?, completion: @escaping () -> Void) {
self.revealVC = revealVC
self.view = view
self.toVC = toVC
self.fromVC = fromVC
self.completion = completion
super.init()
}
var containerView: UIView {
return view!
}
var isAnimated: Bool {
return true
}
var isInteractive: Bool {
return false
}
var transitionWasCancelled: Bool{
return false
}
var presentationStyle: UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
func updateInteractiveTransition(_ percentComplete: CGFloat) {
//Not supported
}
func finishInteractiveTransition() {
//Not supported
}
func cancelInteractiveTransition() {
//Not supported
}
func pauseInteractiveTransition() {
//Not supported
}
func completeTransition(_ didComplete: Bool) {
completion!()
}
func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? {
switch key {
case .from:
return fromVC
case .to:
return toVC
default:
return nil
}
}
func view(forKey key: UITransitionContextViewKey) -> UIView? {
return nil
}
var targetTransform: CGAffineTransform {
return CGAffineTransform.identity
}
func initialFrame(for vc: UIViewController) -> CGRect {
return view!.bounds
}
func finalFrame(for vc: UIViewController) -> CGRect {
return view!.bounds
}
}
// MARK: - SlideRevealAnimationController class
class SlideRevealAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
var duration: TimeInterval
init(with duration: TimeInterval) {
self.duration = duration
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: .from)
let toViewController = transitionContext.viewController(forKey: .to)
if fromViewController != nil {
UIView.transition(from: (fromViewController?.view)!, to: (toViewController?.view)!, duration: duration, options: [.transitionCrossDissolve, .overrideInheritedOptions], completion: {(_ finished: Bool) -> Void in
transitionContext.completeTransition(finished)
})
} else {
let toView = toViewController?.view
let alpha = toView?.alpha
toView?.alpha = 0
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseOut], animations: {() -> Void in
toView?.alpha = alpha!
}, completion: {(_ finshed: Bool) -> Void in
transitionContext.completeTransition(finshed)
})
}
}
}
// MARK: - SlideRevealPanGestureRecognizer class
class SlideRevealPanGestureRecognizer: UIPanGestureRecognizer {
var dragging = false
var beginPoint = CGPoint.zero
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
let touch = touches.first
beginPoint = (touch?.location(in: view))!
dragging = false
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if dragging || state == .failed {
return
}
let kDirectionPanThreshold: CGFloat = 5.0
let touch = touches.first
let nowPoint = touch?.location(in: view)
if (abs((nowPoint?.x)! - (beginPoint.x)) > kDirectionPanThreshold) {
dragging = true
} else if abs((nowPoint?.y)! - beginPoint.y) > kDirectionPanThreshold {
state = .failed
}
}
}
// MARK: - SlideRevealViewController class
open class SlideRevealViewController: UIViewController, UIGestureRecognizerDelegate, UIViewControllerRestoration
{
//MARK: Properties
//UIViewController instance variables for holding values of each view controller
var leftViewController: UIViewController?
var rightViewController: UIViewController?
var frontViewController: UIViewController?
//Defines the width of the left when shown default is 260.0
var leftViewRevealWidth: CGFloat = 260.0
//defines the width of the right view when shown default is 260.0
var rightViewRevealWidth: CGFloat = 260.0
//Defines how much overdraw can occur when sliding further than leftViewRevealWidth default is 60.0
var leftViewRevealOverdraw: CGFloat = 60.0
//Defines how much overdraw can occur when sliding further than leftViewRevealWidth default is 60.0
var rightViewRevealOverdraw: CGFloat = 60.0
//Defines how much displacement is applied to the left view when animating or dragging the front view
//default is 40.0
var leftViewRevealDisplacement: CGFloat = 40.0
//Defines how much displacement is applied to the right view when animating or dragging the front view
//default is 40.0
var rightViewRevealDisplacement: CGFloat = 40.0
//Boolean value to determine if the front view should close if pulled open passed the
//leftViewRevealOverdraw default is true
var bounceBackOnOverdraw: Bool = true
//Boolean value to determine if the front view should close if pulled open passed the
//rightViewRevealOverdraw default is true
var bounceBackOnLeftOverdraw: Bool = true
//Boolean value to determine if the front view should be able to be stable if dragged passed the
//leftViewRevealOverdraw default is false
var stableDragOnOverdraw: Bool = false
//Boolean value to determine if the front view should be able to be stable if dragged passed the
//rightViewRevealOverdraw default is false
var stableDragOnLeftOverdraw: Bool = false
//Defines the draggable border width default is 0.0
var draggableBorderWidth: CGFloat = 0.0
//Default is false if true the view controller will be offset vertically by the height of the navigation
//bar
var isPresentFrontViewHierarchically: Bool = false
//Velocity required in a pan direction to toggle a view controller default is 250.0
var quickFlickVelocity: CGFloat = 250.0
//Duration for animated view controller replacement using the toggle methods default is 0.3
var toggleAnimationDuration: TimeInterval = 0.3
//Type of animation for view controller replacement default is spring
var toggleAnimationType = SlideRevealAnimationType.spring
//Defines the damping ratio of the spring animation default is 1.0
var springDampingRatio: CGFloat = 1.0
//Duration for animated view controller replacement default is 0.25
var replaceViewAnimationDuration: TimeInterval = 0.25
//Defines the radius of the front view controller's shadow, default is 2.5.
var frontViewShadowRadius: CGFloat = 2.5
//Defines the front view controller's shadow offset, default is {0.0, 2.5}.
var frontViewShadowOffset = CGSize(width: CGFloat(0.0), height: CGFloat(2.5))
//Defines the front view controller's shadow opacity, default is 1.0.
var frontViewShadowOpacity: CGFloat = 1.0
//Defines the front view controller's shadow color, default is black.
var frontViewShadowColor: UIColor = .black
//Boolean value to determine if subviews are clipped to the bounds of the screen default is false
var isClipsViewsToBounds: Bool = false
//Boolean value to determine if extends point inside the view is hit default is true
var isExtendsPointInsideHit: Bool = false
//Instance of UIPanGestureRecognizer used to reveal views
var panGestureRecognizer: UIPanGestureRecognizer?
//Instance of UITapGestureRecognizer used to hide views
var tapGestureRecognizer: UITapGestureRecognizer?
//Insatnce of the SlideRevealViewControllerDelegate
weak var delegate: SlideRevealViewControllerDelegate?
//Instance of view position used to hold the front view position
var frontViewPosition: ViewPosition? = .left
//Instance of view position used to hold the right view position
var rightViewPosition: ViewPosition? = .left
//Instance of view position used to hold the left view position
var leftViewPosition: ViewPosition? = .left
//The initial front position used in pan gesture based reveals
var panInitialFrontPosition: ViewPosition?
//Instance of the SlideRevealView class
private var contentView: SlideRevealView?
//Boolean value used to hold the state of user interaction enabled vs disabled default is true during
//initilization and changes during pan gestures
private var userInteractionStore: Bool = true
//Animation queue array used to hold any animations in queue
var animationQueue = [Any]()
//MARK: - Initialization
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initDefaultProperties()
}
convenience init() {
self.init(with: nil, frontViewController: nil)
}
init(with rearViewController: UIViewController?, frontViewController: UIViewController?) {
super.init(nibName: nil, bundle: nil)
initDefaultProperties()
performTransitionOperation(SlideRevealViewOperation.replaceLeftController, with: rearViewController, animated: false)
performTransitionOperation(SlideRevealViewOperation.replaceFrontController, with: frontViewController, animated: false)
}
func initDefaultProperties() {
frontViewPosition = .left
leftViewPosition = .left
rightViewPosition = .left
leftViewRevealWidth = 260.0
leftViewRevealOverdraw = 60.0
leftViewRevealDisplacement = 40.0
rightViewRevealWidth = 260.0
rightViewRevealOverdraw = 60.0
rightViewRevealDisplacement = 40.0
bounceBackOnOverdraw = true
bounceBackOnLeftOverdraw = true
stableDragOnOverdraw = false
stableDragOnLeftOverdraw = false
isPresentFrontViewHierarchically = false
quickFlickVelocity = 250.0
toggleAnimationDuration = 0.3
toggleAnimationType = .spring
springDampingRatio = 1
replaceViewAnimationDuration = 0.25
frontViewShadowRadius = 2.5
frontViewShadowOffset = CGSize(width: CGFloat(0.0), height: CGFloat(2.5))
frontViewShadowOpacity = 1.0
frontViewShadowColor = UIColor.black
userInteractionStore = true
animationQueue = [Any]()
draggableBorderWidth = 0.0
isClipsViewsToBounds = false
isExtendsPointInsideHit = false
}
//MARK: - StatusBar
func childViewControllerForStatusBarStyles() -> UIViewController {
let positionDif = (frontViewPosition?.rawValue)! - ViewPosition.left.rawValue
var controller: UIViewController = frontViewController!
if positionDif > 0 {
controller = leftViewController!
return controller
} else if positionDif < 0 {
controller = rightViewController!
return controller
}
return controller
}
func childViewControllerForStatusBarHidden() -> UIViewController {
let controller = childViewControllerForStatusBarStyles()
return controller
}
//MARK: - View life cycle
override open func loadView() {
loadStoryboardControllers()
let frame = UIScreen.main.bounds
contentView = SlideRevealView(frame: frame, controller: self)
contentView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView?.clipsToBounds = isClipsViewsToBounds
self.view = contentView
contentView?.addGestureRecognizer(_panGestureRecognizer)
contentView?.frontView?.addGestureRecognizer(_tapGestureRecognizer)
contentView?.backgroundColor = UIColor.black
let initialPosition: ViewPosition = frontViewPosition!
frontViewPosition = ViewPosition.none
leftViewPosition = ViewPosition.none
rightViewPosition = ViewPosition.none
setFrontViewPosition(newPosition: initialPosition, with: 0.0)
}
override open func viewDidLoad() {
print("called viewDidLoad")
panGestureRecognizer = _panGestureRecognizer
tapGestureRecognizer = _tapGestureRecognizer
super.viewDidLoad()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
userInteractionStore = (contentView?.isUserInteractionEnabled)!
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return super.supportedInterfaceOrientations
}
func setUpGestureRecognizers() {
var tapGestureRecognizer: UITapGestureRecognizer? {
let tapGestureRecognizer: UITapGestureRecognizer? = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(recognizer:)))
tapGestureRecognizer?.delegate = self
contentView?.frontView?.addGestureRecognizer(tapGestureRecognizer!)
return tapGestureRecognizer
}
self.tapGestureRecognizer = tapGestureRecognizer
panGestureRecognizer = SlideRevealPanGestureRecognizer(target: self, action: #selector(handleRevealGesture(recognizer:)))
panGestureRecognizer!.delegate = self
contentView?.frontView?.addGestureRecognizer(panGestureRecognizer!)
}
//MARK: - Public methods and property accessors
public func setFront(viewController: UIViewController?) {
setFront(viewController: viewController, animated: false)
}
public func setFront(viewController: UIViewController?, animated: Bool) {
if !self.isViewLoaded {
print("isViewLoaded = false")
performTransitionOperation(.replaceFrontController, with: viewController, animated: false)
return
}
print("isViewLoaded = true")
dispatchTransition(operation: .replaceFrontController, withNew: viewController, animated: animated)
}
public func pushFront(viewController: UIViewController, animated: Bool) {
if !self.isViewLoaded {
performTransitionOperation(.replaceFrontController, with: viewController, animated: false)
return
}
dispatchPush(frontViewController: viewController, animated: animated)
}
public func setLeft(viewController: UIViewController?) {
setLeft(viewController: viewController, animated: false)
}
public func setLeft(viewController: UIViewController?, animated: Bool) {
if !self.isViewLoaded {
performTransitionOperation(.replaceLeftController, with: viewController, animated: false)
return
}
dispatchTransition(operation: .replaceLeftController, withNew: viewController, animated: animated)
}
public func setRight(viewController: UIViewController?) {
setRight(viewController: viewController, animated: false)
}
public func setRight(viewController: UIViewController?, animated: Bool) {
if !self.isViewLoaded {
performTransitionOperation(.replaceRightController, with: viewController, animated: false)
return
}
dispatchTransition(operation: .replaceRightController, withNew: viewController, animated: animated)
}
public func leftRevealToggle(animated: Bool) {
var toggleViewPosition = ViewPosition.left
if (frontViewPosition?.rawValue)! <= ViewPosition.left.rawValue {
toggleViewPosition = ViewPosition.right
}
setFront(viewPosition: toggleViewPosition, animated: animated)
}
public func rightRevealToggle(animated: Bool) {
var toggleViewPosition = ViewPosition.left
if (frontViewPosition?.rawValue)! >= ViewPosition.left.rawValue {
toggleViewPosition = ViewPosition.leftSide
}
setFront(viewPosition: toggleViewPosition, animated: animated)
}
public func setFront(viewPosition: ViewPosition?) {
setFront(viewPosition: viewPosition, animated: false)
}
public func setFront(viewPosition: ViewPosition?, animated: Bool) {
if !self.isViewLoaded {
frontViewPosition = viewPosition
leftViewPosition = viewPosition
rightViewPosition = viewPosition
return
}
dispatchSet(frontViewPosition: viewPosition, animated: animated)
}
public func setFrontView(shadowOffset: CGSize) {
frontViewShadowOffset = shadowOffset
contentView?.reloadShadow()
}
public func setFrontView(shadowOpacity: CGFloat) {
frontViewShadowOpacity = shadowOpacity
contentView?.reloadShadow()
}
public func setFrontView(shadowColor: UIColor) {
frontViewShadowColor = shadowColor
contentView?.reloadShadow()
}
public var _panGestureRecognizer: UIPanGestureRecognizer {
if panGestureRecognizer == nil {
panGestureRecognizer = SlideRevealPanGestureRecognizer(target: self, action: #selector(handleRevealGesture(recognizer:)))
panGestureRecognizer?.delegate = self
contentView?.frontView?.addGestureRecognizer(panGestureRecognizer!)
}
return panGestureRecognizer!
}
public var _tapGestureRecognizer: UITapGestureRecognizer {
if tapGestureRecognizer == nil {
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(recognizer:)))
tapGestureRecognizer?.delegate = self
contentView?.frontView?.addGestureRecognizer(tapGestureRecognizer!)
}
return tapGestureRecognizer!
}
public func setClipsToBounds(clipsToBounds: Bool) {
isClipsViewsToBounds = clipsToBounds
contentView?.clipsToBounds = isClipsViewsToBounds
}
//MARK: - Provided action methods
@IBAction public func leftRevealToggle(sender: Any) {
leftRevealToggle(animated: true)
}
@IBAction public func rightRevealToggle(sender: Any) {
rightRevealToggle(animated: true)
}
//MARK: - User interaction enabling
func disableUserInteraction() {
contentView?.isUserInteractionEnabled = false
contentView?.disableLayout = true
}
func restoreUserInteraction() {
contentView?.isUserInteractionEnabled = userInteractionStore
contentView?.disableLayout = false
}
//MARK: - Pan gesture progress notification
func notifyPanGestureBegin() {
//if delegate != nil {
var xLocation , dragProgress , overProgress: CGFloat
xLocation = 0.0
dragProgress = 0.0
overProgress = 0.0
if let delegateMethod = delegate?.panGestureBegan?(self) {
delegateMethod
}
getDragLocation(xLocation: &xLocation, progress: &dragProgress, overdrawProgress: &overProgress)
if let delegateMethod = delegate?.revealController?(self, panGestureBeganFromLocation: xLocation, progress: dragProgress, overProgress: overProgress) {
delegateMethod
}
//}
}
func notifyPanGestureMoved() {
if delegate != nil {
var xLocation , dragProgress , overProgress: CGFloat
xLocation = 0.0
dragProgress = 0.0
overProgress = 0.0
getDragLocation(xLocation: &xLocation, progress: &dragProgress, overdrawProgress: &overProgress)
if (delegate?.responds(to: #selector(delegate?.revealController(_:panGestureMovedToLocation:progress:overProgress:))))! {
delegate?.revealController!(self, panGestureMovedToLocation: xLocation, progress: dragProgress, overProgress: overProgress)
}
}
}
func notifyPanGestureEnded() {
if delegate != nil {
var xLocation , dragProgress , overProgress: CGFloat
xLocation = 0.0
dragProgress = 0.0
overProgress = 0.0
getDragLocation(xLocation: &xLocation, progress: &dragProgress, overdrawProgress: &overProgress)
if (delegate?.responds(to: #selector(delegate?.revealController(_:panGestureEndedToLocation:progress:overProgress:))))! {
delegate?.revealController!(self, panGestureEndedToLocation: xLocation, progress: dragProgress, overProgress: overProgress)
}
if (delegate?.responds(to: #selector(delegate?.panGestureEnded(_:))))! {
delegate?.panGestureEnded!(self)
}
}
}
//MARK: - Symetry
func getRevealWidth(revealWidth: UnsafeMutablePointer<CGFloat>, revealOverdraw: UnsafeMutablePointer<CGFloat>, symetry: Int) {
if symetry < 0 {
revealWidth.pointee = rightViewRevealWidth
revealOverdraw.pointee = rightViewRevealOverdraw
} else {
revealWidth.pointee = leftViewRevealWidth
revealOverdraw.pointee = leftViewRevealOverdraw
}
if revealWidth.pointee < 0 {
revealWidth.pointee = (contentView?.bounds.size.width)! + revealWidth.pointee
}
}
func getBounceBack(bounceBack: UnsafeMutablePointer<Bool>, stableDrag: UnsafeMutablePointer<Bool>, symetry: Int) {
if symetry < 0 {
bounceBack.pointee = bounceBackOnLeftOverdraw
stableDrag.pointee = stableDragOnLeftOverdraw
} else {
bounceBack.pointee = bounceBackOnOverdraw
stableDrag.pointee = stableDragOnOverdraw
}
}
func getAdjusted(frontViewPosition: UnsafeMutablePointer<ViewPosition>, symetry: Int) {
if symetry < 0 {
frontViewPosition.pointee = ViewPosition(rawValue: ViewPosition.left.rawValue + symetry * (frontViewPosition.pointee.rawValue - ViewPosition.left.rawValue))!
}
}
func getDragLocation(xLocation: UnsafeMutablePointer<CGFloat>, progress: UnsafeMutablePointer<CGFloat>) {
let frontView = contentView?.frontView
xLocation.pointee = (frontView?.frame.origin.x)!
let symetry = xLocation.pointee < 0 ? -1 : 1
var xWidth: CGFloat = CGFloat(symetry) < 0 ? rightViewRevealWidth : leftViewRevealWidth
if xWidth < 0 {
xWidth = (contentView?.bounds.size.width)! + xWidth
}
progress.pointee = xLocation.pointee / xWidth * CGFloat(symetry)
}
func getDragLocation(xLocation: UnsafeMutablePointer<CGFloat>, progress: UnsafeMutablePointer<CGFloat>, overdrawProgress: UnsafeMutablePointer<CGFloat>) {
let frontView = contentView?.frontView
xLocation.pointee = (frontView?.frame.origin.x)!
let symetry = xLocation.pointee < 0 ? -1 : 1
var xWidth: CGFloat = CGFloat(symetry) < 0 ? rightViewRevealWidth : leftViewRevealWidth
let xOverWidth: CGFloat = CGFloat(symetry) < 0 ? rightViewRevealOverdraw : leftViewRevealOverdraw
if xWidth < 0 {
xWidth = (contentView?.bounds.size.width)! + xWidth
}
progress.pointee = (xLocation.pointee * CGFloat(symetry) / xWidth)
overdrawProgress.pointee = ((xLocation.pointee * CGFloat(symetry) - xWidth) / xOverWidth)
}
//MARK: - Deferred block execution queue
// Defines a convienience macro to enqueue single statements
func enqueue(code: Any) {
return enqueueBlock({() -> Void in
})
}
//Enqueue Block
func enqueueBlock(_ block: @escaping () -> Void) {
animationQueue.insert(block, at: 0)
if animationQueue.count == 1 {
block()
}
}
//Dequeue
func dequeue() {
if animationQueue.count > 0 {
animationQueue.removeLast()
if animationQueue.count > 0 {
let block: (() -> Void)?? = animationQueue.last as? (() -> Void)
block!!()
}
}
}
//MARK: - UIGestureRecognizer Delegate
private func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if animationQueue.count == 0 {
print(animationQueue)
if gestureRecognizer == panGestureRecognizer {
return panGestureShouldBegin()
}
if gestureRecognizer == tapGestureRecognizer {
return tapGestureShouldBegin()
}
}
return false
}
private func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panGestureRecognizer {
//if delegate != nil {
if delegate?.panGestureRecognizesSimutaneouslyWith?(otherGestureRecognizer, revealController: self) == true {
return true
}
//}
}
if gestureRecognizer == tapGestureRecognizer {
//if delegate != nil {
if delegate?.tapGestureRecognizesSimutaneouslyWith?(otherGestureRecognizer, revealController: self) == true {
return true
}
//}
}
return false
}
func tapGestureShouldBegin() -> Bool {
if frontViewPosition == .left || frontViewPosition == .rightSideMostRemoved || frontViewPosition == .leftSideMostRemoved {
return false
}
//if delegate != nil {
if delegate?.tapGestureRecognizerShouldBegin?(self) == false{
return false
}
//}
return true
}
func panGestureShouldBegin() -> Bool {
let recognizerView = panGestureRecognizer?.view
let translation: CGPoint = (panGestureRecognizer?.translation(in: recognizerView))!
//if delegate != nil {
if delegate?.panGestureRecognizerShouldBegin?(self) == false {
return false
}
//}
let xLocation: CGFloat = (panGestureRecognizer?.location(in: recognizerView).x)!
let width = recognizerView?.bounds.size.width
let draggableBorderAllowing = (
draggableBorderWidth == 0.0 || (leftViewController != nil && xLocation <= draggableBorderWidth) || (rightViewController != nil && xLocation >= (width! - draggableBorderWidth))
)
let translationForbidding = (
frontViewPosition == .left && ((leftViewController == nil && translation.x > 0) || (rightViewController == nil && translation.x < 0))
)
return draggableBorderAllowing && !translationForbidding
}
//MARK: - Gesture based reveal
@objc func handleTapGesture(recognizer: UITapGestureRecognizer) {
let duration = toggleAnimationDuration
setFrontViewPosition(newPosition: .left, with: duration)
}
@objc func handleRevealGesture(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .began:
handleRevealGestureStateBegin(recognizer: recognizer)
case .changed:
handleRevealGestureStateChanged(recognizer: recognizer)
case .ended:
handleRevealGestureStateEnded(recognizer: recognizer)
case .cancelled:
handleRevealGestureStateCancelled(recognizer: recognizer)
default:
break
}
}
func handleRevealGestureStateBegin(recognizer: UIPanGestureRecognizer) {
enqueueBlock {
}
panInitialFrontPosition = frontViewPosition
disableUserInteraction()
notifyPanGestureBegin()
}
func handleRevealGestureStateChanged(recognizer: UIPanGestureRecognizer) {
let xTranslation = recognizer.translation(in: contentView).x
let baseXLocation = contentView?.frontLocation(for: panInitialFrontPosition!)
var xLocation = baseXLocation! + xTranslation
if xLocation < 0 {
if rightViewController == nil {
xLocation = 0
}
rightViewDeploymentFor(newPosition: .leftSide)()
leftViewDeploymentFor(newPosition: .leftSide)()
}
if xLocation > 0 {
if leftViewController == nil {
xLocation = 0
}
rightViewDeploymentFor(newPosition: .right)()
leftViewDeploymentFor(newPosition: .right)()
}
contentView?.dragFrontViewTo(xLocation: xLocation)
notifyPanGestureMoved()
}
func handleRevealGestureStateEnded(recognizer: UIPanGestureRecognizer) {
let frontView = contentView?.frontView
var xLocation: CGFloat = (frontView?.frame.origin.x)!
let velocity = recognizer.velocity(in: contentView).x
let symetry: Int = Int(xLocation) < 0 ? -1 : 1
var revealWidth: CGFloat = 0.0
var revealOverdraw: CGFloat = 0.0
var bounceBack = false
var stableDrag = false
getRevealWidth(revealWidth: &revealWidth, revealOverdraw: &revealOverdraw, symetry: symetry)
getBounceBack(bounceBack: &bounceBack, stableDrag: &stableDrag, symetry: symetry)
xLocation = xLocation * CGFloat(symetry)
var frontViewPosition: ViewPosition
frontViewPosition = ViewPosition.left
var duration = toggleAnimationDuration
if abs(velocity) > quickFlickVelocity {
var journey = xLocation
if (velocity * CGFloat(symetry)) > 0.0 {
frontViewPosition = ViewPosition.right
journey = revealWidth - xLocation
if xLocation > revealWidth {
if !bounceBack && stableDrag {
frontViewPosition = ViewPosition.rightSideMostRemoved
journey = revealWidth + revealOverdraw - xLocation
}
}
}
duration = abs(Double(journey / velocity))
}
else {
if xLocation > revealWidth * 0.5 {
frontViewPosition = ViewPosition.right
if xLocation > revealWidth {
if bounceBack {
frontViewPosition = ViewPosition.left
}
else if stableDrag && xLocation > revealWidth + revealOverdraw * 0.5 {
frontViewPosition = ViewPosition.rightMost
}
}
}
}
getAdjusted(frontViewPosition: &frontViewPosition, symetry: symetry)
restoreUserInteraction()
notifyPanGestureEnded()
setFrontViewPosition(newPosition: frontViewPosition, with: duration)
}
func handleRevealGestureStateCancelled(recognizer: UIPanGestureRecognizer) {
restoreUserInteraction()
notifyPanGestureEnded()
dequeue()
}
//MARK: - Enqueue position and controller setup
func dispatchSet(frontViewPosition: ViewPosition?, animated: Bool) {
let duration = animated ? toggleAnimationDuration : 0.0
weak var theSelf: SlideRevealViewController? = self
enqueue(code: theSelf!.setFrontViewPosition(newPosition: frontViewPosition, with: duration))
}
func dispatchPush(frontViewController: UIViewController, animated: Bool) {
var preReplacementPosition = ViewPosition.left
if (frontViewPosition?.rawValue)! > ViewPosition.left.rawValue {
preReplacementPosition = .rightMost
}
if (frontViewPosition?.rawValue)! < ViewPosition.left.rawValue {
preReplacementPosition = .leftSideMost
}
let duration = animated ? toggleAnimationDuration : 0.0
var firstDuration = duration
let initialPosDif = abs((frontViewPosition?.rawValue)! - preReplacementPosition.rawValue)
if initialPosDif == 1 {
firstDuration *= 0.8
}
else if initialPosDif == 0 {
firstDuration = 0
}
weak var theSelf: SlideRevealViewController? = self
if animated {
enqueue(code: theSelf!.setFrontViewPosition(newPosition: preReplacementPosition, with: firstDuration))
enqueue(code: theSelf!.performTransitionOperation(.replaceFrontController, with: frontViewController, animated: false))
enqueue(code: theSelf!.setFrontViewPosition(newPosition: .left, with: duration))
}
else {
enqueue(code: theSelf!.performTransitionOperation(.replaceFrontController, with: frontViewController, animated: false))
}
}
func dispatchTransition(operation: SlideRevealViewOperation, withNew viewController: UIViewController?, animated: Bool) {
weak var theSelf: SlideRevealViewController? = self
enqueue(code: theSelf!.performTransitionOperation(operation, with: viewController, animated: animated))
}
//MARK: - Animated view controller deployment and layout
func setFrontViewPosition(newPosition: ViewPosition?, with duration: TimeInterval) {
let leftDeploymentCompletion = leftViewDeploymentFor(newPosition: newPosition)
let rightDeploymentCompletion = rightViewDeploymentFor(newPosition: newPosition)
let frontDeploymentCompletion = frontViewDeploymentFor(newPosition: newPosition)
let animations = {() -> Void in
self.setNeedsStatusBarAppearanceUpdate()
self.contentView?.layoutSubviews()
if self.delegate != nil {
if (self.delegate?.responds(to: #selector(self.delegate?.revealController(_:animateTo:))))! {
self.delegate?.revealController!(self, animateTo: self.frontViewPosition!)
}
}
}
let completion: ((_: Bool) -> Void) = {(_ finished: Bool) -> Void in
leftDeploymentCompletion()
rightDeploymentCompletion()
frontDeploymentCompletion()
self.dequeue()
}
if duration > 0.0 {
if toggleAnimationType == SlideRevealAnimationType.easeout {
UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseOut], animations: animations, completion: completion)
}
else {
UIView.animate(withDuration: toggleAnimationDuration, delay: 0.0, usingSpringWithDamping: springDampingRatio, initialSpringVelocity: CGFloat(1.0 / duration), options: [], animations: animations, completion: completion)
}
}
else {
animations()
completion(true)
}
}
func performTransitionOperation(_ operation: SlideRevealViewOperation, with viewController: UIViewController?, animated: Bool) {
if delegate != nil {
if (delegate?.responds(to: #selector(delegate?.revealController(_:willAdd:forOperation:animated:))))! {
delegate?.revealController!(self, willAdd: viewController, forOperation: operation, animated: animated)
}
}
var old: UIViewController?
var view: UIView?
if operation == SlideRevealViewOperation.replaceLeftController {
old = leftViewController
leftViewController = viewController
view = contentView?.leftView
}
else if operation == SlideRevealViewOperation.replaceFrontController {
old = frontViewController
frontViewController = viewController
view = (contentView?.frontView)
}
else if operation == SlideRevealViewOperation.replaceRightController {
old = rightViewController
rightViewController = viewController
view = (contentView?.rightView)
}
let completion = transition(fromViewController: old, toViewController: viewController, in: view)
let animationCompletion = {() -> Void in
completion()
if self.delegate != nil {
if (self.delegate?.responds(to: #selector(self.delegate?.revealController(_:didAdd:forOperation:animated:))))! {
self.delegate?.revealController!(self, didAdd: viewController, forOperation: operation, animated: animated)
self.dequeue()
}
}
}
if animated {
var animationController = SlideRevealAnimationController(with: replaceViewAnimationDuration)
if delegate != nil {
print("delegate is not nil")
if (delegate?.responds(to: #selector(delegate?.revealController(_:animationControllerFor:from:to:))))! {
print("resonded to delegate")
animationController = (delegate?.revealController!(self, animationControllerFor: operation, from: old, to: viewController))! as! SlideRevealAnimationController
}
}
let transitionObject = SlideRevealContextTransitioningObject(revealController: self, containerView: view, fromVC: old!, toVC: viewController, completion: animationCompletion)
if (animationController.transitionDuration(using: transitionObject)) > TimeInterval(0) {
animationController.animateTransition(using: transitionObject)
}
else {
animationCompletion()
}
}
else {
animationCompletion()
}
}
//MARK: - position based view controller deployment
// Deploy/Undeploy of the front view controller following the containment principles. Returns a block
// that must be invoked on animation completion in order to finish deployment
func frontViewDeploymentFor(newPosition: ViewPosition?) -> () -> Void {
var newPosition = newPosition
if rightViewController == nil && (newPosition?.rawValue)! < ViewPosition.left.rawValue || leftViewController == nil && (newPosition?.rawValue)! > ViewPosition.left.rawValue {
newPosition = ViewPosition(rawValue: ViewPosition.left.rawValue)!
}
let positionIsChanging = frontViewPosition?.rawValue != newPosition?.rawValue
let appear = ((frontViewPosition?.rawValue)! >= ViewPosition.rightSideMostRemoved.rawValue || (frontViewPosition?.rawValue)! <= ViewPosition.leftSideMostRemoved.rawValue || frontViewPosition?.rawValue == ViewPosition.none.rawValue) && ((newPosition!.rawValue) < ViewPosition.rightSideMostRemoved.rawValue && (newPosition!.rawValue) > ViewPosition.leftSideMostRemoved.rawValue)
let disappear = ((newPosition?.rawValue)! >= ViewPosition.rightSideMostRemoved.rawValue || newPosition!.rawValue <= ViewPosition.leftSideMostRemoved.rawValue) && ((frontViewPosition?.rawValue)! < ViewPosition.rightSideMostRemoved.rawValue && (frontViewPosition?.rawValue)! > ViewPosition.leftSideMostRemoved.rawValue && frontViewPosition?.rawValue != ViewPosition.none.rawValue)
if positionIsChanging {
if delegate != nil {
if (delegate?.responds(to: #selector(delegate?.revealController(_:willMoveTo:))))! {
delegate?.revealController!(self, willMoveTo: newPosition!)
}
}
}
frontViewPosition = newPosition
let deploymentCompletion: (() -> Void) = deploymentFor(viewController: frontViewController, in: contentView?.frontView, appear: appear, disappear: disappear)
let completion: (() -> Void) = {() -> Void in
deploymentCompletion()
if positionIsChanging {
if self.delegate != nil {
if (self.delegate?.responds(to: #selector(self.delegate?.revealController(_:didMoveTo:))))! {
self.delegate?.revealController!(self, didMoveTo: newPosition!)
}
}
}
}
return completion
}
// Deploy/Undeploy of the left view controller following the containment principles. Returns a block
// that must be invoked on animation completion in order to finish deployment
func leftViewDeploymentFor(newPosition: ViewPosition?) -> () -> Void {
var newPosition = newPosition
if isPresentFrontViewHierarchically {
newPosition = ViewPosition.right
}
if leftViewController == nil && newPosition!.rawValue > ViewPosition.left.rawValue {
newPosition = ViewPosition.left
}
let appear = ((leftViewPosition?.rawValue)! <= ViewPosition.left.rawValue || leftViewPosition?.rawValue == ViewPosition.none.rawValue) && (newPosition?.rawValue)! > ViewPosition.left.rawValue
let disappear = (newPosition?.rawValue)! <= ViewPosition.left.rawValue && ((leftViewPosition?.rawValue)! > ViewPosition.left.rawValue && leftViewPosition?.rawValue != ViewPosition.none.rawValue)
if appear {
contentView?.prepareLeftView(for: newPosition!)
}
leftViewPosition = newPosition
let deploymentCompletion: (() -> Void) = deploymentFor(viewController: leftViewController, in: contentView?.leftView, appear: appear, disappear: disappear)
let completion: (() -> Void) = {() -> Void in
deploymentCompletion()
if disappear {
self.contentView?.unloadLeftView()
}
}
return completion
}
// Deploy/Undeploy of the right view controller following the containment principles. Returns a block
// that must be invoked on animation completion in order to finish deployment
func rightViewDeploymentFor(newPosition: ViewPosition?) -> () -> Void {
var newPosition = newPosition
if rightViewController == nil && (newPosition?.rawValue)! < ViewPosition.left.rawValue {
newPosition = ViewPosition.left
}
let appear = ((rightViewPosition?.rawValue)! >= ViewPosition.left.rawValue || rightViewPosition?.rawValue == ViewPosition.none.rawValue) && (newPosition?.rawValue)! < ViewPosition.left.rawValue
let disappear = (newPosition?.rawValue)! >= ViewPosition.left.rawValue && ((rightViewPosition?.rawValue)! < ViewPosition.left.rawValue && rightViewPosition?.rawValue != ViewPosition.none.rawValue)
if appear {
contentView?.prepareRightView(for: newPosition!)
}
rightViewPosition = newPosition
let deploymentCompletion: (() -> Void) = deploymentFor(viewController: rightViewController, in: (contentView?.rightView), appear: appear, disappear: disappear)
let completion: (() -> Void) = {() -> Void in
deploymentCompletion()
if disappear {
self.contentView?.unloadRightView()
}
}
return completion
}
func deploymentFor(viewController: UIViewController?, in view: UIView?, appear: Bool, disappear: Bool) -> () -> Void {
if appear {
return deployFor(viewController: viewController, in: view)
}
if disappear {
return undeployFor(viewController: viewController)
}
return {
() -> Void in
}
}
//MARK: - Containment view controller deployment and transistion
// Containment Deploy method. Returns a block to be invoked at the
// animation completion, or right after return in case of non-animated deployment.
func deployFor(viewController: UIViewController?, in view: UIView?) -> () -> Void {
if viewController == nil || view == nil {
return {
() -> Void in
}
}
let frame = view?.bounds
let controllerView = viewController?.view
controllerView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
controllerView?.frame = frame!
//if controllerView != nil {
if (controllerView?.isKind(of: UIScrollView.self))! {
let adjust = viewController?.automaticallyAdjustsScrollViewInsets
if adjust! {
((viewController as Any) as! UIScrollView).contentInset = UIEdgeInsets(top: statusBarAdjustment(contentView!), left: 0, bottom: 0, right: 0)
}
}
//}
view?.addSubview(controllerView!)
let completion = {() -> Void in
//nothing to do at this point
}
return completion
}
// Containment Undeploy method. Returns a block to be invoked at the
// animation completion, or right after return in case of non-animated deployment.
func undeployFor(viewController: UIViewController?) -> () -> Void {
if viewController?.isViewLoaded == false {
return {() -> Void in
}
}
let completion = {() -> Void in
viewController?.view.removeFromSuperview()
}
return completion
}
// Containment Transition method. Returns a block to be invoked at the
// animation completion, or right after return in case of non-animated transition.
func transition(fromViewController: UIViewController?, toViewController: UIViewController?, in view: UIView?) -> () -> Void {
if fromViewController == toViewController {
return {() -> Void in
}
}
if toViewController != nil {
addChild(toViewController!)
}
let deployCompletion = deployFor(viewController: toViewController, in: view)
fromViewController?.willMove(toParent: nil)
let undeployCompletion = undeployFor(viewController: fromViewController)
let completionBlock: (() -> Void) = {() -> Void in
undeployCompletion()
fromViewController?.removeFromParent()
deployCompletion()
toViewController?.didMove(toParent: self)
}
return completionBlock
}
// Load any defined front/rear controllers from the storyboard
// This method is intended to be overrided in case the default behavior will not meet your needs
func loadStoryboardControllers() {
if self.storyboard != nil && leftViewController == nil {
defer{
if doesSegueExist(identifier: slideLeftIdentifier) {
performSegue(withIdentifier: slideLeftIdentifier, sender: nil)
}
}
defer {
if doesSegueExist(identifier: slideFrontIdentifier) {
performSegue(withIdentifier: slideFrontIdentifier, sender: nil)
}
}
defer {
if doesSegueExist(identifier: slideRightIdentifier) {
performSegue(withIdentifier: slideRightIdentifier, sender: nil)
}
}
}
}
func doesSegueExist(identifier: String) -> Bool {
let segues = value(forKey: "storyboardSegueTemplates") as? [NSObject]
guard let filteredSegues = segues?.filter({ $0.value(forKey: "identifier") as? String == identifier})
else {
return false
}
return filteredSegues.count > 0
}
//MARK: state preservation and restoration
//MARK: UIViewControllerRestoration delegate method
public static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? {
var viewController: SlideRevealViewController? = nil
let storyboard = coder.decodeObject(forKey: UIApplication.stateRestorationViewControllerStoryboardKey) as? UIStoryboard
if storyboard != nil {
viewController = storyboard?.instantiateViewController(withIdentifier: "SlideRevealViewController") as? SlideRevealViewController
viewController?.restorationIdentifier = identifierComponents.last
viewController?.restorationClass = SlideRevealViewController.self
}
return viewController
}
override open func encodeRestorableState(with coder: NSCoder) {
coder.encode(Double(leftViewRevealWidth), forKey: "leftViewRevealWidth")
coder.encode(Double(leftViewRevealOverdraw), forKey: "leftViewRevealOverdraw")
coder.encode(Double(leftViewRevealDisplacement), forKey: "leftViewRevealDisplacement")
coder.encode(Double(rightViewRevealWidth), forKey: "rightViewRevealWidth")
coder.encode(Double(rightViewRevealOverdraw), forKey: "rightViewRevealOverdraw")
coder.encode(Double(rightViewRevealDisplacement), forKey: "rightViewRevealDisplacement")
coder.encode(bounceBackOnOverdraw, forKey: "bounceBackOnOverdraw")
coder.encode(bounceBackOnLeftOverdraw, forKey: "bounceBackOnLeftOverdraw")
coder.encode(stableDragOnOverdraw, forKey: "stableDragOnOverdraw")
coder.encode(stableDragOnLeftOverdraw, forKey: "stableDragOnLeftOverdraw")
coder.encode(isPresentFrontViewHierarchically, forKey: "presentFrontViewHierarchically")
coder.encode(Double(quickFlickVelocity), forKey: "quickFlickVelocity")
coder.encode(Double(toggleAnimationDuration), forKey: "toggleAnimationDuration")
coder.encode(toggleAnimationType.rawValue, forKey: "toggleAnimationType")
coder.encode(Double(springDampingRatio), forKey: "springDampingRatio")
coder.encode(Double(replaceViewAnimationDuration), forKey: "replaceViewAnimationDuration")
coder.encode(Double(frontViewShadowRadius), forKey: "frontViewShadowRadius")
coder.encode(frontViewShadowOffset, forKey: "frontViewShadowOffset")
coder.encode(Double(frontViewShadowOpacity), forKey: "frontViewShadowOpacity")
coder.encode(frontViewShadowColor, forKey: "frontViewShadowColor")
coder.encode(userInteractionStore, forKey: "userInteractionStore")
coder.encode(Double(draggableBorderWidth), forKey: "draggableBorderWidth")
coder.encode(isClipsViewsToBounds, forKey: "clipsViewsToBounds")
coder.encode(isExtendsPointInsideHit, forKey: "extendsPointInsideHit")
coder.encode(leftViewController, forKey: "leftViewController")
coder.encode(frontViewController, forKey: "frontViewController")
coder.encode(rightViewController, forKey: "rightViewController")
coder.encode(Int(frontViewPosition!.rawValue), forKey: "frontViewPosition")
super.encodeRestorableState(with: coder)
}
override open func decodeRestorableState(with coder: NSCoder) {
print("called decodeRestorableState")
leftViewRevealWidth = CGFloat(coder.decodeDouble(forKey: "leftViewRevealWidth"))
leftViewRevealOverdraw = CGFloat(coder.decodeDouble(forKey: "leftViewRevealOverdraw"))
leftViewRevealDisplacement = CGFloat(coder.decodeDouble(forKey: "leftViewRevealDisplacement"))
rightViewRevealWidth = CGFloat(coder.decodeDouble(forKey: "rightViewRevealWidth"))
rightViewRevealOverdraw = CGFloat(coder.decodeDouble(forKey: "rightViewRevealOverdraw"))
rightViewRevealDisplacement = CGFloat(coder.decodeDouble(forKey: "rightViewRevealDisplacement"))
bounceBackOnOverdraw = coder.decodeBool(forKey: "bounceBackOnOverdraw")
bounceBackOnLeftOverdraw = coder.decodeBool(forKey: "bounceBackOnLeftOverdraw")
stableDragOnOverdraw = coder.decodeBool(forKey: "stableDragOnOverdraw")
stableDragOnLeftOverdraw = coder.decodeBool(forKey: "stableDragOnLeftOverdraw")
isPresentFrontViewHierarchically = coder.decodeBool(forKey: "presentFrontViewHierarchically")
quickFlickVelocity = CGFloat(coder.decodeDouble(forKey: "quickFlickVelocity"))
toggleAnimationDuration = coder.decodeDouble(forKey: "toggleAnimationDuration")
toggleAnimationType = SlideRevealAnimationType(rawValue: coder.decodeInteger(forKey: "toggleAnimationType"))!
springDampingRatio = CGFloat(coder.decodeDouble(forKey: "springDampingRatio"))
replaceViewAnimationDuration = coder.decodeDouble(forKey: "replaceViewAnimationDuration")
frontViewShadowRadius = CGFloat(coder.decodeDouble(forKey: "frontViewShadowRadius"))
frontViewShadowOffset = coder.decodeCGSize(forKey: "frontViewShadowOffset")
frontViewShadowOpacity = CGFloat(coder.decodeDouble(forKey: "frontViewShadowOpacity"))
frontViewShadowColor = coder.decodeObject(forKey: "frontViewShadowColor") as? UIColor ?? UIColor.black
userInteractionStore = coder.decodeBool(forKey: "userInteractionStore")
animationQueue = [Any]()
draggableBorderWidth = CGFloat(coder.decodeDouble(forKey: "draggableBorderWidth"))
isClipsViewsToBounds = coder.decodeBool(forKey: "clipsViewsToBounds")
isExtendsPointInsideHit = coder.decodeBool(forKey: "extendsPointInsideHit")
//leftViewController = coder.decodeObject(forKey: "leftViewController") as? UIViewController
//frontViewController = coder.decodeObject(forKey: "frontViewController") as? UIViewController
//rightViewController = coder.decodeObject(forKey: "rightViewController") as? UIViewController
setLeft(viewController: leftViewController)
setFront(viewController: frontViewController)
setRight(viewController: rightViewController)
//frontViewPosition = ViewPosition(rawValue: coder.decodeInteger(forKey: "frontViewPosition"))
setFront(viewPosition: frontViewPosition!)
//panGestureRecognizer = _panGestureRecognizer
//tapGestureRecognizer = _tapGestureRecognizer
super.decodeRestorableState(with: coder)
}
override open func applicationFinishedRestoringState() {
}
}
// MARK: - Global constants
let slideLeftIdentifier = "slide_left" //Segue identifier for view controller appearing on the left
let slideFrontIdentifier = "slide_front" //Segue identifier for the front (main) view controller
let slideRightIdentifier = "slide_right" //Segue identifier for the view controller appearing on the right
// MARK: - Extension of UIViewController to help with parent controller presentation
public extension UIViewController {
public func revealViewController() -> SlideRevealViewController? {
var parent: UIViewController? = self
if parent != nil && parent is SlideRevealViewController {
return parent as? SlideRevealViewController
}
while (!(parent is SlideRevealViewController) && parent?.parent != nil) {
parent = parent?.parent
}
if parent is SlideRevealViewController {
return parent as? SlideRevealViewController
}
return nil
}
}
// MARK: - SlideRevealViewControllerSegueSetController class
class SlideRevealViewControllerSegueSetController: UIStoryboardSegue {
override func perform() {
var operation: SlideRevealViewOperation = .none
let identifier: String = self.identifier!
let rvc: SlideRevealViewController? = self.source as? SlideRevealViewController
let dvc: UIViewController? = self.destination
if (identifier == slideFrontIdentifier) {
operation = SlideRevealViewOperation.replaceFrontController
}
else if (identifier == slideLeftIdentifier) {
operation = SlideRevealViewOperation.replaceLeftController
}
else if (identifier == slideRightIdentifier) {
operation = SlideRevealViewOperation.replaceRightController
}
if operation != SlideRevealViewOperation.none {
rvc?.performTransitionOperation(operation, with: dvc!, animated: false)
}
}
}
// MARK: - SlideRevealViewControllerSeguePushController class
class SlideRevealViewControllerSeguePushController: UIStoryboardSegue {
override func perform() {
let rvc: SlideRevealViewController? = self.source.revealViewController()
let dvc: UIViewController? = self.destination
rvc?.pushFront(viewController: dvc!, animated: true)
}
}
| true
|
1b44a0d30b41cb695c3fdccc456bf8d1fab71e61
|
Swift
|
olegsavelev78/Test
|
/Test/ViewController.swift
|
UTF-8
| 3,235
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Test
//
// Created by Олег Савельев on 19.04.2021.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var repositories: [Repository] = []
var fetchingMore = false
var urlNext = ""
override func viewDidLoad() {
super.viewDidLoad()
let loadingNib = UINib(nibName: "LoadCell", bundle: nil)
self.tableView.register(loadingNib, forCellReuseIdentifier: "loadingCell")
self.tableView.delegate = self
self.tableView.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Loader().loadRepo { repositories,url in
self.urlNext = url
self.repositories = repositories
self.tableView.reloadData()
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return repositories.count
} else if section == 1 && fetchingMore {
return 1
}
return 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell
let item = repositories[indexPath.row]
cell.initCell(item: item)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "loadingCell") as! LoadTableViewCell
cell.activityIndicator.startAnimating()
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "WebView") as! WebViewController
vc.htmlUrl = repositories[indexPath.row].htmlUrl
self.navigationController?.pushViewController(vc, animated: true)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if contentHeight != 0{
if offsetY > contentHeight - scrollView.frame.height {
if !fetchingMore{
beginBatchFetch()
}
}
}
}
func beginBatchFetch() {
fetchingMore = true
print("Load Next Page")
tableView.reloadSections(IndexSet(integer: 1), with: .none)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
Loader().loadMoreRepo(url: self.urlNext, completion: { repositories,url in
let newItem = repositories
self.repositories.append(contentsOf: newItem)
self.urlNext = url
self.fetchingMore = false
self.tableView.reloadData()
})
}
}
}
| true
|
75629280ad39a8c3b7e4616a6fc4624b26f46269
|
Swift
|
mahirekici/MaervelApp
|
/Marvel/Services/Network/NetworkService.swift
|
UTF-8
| 2,298
| 2.640625
| 3
|
[] |
no_license
|
import Foundation
import Alamofire
import SwiftyJSON
import Kingfisher
class NetworkService {
static let sharedInstance = NetworkService()
var imageDownloader: ImageDownloader = {
var imageDownloader = ImageDownloader.default
imageDownloader.trustedHosts = Set(["i.annihil.us"])
return imageDownloader
}()
private init() {
KingfisherManager.shared.downloader = imageDownloader
}
var manager: SessionManager!
func request(_ url: String, method: HTTPMethod, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding(destination: .queryString), headers: HTTPHeaders = NetworkConstants.contentType, completion: @escaping (_ response: JSON) ->(), failure: @escaping (_ error: String, _ errorCode: Int) -> ()) {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 30
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
manager = Alamofire.SessionManager(configuration: configuration)
DispatchQueue.global().async {
self.manager.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers).responseString(queue: DispatchQueue.main, encoding: String.Encoding.utf8) { response in
print("\n\n-- RESPONSE: \(response)")
if response.response?.statusCode == 200 {
guard let callback = response.data else {
failure(self.generateErrorMessage(), 0)
return
}
let json = JSON(callback)
if json["code"].intValue == 200 {
completion(json["data"]["results"])
} else {
failure(self.generateErrorMessage(), 0)
}
} else {
failure(self.generateErrorMessage(), 0)
}
}
}
}
func generateErrorMessage() -> String {
return "error_message.somethings_wrong".localized
}
}
| true
|
ac31111fd9d2c5c769637b50fac005a9b2e8fdd2
|
Swift
|
serg-vinnie/AppCore
|
/Src/Ext/MoreSwiftUI/AccordionBlock.swift
|
UTF-8
| 1,753
| 2.703125
| 3
|
[] |
no_license
|
//
// Accordion.swift
// AppCore
//
// Created by UKS_neo on 15.01.2020.
// Copyright © 2020 Loki. All rights reserved.
//
import Foundation
import SwiftUI
@available(OSX 10.15, *)
public struct AccordionBlock : View {
@State var collapsed: Bool = false
@Binding var header: String
//var subView: some View
public init (header: Binding<String>)//, subView: some View )
{
_header = header
//self.subView = subView
}
public var body : some View {
HStack (alignment: .top, spacing: 0) {
VStack (alignment: .leading, spacing: 0) {
GeometryReader { geometry in
Button ( action: { self.collapsed.toggle() } ){
HStack{
Text( self.collapsed ? "+" : "-" )
.font(.system(size: 20))
.animation(.easeInOut)
.padding(.leading, 8)
Text( self.header )
.font(.system(size: 15))
Spacer()
}.frame(width: geometry.size.width)
}.buttonStyle( PlainButtonStyle() )
.background(Color(hex: 0x444444))
}
if !collapsed {
HStack (alignment: .top, spacing: 0) {
Text("test")
Spacer()
}.padding(5)
.background(Color(hex: 0x777777))
}
Spacer()
}
}
}
}
| true
|
20109640eb6309b6ee9f2c609a1a382cb7c76980
|
Swift
|
Prag1396/SocialApp
|
/SocialApp/Post.swift
|
UTF-8
| 1,613
| 3.09375
| 3
|
[] |
no_license
|
//
// Post.swift
// SocialApp
//
// Created by Pragun Sharma on 04/08/17.
// Copyright © 2017 Pragun Sharma. All rights reserved.
//
import Foundation
import Firebase
class Post {
private var _caption: String!
private var _imageURL: String!
private var _numberOfLikes: Int!
private var _postKey: String! //The ID
private var _postLiked: DatabaseReference!
var caption: String {
return _caption
}
var imageURL: String {
return _imageURL
}
var likes: Int {
return _numberOfLikes
}
var postID: String {
return _postKey
}
init(caption: String, imageURL: String, likes: Int) {
self._caption = caption
self._imageURL = imageURL
self._numberOfLikes = likes
}
init(postKey: String, postData: Dictionary<String, AnyObject>) {
self._postKey = postKey
if let caption = postData["caption"] as? String {
self._caption = caption
}
if let imageURL = postData["imageUrl"] as? String {
self._imageURL = imageURL
}
if let likes = postData["likes"] as? Int {
self._numberOfLikes = likes
}
_postLiked = DataService.dbs.REF_POSTS.child(_postKey)
}
func setLikes(addLike: Bool) {
if addLike {
_numberOfLikes = _numberOfLikes + 1
} else {
_numberOfLikes = _numberOfLikes - 1
}
_postLiked.child("likes").setValue(_numberOfLikes)
}
}
| true
|
a1f1b8fc133f834609f78ba0ce9f7b4db03d93cc
|
Swift
|
NekoFluff/Devil-s-Agenda
|
/DevilsAgenda/DataStructures/Class.swift
|
UTF-8
| 4,938
| 3.03125
| 3
|
[] |
no_license
|
//
// Class.swift
// Devil's Agenda
//
// Created by Alexander Nou on 9/13/17.
// Copyright © 2017 Team PlanIt. All rights reserved.
//
import Foundation
class Class : Equatable {
//MARK: - Main Variables
var name : String
var color : String
var databaseKey : String?
var isShared : Bool = false
var owner : String
var tasks = Dictionary<String, [Task]>()
//MARK: - Optional Variables
var professor : String?
var location : String?
var startTime : Date?
var endTime : Date?
var daysOfTheWeek : [Bool]?
//MARK: - Initializers
init(name: String, color: String, owner: String, professor: String?, location: String?, startTime : Date?, endTime : Date?, daysOfTheWeek : [Bool]?, shared: Bool? = false) {
self.name = name
self.color = color
self.owner = owner
self.professor = professor
self.location = location
self.startTime = startTime
self.endTime = endTime
self.daysOfTheWeek = daysOfTheWeek
self.isShared = shared!
}
init(data : [String : Any], databaseKey: String) {
self.name = data[Constants.ClassFields.name] as? String ?? ""
self.color = data[Constants.ClassFields.color] as? String ?? ""
self.owner = data[Constants.ClassFields.owner] as? String ?? ""
self.isShared = data[Constants.ClassFields.shared] as? Bool ?? false
self.professor = data[Constants.ClassFields.professor] as? String
self.location = data[Constants.ClassFields.location] as? String
self.daysOfTheWeek = data[Constants.ClassFields.daysOfTheWeek] as? [Bool]
let df = DateFormatter()
df.dateFormat = "HH:mm:ss"
if let start = data[Constants.ClassFields.startTime] as? String {
self.startTime = df.date(from : start)
}
if let end = data[Constants.ClassFields.endTime] as? String {
self.endTime = df.date(from : end)
}
self.databaseKey = databaseKey
}
deinit {
print("De-allocating Class \(name)")
}
//MARK: - Public functions
func toDict() -> [String : Any] {
var data = [Constants.ClassFields.name : name,
Constants.ClassFields.color : color,
Constants.ClassFields.owner : owner,
Constants.ClassFields.shared : isShared] as [String : Any]
if let professor = self.professor {
data[Constants.ClassFields.professor] = professor
}
if let location = self.location {
data[Constants.ClassFields.location] = location
}
if let startTime = self.startTime {
data[Constants.ClassFields.startTime] = convertTimeToString(startTime)
}
if let endTime = self.endTime {
data[Constants.ClassFields.endTime] = convertTimeToString(endTime)
}
if let daysOfTheWeek = self.daysOfTheWeek {
data[Constants.ClassFields.daysOfTheWeek] = daysOfTheWeek
}
if databaseKey != nil {
data[Constants.ClassFields.key] = databaseKey
}
return data
}
static func ==(left: Class, right: Class) -> Bool {
return left.name == right.name && left.databaseKey == right.databaseKey && left.color == right.color
}
func convertTimeToString(_ time: Date, format: String? = "HH:mm:ss") -> String {
let df = DateFormatter()
df.dateFormat = format!
return df.string(from: time)
}
func addTask(_ t : Task, forKey k: String) {
if self.tasks[t.desc] != nil {
print("Added Task \(t.desc) to existing list.")
self.tasks[t.desc]!.append(t);
} else {
print("Added Task \(t.desc) to new list.")
self.tasks[t.desc] = [t]
}
}
func removeTask(_ t: Task) {
if let taskArray = self.tasks[t.desc] {
for (i, task) in taskArray.enumerated() {
if task == t {
self.tasks[t.desc]!.remove(at: i)
}
}
}
}
func minFromMidnight(date : Date) -> Int {
let hour = date.hour
let min = date.minute
return hour * 60 + min
}
func minSinceHour(date: Date?, comparedToHour hour: Int) -> Int {
//assume compare date is the current hour.
if let date = date {
let targetHour = date.hour
let targetMin = date.minute
var result = (targetHour-hour) * 60 + targetMin
if result < 0 {
result = (24*60) + result //total minutes in day (24*60) + negative time
}
return result
} else {
return 0;
}
}
}
| true
|
f22636aa3db24a0e89dd28885139742bd1f36ded
|
Swift
|
Jae-eun/YAPP-13th_FruitSchool
|
/FruitSchool/Response/FruitResponse.swift
|
UTF-8
| 1,869
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// FruitResponse.swift
// FruitSchool
//
// Created by Presto on 2018. 9. 17..
// Copyright © 2018년 YAPP. All rights reserved.
//
/*
과일 세부정보 응답 모델
*/
struct FruitResponse: Codable {
struct Data: Codable {
let id: String
let title: String
let english: String
let grade: Int
let season: String
let standardTip: StandardTip
let nutritionTip: NutritionTip
enum CodingKeys: String, CodingKey {
case id = "_id"
case title, english, grade, season, standardTip, nutritionTip
}
}
let message: String
let data: [Data]
}
struct StandardTip: Codable {
let purchasingTip: String
let storageTemperature: String?
let storageDate: String?
let storageMethod: String?
let careMethod: String?
var tips: [(title: String, content: String)] {
let array = [("구입 요령", purchasingTip), ("보관 온도", storageTemperature), ("보관일", storageDate), ("보관법", storageMethod), ("손질법", careMethod)]
let filtered = array.filter { $0.1 != nil }
return filtered as? [(title: String, content: String)] ?? [(title: String, content: String)]()
}
var validCount: Int {
var count = 1
if storageTemperature != nil {
count += 1
}
if storageDate != nil {
count += 1
}
if storageMethod != nil {
count += 1
}
if careMethod != nil {
count += 1
}
return count
}
}
struct NutritionTip: Codable {
let sodium: Double
let protein: Double
let sugar: Double
var sodiumText: String {
return "\(sodium)mg"
}
var proteinText: String {
return "\(protein)g"
}
var sugarText: String {
return "\(sugar)g"
}
}
| true
|
543983556230a4f961635191ccac2d9333da6d43
|
Swift
|
emiclark/CatApi
|
/CatApi/CatApi/View/MyTableViewController.swift
|
UTF-8
| 3,327
| 2.84375
| 3
|
[] |
no_license
|
//
// MyTableViewController.swift
// CatApi
//
// Created by Emiko Clark on 3/20/18.
// Copyright © 2018 Emiko Clark. All rights reserved.
//
import UIKit
class MyTableViewController: UITableViewController {
let catds = CatDataStore()
let imageFromCache = UIImage()
let imageCache = NSCache<NSString, UIImage>()
var continuousScrollIndexPath = 0
var pageNum = 1
override func viewDidLoad() {
super.viewDidLoad()
catds.delegate = self
catds.getCatDataWithPageNum(pageNum: pageNum)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return catds.Cats.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var urlImageString: String?
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
let urlString = catds.Cats[indexPath.row].image_url
let url = URL(string: urlString!)
urlImageString = urlString!
cell.catImage.image = #imageLiteral(resourceName: "placeholder")
cell.title.text = catds.Cats[indexPath.row].title
cell.catDescription.text = catds.Cats[indexPath.row].catDescription
// download cat image async
if let img = imageCache.object(forKey: urlString! as NSString) {
cell.catImage.image = img
} else {
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error ?? "Error with downloading catImage")
return
}
guard let data = data else { print("data nil"); return }
DispatchQueue.main.async {
let imageToCache = UIImage(data: data)
// check to ensure get loaded into the correct cells
if urlImageString == urlString {
cell.catImage.image = imageToCache
}
self.imageCache.setObject(imageToCache!, forKey: urlString! as NSString)
}
}.resume()
}
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if continuousScrollIndexPath != indexPath.row {
continuousScrollIndexPath = indexPath.row
let lastElement = self.catds.Cats.count - 3
if indexPath.row == lastElement {
print("Getting more cat images - pageNum:",pageNum,"\n")
catds.getCatDataWithPageNum(pageNum: pageNum)
self.pageNum += 1
}
}
}
}
extension MyTableViewController : reloadCatDataDelegate {
func UpdateUI() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
| true
|
dc641525901cce9d0ff9495b50b07549bcb0c88e
|
Swift
|
stokatyan/ScrollCounter
|
/ScrollCounter/Extensions.swift
|
UTF-8
| 539
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// Extensions.swift
// ScrollCounter
//
// Created by Shant Tokatyan on 12/5/19.
// Copyright © 2019 Stokaty. All rights reserved.
//
import UIKit
extension UIView {
var bottom: CGFloat {
return frame.origin.y + frame.height
}
var top: CGFloat {
return frame.origin.y
}
func animateIn() {
}
}
extension Float {
func round(toPlaces places: Int) -> Float {
let divisor = pow(10.0, Float(places))
return (self * divisor).rounded() / divisor
}
}
| true
|
1596c7888408b7c3f949d3ecb82e9e790d876629
|
Swift
|
Deerdev/iOSDemoCollection
|
/20_DXTableViewWidget/DXTableViewWidget/Source/DXTableViewInfo.swift
|
UTF-8
| 6,660
| 2.75
| 3
|
[] |
no_license
|
//
// DXTableViewInfo.swift
// DXTableViewWidget
//
// Created by deer on 2018/7/20.
// Copyright © 2018年 deer. All rights reserved.
//
import UIKit
class DXTableViewInfo: NSObject {
private var tableView: UITableView!
private lazy var sectionInfos = [DXTableViewSectionInfo]()
init(frame: CGRect, style: UITableView.Style) {
super.init()
tableView = DXTableView(frame: frame, style: style)
tableView.delegate = self
tableView.dataSource = self
}
func getTableView() -> UITableView {
return tableView
}
// MARK: - section operation
func sectionCount() -> Int {
return sectionInfos.count
}
func sectionInfo(at index: Int) -> DXTableViewSectionInfo? {
guard index < sectionInfos.count else { return nil }
return sectionInfos[index]
}
func addSection(_ sectionInfo: DXTableViewSectionInfo) {
sectionInfos.append(sectionInfo)
}
func insertSection(_ sectionInfo: DXTableViewSectionInfo, at index: Int) {
sectionInfos.insert(sectionInfo, at: index)
}
func replaceSection(_ sectionInfo: DXTableViewSectionInfo, at index: Int) {
if index < sectionInfos.count {
sectionInfos[index] = sectionInfo
}
}
func removeSection(at index: Int) {
sectionInfos.remove(at: index)
}
func removeAllSection() {
sectionInfos.removeAll()
}
// MARK: - cell operation
func insertCell(_ cellInfo: DXTableViewCellInfo, at indexPath: IndexPath) {
guard indexPath.section < sectionInfos.count else { return }
let section = sectionInfos[indexPath.section]
section.insert(cellInfo, at: indexPath.row)
}
func replaceCell(_ cellInfo: DXTableViewCellInfo, at indexPath: IndexPath) {
guard indexPath.section < sectionInfos.count else { return }
let section = sectionInfos[indexPath.section]
section.replace(cellInfo, at: indexPath.row)
}
func replaceCell(at indexPath: IndexPath) {
guard indexPath.section < sectionInfos.count else { return }
let section = sectionInfos[indexPath.section]
section.removeCell(at: indexPath.row)
}
}
extension DXTableViewInfo: UITableViewDataSource {
//MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return sectionInfos.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section < sectionInfos.count else { return 0 }
return sectionInfos[section].cellCount()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard indexPath.section < sectionInfos.count,
let cellInfo = sectionInfos[indexPath.section].cell(at: indexPath.row) else {
return UITableViewCell()
}
let identifier = "DXTableView_\(indexPath.section)_\(indexPath.row)"
var cell: DXTableViewCell
if let reuseCell = tableView.dequeueReusableCell(withIdentifier: identifier) as? DXTableViewCell {
cell = reuseCell
} else {
cell = DXTableViewCell(style: cellInfo.cellStyle, reuseIdentifier: identifier)
}
// 有额外的操作,先执行一下
if let target = cellInfo.extraTarget, let sel = cellInfo.extraSel, target.responds(to: sel) {
target.perform(sel, with: cell, with: cellInfo)
}
cell.accessoryType = cellInfo.accessoryType
cell.selectionStyle = cellInfo.selectionStyle
cell.textLabel?.text = cellInfo.getValueFor(key: "title") as? String
cell.detailTextLabel?.text = cellInfo.getValueFor(key: "rightValue") as? String
cellInfo.indexPath = indexPath
if let imageName = cellInfo.getValueFor(key: "imageName") as? String, !imageName.isEmpty {
cell.imageView?.image = UIImage(named: imageName)
}
return cell
}
}
extension DXTableViewInfo: UITableViewDelegate {
//MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard indexPath.section < sectionInfos.count,
let cellInfo = sectionInfos[indexPath.section].cell(at: indexPath.row) else {
return
}
if cellInfo.selectionStyle == .none {
return
}
// 将cell的点击事件传递过去
if let target = cellInfo.target, let sel = cellInfo.selector, target.responds(to: sel) {
target.perform(sel, with: cellInfo, with: indexPath)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard indexPath.section < sectionInfos.count else { return 0 }
let section = sectionInfos[indexPath.section]
return section.cell(at: indexPath.row)?.cellHeight ?? 0
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard section < sectionInfos.count else { return 0.01 }
let sectionInfo = sectionInfos[section]
return sectionInfo.headerHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard section < sectionInfos.count else { return 0.01 }
let sectionInfo = sectionInfos[section]
return sectionInfo.footerHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard section < sectionInfos.count else { return nil }
let sectionInfo = sectionInfos[section]
return sectionInfo.getValueFor(key: "header") as? UIView
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard section < sectionInfos.count else { return nil }
let sectionInfo = sectionInfos[section]
return sectionInfo.getValueFor(key: "footer") as? UIView
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard section < sectionInfos.count else { return nil }
let sectionInfo = sectionInfos[section]
return sectionInfo.getValueFor(key: "footerTitle") as? String
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard section < sectionInfos.count else { return nil }
let sectionInfo = sectionInfos[section]
return sectionInfo.getValueFor(key: "headerTitle") as? String
}
}
| true
|
849b58d421d062ec84658b6a8f6638c859aa0543
|
Swift
|
hao1234/BaseNetworking
|
/BaseNetworking/Resources/lang/L10n.swift
|
UTF-8
| 1,987
| 2.53125
| 3
|
[] |
no_license
|
// swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Strings
// swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:disable nesting type_body_length type_name
internal enum L10n {
/// Hello
internal static var hello: String { L10n.tr("Localizable", "hello") }
/// Pull to refresh
internal static var pullToRefresh: String { L10n.tr("Localizable", "pull_to_refresh") }
internal enum Main {
/// Hello %@
internal static func hello(_ p1: String) -> String {
return L10n.tr("Localizable", "Main.hello", p1)
}
/// Setting
internal static var setting: String { L10n.tr("Localizable", "Main.Setting") }
}
}
// swiftlint:enable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:enable nesting type_body_length type_name
// MARK: - Implementation Details
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
// swiftlint:disable:next nslocalizedstring_key
let languageCode = Language.sharedInstance.languageCode.rawValue
guard let path = Bundle.main.path(forResource: languageCode, ofType: "lproj"),
let bundle = Bundle(path: path) else {
return NSLocalizedString(key, comment: "")
}
let defaultValue: String
if let path = Bundle.main.path(forResource: LanguageCode.english.rawValue, ofType: "lproj"),
let englishBundle = Bundle(path: path) {
defaultValue = NSLocalizedString(key, tableName: table, bundle: englishBundle, comment: "")
} else {
defaultValue = NSLocalizedString(key, comment: "")
}
let format = NSLocalizedString(key, tableName: table, bundle: bundle, value: defaultValue, comment: "")
return String(format: format, locale: Locale.current, arguments: args)
}
}
| true
|
7c87f504d2f22b2675dc3967407d7ccc37c10de3
|
Swift
|
ElfSundae/ffmpeg-player
|
/FFmpegPlayer-Swift/player/audio/FFAudioPlayer.swift
|
UTF-8
| 5,062
| 2.578125
| 3
|
[] |
no_license
|
//
// FFAudioPlayer.swift
// FFmpegPlayer-Swift
//
// Created by youxiaobin on 2021/1/21.
//
import Foundation
import AudioToolbox
protocol FFAudioPlayerProtocol {
func readNextAudioFrame(_ aqBuffer: AudioQueueBufferRef)
func updateAudioClock(pts: Double, duration: Double)
}
func audioQueueCallBack(inUserData: UnsafeMutableRawPointer?, audioQueue: AudioQueueRef, aqBuffer: AudioQueueBufferRef) {
guard let inUserData = inUserData else { return }
let player = Unmanaged<FFAudioPlayer>.fromOpaque(inUserData).takeUnretainedValue()
player.reuseAQBuffer(aqBuffer)
}
class FFAudioPlayer {
private var absd: AudioStreamBasicDescription
private let delegate: FFAudioPlayerProtocol
private let audioInformation: FFAudioInformation
private var audioQueue: AudioQueueRef?
private var buffers: CFMutableArray!
private let maxBufferCount = 3
deinit {
if let audioQueue = self.audioQueue {
AudioQueueDispose(audioQueue, true)
(0..<maxBufferCount).forEach {
let p = CFArrayGetValueAtIndex(self.buffers, $0).bindMemory(to: AudioQueueBuffer.self, capacity: 1)
let aqBuffer = AudioQueueBufferRef.init(mutating: p)
AudioQueueFreeBuffer(audioQueue, aqBuffer)
}
}
CFArrayRemoveAllValues(self.buffers)
}
init(_ audioInformation: FFAudioInformation, _ delegate: FFAudioPlayerProtocol) {
self.audioInformation = audioInformation
self.absd = AudioStreamBasicDescription.init(mSampleRate: Float64(audioInformation.rate),
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked,
mBytesPerPacket: UInt32(audioInformation.bytesPerSample),
mFramesPerPacket: 1,
mBytesPerFrame: UInt32(audioInformation.bytesPerSample),
mChannelsPerFrame: UInt32(audioInformation.channels),
mBitsPerChannel: UInt32(audioInformation.bitsPerChannel),
mReserved: 0)
self.delegate = delegate
_ = setupAudioQueue()
}
//MARK: -
private func setupAudioQueue() -> Bool {
let p = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
let ret = AudioQueueNewOutput(&(self.absd), audioQueueCallBack, p, nil, nil, 0, &audioQueue)
guard ret == errSecSuccess else { return false }
self.buffers = CFArrayCreateMutable(kCFAllocatorDefault, maxBufferCount, nil)
(0..<maxBufferCount).forEach { _ in
var aqBuffer: AudioQueueBufferRef? = nil
let status = AudioQueueAllocateBuffer(self.audioQueue!, UInt32(self.audioInformation.bufferSize), &aqBuffer)
guard status == errSecSuccess else { fatalError() }
CFArrayAppendValue(self.buffers, aqBuffer)
}
return true
}
}
extension FFAudioPlayer {
public func reuseAQBuffer(_ aqBuffer: AudioQueueBufferRef) {
print("[AudioPlayer]Reuse AQ Buffer")
self.delegate.readNextAudioFrame(aqBuffer)
}
}
// MARK: - Control
extension FFAudioPlayer {
public func play() {
guard let audioQueue = self.audioQueue else { return }
AudioQueueStart(audioQueue, nil)
(0..<maxBufferCount).forEach {
let p = CFArrayGetValueAtIndex(self.buffers, $0)
let aqBuffer = AudioQueueBufferRef.init(mutating: p!.bindMemory(to: AudioQueueBuffer.self, capacity: 1))
self.delegate.readNextAudioFrame(aqBuffer)
}
}
public func stop() {
guard let audioQueue = self.audioQueue else { return }
AudioQueueStop(audioQueue, true)
}
public func pause() {
guard let audioQueue = self.audioQueue else { return }
AudioQueuePause(audioQueue)
}
public func resume() {
guard let audioQueue = self.audioQueue else { return }
AudioQueueStart(audioQueue, nil)
}
public func cleanCacheData() {
guard let audioQueue = self.audioQueue else { return }
AudioQueueFlush(audioQueue)
}
}
// MARK: -
extension FFAudioPlayer {
public func receive(data: UnsafeMutablePointer<UInt8>,
length: UInt32,
aqBuffer: AudioQueueBufferRef,
pts: Double,
duration: Double) {
guard let audioQueue = self.audioQueue else { return }
aqBuffer.pointee.mAudioDataByteSize = length
memcpy(aqBuffer.pointee.mAudioData, data, Int(length))
AudioQueueEnqueueBuffer(audioQueue, aqBuffer, 0, nil)
self.delegate.updateAudioClock(pts: pts, duration: duration)
// print("[AudioPlayer]Receive audio data: \(length)")
}
}
| true
|
a0bdf91c3bdbfc327e6227f68e91342b344dc4ea
|
Swift
|
walterevansaugusta/KindergartenLiteracy
|
/Kindergarten Literacy/Letter Page/letterMainPage.swift
|
UTF-8
| 3,669
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// LettersViewController.swift
// Kindergarten Literacy
//
// Created by Bingqing Xu on 11/23/20.
// Development taken over by TigerSHe
//
import UIKit
import AVFoundation
class letterMainPage: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
playIntroMessage()
// Do any additional setup after loading the view.
}
// reference to different storyboards
let letterStoryBoard:UIStoryboard = UIStoryboard(name: "LetterPages", bundle:nil)
let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let beginStoryBoard:UIStoryboard = UIStoryboard(name: "BeginningSounds", bundle:nil)
//play intro sound
var audioPlayer: AVAudioPlayer?
func playIntroMessage() {
let pathToSound = Bundle.main.path(forResource: "00alphabet_letters", ofType: "mp3")!
let url = URL(fileURLWithPath: pathToSound)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.play()
} catch {
//bruh
}
}
// functions for sidebar
@IBAction func backButtonTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func homeButtonTapped(_ sender: Any) {
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
@IBAction func puzzleButtonTapped(_ sender: Any) {
let vc = mainStoryBoard.instantiateViewController(identifier: "puzzle_vc")
present(vc, animated: true)
}
@IBAction func coinButtonTapped(_ sender: Any) {
let vc = mainStoryBoard.instantiateViewController(identifier: "coin_vc")
present(vc, animated: true)
}
// code for main level select buttons
@IBAction func toNameBmras(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "namebmras_vc")
present(vc, animated: true)
}
@IBAction func toNameBmrasCap(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "namebmrascap_vc")
present(vc, animated: true)
}
@IBAction func toNameAbcde(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "nameabcde_vc")
present(vc, animated: true)
}
@IBAction func toNameAbcdeCap(_ sender: Any) {
let vc = letterStoryBoard.instantiateViewController(identifier: "nameabcdecap_vc")
present(vc, animated: true)
}
//goes to beginning sound
@IBAction func toSoundBmras(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "twoButton_vc")
present(vc, animated: true)
}
@IBAction func toSoundAbcde(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "oneButton_vc")
present(vc, animated: true)
}
@IBAction func toSoundBmrasCap(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "fourButton_vc")
present(vc, animated: true)
}
@IBAction func toSoundAbcdeCap(_ sender: Any) {
let vc = beginStoryBoard.instantiateViewController(identifier: "threeButton_vc")
present(vc, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
448a9ea4766527b7f0b4a73cdd65d9bc555c61bc
|
Swift
|
thinkaboutiter/serverside-swift-with-perfect
|
/BubblyChat/client/BubblyChatClient/BubblyChatClient/Source/Utilities/AppUtilities.swift
|
UTF-8
| 818
| 3
| 3
|
[] |
no_license
|
//
// AppUtilities.swift
// BubblyChatClient
//
// Created by boyankov on W08 22/Feb/2018 Thu.
// Copyright © 2018 boyankov@yahoo.com. All rights reserved.
//
import Foundation
/**
Execute closure on main queue *async* after delay (in seconds)
- parameter delay: Time interval (in seconds) after which closure will be executed
- parameter completion: Closure to be executed on `main` thread
*/
func executeAsyncOnMainQueue(afterDelay delay: Double, _ completion: @escaping (() -> Void)) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
completion()
}
}
func executeOnMainQueue(async: Bool, block: @escaping () -> Void) {
if async {
DispatchQueue.main.async {
block()
}
}
else {
DispatchQueue.main.sync {
block()
}
}
}
| true
|
d52f3d83ec5e554c79b111adcc68301fed542f8a
|
Swift
|
n3wtype/NagBar
|
/NagBar/ServiceMonitoringItem.swift
|
UTF-8
| 429
| 2.5625
| 3
|
[
"CC0-1.0",
"CC-BY-3.0",
"CC-BY-4.0",
"Apache-2.0"
] |
permissive
|
//
// ServiceMonitoringItem.swift
// NagBar
//
// Created by Volen Davidov on 10/25/15.
// Copyright © 2015 Volen Davidov. All rights reserved.
//
import Foundation
class ServiceMonitoringItem: MonitoringItem {
override init() {
super.init()
self.monitoringItemType = .service
}
override func uniqueIdentifier() -> String {
return self.host + ":" + self.service + ":" + self.status
}
}
| true
|
614259d7c14c675f8a4b62906357281c8580116c
|
Swift
|
6110613285/Finalprojectcn333
|
/RURIGHTGAME/lastpage.swift
|
UTF-8
| 2,498
| 2.6875
| 3
|
[] |
no_license
|
//
// lastpage.swift
// project311(R U RIGHT)
//
// Created by Rathapol Putharaksa on 6/5/2564 BE.
//
import SwiftUI
struct lastpage: View {
@Binding var showyourname : Bool
@Binding var showhome : Bool
@Binding var showlastpage : Bool
@Binding var score : Int
@Binding var name : String
@Binding var showscore : Bool
@ObservedObject var highscoreplayer = highscoredata()
var body: some View {
ZStack{
Color.black
.ignoresSafeArea()
VStack{
Text("HIGH SCORE").font(.largeTitle).bold().colorInvert().padding(.top,100).padding(.bottom,50)
HStack{
Spacer()
VStack{
Text("NAME").font(.title).bold().colorInvert()
}
Spacer()
VStack{
Text("SCORE").font(.title).bold().colorInvert()
}
Spacer()
}.frame(width:UIScreen.main.bounds.width)
VStack{
HStack{
Spacer()
VStack{
ForEach(highscoreplayer.getdata()){i in
Text("\(i.name)").colorInvert().font(.title)
}
/*Text("\(name)").colorInvert().font(.title)*/
}.padding(.horizontal)
Spacer()
VStack{
ForEach(highscoreplayer.getdata()){i in
Text("\(i.score)").colorInvert().font(.title)
}
/*if (showscore){
Text("\(score)" ).colorInvert().font(.title)
}*/
}.padding(.horizontal,40)
Spacer()
}.frame(width:UIScreen.main.bounds.width)
}
Spacer()
Button("NEW GAME"){
showhome = true
score = 0
showyourname = false
showlastpage = false
name = ""
}.frame(width: UIScreen.main.bounds.width - 50, height: 50)
.foregroundColor(.white).background(Color.orange).padding(.bottom,100)
}
}
}
}
| true
|
a82ad3d42e1a09201846e7d57c0ced1eacaffa84
|
Swift
|
apeksha-b/iOS-Curriculum
|
/Workshop 3/workshop 3.2/workshop 3/GameOverViewController.swift
|
UTF-8
| 573
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// GameOverViewController.swift
// workshop 3
//
// Created by Federico Naranjo on 2019-08-22.
// Copyright © 2019 Federico Naranjo. All rights reserved.
//
import UIKit
class GameOverViewController: UIViewController {
var winner: String!
@IBOutlet weak var winnerLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print("\n# end game view controller\n")
if let winnerText = winner {
winnerLabel.text = winnerText
}
}
}
| true
|
3093c40b071c447613415d246dca61be64b20a37
|
Swift
|
ddrccw/ConnectionKit
|
/ConnectionKit/Classes/Socket/CKSResponse.swift
|
UTF-8
| 1,025
| 3.09375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// CKSResponse.swift
// ConnectionKit-iOS
//
// Created by ddrccw on 2018/3/19.
// Copyright © 2018年 ddrccw. All rights reserved.
//
import Foundation
/// Used to store all data associated with an non-serialized response of a data or upload request.
struct CKSDefaultDataResponse {
/// The task sent to the server.
let task: CKSTask?
/// The data returned by the server.
public let data: Data?
/// The error encountered while executing or validating the request.
public let error: Error?
/// Creates a `DefaultDataResponse` instance from the specified parameters.
///
/// - Parameters:
/// - request: The URL request sent to the server.
/// - data: The data returned by the server.
/// - error: The error encountered while executing or validating the request.
public init(
task: CKSTask?,
data: Data?,
error: Error?)
{
self.task = task
self.data = data
self.error = error
}
}
| true
|
944e0a39cefe4ebf926ccac2b308092ad24fe4d3
|
Swift
|
wikimedia/wikipedia-ios
|
/Wikipedia/Code/WMFDeleteBackwardReportingTextField.swift
|
UTF-8
| 694
| 3
| 3
|
[
"MIT"
] |
permissive
|
/// Protocol for notifying a delegate that a UITextField's keyboard delete button
/// was pressed even if the text field is empty, which doesn't appear to get
/// reported to other UITextFieldDelegate methods.
/// See: http://stackoverflow.com/a/13017462/135557
public protocol WMFDeleteBackwardReportingTextFieldDelegate {
func wmf_deleteBackward(_ sender: WMFDeleteBackwardReportingTextField)
}
public class WMFDeleteBackwardReportingTextField : ThemeableTextField {
var deleteBackwardDelegate: WMFDeleteBackwardReportingTextFieldDelegate?
override public func deleteBackward() {
deleteBackwardDelegate?.wmf_deleteBackward(self)
super.deleteBackward()
}
}
| true
|
677c25f773436c367b2f15bf9fb1e8a11912d4c8
|
Swift
|
abable/Swift_PageControl_Controls
|
/PageControl/PageControl/ViewController.swift
|
UTF-8
| 3,029
| 3.109375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// PageControl
//
// Created by Seungjun Lim on 22/05/2019.
// Copyright © 2019 Seungjun Lim. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var listCollectionView: UICollectionView!
@IBOutlet weak var pager: UIPageControl!
let list = [UIColor.red, UIColor.green, UIColor.blue, UIColor.gray, UIColor.black]
// Action 을 연결하고 value changed 를 처리하겠습니다.
@IBAction func pageChanged(_ sender: UIPageControl) {
fromTap = true // 플래그를 트루로 변경..
// 컬렉션 뷰를 새로운 페이지로 스크롤하도록 구현..
let indexPath = IndexPath(item: sender.currentPage, section: 0)
listCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
// 페이지업데이트가 탭이벤트로 시작되었는지 확인하기 위해 클래스에 플래그 추가.
var fromTap = false
override func viewDidLoad() {
super.viewDidLoad()
pager.numberOfPages = list.count
pager.currentPage = 0
pager.pageIndicatorTintColor = UIColor.lightGray
pager.currentPageIndicatorTintColor = UIColor.red
// page 인디케이터가 자동으로 업데이트 되지 않도록 해야한다. 스크롤이 끝난후에 메소드를 호출해서 수동으로 업데이트 해야한다.
pager.defersCurrentPageDisplay = true
}
}
// extension...
extension ViewController: UIScrollViewDelegate {
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
// 플래그를 초기화 하고, 페이지 인디케이터를 업데이트 하겠습니다.
fromTap = false
pager.updateCurrentPageDisplay()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 플래그가 폴스일때만 실행하도록..
guard !fromTap else {return}
let width = scrollView.bounds.size.width
let x = scrollView.contentOffset.x + (width / 2.0)
let newPage = Int(x / width)
if pager.currentPage != newPage {
pager.currentPage = newPage
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = list[indexPath.item]
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.bounds.size
}
}
| true
|
c063bbd1e6f3eab20814b21ff2530b2145df3b26
|
Swift
|
Flyte27/Haven
|
/Haven/AnimalBasicCell.swift
|
UTF-8
| 700
| 2.703125
| 3
|
[] |
no_license
|
//
// AnimalBasicCell.swift
// Haven
//
// Created by Alex Payne on 2018-04-17.
// Copyright © 2018 Alex Payne. All rights reserved.
//
import UIKit
class AnimalBasicCell: UITableViewCell {
@IBOutlet weak var animalImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var cutenessLabel: UILabel!
override func awakeFromNib() {
animalImageView.layer.cornerRadius = 5.0
animalImageView.layer.masksToBounds = true
}
func populate(animal: Animal) {
animalImageView.image = animal.image ?? UIImage(named: "dog-icon")
nameLabel.text = animal.name
cutenessLabel.text = String.getCutenessString()
}
}
| true
|
4911693c2521787273a95de1583f83fbabb3878c
|
Swift
|
erictang0212/Real
|
/Real/Real/View/Cell/Chat/ReceiverTableViewCell.swift
|
UTF-8
| 1,100
| 2.515625
| 3
|
[] |
no_license
|
//
// ReceiverTableViewCell.swift
// Real
//
// Created by 唐紹桓 on 2020/12/8.
//
import UIKit
class ReceiverTableViewCell: UITableViewCell {
@IBOutlet weak var createdTimeLabel: UILabel!
@IBOutlet weak var receiverImageView: UIImageView!
@IBOutlet weak var messageLabel: LabelPadding! {
didSet {
messageLabel.textColor = .white
messageLabel.backgroundColor = .black
messageLabel.clipsToBounds = true
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
messageLabel.setup(cornerRadius: 10)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setup(data: Message, image: String) {
messageLabel.text = data.message
receiverImageView.loadImage(urlString: image)
createdTimeLabel.text = data.createdTime.compareCurrentTime()
}
}
| true
|
fc3d45e51fd009731da005259173f7c1418993be
|
Swift
|
kevinjdonohue/swiftPlaygrounds
|
/Structures.playground/Contents.swift
|
UTF-8
| 464
| 3.78125
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
class Person {
var firstName: String = ""
var lastName: String = ""
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
struct AnotherPerson {
var firstName: String = ""
var lastName: String = ""
}
var ap1 = AnotherPerson(firstName: "Kevin", lastName: "Donohue")
var ap2 = ap1
print(ap1)
print(ap2)
| true
|
f0841ab9d30b2bc8d667a8079522e2c248e57376
|
Swift
|
estherjk/esthers-books-swiftui
|
/EsthersBooks/Shared/Stores/TokenStore.swift
|
UTF-8
| 933
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// TokenStore.swift
// EsthersBooks (iOS)
//
// Created by Esther Kim on 8/20/20.
//
import SwiftUI
import KeychainAccess
class TokenStore {
let keychain = Keychain(service: "tech.esthermakes.EsthersBooks.TokenStore")
private struct Keys {
static let accessToken = "accessToken"
static let refreshToken = "refreshToken"
}
func saveAccessToken(tokenString: String) {
keychain[Keys.accessToken] = tokenString
}
func getAccessToken() -> String? {
return keychain[Keys.accessToken]
}
func removeAccessToken() {
keychain[Keys.accessToken] = nil
}
func saveRefreshToken(tokenString: String) {
keychain[Keys.refreshToken] = tokenString
}
func getRefreshToken() -> String? {
return keychain[Keys.refreshToken]
}
func removeRefreshToken() {
keychain[Keys.refreshToken] = nil
}
}
| true
|
285126c6227b2db7b169d5ffb78983ca1096f4a6
|
Swift
|
Magic-Solutions-DMCC/VDKit
|
/Sources/VDKit/UIKitExtensions/BlurView.swift
|
UTF-8
| 1,617
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// BlurView.swift
// MusicImport
//
// Created by Данил Войдилов on 05.07.2019.
// Copyright © 2019 Данил Войдилов. All rights reserved.
//
import UIKit
open class BlurEffectView: UIVisualEffectView {
@IBInspectable open var blurColor: UIColor? {
get { return subviews.filter { $0.backgroundColor != nil }.last?.backgroundColor }
set {
if let color = newValue {
style = .custom(color)
} else {
style = .light
}
}
}
public enum Style {
case light, dark, extraLight, custom(UIColor)
var defaultStyle: UIBlurEffect.Style {
switch self {
case .dark: return .dark
case .extraLight: return .extraLight
default: return .light
}
}
}
open var style: Style {
didSet {
if case .custom(let color) = style {
setColor(color)
} else {
super.effect = UIBlurEffect(style: style.defaultStyle)
}
}
}
public init(style: Style) {
self.style = style
super.init(effect: UIBlurEffect(style: style.defaultStyle))
}
public convenience init(color: UIColor?) {
self.init(style: .custom(color ?? .clear))
}
required public init?(coder aDecoder: NSCoder) {
self.style = .light
super.init(coder: aDecoder)
}
override open func addSubview(_ view: UIView) {
if case .custom(let color) = style, view.backgroundColor != nil {
view.backgroundColor = color
}
super.addSubview(view)
}
override open func layoutSubviews() {
super.layoutSubviews()
if case .custom(let color) = style {
setColor(color)
}
}
private func setColor(_ color: UIColor) {
subviews.filter { $0.backgroundColor != nil }.last?.backgroundColor = color
}
}
| true
|
56816f257b70868b2c34e38e8a11dcb897935d35
|
Swift
|
JanuszPXYZ/NeumorphicTicTacToe
|
/NeumorphicTTT/ContentView.swift
|
UTF-8
| 8,552
| 3.203125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// NeumorphicTTT
//
// Created by Janusz Polowczyk on 15/09/2021.
//
import SwiftUI
struct ContentView: View {
let columns = [GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())]
@State var toggled = Array(repeating: false, count: 9)
@State private var moves: [Move?] = Array(repeating: nil, count: 9)
@State private var humanScore = 0
@State private var draw = 0
@State private var computerScore = 0
@State private var isGameboardDisabled = false
@State private var alertItem: AlertItem?
var body: some View {
ZStack {
LinearGradient(Color.darkStart, Color.darkEnd)
LazyVGrid(columns: columns) {
ForEach(0..<9) { item in
ZStack {
Circle()
.foregroundColor(Color.black)
.shadow(color: moves[item]?.boardIndex != nil ? Color.darkStart : Color.darkEnd, radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/, x: 10.0, y: 10.0)
.shadow(color: moves[item]?.boardIndex != nil ? Color.darkEnd : Color.darkStart, radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/, x: -5.0, y: -5.0)
.frame(width: 80, height: 80)
//
Image(systemName: moves[item]?.indicator ?? "")
}
.onTapGesture {
if isSquareOccupied(in: moves, for: item) { return }
moves[item] = Move(player: .human, boardIndex: item, isChecked: true)
toggled[item] = true
// check for win condition or draw
if checkWinCondition(for: .human, in: moves) {
print("Human wins")
humanScore += 1
alertItem = AlertContext.humanWin
return
}
if checkForDraw(in: moves) {
print("Draw")
draw += 1
alertItem = AlertContext.draw
return
}
isGameboardDisabled = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
let computerPosition = determineComputerMovePosition(in: moves)
moves[computerPosition] = Move(player: .computer, boardIndex: computerPosition, isChecked: true)
toggled[computerPosition] = true
isGameboardDisabled = false
if checkWinCondition(for: .computer, in: moves) {
print("Computer wins")
computerScore += 1
alertItem = AlertContext.computerWin
return
}
if checkForDraw(in: moves) {
print("Draw")
draw += 1
return
}
}
}
}
}
.disabled(isGameboardDisabled)
.padding()
.alert(item: $alertItem) { alertItem in
Alert(title: alertItem.title, message: alertItem.message,
dismissButton: .default(alertItem.buttonTitle,
action: { resetGame() }))
}
VStack(spacing: 20) {
Text("Tic - Tac - Toe")
.font(.system(size: 35, weight: .light, design: .monospaced))
.foregroundColor(.white)
Spacer()
// MARK: Scoreboard here, uncomment to add to the VStack
// VStack(alignment: .center, spacing: 5) {
// Text("AI score: \(computerScore)")
// .font(.system(.headline))
// .foregroundColor(Color.white)
// Text("Draws: \(draw)")
// .font(.system(.headline))
// .foregroundColor(Color.white)
// Text("Human score: \(humanScore)")
// .font(.system(.headline))
// .foregroundColor(Color.white)
// }
// .frame(width: 200, height: 80)
// .background(Color.black)
// .cornerRadius(10.0)
// .shadow(color: Color.darkStart, radius: 10, x: 10, y: 10)
// .shadow(color: Color.darkEnd, radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/, x: -5.0, y: -5.0)
}
.padding(.top, 100)
.padding(.bottom, 100)
}
.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
}
func isSquareOccupied(in moves: [Move?], for index: Int) -> Bool {
return moves.contains(where: { $0?.boardIndex == index })
}
func determineComputerMovePosition(in moves: [Move?]) -> Int {
// If AI can win, then win
let winPatterns: Set<Set<Int>> = [[0,1,2], [3,4,5], [6,7,8], [0,3,6],
[1,4,7], [2,5,8], [0,4,8], [2,4,6]]
let computerMoves = moves.compactMap { $0 }.filter{ $0.player == .computer }
let computerPositions = Set(computerMoves.map { $0.boardIndex })
for pattern in winPatterns {
let winPositions = pattern.subtracting(computerPositions)
if winPositions.count == 1 {
let isAvailable = !isSquareOccupied(in: moves, for: winPositions.first!)
if isAvailable { return winPositions.first! }
}
}
// If AI can't win, then block
let humanMoves = moves.compactMap { $0 }.filter{ $0.player == .human }
let humanPositions = Set(humanMoves.map { $0.boardIndex })
for pattern in winPatterns {
let winPositions = pattern.subtracting(humanPositions)
if winPositions.count == 1 {
let isAvailable = !isSquareOccupied(in: moves, for: winPositions.first!)
if isAvailable { return winPositions.first! }
}
}
// If AI can't block, then take middle square
let centerSquare = 4
if !isSquareOccupied(in: moves, for: centerSquare) {
return centerSquare
}
// If AI can't take middle square, take random available square
var movePosition = Int.random(in: 0..<9)
while isSquareOccupied(in: moves, for: movePosition) {
movePosition = Int.random(in: 0..<9)
}
return movePosition
}
func checkWinCondition(for player: Player, in moves: [Move?]) -> Bool {
let winPatterns: Set<Set<Int>> = [[0,1,2], [3,4,5], [6,7,8], [0,3,6],
[1,4,7], [2,5,8], [0,4,8], [2,4,6]]
let playerMoves = moves.compactMap { $0 }.filter{ $0.player == player }
let playerPositions = Set(playerMoves.map { $0.boardIndex })
for pattern in winPatterns where pattern.isSubset(of: playerPositions) { return true }
return false
}
func checkForDraw(in moves: [Move?]) -> Bool {
return moves.compactMap { $0 }.count == 9
}
func resetGame() {
moves = Array(repeating: nil, count: 9)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
4986556e0eac3963e0a7165eed2d0ac9d4f072ee
|
Swift
|
srikanth1222/Piingo-App-Objective-C
|
/Piingo App/PiingApp/GeofenceViewController.swift
|
UTF-8
| 10,408
| 2.984375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Test Geofence
//
// Created by Veedepu Srikanth on 04/01/18.
// Copyright © 2018 Piing. All rights reserved.
//
import UIKit
import CoreLocation
import UserNotifications
@available(iOS 10.0, *)
@objc class GeofenceViewController: UIViewController, CLLocationManagerDelegate, UNUserNotificationCenterDelegate {
let ENTERED_REGION_MESSAGE = "Welcome to Piing!"
let ENTERED_REGION_NOTIFICATION_ID = "EnteredRegionNotification"
let EXITED_REGION_MESSAGE = "Bye! Hope you had a great day at Piing!"
let EXITED_REGION_NOTIFICATION_ID = "ExitedRegionNotification"
var notificationCenter = UNUserNotificationCenter.current()
var locationManager = CLLocationManager()
let radius:Double = 100
@IBOutlet weak var lblLatitude: UILabel!
@IBOutlet weak var lblLongitude: UILabel!
// Gachibowli
let latitude = 17.431381
let longitude = 78.373930
// ABR Residency
// let latitude = 17.359114
// let longitude = 78.520559
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
// register as it's delegate
notificationCenter.delegate = self
// define what do you need permission to use
let options: UNAuthorizationOptions = [.alert, .sound]
// request permission
notificationCenter.requestAuthorization(options: options) { (granted, error) in
if !granted {
print("Permission not granted")
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func geofenceMethod () {
// Your coordinates go here (lat, lon)
let geofenceRegionCenter = CLLocationCoordinate2DMake(latitude,longitude)
/* Create a region centered on desired location,
choose a radius for the region (in meters)
choose a unique identifier for that region */
let geofenceRegion = CLCircularRegion(center: geofenceRegionCenter,
radius: radius,
identifier: "UniqueIdentifier2")
geofenceRegion.notifyOnEntry = true
geofenceRegion.notifyOnExit = true
locationManager.startMonitoring(for: geofenceRegion)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.authorizedAlways) {
//App Authorized, stablish geofence
geofenceMethod()
}
else if (status == CLAuthorizationStatus.authorizedWhenInUse) {
//App Authorized, stablish geofence
geofenceMethod()
}
}
func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
print("Started Monitoring Region: \(region.identifier)")
self.locationManager.requestState(for: region);
}
// called when user Exits a monitored region
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
if region is CLCircularRegion {
// Do what you want if this information
print("Region exited")
self.handleEvent(forRegion: region, withMessage:EXITED_REGION_MESSAGE, notifIdentifier:EXITED_REGION_NOTIFICATION_ID)
}
let alertCon = UIAlertController(title: "oooopss!!!", message: "Region Exited", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertCon.addAction(action)
present(alertCon, animated: true, completion: nil)
}
// called when user Enters a monitored region
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLCircularRegion {
// Do what you want if this information
print("Region entered")
self.handleEvent(forRegion: region, withMessage:ENTERED_REGION_MESSAGE, notifIdentifier:ENTERED_REGION_NOTIFICATION_ID)
}
let alertCon = UIAlertController(title: "Yahoo!!!", message: "Region Entered", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertCon.addAction(action)
present(alertCon, animated: true, completion: nil)
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
print(state)
if state == .inside {
let alertCon = UIAlertController(title: "Yahoo!!!", message: "Region Entered", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertCon.addAction(action)
present(alertCon, animated: true, completion: nil)
}
else if state == .outside {
let alertCon = UIAlertController(title: "oooopss!!!", message: "Region Exited", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertCon.addAction(action)
present(alertCon, animated: true, completion: nil)
}
else if state == .unknown {
let alertCon = UIAlertController(title: "Error!", message: "Region Unknown", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertCon.addAction(action)
present(alertCon, animated: true, completion: nil)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let latestLocation = locations.last
let latitude = String(format: "%f", latestLocation!.coordinate.latitude)
let longitude = String(format: "%f", latestLocation!.coordinate.longitude)
lblLatitude.text = latitude
lblLongitude.text = longitude
print("Latitude: \(latitude)")
print("Longitude: \(longitude)")
}
func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
let alertCon = UIAlertController(title: "", message: "Paused Location", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertCon.addAction(action)
present(alertCon, animated: true, completion: nil)
print ("Paused location")
}
func locationManagerDidResumeLocationUpdates(_ manager: CLLocationManager) {
let alertCon = UIAlertController(title: "", message: "Resumed Location", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alertCon.addAction(action)
present(alertCon, animated: true, completion: nil)
print ("Resumed location")
}
func handleEvent(forRegion region: CLRegion!, withMessage message:String, notifIdentifier identifier:String) {
// customize your notification content
let content = UNMutableNotificationContent()
content.title = "Piing!"
content.body = message
content.sound = UNNotificationSound.default()
// // when the notification will be triggered
// let timeInSeconds: TimeInterval = (60 * 15) // 60s * 15 = 15min
// // the actual trigger object
// let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInSeconds,
// repeats: false)
//
// notification unique identifier, for this example, same as the region to avoid duplicate notifications
//let identifier = region.identifier
// the notification request object
let request = UNNotificationRequest(identifier: identifier,
content: content,
trigger: nil)
// trying to add the notification request to notification center
notificationCenter.add(request, withCompletionHandler: { (error) in
if error != nil {
print("Error adding notification with identifier: \(identifier)")
}
})
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// when app is onpen and in foregroud
completionHandler(.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// get the notification identifier to respond accordingly
let identifier = response.notification.request.identifier
// do what you need to do
// ...
}
}
| true
|
c6a7467410566c6bed5e5756669980eaad1acdc3
|
Swift
|
hugosilvac/top-movies
|
/topmovies/Network/Api/Configuration/Request.swift
|
UTF-8
| 2,074
| 2.921875
| 3
|
[] |
no_license
|
//
// Request.swift
// topmovies
//
// Created by HugoSilva on 3/21/19.
// Copyright © 2019 HugoSilva. All rights reserved.
//
import RxSwift
import Alamofire
enum Method: String {
case GET, POST, PUT, PATCH, DELETE
}
enum UrlEncoding {
case json
case url
}
class Request {
fileprivate static var baseURL: String = NetworkConstants.Config.BaseURL
fileprivate static var url: String = baseURL
fileprivate static var method: Alamofire.HTTPMethod = .get
fileprivate static var parameters: [String: Any] = [:]
fileprivate static var data: Data = Data()
fileprivate static var headers: [String: String] = [:]
fileprivate static var encoding: ParameterEncoding = URLEncoding.queryString
fileprivate static let disposeBag = DisposeBag()
public static func method(_ method: Method) -> Request.Type {
self.method = HTTPMethod(rawValue: method.rawValue)!
return self
}
public static func queryParameters(_ parameters: [String: Any]) -> Request.Type {
self.parameters = parameters
self.parameters["api_key"] = "51c0a758d5713ea61827aab48b4664d0"
return self
}
public static func header(_ headers: [String: String]) -> Request.Type {
self.headers = headers
self.headers["Content-Type"] = "application/json"
self.headers["Accept-Encoding"] = "application/gzip"
return self
}
public static func encodParameters(_ encoding: UrlEncoding) -> Request.Type {
self.encoding = encoding == .json ? JSONEncoding.default : URLEncoding.queryString
return self
}
public static func request() -> Observable<(HTTPURLResponse, Any)> {
let result = Request.sharedManager
.rx.responseJSON(method, url, parameters: parameters, encoding: encoding, headers: headers)
return result
}
}
typealias RequestURL = Request
extension RequestURL {
public static func fromPathURL(_ path: String) -> Request.Type {
self.url = baseURL + path
return self
}
}
| true
|
32c24aea7ca6be55ef6a8a1f9968f7eb01deb7f1
|
Swift
|
The-Fighting-Mongeese/TowerVille
|
/TowerVille/Rendering/UI/UICellStructure.swift
|
UTF-8
| 535
| 2.546875
| 3
|
[] |
no_license
|
//
// UICellTower.swift
// TowerVille
//
// Created by Jason Cheung on 2018-02-28.
// Copyright © 2018 The-Fighting-Mongeese. All rights reserved.
//
import Foundation
import UIKit
class UICellStructure: UICollectionViewCell {
@IBOutlet var icon: UIImageView!
@IBOutlet var label: UILabel!
@IBOutlet var costLabel: UILabel!
func displayContent(image: UIImage, title: String, cost: Int)
{
self.icon.image = image
self.label.text = title
self.costLabel.text = String(cost)
}
}
| true
|
55affa78da50f9121ee12167a40a38b10b9ac269
|
Swift
|
toffeedekcom/SoccerSquad
|
/SoccerSquad/Reachabillity.swift
|
UTF-8
| 1,049
| 2.53125
| 3
|
[] |
no_license
|
//
// Reachabillity.swift
// Soccer Squad
//
// Created by CSmacmini on 4/4/2560 BE.
// Copyright © 2560 firebaseDB. All rights reserved.
//
//Network checking
import Foundation
import SystemConfiguration
public class Reachabillity {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
| true
|
fb88326d3444c3fa814090ec3e57e15f885ef799
|
Swift
|
kindaof/SBCourse-1
|
/SBCourse1 HW3.playground/Pages/Задание 3.xcplaygroundpage/Contents.swift
|
UTF-8
| 665
| 4.21875
| 4
|
[] |
no_license
|
import Foundation
/*:
### Задание 3
3.1 Определите квартал в котором вы родились, используя switch.
*/
let monthOfBirth = 8
switch monthOfBirth {
case 1...3:
print("ты родился в первом квартале")
case 4...6:
print("ты родился во втором квартале")
case 7...9:
print("ты родился в третьем квартале")
case 10...12:
print("ты родился в четвертом квартале")
default:
break
}
//: [Ранее: Задание 2](@previous) | задание 3 из 6 | [Далее: Задание 4](@next)
| true
|
6b85a3fdd109dd2f96ae01ff8ec156041191c1dd
|
Swift
|
MhmdSalah/Subscriptions
|
/In-App Purchases/Models/Session.swift
|
UTF-8
| 1,392
| 2.640625
| 3
|
[] |
no_license
|
//
// Session.swift
// In-App Purchases
//
// Created by Igor Medelian on 10/1/19.
// Copyright © 2019 imedelyan. All rights reserved.
//
import Foundation
public struct Session {
public let id: String
public var paidSubscriptions: [PaidSubscription]
public var currentSubscriptions: [PaidSubscription] {
let activeSubscriptions = paidSubscriptions.filter { $0.isActive }
return activeSubscriptions.sorted { $0.purchaseDate > $1.purchaseDate }
}
public var receiptData: Data
public var parsedReceipt: [String: Any]
init(receiptData: Data, parsedReceipt: [String: Any]) {
id = UUID().uuidString
self.receiptData = receiptData
self.parsedReceipt = parsedReceipt
if let receipt = parsedReceipt["receipt"] as? [String: Any], let purchases = receipt["in_app"] as? [[String: Any]] {
var subscriptions = [PaidSubscription]()
for purchase in purchases {
if let paidSubscription = PaidSubscription(json: purchase) {
subscriptions.append(paidSubscription)
}
}
paidSubscriptions = subscriptions
} else {
paidSubscriptions = []
}
}
}
// MARK: - Equatable
extension Session: Equatable {
public static func ==(lhs: Session, rhs: Session) -> Bool {
return lhs.id == rhs.id
}
}
| true
|
56b223e8ef3508ceba1b80a72beb30f4d4945ed4
|
Swift
|
ushisantoasobu/HotChat
|
/HotChat/models/User.swift
|
UTF-8
| 405
| 2.515625
| 3
|
[] |
no_license
|
//
// User.swift
// HotChat
//
// Created by 佐藤 俊輔 on 2016/04/20.
// Copyright © 2016年 moguraproject. All rights reserved.
//
import Foundation
struct User {
var identifier :Int = 0
var name :String = ""
var imageUrl :String = ""
var openFb :Bool = false
init() {}
init(name :String, imageUrl :String) {
self.name = name
self.imageUrl = imageUrl
}
}
| true
|
660eeaa185cdb53a6c554642cb8695aa84411d7a
|
Swift
|
yeisonvargasf/ShoppingCart
|
/Shopping Cart/ViewController.swift
|
UTF-8
| 3,221
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Shopping Cart
//
// Created by Yeison Vargas on 17/03/17.
// Copyright © 2017 Megaterios. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
var allProducts = Product.allProducts
var productAddedArray = [Product]()
var total = 0.0
@IBOutlet weak var rightCornerCounter: UILabel!
@IBOutlet weak var productsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.labelAction(_:)))
rightCornerCounter.addGestureRecognizer(tap)
tap.delegate = self
}
func labelAction(_: UITapGestureRecognizer) {
let modalShoppingCart = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "modal") as! ModalViewController
self.addChildViewController(modalShoppingCart)
modalShoppingCart.view.frame = self.view.frame
self.view.addSubview(modalShoppingCart.view)
modalShoppingCart.didMove(toParentViewController: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Table View Data Source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "product")!
let product = self.allProducts[(indexPath as NSIndexPath).row]
// Set the name and image
(cell.viewWithTag(1) as! UILabel).text = product.name
(cell.viewWithTag(2) as! UILabel).text = product.price
(cell.viewWithTag(3) as! UILabel).text = product.stock
let buy = (cell.viewWithTag(4) as! UIButton)
buy.tag = indexPath.row
buy.addTarget(self, action: #selector(addToShoppingCar(buttonClicked:)), for: .touchUpInside)
return cell
}
func addToShoppingCar(buttonClicked: UIButton) {
var product = self.allProducts[buttonClicked.tag]
self.productAddedArray.append(product)
if Int(product.stock) == 0 {
allProducts.remove(at: buttonClicked.tag)
//self.productsTableView!.deleteRows(at: [IndexPath(row: buttonClicked.tag, section: 0),], with: .automatic)
} else {
product.stock = "\(Int(product.stock)! - 1)"
}
rightCornerCounter.text = "\(self.productAddedArray.count) - \(getTotal())"
//self.productsTableView!.reloadRows(at: [IndexPath(row: buttonClicked.tag, section: 0),], with: .automatic)
}
func getTotal() -> Double {
for productAdded in productAddedArray {
total += Double(productAdded.price)!
}
return total
}
}
| true
|
d0cc4b9ab6133cedb965f273cb336217f3b77aeb
|
Swift
|
tomer-mil/Tipapp
|
/Tipapp/Models/TaxStep.swift
|
UTF-8
| 391
| 2.890625
| 3
|
[] |
no_license
|
//
// File.swift
// Tipapp
//
// Created by Tomer Mildworth on 09/03/2020.
// Copyright © 2020 Tomer Mildworth. All rights reserved.
//
import Foundation
struct TaxStep {
var until : Double
var taxRate : Double
var maxTax : Double
init(until: Double, taxRate: Double, maxTax: Double) {
self.until = until
self.taxRate = taxRate
self.maxTax = maxTax
}
}
| true
|
5509b6ec6a46a6d3d5dc07552aaa5ee4c0971a0d
|
Swift
|
mcand/CarrosSwift
|
/Carros/DownloadImageView.swift
|
UTF-8
| 2,194
| 2.890625
| 3
|
[] |
no_license
|
//
// DownloadImageView.swift
// Carros
//
// Created by Andre Furquin on 12/25/14.
// Copyright (c) 2014 Andre Furquim. All rights reserved.
//
import UIKit
class DownloadImageView : UIImageView {
// Para exibir a animação durante o download
var progress: UIActivityIndicatorView!
let queue = NSOperationQueue()
let mainQueue = NSOperationQueue.mainQueue()
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
createProgress()
}
// Construtor
override init(frame: CGRect) {
super.init(frame: frame)
createProgress()
}
func createProgress(){
progress = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
addSubview(progress)
}
override func layoutSubviews() {
progress.center = convertPoint(self.center,fromView: self.superview)
}
func setUrl(url: String) {
setUrl(url, cache: true)
}
func setUrl(url: String, cache: Bool){
self.image = nil
progress.startAnimating()
queue.addOperationWithBlock({self.downloadImg(url, cache: true)})
}
func downloadImg(url: String, cache: Bool) {
var data: NSData!
if(!cache) {
data = NSData(contentsOfURL: NSURL(string: url)!)!
} else {
var path = StringUtils.replace(url, string: "/", withString: "_")
path = StringUtils.replace(path, string: "\\", withString: "_")
path = StringUtils.replace(path, string: ":", withString: "_")
path = NSHomeDirectory() + "/Documents/" + path
// Se o arquivo existir no cache
let exists = NSFileManager.defaultManager().fileExistsAtPath(path)
if (exists) {
data = NSData(contentsOfFile: path)
} else {
data = NSData(contentsOfURL: NSURL(string: url)!)!
data.writeToFile(path, atomically: true)
}
}
mainQueue.addOperationWithBlock({self.showImg(data)})
}
func showImg(data: NSData) {
if(data.length > 0) {
self.image = UIImage(data: data)
}
progress.stopAnimating()
}
}
| true
|
0a7f946f0352bc7e8f5d5e90f14712e532b098ce
|
Swift
|
vapor/vapor
|
/Sources/Vapor/HTTP/Headers/HTTPHeaderCacheControl.swift
|
UTF-8
| 9,526
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import NIOHTTP1
// Comments on these properties are copied from the mozilla doc URL shown below.
extension HTTPHeaders {
/// Represents the HTTP `Cache-Control` header.
/// - See Also:
/// [Cache-Control docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
public struct CacheControl {
/// The max-stale option can be present with no value, or be present with a number of seconds. By using
/// a struct you can check the nullability of the `maxStale` variable as well as then check the nullability
/// of the `seconds` to differentiate.
public struct MaxStale {
/// The upper limit of staleness the client will accept.
public var seconds: Int?
}
/// Indicates that once a resource becomes stale, caches must not use their stale copy without
/// successful [validation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#Cache_validation) on the origin server.
public var mustRevalidate: Bool
/// Caches must check with the origin server for
/// [validation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#Cache_validation) before using the cached copy.
public var noCache: Bool
/// The cache **should not store anything** about the client request or server response.
public var noStore: Bool
/// No transformations or conversions should be made to the resource. The Content-Encoding, Content-Range, Content-Type headers must not be modified
/// by a proxy. A non-transparent proxy or browser feature such as
/// [Google's Light Mode](https://support.google.com/webmasters/answer/6211428?hl=en) might, for example, convert between image
/// formats in order to save cache space or to reduce the amount of traffic on a slow link. The `no-transform` directive disallows this.
public var noTransform: Bool
/// The response may be cached by any cache, even if the response is normally non-cacheable
public var isPublic: Bool
/// The response is for a single user and **must not** be stored by a shared cache. A private cache (like the user's browser cache) may store the response.
public var isPrivate: Bool
/// Like `must-revalidate`, but only for shared caches (e.g., proxies). Ignored by private caches.
public var proxyRevalidate: Bool
/// Indicates to not retrieve new data. This being the case, the server wishes the client to obtain a response only once and then cache. From this moment the
/// client should keep releasing a cached copy and avoid contacting the origin-server to see if a newer copy exists.
public var onlyIfCached: Bool
/// Indicates that the response body **will not change** over time.
///
/// The resource, if *unexpired*, is unchanged on the server and therefore the client should
/// not send a conditional revalidation for it (e.g. `If-None-Match` or `If-Modified-Since`) to check for updates, even when the user explicitly refreshes
/// the page. Clients that aren't aware of this extension must ignore them as per the HTTP specification. In Firefox, immutable is only honored on https:// transactions.
/// For more information, see also this [blog post](https://bitsup.blogspot.de/2016/05/cache-control-immutable.html).
public var immutable: Bool
/// The maximum amount of time a resource is considered fresh. Unlike the`Expires` header, this directive is relative to the time of the request.
public var maxAge: Int?
/// Overrides max-age or the Expires header, but only for shared caches (e.g., proxies). Ignored by private caches.
public var sMaxAge: Int?
/// Indicates the client will accept a stale response. An optional value in seconds indicates the upper limit of staleness the client will accept.
public var maxStale: MaxStale?
/// Indicates the client wants a response that will still be fresh for at least the specified number of seconds.
public var minFresh: Int?
/// Indicates the client will accept a stale response, while asynchronously checking in the background for a fresh one. The value indicates how long the client will accept a stale response.
public var staleWhileRevalidate: Int?
/// Indicates the client will accept a stale response if the check for a fresh one fails. The value indicates how many *seconds* long the client will accept the stale response after the initial expiration.
public var staleIfError: Int?
/// Creates a new `CacheControl`.
public init(
mustRevalidated: Bool = false,
noCache: Bool = false,
noStore: Bool = false,
noTransform: Bool = false,
isPublic: Bool = false,
isPrivate: Bool = false,
proxyRevalidate: Bool = false,
onlyIfCached: Bool = false,
immutable: Bool = false,
maxAge: Int? = nil,
sMaxAge: Int? = nil,
maxStale: MaxStale? = nil,
minFresh: Int? = nil,
staleWhileRevalidate: Int? = nil,
staleIfError: Int? = nil
) {
self.mustRevalidate = mustRevalidated
self.noCache = noCache
self.noStore = noStore
self.noTransform = noTransform
self.isPublic = isPublic
self.isPrivate = isPrivate
self.proxyRevalidate = proxyRevalidate
self.onlyIfCached = onlyIfCached
self.immutable = immutable
self.maxAge = maxAge
self.sMaxAge = sMaxAge
self.maxStale = maxStale
self.minFresh = minFresh
self.staleWhileRevalidate = staleWhileRevalidate
self.staleIfError = staleIfError
}
public static func parse(_ value: String) -> CacheControl? {
var set = CharacterSet.whitespacesAndNewlines
set.insert(",")
var foundSomething = false
var cache = CacheControl()
value
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "\t", with: "")
.lowercased()
.split(separator: ",")
.forEach {
let str = String($0)
if let keyPath = Self.exactMatch[str] {
cache[keyPath: keyPath] = true
foundSomething = true
return
}
if value == "max-stale" {
cache.maxStale = .init()
foundSomething = true
return
}
let parts = str.components(separatedBy: "=")
guard parts.count == 2, let seconds = Int(parts[1]), seconds >= 0 else {
return
}
if parts[0] == "max-stale" {
cache.maxStale = .init(seconds: seconds)
foundSomething = true
return
}
guard let keyPath = Self.prefix[parts[0]] else {
return
}
cache[keyPath: keyPath] = seconds
foundSomething = true
}
return foundSomething ? cache : nil
}
/// Generates the header string for this instance.
public func serialize() -> String {
var options = Self.exactMatch
.filter { self[keyPath: $0.value] == true }
.map { $0.key }
var optionsWithSeconds = Self.prefix
.filter { self[keyPath: $0.value] != nil }
.map { "\($0.key)=\(self[keyPath: $0.value]!)" }
if let maxStale = self.maxStale {
if let seconds = maxStale.seconds {
optionsWithSeconds.append("max-stale=\(seconds)")
} else {
options.append("max-stale")
}
}
return (options + optionsWithSeconds).joined(separator: ", ")
}
private static let exactMatch: [String: WritableKeyPath<Self, Bool>] = [
"immutable": \.immutable,
"must-revalidate": \.mustRevalidate,
"no-cache": \.noCache,
"no-store": \.noStore,
"no-transform": \.noTransform,
"public": \.isPublic,
"private": \.isPrivate,
"proxy-revalidate": \.proxyRevalidate,
"only-if-cached": \.onlyIfCached
]
private static let prefix: [String: WritableKeyPath<Self, Int?>] = [
"max-age": \.maxAge,
"s-maxage": \.sMaxAge,
"min-fresh": \.minFresh,
"stale-while-revalidate": \.staleWhileRevalidate,
"stale-if-error": \.staleIfError
]
}
/// Gets the value of the `Cache-Control` header, if present.
public var cacheControl: CacheControl? {
get { self.first(name: .cacheControl).flatMap(CacheControl.parse) }
set {
if let new = newValue?.serialize() {
self.replaceOrAdd(name: .cacheControl, value: new)
} else {
self.remove(name: .expires)
}
}
}
}
| true
|
c06bf208130b80958a932a43ecbc194203fe62da
|
Swift
|
ehardacre/PeakPackage
|
/Sources/PeakPackage/Content/Tasks2/TaskCardView2.swift
|
UTF-8
| 3,502
| 3.0625
| 3
|
[] |
no_license
|
//
// SwiftUIView.swift
//
//
// Created by Ethan Hardacre on 3/23/21.
//
import SwiftUI
struct TaskCardView2: View {
var id = UUID()
@ObservedObject var selectionManager : SelectionManager
@State var taskManager : TaskManager2
var task : Task? //allow nil for testing
//the type of the task is passed as an argument
var type : TaskType
//Information
var date : String
var content : String
@State var statusIndex = 0
let statusOptions = ["Open", "In Progress", "Complete"]
//height of the row
var height : CGFloat = 105
@State var showMoreInfo = false
var body: some View {
ZStack{
if self.type.origin == TaskOrigin.complementary {
CardView(
id: id,
selectionManager: selectionManager,
color: Color.mid,
icon: Image(systemName: "bolt.fill"),
title: "Complimentary",
sub: self.date,
content: self.content,
showMoreInfo: $showMoreInfo)
} else {
if self.type.status == TaskStatus.complete {
CardView(
id: id,
selectionManager: selectionManager,
color: Color.darkAccent,
icon: Image(systemName: "checkmark.seal.fill"),
iconColor: Color.main,
title: "Requested",
sub: self.date,
content: self.content,
showMoreInfo: $showMoreInfo)
} else if self.type.status == TaskStatus.inProgress {
CardView(
id: id,
selectionManager: selectionManager,
color: Color.mid,
icon: Image(systemName: "seal.fill"),
title: "Requested",
sub: self.date,
content: self.content,
showMoreInfo: $showMoreInfo)
} else { //open
CardView(
id: id,
selectionManager: selectionManager,
color: Color.mid,
icon: Image(systemName: "seal"),
title: "Requested",
sub: self.date,
content: self.content,
showMoreInfo: $showMoreInfo)
}
}
}
.sheet(
isPresented: $showMoreInfo,
content: {
if self.task != nil {
TaskInfoView(manager: taskManager, task: self.task!)
.onDisappear{
self.selectionManager.id = nil
}
}
})
}
}
struct TaskCardView2_Previews: PreviewProvider {
static var previews: some View {
TaskCardView2(
selectionManager: SelectionManager(),
taskManager: TaskManager2(),
task: nil,
type: TaskType(
status: TaskStatus.inProgress,
origin: TaskOrigin.userRequested),
date: "11/20/20",
content: "(Service Page Addition for admin) Details include [Service Title: Test Service][Custom Content: Testing new teams update]")
}
}
| true
|
e5d2290be0da49b2de8d17528baf13f074cc66a1
|
Swift
|
ttkien/WeatherAppWithCleanArchitecture
|
/WeatherUI/HourlyWeather/HourlyWeatherViewCollectionCell.swift
|
UTF-8
| 1,118
| 3.078125
| 3
|
[
"Unlicense"
] |
permissive
|
import Foundation
import UIKit
public struct HourlyWeatherViewCollectionCellPresentModel {
public let hour: String
public let percentage: String
public let weatherImage: UIImage
public let temperature: String
public init(hour: String, percentage: String, weatherImage: UIImage, temperature: String) {
self.hour = hour
self.percentage = percentage
self.weatherImage = weatherImage
self.temperature = temperature
}
}
class HourlyWeatherViewCollectionCell : UICollectionViewCell {
@IBOutlet weak var hourLabel: UILabel!
@IBOutlet weak var percentageLabel: UILabel!
@IBOutlet weak var weatherImageView: UIImageView!
@IBOutlet weak var temperatureLabel: UILabel!
override var intrinsicContentSize: CGSize {
return CGSize(width: 76, height: 110)
}
func bind(model: HourlyWeatherViewCollectionCellPresentModel) {
self.hourLabel.text = model.hour
self.percentageLabel.text = model.percentage
self.weatherImageView.image = model.weatherImage
self.temperatureLabel.text = model.temperature
}
}
| true
|
b594ab3216634adac1fc0fc237c6d2b36fe36dbf
|
Swift
|
accountos/Nike
|
/ZAlgoDemoSwift/ZAlgoDemoSwift/ZAlgoDemoHeap/ZAlgoDemoHeapViewController.swift
|
UTF-8
| 4,405
| 2.609375
| 3
|
[] |
no_license
|
//
// ZAlgoDemoHeapViewController.swift
// ZAlgoDemoSwift
//
// Created by zjixin on 2019/6/28.
// Copyright © 2019 zjixin. All rights reserved.
//
import UIKit
let heapIdentifier = "ZAlgoDemoHeapCell"
class ZAlgoDemoHeapViewController: UITableViewController {
var dataSource:Array<Dictionary<String, String>>!
var originalArray:Array<Int>!
var stepCount:Int = 0
var heap:ZAlgoHeap?
lazy var textView:UITextView = {
let textView:UITextView = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: view.frame.width, height: 200))
textView.font = UIFont.systemFont(ofSize: 15)
textView.textColor = .black
textView.backgroundColor = .brown
return textView
}()
override func viewDidLoad() {
setupData()
self.tableView.tableFooterView = textView
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: heapIdentifier)
self.tableView.reloadData()
}
func setupData() {
self.dataSource = [
["title" : "1. 生成堆 -- 大顶堆",
"action" : "generateHeap"],
["title" : "2.1 移除堆顶值",
"action" : "removeMaxDemo"],
["title" : "2.2 移除指定值",
"action" : "removeValueDemo"],
["title" : "3. 堆排序",
"action" : "heapSortDemo"],
]
self.originalArray = [33, 17, 13, 16, 18, 25, 19, 27, 50, 34, 58, 66, 51, 55];
}
//MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: heapIdentifier, for: indexPath)
let dic:Dictionary = self.dataSource[indexPath.row]
let title:String = dic["title"]!
cell.textLabel?.text = title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
self.stepCount = 0
let dic:Dictionary = self.dataSource[indexPath.row]
let action:String! = dic["action"]
if (action != nil) {
let sel:Selector! = Selector.init(action)
if (self.responds(to: sel)) {
self.perform(sel, with: dic)
}
}
}
//MARK: Binary search
@objc func generateHeap() {
self.heap = ZAlgoHeap.init(capacity: self.originalArray.count)
for element in self.originalArray {
self.heap?.insert(value: element)
}
let array = self.heap?.array
var string:String = "\nheap's array = ["
for element in array! {
string.append(contentsOf: "\(element), ")
}
string.append(contentsOf: "]\n\n")
string.append(#function)
self.textView.text = string
}
@objc func removeMaxDemo() {
self.heap?.removeMax()
let array = self.heap?.array
var string:String = "\nheap's array = ["
for element in array! {
string.append(contentsOf: "\(element), ")
}
string.append(contentsOf: "]\n\n")
string.append(#function)
self.textView.text = string
}
@objc func removeValueDemo() {
self.heap?.delete(value: 13)
let array = self.heap?.array
var string:String = "\nheap's array = ["
for element in array! {
string.append(contentsOf: "\(element), ")
}
string.append(contentsOf: "]\n\n")
string.append(#function)
self.textView.text = string
}
@objc func heapSortDemo() {
let array = self.heap?.sort()
guard array != nil else {
return
}
var string:String = "\nsorted array = ["
for element in array! {
string.append(contentsOf: "\(element), ")
}
string.append(contentsOf: "]\n\n")
string.append(#function)
self.textView.text = string
}
}
| true
|
cdd432a33c43ccf5b2f463678e6cb83c82886412
|
Swift
|
jajackleon/MiniChallenge2
|
/MiniChallenge2/CollectionViewCells/DatePlanCollectionViewCells/DatePlanCollectionViewCell.swift
|
UTF-8
| 1,874
| 2.734375
| 3
|
[] |
no_license
|
//
// DatePlanCollectionViewCell.swift
// MiniChallenge2
//
// Created by Puras Handharmahua on 08/06/21.
//
import UIKit
class DatePlanCollectionViewCell: UICollectionViewCell {
static let identifier = "DatePlanCollectionViewCell"
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var dateMonthLabel: UILabel!
static func nib() -> UINib {
return UINib(nibName: "DatePlanCollectionViewCell", bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
private func setupUI() {
containerView.layer.cornerRadius = 8
numberLabel.textColor = .white
topLabel.textColor = .white
dayLabel.textColor = .white
dateMonthLabel.textColor = .white
}
public func configureUI(idx: Int) {
let date = Date()
let formatter = DateFormatter()
if idx == 0 {
containerView.backgroundColor = MCColor.MCColorPrimary
}
numberLabel.text = "\(idx + 1)"
if idx == 0 {
formatter.dateFormat = "E"
dayLabel.text = formatter.string(from: date)
formatter.dateFormat = "d MMM"
dateMonthLabel.text = formatter.string(from: date)
} else {
formatter.dateFormat = "E"
let dateNow = Calendar.current.date(byAdding: .day, value: idx*3, to: date)!
dayLabel.text = "\(formatter.string(from: dateNow))"
formatter.dateFormat = "d MMM"
dateMonthLabel.text = formatter.string(from: dateNow)
}
}
override func prepareForReuse() {
containerView.backgroundColor = .systemGray4
}
}
| true
|
0762bb5920c04bf6a99988f7cfa0cbe0658325be
|
Swift
|
hamasugar/hyoutei
|
/hyoutei/MakeView.swift
|
UTF-8
| 1,190
| 2.546875
| 3
|
[] |
no_license
|
//
// MakeView.swift
// hyoutei
//
// Created by user on 2018/09/18.
// Copyright © 2018年 hamasugartanaka. All rights reserved.
//
import Foundation
import UIKit
class MakeView{
static let buttonHeight:Int = 60
static let space:Int = 10
static var buttonSpace:Int{return buttonHeight+space}
static let backgroundColor = UIColor(red: 228.0/256, green: 221.0/256, blue: 201.0/256, alpha: 1.0)
static let buttonColor = UIColor.white
static let fontsize = UIFont.systemFont(ofSize: 22.0)
static let cornerRadius = CGFloat(10.0)
static let underButtonColor = UIColor(red: 255.0/256, green: 169.0/256, blue: 146.0/256, alpha: 1.0)
static let underButtonHeight = 50
static func puyopuyo(sender:UIButton){
UIView.animate(withDuration: 0.1,
animations: { () -> Void in
// 拡大用アフィン行列を作成する.
sender.transform = CGAffineTransform(scaleX: 0.4, y: 0.4)
// 縮小用アフィン行列を作成する.
sender.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
}
}
| true
|
932d0fd9c837e7a75ad7263396a953ee19f3f97a
|
Swift
|
AntonBal/Demo
|
/Demo/Domain/News/NewsService.swift
|
UTF-8
| 729
| 2.578125
| 3
|
[] |
no_license
|
//
// NewsService.swift
// Demo
//
// Created by Anton Bal’ on 02.07.2020.
// Copyright © 2020 Anton Bal’. All rights reserved.
//
import Foundation
import Moya
import RxSwift
import Alamofire
struct NewsParams {
let count: Int
let offset: Int
var parameters: [String: Any] {
return ["textFormat": "Raw", "safeSearch": "Off", "count": "\(count)", "offset": "\(offset)"]
}
}
class NewsService: NewsUseCase {
let context: ServiceContext
init(context: ServiceContext) {
self.context = context
}
//MARK: - NewsUseCase
func all(params: NewsParams) -> Single<AllNews> {
context.network.request(NewsAPI.all(params: params)).map(AllNews.self)
}
}
| true
|
eeffa4520f97603fd144696a6beb3f7d4b170bc7
|
Swift
|
felixssimoes/iOS_architecture_test
|
/architecture_test/Models/Memory Data Store/MemoryTransactionsDataStore.swift
|
UTF-8
| 2,674
| 2.875
| 3
|
[] |
no_license
|
//
// Created by Felix Simoes on 31/10/2016.
//
import Foundation
private class MemoryTransaction {
let id: String
let account: AccountModel
let accountId: String
var category: String
var date: Date
var amount: Decimal
init(transactionModel model: TransactionModel) {
id = UUID().uuidString
account = model.account
accountId = account.id
category = model.category
date = model.date
amount = model.amount
}
init(accountModel: AccountModel) {
id = UUID().uuidString
account = accountModel
accountId = account.id
category = ""
date = Date()
amount = 0
}
func transactionModel() -> TransactionModel {
return TransactionModel(id: id, account: account, category: category, date: date, amount: amount)
}
}
private var transactions: [MemoryTransaction] = []
final class MemoryTransactionsDataStore: TransactionsDataStore {
init(account: AccountModel) {
let t1 = MemoryTransaction(accountModel: account); t1.category = "Category 1"; t1.amount = 11
let t2 = MemoryTransaction(accountModel: account); t2.category = "Category 1"; t2.amount = 22
let t3 = MemoryTransaction(accountModel: account); t3.category = "Category 2"; t3.amount = 33
transactions = [t1, t2, t3]
}
init() {
}
func all(forAccount account: AccountModel) throws -> [TransactionModel] {
return transactions.filter { $0.accountId == account.id } .map { $0.transactionModel() }
}
func newTransaction(forAccount account: AccountModel) throws -> TransactionModel {
return MemoryTransaction(accountModel: account).transactionModel()
}
func add(transaction: TransactionModel) throws {
transactions.append(MemoryTransaction(transactionModel: transaction))
}
func update(transaction: TransactionModel) throws {
guard let existingTransaction = findTransaction(withId: transaction.id) else {
throw TransactionError.transactionNotFound
}
existingTransaction.category = transaction.category
existingTransaction.date = transaction.date
existingTransaction.amount = transaction.amount
}
func delete(transaction: TransactionModel) throws {
guard let existingTransaction = findTransaction(withId: transaction.id) else {
throw TransactionError.transactionNotFound
}
transactions = transactions.filter { $0.id != existingTransaction.id }
}
private func findTransaction(withId id: String) -> MemoryTransaction? {
return transactions.first { $0.id == id }
}
}
| true
|
ee325f3eb590c00f534e3270e390d0334821691b
|
Swift
|
codecat15/Youtube-tutorial
|
/CoreData/DeleteRule/DeleteRuleDemo/DeleteRuleDemo/DataManager/EmployeeDataManager.swift
|
UTF-8
| 2,164
| 2.84375
| 3
|
[] |
no_license
|
//
// EmployeeDataManager.swift
// DeleteRuleDemo
//
// Created by CodeCat15 on 8/29/20.
// Copyright © 2020 CodeCat15. All rights reserved.
//
import Foundation
import CoreData
struct EmployeeDataManager
{
func create(record: Employee) {
let cdEmployee = CDEmployee(context: PersistentStorage.shared.context)
cdEmployee.id = record.id
cdEmployee.email = record.email
cdEmployee.name = record.name
if(record.passport != nil)
{
let cdPassport = CDPassport(context: PersistentStorage.shared.context)
cdPassport.placeOfIssue = record.passport?.placeOfIssue
cdPassport.id = record.passport?.id
cdPassport.passportNumber = record.passport?.passportNumber
cdEmployee.toPassport = cdPassport
}
PersistentStorage.shared.saveContext()
}
func updateEmployee(record: Employee)
{
let employee = getCdEmployee(byId: record.id)
guard employee != nil else {return }
}
func getAllEmployee() -> [Employee]?
{
let records = PersistentStorage.shared.fetchManagedObject(managedObject: CDEmployee.self)
guard records != nil && records?.count != 0 else {return nil}
var results: [Employee] = []
records!.forEach({ (cdEmployee) in
results.append(cdEmployee.convertToEmployee())
})
return results
}
func deleteEmployee(byIdentifier id: UUID) -> Bool
{
let employee = getCdEmployee(byId: id)
guard employee != nil else {return false}
PersistentStorage.shared.context.delete(employee!)
PersistentStorage.shared.saveContext()
return true
}
private func getCdEmployee(byId id: UUID) -> CDEmployee?
{
let fetchRequest = NSFetchRequest<CDEmployee>(entityName: "CDEmployee")
let fetchById = NSPredicate(format: "id==%@", id as CVarArg)
fetchRequest.predicate = fetchById
let result = try! PersistentStorage.shared.context.fetch(fetchRequest)
guard result.count != 0 else {return nil}
return result.first
}
}
| true
|
0b7e477a830251cf73c5e7a35b351bd5df53528d
|
Swift
|
niceland/clickCounterOnAppleWatch
|
/clickCounter WatchKit Extension/InterfaceController.swift
|
UTF-8
| 937
| 2.6875
| 3
|
[] |
no_license
|
//
// InterfaceController.swift
// clickCounter WatchKit Extension
//
// Created by Magdalena Pamuła on 10/07/15.
// Copyright (c) 2015 Magdalena Pamuła. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
var counter = 0
@IBOutlet weak var counterLabel: WKInterfaceLabel!
@IBAction func buttonPressed() {
counter++
counterLabel.setText("\(counter)")
}
}
| true
|
bdab69931220c5ac68db0086c8df467cde823f93
|
Swift
|
ilyabelyakov1989/VK-Social-Project
|
/VK-Social/VkClient/Groups/AllGroupsTableViewController.swift
|
UTF-8
| 2,615
| 2.640625
| 3
|
[] |
no_license
|
//
// AllGroupsTableViewController.swift
// VkClient
//
// Created by Ilya Belyakov on 27.03.2021.
//
import UIKit
class AllGroupsTableViewController: UITableViewController {
@IBOutlet weak var searchBar: UISearchBar!
var allGroups = [Group(name: "Пикабу", screen_name: "pikabu", logo: #imageLiteral(resourceName: "rZi7F9_vu-8") ),
Group(name: "ТОПОР — Хранилище", screen_name: "toportg", logo: #imageLiteral(resourceName: "-LGOrMnatj4")),
Group(name: "Подслушано Коломна", screen_name: "kolomna_tut", logo: #imageLiteral(resourceName: "i9FnKM0Gxt4")),]
var filtredAllGroups = [Group]()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
filtredAllGroups = allGroups
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
}
// MARK: - Table view data source
override func numberOfSections(in 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 filtredAllGroups.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard
let cell = tableView.dequeueReusableCell(withIdentifier: "AllGroupCell", for: indexPath) as? AllGroupsTableViewCell
else { return UITableViewCell()}
cell.groupName.text = filtredAllGroups[indexPath.row].name
//cell.groupImage.image = filtredAllGroups[indexPath.row].logo!
cell.groupImage.logoView.image = filtredAllGroups[indexPath.row].logo ?? UIImage()
return cell
}
}
extension AllGroupsTableViewController: UISearchBarDelegate {
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchBar.endEditing(true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard searchText != "" else {
filtredAllGroups = allGroups
tableView.reloadData()
return
}
filtredAllGroups = allGroups.filter{ $0.name.lowercased().contains(searchText.lowercased())}
tableView.reloadData()
}
}
| true
|
76edf85edc6050ef33e7f6006c1edd3927b24b7f
|
Swift
|
JustasPolis/AudioBookie-Alpha
|
/AudioBookie/Utilities/Extensions/Double+Extensions.swift
|
UTF-8
| 355
| 3.015625
| 3
|
[] |
no_license
|
//
// Double+Extensions.swift
// AudioBookie
//
// Created by Justin on 2021-01-28.
//
import Foundation
extension Double {
func formatToTimeString() -> String {
let minutes = Int(self) / 60
let remainder = Int(self) % 60
let timeString = String(format: "%02d:%02d", minutes, remainder)
return timeString
}
}
| true
|
f8d0d794d0bb9b0e7f88c78f0f980a0c49c4d03f
|
Swift
|
vsmcdemo/mobile-center-demoapp-iOS
|
/MobileCenterExample/Routing.swift
|
UTF-8
| 2,633
| 2.53125
| 3
|
[] |
no_license
|
//
// Routing.swift
// MobileCenterExample
//
// Created by Ruslan Mansurov on 5/31/17.
// Copyright © 2017 Akvelon. All rights reserved.
//
import Foundation
import UIKit
class Routing {
var services: ServicesFactory
var window: UIWindow!
var mainStoryboard: UIStoryboard {
return UIStoryboard(name: "Main", bundle: nil)
}
init(servicesFactory: ServicesFactory) {
services = servicesFactory
}
func installToWindow(_ window: UIWindow) {
self.window = window
presentLoginController()
}
func presentLoginController() {
window.rootViewController = loginController()
}
func presentMainController(user: User) {
let controller = mainController()
controller.viewControllers = [profileController(user: user), statisticsController()]
window.rootViewController?.present(controller, animated: true, completion: nil)
}
func loginController() -> LoginViewController {
let loginController = mainStoryboard.instantiateInitialViewController() as! LoginViewController
loginController.configure(routing: self,
analyticsService: services.analyticsService,
twitterService: services.twitterService,
facebookService: services.facebookService
)
return loginController;
}
func mainController() -> MainTabBarController {
let identifier = String(describing: MainTabBarController.self)
let controller = mainStoryboard.instantiateViewController(withIdentifier: identifier) as! MainTabBarController
controller.configure(analyticsService: services.analyticsService, fitnessService: services.fitnessService)
return controller;
}
func profileController(user: User) -> ProfilePageViewController {
let identifier = String(describing: ProfilePageViewController.self)
let controller = mainStoryboard.instantiateViewController(withIdentifier: identifier) as! ProfilePageViewController
controller.user = user
return controller;
}
func statisticsController() -> StatisticsViewController {
let identifier = String(describing: StatisticsViewController.self)
let controller = mainStoryboard.instantiateViewController(withIdentifier: identifier) as! StatisticsViewController
controller.configure(analyticsService: services.analyticsService, crashesService: services.crashesService)
return controller;
}
}
| true
|
30c76cbebbbb8fdef97625dfa04210ff035bb76f
|
Swift
|
gydroperit/iosoblako
|
/Oblako/Project.swift
|
UTF-8
| 893
| 2.78125
| 3
|
[] |
no_license
|
// NavController2.swift
// Oblako
//
// Created by Admin on 11.07.15.
// Copyright (c) 2015 Admin. All rights reserved.
//
import UIKit
import Alamofire
final class Project: ResponseObjectSerializable,ResponseCollectionSerializable{
let id : Int
var title = String()
var todos:[Todo] = [Todo]()
@objc required init?(response: NSHTTPURLResponse, representation: AnyObject) {
self.id = representation.valueForKeyPath("id") as! Int
self.title = representation.valueForKeyPath("title") as! String
}
@objc class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Project] {
var postArray = representation as! [AnyObject]
// using the map function we are able to instantiate Post while reusing our init? method above
return postArray.map({ Project(response:response, representation: $0)! })
}}
| true
|
148485371ea9c52360e55864dd22678a42e2ae4c
|
Swift
|
kozhemin/GU_IOS_1640
|
/3l_КожеминЕгор.playground/Contents.swift
|
UTF-8
| 5,963
| 4.09375
| 4
|
[] |
no_license
|
import UIKit
// 1. Описать несколько структур
// 2. Структуры должны содержать свойства - номер, состояние покоя, год выпска, тип транспорта и тд
// 3. Описать перечисление с возможными действиями над структурами
// 4. Добавить в структуры метод с одним аргументом типа перечисления, который будет менять свойства структуры в зависимости от действия.
// 5. Инициализировать несколько экземпляров структур. Применить к ним различные действия.
// 6. Вывести значения свойств экземпляров в консоль.
enum State {
case stationary // Без движения
case readyToGo // Готов к движению
case enRoute // В пути
}
enum PlanType {
case passenger // Пассажирский
case cargo // Грузовой
}
print("\n\n======Структура Самолет======\n")
struct Plane {
var number: String
var year: Int
var seats: Int
var planeLadderState = 1 // Состояние трапа 0 - Закрыт; 1 - Открыт
private var state: State = .stationary
var type: PlanType
var currentStateName: String {
switch state {
case .enRoute:
return "В полете"
case .readyToGo:
return "Готов к полету"
default:
return "В порту"
}
}
init(number: String, year: Int, type: PlanType) {
self.number = number
self.year = year
self.type = type
seats = (type == .passenger) ? 100 : 50
}
init(type: PlanType) {
self.type = type
switch type {
case .cargo:
number = "Ан-225 «Мрия»"
year = 2015
seats = 50
default:
number = "Sukhoi Superjet 100"
year = 2020
seats = 108
}
}
// Убрать трап
mutating func closeLadder() {
if planeLadderState == 1 {
planeLadderState = 0
print("Трап убран.")
}
}
// Подготовить к вылету
mutating func setReadyToGo() -> Bool {
if planeLadderState != 0 {
print("Необходимо убрать трап!")
return false
}
if state != .stationary {
print("Самолет \(number) уже в движении!")
return false
}
state = .readyToGo
print("Самолет \(number) готов к вылету.")
return true
}
// Взлет
mutating func go() -> Bool {
if state != .readyToGo {
print("Самолет \(number) не готов к вылету!")
return false
}
state = .enRoute
return true
}
// Посадка
mutating func setLanding() -> Bool {
if state == .enRoute {
state = .stationary
print("Самолет \(number) совершил успешную посадку!")
return true
}
print("Самолет \(number) на текущий момент не в полете!")
return false
}
}
var planePassenger = Plane(type: .passenger)
if !planePassenger.go() {
planePassenger.closeLadder()
planePassenger.setReadyToGo()
if planePassenger.go() {
print("Взлет успешный")
}
}
// Совершаем посадку
planePassenger.setLanding()
print("""
Информация:
==========
Марка самолета: \(planePassenger.number)
Тип: \(planePassenger.type)
Всего мест: \(planePassenger.seats)
Год выпуска: \(planePassenger.year)
Текущее состояние: \(planePassenger.currentStateName)
""")
print("\n\n======Структура Корабль======\n")
struct Ship {
var number = ""
var neme = ""
private var state: State = .stationary {
didSet {
print("Запись бортового журнала: \(Ship.getStateName(state: oldValue)) -> \(Ship.getStateName(state: state))")
}
}
var type: PlanType = .passenger
// Управление движением
mutating func control(state: State) -> Bool {
switch state {
case .readyToGo where !checkPassport(), .enRoute where !checkPassport():
print("Движение кораблю запрещено т.к. нет номера или названия!")
return false
default:
self.state = state
return true
}
}
mutating func setParam(number: String, name: String) {
neme = name
self.number = number
print("Номер и название кораблю присвоены")
}
func checkPassport() -> Bool {
return (neme != "" && number != "")
}
func printInfo() {
print("""
Информация:
==========
Корабль: \(neme), \(number)
Тип Корабля: \(type)
Текущее состояние: \(Ship.getStateName(state: state))
""")
}
static func getStateName(state: State) -> String {
switch state {
case .enRoute:
return "В движении"
case .readyToGo:
return "Готов к отплытию"
default:
return "В порту"
}
}
}
var ship = Ship()
ship.control(state: .enRoute)
ship.setParam(number: "A-270", name: "Great Eastern")
ship.control(state: .readyToGo)
ship.control(state: .enRoute)
ship.control(state: .stationary)
ship.printInfo()
| true
|
8c2d13e34a880f81a0acc2a0b5d35e8577060386
|
Swift
|
walle19/Breakout-Game
|
/Breakout/Ball.swift
|
UTF-8
| 2,769
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// Ball.swift
// Breakout
//
// Created by Nikhil Wali on 02/04/17.
// Copyright © 2017 Nikhil Wali. All rights reserved.
//
/*
Ball class creates ball(s) depending upon the input parameter values. Also takes into consideration the gameView to construct the ball size accordingly followed with handling the dynamic behavior of the ball(s).
Mandatory parameter: numberOfBalls, speed, gameView and dynamicBehavior
*/
import UIKit
class Ball:NSObject {
init(numberOfBalls: Int, speed: CGFloat) {
ballCount = numberOfBalls
speedOfBall = speed
}
fileprivate struct BallInfo {
static let BallSizeConstant: CGFloat = 0.05
static let BallColor = UIColor.red
}
var speedOfBall: CGFloat!
var ballCount: Int!
var gameView: BezierPathsView!
var breakoutBehavior: BreakoutBehavior!
var paddleCenter: CGPoint!
var paddleHeight: CGFloat!
fileprivate var ballSize: CGSize {
let size = BallInfo.BallSizeConstant * min(gameView.bounds.size.width, gameView.bounds.size.height)
return CGSize(width: size, height: size)
}
/*
Place ball(s) at center of the paddle in gameView
@return : [UIPushBehavior]
*/
func placeBall() -> [UIPushBehavior] {
var pushes = [UIPushBehavior]()
/*
place number of balls as per the count from settings
default value is 1
*/
for _ in 1...ballCount {
let ballView = UIView(frame: CGRect(origin: CGPoint.zero, size: ballSize))
ballView.center = paddleCenter
ballView.center.y -= (paddleHeight + ballSize.height) / 2
ballView.backgroundColor = BallInfo.BallColor
ballView.layer.cornerRadius = ballSize.width / 2.0
breakoutBehavior.addBall(ballView)
pushes.append(push(breakoutBehavior.items.last!))
}
return pushes
}
/*
Add push behavoir to the ball(s)
@return : UIPushBehavior
*/
fileprivate func push(_ view: UIView) -> UIPushBehavior {
let pushBehaviour = UIPushBehavior(items: [view], mode: UIPushBehaviorMode.instantaneous)
pushBehaviour.magnitude = speedOfBall * CGFloat(M_PI) / 100
pushBehaviour.angle = CGFloat(getRandomAngle())
pushBehaviour.action = {
[unowned pushBehaviour] in pushBehaviour.dynamicAnimator!.removeBehavior(pushBehaviour)
}
return pushBehaviour
}
// Generate random angle for the ball(s)
fileprivate func getRandomAngle() -> Double {
return M_PI * (Double(arc4random_uniform(30)) + 1) + 10 // To get the right anlge for starting the ball
}
}
| true
|
0ea1e98b8fd1ddce689fb16b4dbf06e29988cb97
|
Swift
|
wsl100624/SwiftUICoreData
|
/SwiftUICoreData/MainView.swift
|
UTF-8
| 6,925
| 2.8125
| 3
|
[] |
no_license
|
//
// MainView.swift
// MainView
//
// Created by Will Wang on 9/12/21.
//
import SwiftUI
struct MainView: View {
@State private var presentCardForm = false
@State private var shouldShowAddTransactionForm = false
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Card.timestamp, ascending: false)],
animation: .default)
private var cards: FetchedResults<Card>
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \CardTransaction.timestamp, ascending: false)],
animation: .default)
private var transactions: FetchedResults<CardTransaction>
var body: some View {
NavigationView {
ScrollView {
if !cards.isEmpty {
TabView {
ForEach(cards) { card in
CreditCardView(card: card)
.padding(.bottom, 60)
}
}
.tabViewStyle(.page(indexDisplayMode: .always))
.frame(height: 300)
.indexViewStyle(.page(backgroundDisplayMode: .always))
if !transactions.isEmpty {
ForEach(transactions) { transaction in
VStack {
HStack {
Text(transaction.name ?? "")
.font(.headline.bold())
Spacer()
Button {
print("dot pressed")
} label: {
Image(systemName: "ellipsis")
.font(.system(size: 24))
}
}
.padding(.top, 12)
.padding(.horizontal)
HStack {
Text(transaction.timestamp?.formatted() ?? "")
Spacer()
Text("$ \(String(format: "%.2f", transaction.amount))")
}
.font(.subheadline)
.padding(.horizontal)
if let data = transaction.photoData, let image = UIImage(data: data) {
Image(uiImage: image)
.resizable()
.scaledToFit()
.padding()
}
HStack { Spacer() }
}
.foregroundColor(Color(.label))
.background(Color.white)
.cornerRadius(10)
.shadow(radius: 5)
.padding()
}
} else {
Text("Get started by adding your first transaction")
Button {
shouldShowAddTransactionForm.toggle()
} label: {
Text("+ Transaction")
.padding(.init(top: 10, leading: 14, bottom: 10, trailing: 14))
.background(Color(.label))
.foregroundColor(Color(.systemBackground))
.font(.headline)
.cornerRadius(6)
}
.fullScreenCover(isPresented: $shouldShowAddTransactionForm) {
AddTransactionForm()
}
}
} else {
emptyPromptMessage
}
Spacer()
.fullScreenCover(isPresented: $presentCardForm, onDismiss: nil) {
AddCardForm()
}
}
.navigationTitle("Credit Cards")
.navigationBarItems(leading: HStack {
addItemButton
deleteAllButton
}, trailing: addCardButton)
}
}
private var emptyPromptMessage: some View {
VStack {
Text("You currectly have no cards in the system.")
.padding(.horizontal, 48)
.padding(.vertical)
.multilineTextAlignment(.center)
Button {
presentCardForm.toggle()
} label: {
Text("+ add your first card".capitalized)
.foregroundColor(Color(.systemBackground))
}
.padding()
.background(Color(.label))
.cornerRadius(12)
}.font(.subheadline.bold())
}
var deleteAllButton: some View {
Button(action: {
cards.forEach { card in
viewContext.delete(card)
}
do {
try viewContext.save()
} catch let error {
print(error)
}
}, label: {
Text("Delete All")
})
}
var addItemButton: some View {
Button(action: {
withAnimation {
let viewContext = PersistenceController.shared.container.viewContext
let card = Card(context: viewContext)
card.timestamp = Date()
do {
try viewContext.save()
} catch let error {
print(error)
}
}
}, label: {
Text("Add Item")
})
}
var addCardButton: some View {
Button(action: {
presentCardForm.toggle()
}, label: {
Text("+ card".capitalized)
.foregroundColor(Color(.systemBlue))
.padding(EdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12))
.background(Color(.systemFill))
.font(.callout.bold())
.cornerRadius(5)
})
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
let viewContext = PersistenceController.shared.container.viewContext
MainView()
.environment(\.managedObjectContext, viewContext)
}
}
| true
|
16d2c8a93c8409ef82be33ebfa945de42f546eda
|
Swift
|
treasureisle/blossom_ios
|
/blossom/Cells/BasketViewCell.swift
|
UTF-8
| 1,903
| 2.625
| 3
|
[] |
no_license
|
//
// MessageViewCell.swift
// blossom
//
// Created by Seong Phil on 2016. 12. 21..
// Copyright © 2016년 treasureisle. All rights reserved.
//
import Foundation
import UIKit
class BasketViewCell: UITableViewCell {
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var colorSizeNamesTextField: UITextField!
@IBOutlet weak var colorSizeAmountTextField: UITextField!
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var checkButton: UIButton!
var colorSizeNamesDownPicker: DownPicker!
var colorSizeAmountDownPicker: DownPicker!
var colorSizes = [ColorSize]()
var colorSizeNames = [String]()
var colorSizeAvailable = [String]()
var selectedColorSize: ColorSize!
var selectedAmount: Int = 0
func setSelectedFunc(){
self.colorSizeNamesDownPicker.addTarget(self, action: #selector(self.colorSizeNameSelected(dp:)), for: .valueChanged)
}
func colorSizeNameSelected(dp: Any?) {
self.colorSizeAmountTextField.isUserInteractionEnabled = true
let selectedValue = self.colorSizeNamesDownPicker.text
// do what you want
self.colorSizeAvailable.removeAll()
for colorSize in self.colorSizes {
if colorSize.name == selectedValue {
self.selectedColorSize = colorSize
for i in (1..<colorSize.available){
self.colorSizeAvailable.append(String(i))
}
break
}
}
self.colorSizeAmountDownPicker = DownPicker(textField: self.colorSizeAmountTextField, withData: self.colorSizeAvailable)
self.colorSizeAmountDownPicker.addTarget(self, action: #selector(self.amountSelected(dp:)), for: .valueChanged)
}
func amountSelected(dp: Any?) {
self.selectedAmount = Int(self.colorSizeAmountDownPicker.text)!
}
}
| true
|
1041a38b2d53c632d2108ff60886d40725df9065
|
Swift
|
zachwaugh/GIFKit
|
/GIFKit/ImageDescriptor.swift
|
UTF-8
| 1,208
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ImageDescriptor.swift
// GIFKit
//
// Created by Zach Waugh on 11/14/15.
// Copyright © 2015 Zach Waugh. All rights reserved.
//
import Foundation
struct ImageDescriptor: CustomStringConvertible {
let leftPosition: UInt16
let topPosition: UInt16
let width: UInt16
let height: UInt16
let packedFields: Byte
var localColorTableFlag: Bool {
return (packedFields & 0b10000000) != 0
}
var interlaceFlag: Bool {
return (packedFields & 0b01000000) != 0
}
var sortFlag: Bool {
return (packedFields & 0b00100000) != 0
}
var localColorTableSize: UInt8 {
return packedFields & 0b00000111
}
var description: String {
return "<ImageDescriptor leftPosition: \(leftPosition), topPosition: \(topPosition), width: \(width), height: \(height), packedFields: \(packedFields)>"
}
init(data: NSData) {
var dataStream = DataStream(data: data)
leftPosition = dataStream.takeUInt16()!
topPosition = dataStream.takeUInt16()!
width = dataStream.takeUInt16()!
height = dataStream.takeUInt16()!
packedFields = dataStream.takeByte()!
}
}
| true
|
795f368f3ae1ca6a7dbab66150c3bbf64d63ecbc
|
Swift
|
wanderwaltz/iMMPI
|
/iMMPI/Modules/Sources/UIReusableViews/ReusableViewSource+Meta.swift
|
UTF-8
| 1,824
| 2.890625
| 3
|
[] |
no_license
|
import UIKit
public typealias TableViewCellSource<Data> = ReusableViewSource<UITableView, UITableViewCell, Data>
public typealias CollectionViewCellSource<Data> = ReusableViewSource<UICollectionView, UICollectionViewCell, Data>
public protocol ReusableCellDequeueing {
associatedtype ReuseIdentifier
associatedtype Cell: UIView
func dequeueReusableCell(withIdentifier identifier: ReuseIdentifier, for indexPath: IndexPath) -> Cell
}
public protocol CellClassRegistering {
associatedtype ReuseIdentifier
associatedtype Cell: UIView
func register(_ cellClass: AnyClass?, forCellReuseIdentifier reuseIdentifier: ReuseIdentifier)
}
public protocol CellNibRegistering {
associatedtype ReuseIdentifier
associatedtype Cell: UIView
func register(_ nib: UINib?, forCellReuseIdentifier reuseIdentifier: ReuseIdentifier)
}
extension UITableView: ReusableCellDequeueing, CellClassRegistering, CellNibRegistering {
public typealias ReuseIdentifier = String
public typealias Cell = UITableViewCell
}
extension UICollectionView: ReusableCellDequeueing, CellClassRegistering, CellNibRegistering {
public typealias ReuseIdentifier = String
public typealias Cell = UICollectionViewCell
@nonobjc public func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UICollectionViewCell {
return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
}
@nonobjc public func register(_ cellClass: AnyClass?, forCellReuseIdentifier reuseIdentifier: String) {
register(cellClass, forCellWithReuseIdentifier: reuseIdentifier)
}
@nonobjc public func register(_ nib: UINib?, forCellReuseIdentifier reuseIdentifier: String) {
register(nib, forCellWithReuseIdentifier: reuseIdentifier)
}
}
| true
|
ce98235ccb1b0d555a778e2e53480d2a68ae8e2d
|
Swift
|
MyZenKey/sp-sdk-ios
|
/ZenKeySDK/Tests/Mocks/MockResponseQueue.swift
|
UTF-8
| 1,513
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// MockResponseQueue.swift
// ZenKeySDK
//
// Created by Adam Tierney on 6/6/19.
// Copyright © 2019 ZenKey, LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class MockResponseQueue<T> {
/// FIFO responses
var mockResponses: [T] = []
/// if this flag is set, the final response configured will be repeated indefinitely
var repeatLastResponse: Bool = true
let defaultResponses: [T]
init(_ defaultResponses: [T] = []) {
self.defaultResponses = defaultResponses
self.mockResponses = defaultResponses
}
func clear() {
self.mockResponses = defaultResponses
}
func getResponse() -> T {
guard let result = self.mockResponses.first else {
fatalError("not enough reponses configured")
}
if mockResponses.count > 1 || !repeatLastResponse {
self.mockResponses = Array(self.mockResponses.dropFirst())
}
return result
}
}
| true
|
4aa4004b9357a19e8bc75910280be97814800c17
|
Swift
|
kurczewski9/swift_ProjektDvdshopFinish
|
/DVDShop/Icon.swift
|
UTF-8
| 452
| 2.96875
| 3
|
[] |
no_license
|
//
// Icon.swift
// DVDShop
//
// Created by Slawek Kurczewski on 03.05.2017.
// Copyright © 2017 Slawomir Kurczewski. All rights reserved.
//
import Foundation
struct Icon {
var name: String = ""
var price = 0.0
var isFeatured: Bool = false
var title: String = ""
init(name: String, title: String, price: Double, isFeatured: Bool){
self.name=name
self.title=title
self.price=price
self.isFeatured=isFeatured
}
}
| true
|
895e481bf63d018d81dd696e7f8f7d02c11d2c9c
|
Swift
|
psharanda/Jetpack
|
/Sources/Observable+Logging.swift
|
UTF-8
| 565
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Pavel Sharanda on 20.09.16.
// Copyright © 2016. All rights reserved.
//
import Foundation
extension ObserveValueProtocol {
public func log(_ tag: String? = nil) -> Observable<ValueType> {
let s = tag ?? "\(ValueType.self)"
return forEach {
Swift.print("\(s): \($0)")
}
}
public func dump(_ tag: String? = nil) -> Observable<ValueType> {
let s = tag ?? "\(ValueType.self)"
return forEach {
Swift.print("\(s):")
_ = Swift.dump($0)
}
}
}
| true
|
2024260b861d6a6a98b6303e3399026d1b991f59
|
Swift
|
wn/pace
|
/Pace/Profile/Views/CompareRunCollectionViewCell.swift
|
UTF-8
| 1,672
| 2.53125
| 3
|
[] |
no_license
|
//
// CompareRunCollectionViewCell.swift
// Pace
//
// Created by Tan Zheng Wei on 9/4/19.
// Copyright © 2019 nus.cs3217.pace. All rights reserved.
//
import UIKit
class CompareRunCollectionViewCell: UICollectionViewCell {
@IBOutlet private var content: UIView!
@IBOutlet private var runDate: UILabel!
@IBOutlet private var runnerName: UILabel!
@IBOutlet private var runTime: UILabel!
@IBOutlet private var tickImage: UIImageView!
weak var currentRun: Run?
var run: Run? {
get {
return currentRun
}
set {
currentRun = newValue
guard let currentRun = currentRun else {
return
}
runDate.text = Formatter.formatDate(currentRun.dateCreated)
runnerName.text = currentRun.runner?.name
runTime.text = Formatter.formatTime(currentRun.timeSpent)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
loadXib()
tickImage.isHidden = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadXib()
tickImage.isHidden = true
}
private func loadXib() {
Bundle.main.loadNibNamed(Xibs.compareRunCollectionViewCell, owner: self, options: nil)
addSubview(content)
content.frame = self.bounds
content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
func toggleClicked() {
let oldValue = tickImage.isHidden
tickImage.isHidden = !oldValue
}
override var isSelected: Bool {
willSet {
tickImage.isHidden = !isSelected
}
}
}
| true
|
37ed0d81962011f3903c8e115bcb667a69986a64
|
Swift
|
lucasfernandes/goodweather
|
/GoodWeather/ViewModels/WeatherViewModel.swift
|
UTF-8
| 1,156
| 3.140625
| 3
|
[] |
no_license
|
//
// WeatherViewModel.swift
// GoodWeather
//
// Created by Lucas Silveira on 19/09/19.
// Copyright © 2019 Lucas Silveira. All rights reserved.
//
import Foundation
import Combine
import SwiftUI
class WeatherViewModel: ObservableObject {
private var weatherService: WeatherService
@Published var weather = Weather()
init() {
self.weatherService = WeatherService()
}
var temperature: String {
if let temp = self.weather.temp {
let celsius = temp - 273.15
return String(format: "%.0f", celsius) + "°c"
} else {
return ""
}
}
var humidity: String {
if let humidty = self.weather.humidity {
return String(format: "%.0f", humidty)
} else {
return ""
}
}
var cityName: String = ""
func search() {
if let city = self.cityName.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
fetchWeather(by: city)
}
}
private func fetchWeather(by city: String) {
self.weatherService.getWeather(city: city) { weather in
if let weather = weather {
DispatchQueue.main.async {
self.weather = weather
}
}
}
}
}
| true
|
d78105d6872c6c0b0893182e9bda6686b07e4c03
|
Swift
|
DenRayzer/PixelFlow
|
/PixelFlow/UI/PixelSheet/CalendarHeader/Header.swift
|
UTF-8
| 1,680
| 2.859375
| 3
|
[] |
no_license
|
//
// Header.swift
// PixelFlow
//
// Created by Елизавета on 11.04.2021.
//
import UIKit
class Header: UIView {
private(set) var headerHeight: CGFloat = 44
private(set) var leftButton: SoftUIView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "LeftArrow"))
let button = Button(type: .bulging, view: imageView)
button.layout.height.equal(to: 43)
button.layout.width.equal(to: 43)
return button
}()
private(set) var rightButton: SoftUIView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "arrow"))
let button = Button(type: .bulging, view: imageView)
button.layout.height.equal(to: 43)
button.layout.width.equal(to: 43)
return button
}()
private(set) var titleButton: TextButton = {
let button = TextButton(type: .default(UIColor.PF.regularText, .font(family: .rubik(.regular), size: 22), .center, 1),
textMode: .uppercase,
text: "2021")
button.titleLabel?.adjustsFontSizeToFitWidth = true
return button
}()
override func draw(_ rect: CGRect) {
addSubview(titleButton)
titleButton.layout.center.equal(to: self)
addSubview(leftButton)
leftButton.layout.left.equal(to: self, offset: CGFloat(mainHorizontalMargin))
leftButton.layout.centerY.equal(to: self)
addSubview(rightButton)
rightButton.layout.right.equal(to: self, offset: -CGFloat(mainHorizontalMargin))
rightButton.layout.centerY.equal(to: self)
}
@objc func playTapHandler() {
}
}
| true
|
7db94aad7783aa06391b21a79238f59fb0cfbfc4
|
Swift
|
sainik18/dyd-ios
|
/DYD/UIButtonDesigns.swift
|
UTF-8
| 1,368
| 2.703125
| 3
|
[] |
no_license
|
//
// UIButtonDesigns.swift
// DYD
//
// Created by apple on 2/1/19.
// Copyright © 2019 Kiran. All rights reserved.
//
import UIKit
@IBDesignable
class CustomButton:UIButton
{
@IBInspectable var borderColor:UIColor = UIColor.clear{
didSet {
layer.borderColor = borderColor.cgColor
layer.masksToBounds = true
}
}
@IBInspectable var borderWidth:CGFloat = 0{
didSet {
layer.borderWidth = borderWidth
layer.masksToBounds = borderWidth>0
}
}
@IBInspectable var cornerRadius: CGFloat = 0{
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var shadowOpacity: Float = 0{
didSet {
layer.shadowOpacity = shadowOpacity
}
}
@IBInspectable var shadowRadius: CGFloat = 0{
didSet {
layer.shadowRadius = shadowRadius
}
}
@IBInspectable var shadowOffset: CGSize = CGSize(width: 0.0, height: 0.0) {
didSet {
layer.shadowOffset = shadowOffset
}
}
@IBInspectable var shadowColor: UIColor? = UIColor(red: 157/255, green: 157/255, blue: 157/255, alpha: 1.0) {
didSet {
layer.shadowColor = shadowColor?.cgColor
}
}
}
| true
|
6e13bdbb7801411b5d38d62d2b1673ac747c777b
|
Swift
|
Xobile/CTM-AwofL
|
/RegisterVC.swift
|
UTF-8
| 4,078
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// RegisterVC.swift
// LOGin
//
// Created by Marvin Kankiriho on 26/02/2017.
// Copyright © 2017 HASHPi. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
class RegisterVC: UIViewController {
// MARK: - OUTLETS
// Textfields
@IBOutlet var firstName: UITextField!
@IBOutlet var lastName: UITextField!
@IBOutlet var dateOfBirth: UITextField!
@IBOutlet var contactNumber: UITextField!
@IBOutlet var emailAddress: UITextField!
@IBOutlet var passWord: UITextField!
@IBOutlet var confirmPassword: UITextField!
@IBOutlet var ctmIntro: UITextField!
// BUTTON OUTLETS
@IBOutlet var saveContOUT: UIButton!
@IBOutlet var currentUserOUT: UIButton!
// DATABASE REFERENCE
var dbReference : FIRDatabaseReference!
// MARK: - VIEW DID LOAD
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - ACTIONS
// Save / Continue BUTTON
@IBAction func saveContinueButton(_ sender: Any) {
// Named variables
let fstName = firstName.text
let lstName = lastName.text
let dob = dateOfBirth.text
let mobileNo = contactNumber.text
let email = emailAddress.text
let passW = passWord.text
let passCW = confirmPassword.text
let intro = ctmIntro.text
// Database reference
self.dbReference = FIRDatabase.database().reference()
// if all fields are field in
if mobileNo == "" || email == "" || passW == "" || passCW == "" {
// hide the save / continue button
saveContOUT.tintColor = UIColor.red
} else {
saveContOUT.tintColor = UIColor.green
// Store entered data
self.dbReference.child("Martials").child("\(fstName!) \(lstName!)") // insert sent data
self.dbReference.child("Martials").child("\(fstName!) \(lstName!)").child("General User Detail").child("Email").setValue(email)
if passW == passCW {
self.dbReference.child("Martials").child("\(fstName!) \(lstName!)").child("General User Detail").child("Password").setValue(passCW)
} else {
// show an alert
let alertController = UIAlertController(title: "Ooops", message: "Password Miss Match !!!", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController,animated: true, completion: nil)
}
self.dbReference.child("Martials").child("\(fstName!) \(lstName!)").child("General User Detail").child("DOB").setValue(dob)
self.dbReference.child("Martials").child("\(fstName!) \(lstName!)").child("General User Detail").child("Contact Number").setValue(mobileNo)
self.dbReference.child("Martials").child("\(fstName!) \(lstName!)").child("General User Detail").child("CTM Intro").setValue(intro)
} // end if statement
// perform segue to go to thr next page
performSegue(withIdentifier: "Reg2mDetSegue", sender: self)
} // end of save / continue
// send info to the next segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//Go to profile page
let genInfo : GeneralInfoVC = segue.destination as! GeneralInfoVC
genInfo.fstNameVar = self.firstName.text!
genInfo.lstNameVar = self.lastName.text!
} // end of prepare segue
// Already have an acount button
@IBAction func currentUserButton(_ sender: Any) {
// Go back to login page
//show proifile VC Log2DetsSegue
self.performSegue(withIdentifier: "Reg2LogSegue", sender: self)
}
}
| true
|
16d312f1a21a3350bf7896d272499837ea7640df
|
Swift
|
jonahaung/BalarSarYwatOne
|
/Controllers/Main/Manager/MainManager.swift
|
UTF-8
| 1,160
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// OutlineManager.swift
// BalarSarYwat
//
// Created by Aung Ko Min on 25/2/20.
// Copyright © 2020 Aung Ko Min. All rights reserved.
//
import CoreData
import UIKit
protocol OutlineManagerDelegate: class {
func manager(_ outlineManager: MainManager, didUpdateFolders folders: [Folder])
}
final class MainManager: NSObject {
weak var delegate: OutlineManagerDelegate?
var canRefresh = false
let sectionItems: [MainSectionLayoutKind] = [MainSectionLayoutKind.SystemItems([.AllNotes, .DeletedNotes]), .PinnedNotes, .Folders]
var allNotesCount = 0
var folders = [Folder]()
var pinnedNotes = [Note]()
}
extension MainManager: NSFetchedResultsControllerDelegate {
func updateData() {
pinnedNotes = Note.fetchPinned()
folders = Folder.fetcheAll()
allNotesCount = Note.allNotsCount()
delegate?.manager(self, didUpdateFolders: folders)
}
func folder(at indexPath: IndexPath) -> Folder? {
let folder = folders[indexPath.item]
if canRefresh {
PersistanceManager.shared.viewContext.refresh(folder, mergeChanges: true)
}
return folder
}
}
| true
|
ac0d5557a4115632885ae29f9599166c0aae52e4
|
Swift
|
dbystruev/Get-Outfit-Browser
|
/Get Outfit Browser/View Controllers/OfferViewController.swift
|
UTF-8
| 2,424
| 2.59375
| 3
|
[] |
no_license
|
//
// OfferViewController.swift
// Get Outfit Browser
//
// Created by Denis Bystruev on 19/09/2019.
// Copyright © 2019 Denis Bystruev. All rights reserved.
//
import SDWebImage
import UIKit
class OfferViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
@IBOutlet var categoryLabel: UILabel!
@IBOutlet var idLabel: UILabel!
@IBOutlet var vendorCodeLabel: UILabel!
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var salesNotesLabel: UILabel!
@IBOutlet var priceLabel: UILabel!
var offer: YMLOffer?
}
// MARK: - UI
extension OfferViewController {
func updateUI() {
let label = UILabel()
label.adjustsFontSizeToFitWidth = true
label.text = offer?.title
navigationItem.titleView = label
if let imageURL = offer?.pictures.first {
imageView?.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "icons8-jumper"))
}
if let category = offer?.categoryId {
categoryLabel.text = "Category: \(category)"
} else {
categoryLabel.isHidden = true
}
if let id = offer?.id {
idLabel.text = "id: \(id)"
} else {
idLabel.isHidden = true
}
if let vendorCode = offer?.vendorCode {
vendorCodeLabel.text = "Vendor Code: \(vendorCode)"
} else {
vendorCodeLabel.isHidden = true
}
if let description = offer?.description {
descriptionLabel.text = description
} else {
descriptionLabel.isHidden = true
}
if let salesNotes = offer?.sales_notes {
salesNotesLabel.text = salesNotes
} else {
salesNotesLabel.isHidden = true
}
if let price = offer?.price {
priceLabel.text = "\(price) ₽"
} else {
priceLabel.isHidden = true
}
}
}
// MARK: - UIViewController
extension OfferViewController {
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
}
// MARK: - Actions
extension OfferViewController {
@IBAction func imageTapped(_ sender: UITapGestureRecognizer) {
print(#line, #function)
guard let url = offer?.url else { return }
print(#line, #function, url)
UIApplication.shared.open(url)
}
}
| true
|
fac0fc94d065ee55969d6133996de576ee4dc41e
|
Swift
|
KayoNakao/YoutubeApp
|
/YoutubeApp/Coordinators/AppCoordinator.swift
|
UTF-8
| 2,086
| 2.734375
| 3
|
[] |
no_license
|
//
// AppCoordinator.swift
// YoutubeApp
//
// Created by Filip Jandrijevic on 2018-11-13.
// Copyright © 2018 Guarana Technologies Inc. All rights reserved.
//
import UIKit
import GoogleSignIn
/// The AppCoordinator is our first coordinator
/// In this example the AppCoordinator as a rootViewController
class AppCoordinator: RootViewCoordinator {
// MARK: - Properties
var childCoordinators: [Coordinator] = []
private lazy var splashVC = SplashController()
/// Remember to change the UIViewController instance to your Splash Screen
private(set) var rootViewController: UIViewController = SplashController() {
didSet {
UIView.transition(with: window, duration: 0.3, options: .transitionCrossDissolve, animations: {
self.window.rootViewController = self.rootViewController
})
}
}
/// Window to manage
let window: UIWindow
// MARK: - Init
public init(window: UIWindow) {
self.window = window
self.window.backgroundColor = .white
self.splashVC.delegate = self
self.window.rootViewController = splashVC
self.window.makeKeyAndVisible()
}
// MARK: - Functions
private func setCurrentCoordinator(_ coordinator: RootViewCoordinator) {
rootViewController = coordinator.rootViewController
}
func start() {}
}
extension AppCoordinator: SplashControllerDelegate, HomeCoordinatorDelegate {
func showHomeScreen() {
setupHome()
}
func showConnectionScreen() {
setupConnection()
}
}
extension AppCoordinator {
func setupConnection() {
let connectionCoordinator = ConnectionCoordinator()
addChildCoordinator(connectionCoordinator)
setCurrentCoordinator(connectionCoordinator)
}
func setupHome() {
childCoordinators.removeAll()
let homeCoordinator = HomeCoordinator()
homeCoordinator.delegate = self
addChildCoordinator(homeCoordinator)
setCurrentCoordinator(homeCoordinator)
}
}
| true
|
f93a7bdadd1ac9d85419946749c47b4ab914fb06
|
Swift
|
hiropy0123/swiftCountUp
|
/CountUp/ViewController.swift
|
UTF-8
| 1,244
| 3.171875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CountUp
//
// Created by Hiroki Nakashima on 2017/12/16.
// Copyright © 2017 Hiroki Nakashima. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var digit: UILabel!
var number = 0
override func viewDidLoad() {
super.viewDidLoad()
digit.adjustsFontSizeToFitWidth = true
}
func displayNumber() {
digit.text = String(number)
if number < 0 {
digit.textColor = UIColor.red
} else {
digit.textColor = UIColor.black
}
if number > 30 {
digit.text = "30を超えました"
} else if number < -10 {
digit.text = "-10未満です"
} else {
digit.text = String(number)
}
}
@IBAction func countUp(_ sender: UIButton) {
number += 1
displayNumber()
}
@IBAction func countDown(_ sender: UIButton) {
number -= 1
displayNumber()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| true
|
9eae9f0153ef1996915b8fc4460348c5f85b4242
|
Swift
|
sriramrathinavelu/attendanceSWE2015
|
/ios/project/attendance/Course.swift
|
UTF-8
| 1,367
| 3.03125
| 3
|
[] |
no_license
|
//
// Course.swift
// Attendance Tracker
//
// Created by Yifeng on 10/24/15.
// Copyright © 2015 the Pioneers. All rights reserved.
//
//import Foundation
import UIKit
struct Course {
// var dateComponents = NSCalendar.currentCalendar().components([.Year, .Month, .Day, .Hour, .Minute, .Second, .Weekday] , fromDate: NSDate())
var name: String
var isWeekend: Bool = false
var code: String
var section: Int? = 1
var room: String
var durationStart: NSDate? = NSDate()
var durationEnd: NSDate? = NSDate()
var timeStart: NSDate? = NSDate()
var timeEnd: NSDate? = NSDate()
var dayOfWeek: String? = "Sunday"
var trimester: String? = "Spring 2016"
var professor: String? // email of professor
init(
name: String,
isWeekend: Bool,
code: String,
room: String)
{
self.name = name
self.code = code
self.isWeekend = isWeekend
// self.section = section
self.room = room
// self.durationStart = durationStart
// self.durationEnd = durationEnd
// self.timeStart = timingStart
// self.timeEnd = timingEnd
// self.dayOfWeek = dayOfWeek
// self.trimester = trimester
}
func getCourseCode() -> String {
return self.code + " " + String(self.section!)
}
}
| true
|
f1907f7fc379eed9c5c7484a6051d2a92c368928
|
Swift
|
onurtorna/WordBuzzer
|
/WordBuzzer/WordBuzzer/Scenes/Landing Page/Views/SettingsSelectorViewModel.swift
|
UTF-8
| 4,306
| 3.375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// SettingsSelectorViewModel.swift
// WordBuzzer
//
// Created by Onur Torna on 26/04/18.
// Copyright © 2018 Onur Torna. All rights reserved.
//
import Foundation
final class SettingsSelectorState {
enum Change {
case playerCountChanged(Int)
case roundCountChanged(Int)
case languageChanged((questionLanguage: LanguageKey, answerLanguage: LanguageKey))
case gameStarted(Int, Int, LanguageKey, LanguageKey)
}
/// Possible player count list
var playerCountList = [2, 3, 4]
/// Possible round count list
var roundCountList = [5, 10, 15, 20]
/// Possible language pair tupples
var languageList: [(LanguageKey, LanguageKey)] = [(.englishKey, .spanishKey),
(.spanishKey, .englishKey)]
/// Change closure
var onChange: ((SettingsSelectorState.Change) -> Void)?
/// Selected player count
private var selectedPlayerCount: Int = 0 {
didSet {
onChange?(.playerCountChanged(selectedPlayerCount))
}
}
/// Selected round count
private var selectedRoundCount: Int = 0 {
didSet {
onChange?(.roundCountChanged(selectedRoundCount))
}
}
/// Selected languages
var selectedLanguage: (LanguageKey, LanguageKey) = (.englishKey, .spanishKey) {
didSet {
onChange?(.languageChanged((questionLanguage: selectedLanguage.0,
answerLanguage: selectedLanguage.1)))
}
}
/// Selected player count index in the player count list
var selectedPlayerCountIndex: Int = 0 {
didSet {
selectedPlayerCount = playerCountList[selectedPlayerCountIndex]
}
}
/// Selected round count index in the round count list
var selectedRoundCountIndex: Int = 0 {
didSet {
selectedRoundCount = roundCountList[selectedRoundCountIndex]
}
}
/// Selected language pair index in the language tupple list
var selectedLanguageIndex: Int = 0 {
didSet {
selectedLanguage = languageList[selectedLanguageIndex]
}
}
/// Player count list size
var playerCountListCount: Int {
return playerCountList.count
}
/// Round count list size
var roundCountListCount: Int {
return roundCountList.count
}
var languageListCount: Int {
return languageList.count
}
}
final class SettingsSelectorViewModel {
/// Current state of the view model
private var state = SettingsSelectorState()
var stateChangeHandler: ((SettingsSelectorState.Change) -> Void)? {
get {
return state.onChange
}
set {
state.onChange = newValue
publishInitial()
}
}
/// Updates the round count by incrementing it if possible, resets it if it is not.
func updateRoundCount() {
if state.selectedRoundCountIndex == state.roundCountListCount - 1 {
state.selectedRoundCountIndex = 0
} else {
state.selectedRoundCountIndex += 1
}
}
/// Updates the player count by incrementing it if possible, resets it if it is not.
func updatePlayerCount() {
if state.selectedPlayerCountIndex == state.playerCountListCount - 1 {
state.selectedPlayerCountIndex = 0
} else {
state.selectedPlayerCountIndex += 1
}
}
func updateLanguageSelection() {
if state.selectedLanguageIndex == state.languageListCount - 1 {
state.selectedLanguageIndex = 0
} else {
state.selectedLanguageIndex += 1
}
}
/// Starts the game
func startGame() {
stateChangeHandler?(.gameStarted(state.playerCountList[state.selectedPlayerCountIndex],
state.roundCountList[state.selectedRoundCountIndex],
state.selectedLanguage.0,
state.selectedLanguage.1))
}
/// Publishes initial values for state variables
private func publishInitial() {
state.selectedPlayerCountIndex = 0
state.selectedRoundCountIndex = 0
state.selectedLanguageIndex = 0
}
}
| true
|
9b3cca490219850677760f8f33dfa8e3c17cca4c
|
Swift
|
AdamWorthington/IOUO
|
/ScavengerHunt/ScavengerHunt/ScavengerHuntItem.swift
|
UTF-8
| 1,122
| 2.625
| 3
|
[] |
no_license
|
import UIKit
class ScavengerHuntItem: NSObject, NSCoding {
let NameKey = "Name"
let PhotoKey = "Photo"
let MembersKey = "Members"
var members: [MemberItem] = []
//var memberManager = MemberManager()
let name: String
var photo: UIImage?
//var mem: objc_object
var isComplete: Bool {
get {
return photo != nil
}
}
init(name: String){
self.name = name
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(name, forKey: NameKey)
//coder.encodeObject(members, forKey: MembersKey)
if let thePhoto = photo {
coder.encodeObject(thePhoto, forKey: PhotoKey)
}
coder.encodeObject(members, forKey: MembersKey)
}
required init(coder aDecoder: NSCoder) {
name = aDecoder.decodeObjectForKey(NameKey) as String
photo = aDecoder.decodeObjectForKey(PhotoKey) as? UIImage
members = aDecoder.decodeObjectForKey(MembersKey) as [MemberItem]
//mem = aDecoder.decodeObjectForKey(memberManager) as objc_object
}
}
| true
|
223f56396fce52e9751178ef938aaccdc207a417
|
Swift
|
agung3535/Foodie
|
/FoodLover/Extensions/UIViewExtenstions.swift
|
UTF-8
| 300
| 2.53125
| 3
|
[] |
no_license
|
//
// UIViewExtenstions.swift
// FoodLover
//
// Created by Putra on 04/11/21.
//
import Foundation
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get { return cornerRadius }
set {
self.layer.cornerRadius = newValue
}
}
}
| true
|
b57ee440787ee3dae558e4b8f9cc6961c1a662d5
|
Swift
|
dooublemint/CustomPaging
|
/CustomPaging/Sources/Clamp.swift
|
UTF-8
| 312
| 2.859375
| 3
|
[] |
no_license
|
//
// Clamp.swift
// CustomPaging
//
// Created by Ilya Lobanov on 27/08/2018.
// Copyright © 2018 Ilya Lobanov. All rights reserved.
//
import Foundation
extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
| true
|
99b421e901721341f529761fbb7b72775184aa47
|
Swift
|
arthurfjadecastro/aapp
|
/AAPP/Pin.swift
|
UTF-8
| 710
| 3.234375
| 3
|
[] |
no_license
|
//
// Pin.swift
// AAPP
//
// Created by Arthur Castro on 24/12/2018.
// Copyright © 2018 Arthur Castro. All rights reserved.
//
import Foundation
import GoogleMaps
///Struct Pin
struct Pin {
///Name a pin
let name: String
///Location a pin
let location: Coordinate
///Initializer of a pin with name and location
init(name: String, location: Coordinate) {
self.name = name
self.location = location
}
///Initializer of a pin with name, latitude and longitude
init(name: String, latitude: Double, longitude: Double) {
let location = Coordinate(latitude: latitude, longitude: longitude)
self.init(name: name, location: location)
}
}
| true
|
9a12062063b7b82bc837e72daac1fbde83f6c193
|
Swift
|
sashkir7/SecondOpinion
|
/Classes/BusinessLogic/Models/Tag.swift
|
UTF-8
| 605
| 3.140625
| 3
|
[] |
no_license
|
//
// Created by Alx Krw on 25.10.2020
// Copyright © 2020 Ronas IT. All rights reserved.
//
import Foundation
struct Tag: Codable, Equatable, Identifiable {
typealias ID = UInt
let id: ID
let name: String
private enum CodingKeys: String, CodingKey {
case id
case name
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(.id)
name = try container.decode(.name)
}
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.id == rhs.id
}
}
| true
|
324ce7e3d306becbb5e8a5efd32f9c78d8dafc95
|
Swift
|
mknabbe/musictools
|
/musictools/Metronome.swift
|
UTF-8
| 2,085
| 2.921875
| 3
|
[] |
no_license
|
//
// Metronom.swift
// musictools
//
// Created by Martin Knabbe on 30.01.16.
// Copyright © 2016 Martin Knabbe. All rights reserved.
//
import Foundation
/**
The `Metronome` class provides the functionality of a metronome. It uses a `BeatPlayer` instance
to produce the beat.
- Since: 0.1
*/
final class Metronome: NSObject, MetronomeActions {
static let DefaultTempo = 63
static let MinimumTempo = 40
static let MaximumTempo = 208
static let DefaultBeat = 0
static let MinimumBeat = 0
static let MaximumBeat = 6
@IBOutlet var beatPlayer: BeatPlayer?
/// Timer calling beatPlayer to play 'klick' sound.
private weak var soundTimer: Timer?
private(set) var playing = false
private var _tempo = DefaultTempo
var tempo: Int {
get {
return _tempo
}
set {
_tempo = min(max(newValue, Metronome.MinimumTempo), Metronome.MaximumTempo)
if playing {
startTimerWithBeatsPerSecond(_tempo)
}
}
}
private var _beat = DefaultBeat
var beat: Int {
get {
return _beat
}
set {
if (newValue == 1) {
_beat = Metronome.MinimumBeat
} else {
_beat = min(max(newValue, Metronome.MinimumBeat), Metronome.MaximumBeat)
}
beatPlayer?.alternatingBeatWithInterval = _beat
}
}
func startPlaying() {
playing = true
beatPlayer?.initOpenAL()
startTimerWithBeatsPerSecond(tempo)
}
func stopPlaying() {
soundTimer?.invalidate()
soundTimer = nil
playing = false
}
private func startTimerWithBeatsPerSecond(_ beatsPerSecond: Int) {
guard let beatPlayer = beatPlayer else { return }
let intervalInSeconds = 60.0 / TimeInterval(beatsPerSecond)
soundTimer?.invalidate()
soundTimer = Timer.scheduledTimer(timeInterval: intervalInSeconds, target: beatPlayer, selector: Selector(("playBeat")), userInfo: nil, repeats: true)
}
}
| true
|
cb26129d89a8f844953d1d449c6236255359a3d2
|
Swift
|
Magoxter/iOS_Applications
|
/Developed Applications/17:07/revisao swift/04_Olá mundo.playground/Pages/Exercício – Depuração.xcplaygroundpage/Contents.swift
|
UTF-8
| 3,373
| 4.03125
| 4
|
[] |
no_license
|
/*:
## Exercício – Depuração
Às vezes, é necessário adicionar instruções `print` temporárias para saber por que um programa não está funcionando.
Identificar problemas ou _bugs_ no código é um dos usos mais comuns do console. Os programadores passam muito tempo lidando com códigos que ainda não funcionam. Se tudo funcionasse como eles querem, não seria necessário fazer revisões.
Neste exercício, você vai depurar um código criado por outra pessoa. Boa sorte!
- note:\
(Nota):\
O console deve estar visível, e a barra de resultados, oculta. Mais adiante neste curso, você terá várias oportunidades de depurar usando a barra lateral de resultados.
- callout(Experiment: Pseudo-personalization):
(Experiência: pseudopersonalização):\
Vamos supor que todos os seus amigos fizeram alguma coisa que deixou você chocado. Então, você decidiu enviar uma mensagem personalizada expressando seus sentimentos a cada um deles. Para não perder tempo escrevendo mensagens individuais, você criou um programa para gerá-las. Depois que ele estiver funcionando, você tem certeza de que basta alterar a variável `name` e depois copiar e colar sua reação de choque pseudopersonalizada para cada um dos seus amigos. */
// -------------- 👇 O código que precisa ser corrigido está abaixo 👇 --------------------
let questionWord = "WHY"
let connectorWord = "but"
let question = "\(connectorWord) \\(questionWord)?"
let incessantQuestion = "\(question)\(question)\(question)\(question)"
let name = "Kim"
let summons = "\(name) \(name). \(name)!"
let botheration = "\(summons)\(incessantQuestion)"
// -------------- 👆 O código que precisa ser corrigido está acima 👆 --------------------
//: Infelizmente, o programa tem um bug. Siga as instruções para encontrar e corrigir o erro!
// -------------- 👇 Coloque as instruções print abaixo desta linha 👇 --------------------
/*:
1. Imprima a constante `botheration` assim:
```
(Exemplo):
print(botheration)
```
O resultado ainda não parece uma mensagem de texto típica. A pontuação está estranha, e algumas partes parecem códigos. Para corrigir esses problemas, você poderia analisar bem o código e fazer alterações até o resultado final ficar bom, mas é mais fácil analisar algumas constantes intermediárias.
2. Adicione mais algumas instruções `print` para verificar as constantes intermediárias, como `question`.
3. Quando você tiver ideia de quais linhas provocaram os erros, comece a corrigi-las da primeira à última (se necessário, consulte o playground Strings). Continue conferindo o console para garantir que as constantes intermediárias estejam corretas. Lembre-se de que você sempre pode fazer comentários ou excluir as instruções `print` que não forem mais necessárias.
4. Quando a string final parecer escrita por uma pessoa e não por um computador, ajuste as constantes para criar sua mensagem:
* Altere as constantes string `questionWord`, `connectorWord` e `name` com valores diferente
* Altere `question`, `incessantQuestion` e `summons` para combinar as outras constantes de formas diferentes. Fique à vontade para usar mais repetições, menos repetições ou até inserir frases novas.
[Anterior](@previous) | página 10 de 11 | [Na sequência: Exercício – App Console](@next)
*/
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.