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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
753adeb934961a0693b2f95defc6c73b6238d841
|
Swift
|
salehmasum/AppStoreOld
|
/AppStoreOld/Helper.swift
|
UTF-8
| 819
| 2.609375
| 3
|
[] |
no_license
|
//
// Helper.swift
// AppStoreOld
//
// Created by Saleh Masum on 27/12/18.
// Copyright © 2018 Saleh Masum. All rights reserved.
//
import UIKit
class Helper {
func descriptionAttributedText(desc: String) -> NSAttributedString {
let attributedText = NSMutableAttributedString(string: "Description\n", attributes: [.font: UIFont.systemFont(ofSize: 14)])
let style = NSMutableParagraphStyle()
style.lineSpacing = 10
let range = NSRange(location: 0, length: attributedText.length)
attributedText.addAttributes([.paragraphStyle: style], range: range)
attributedText.append(NSMutableAttributedString(string: desc, attributes: [.font: UIFont.systemFont(ofSize: 11), .foregroundColor: UIColor.darkGray ]))
return attributedText
}
}
| true
|
4419be133d9e8d8c17fbb6859f6103a2fb937d3a
|
Swift
|
nate-parrott/ptrptr
|
/ptrptr/NetImageView.swift
|
UTF-8
| 1,568
| 2.75
| 3
|
[] |
no_license
|
//
// NetImageView.swift
// ptrptr
//
// Created by Nate Parrott on 1/16/16.
// Copyright © 2016 Nate Parrott. All rights reserved.
//
import UIKit
class NetImageView: UIImageView {
var url: NSURL? {
willSet(newVal) {
image = nil
if newVal != url {
_task?.cancel()
_task = nil
loadInProgress = true
if let url_ = newVal {
let req = NSURLRequest(URL: url_)
_task = NSURLSession.sharedSession().dataTaskWithRequest(req, completionHandler: { [weak self] (let dataOpt, let responseOpt, let errorOpt) -> Void in
backgroundThread({ () -> Void in
if let self_ = self, data = dataOpt, image = UIImage(data: data) {
mainThread({ () -> Void in
if self_.url == url_ {
self_.image = image
self_.loadInProgress = false
}
})
}
})
})
_task!.resume()
}
} else {
loadInProgress = false
}
}
}
var _task: NSURLSessionDataTask?
private(set) var loadInProgress = false {
didSet {
backgroundColor = loadInProgress ? UIColor(white: 0.5, alpha: 0.5) : UIColor.clearColor()
}
}
}
| true
|
a3aed38b0f1010658d67884e5d4a413d47874201
|
Swift
|
arkadysmirnov86/currencycalculator
|
/currencycalculatorTests/ConvertorViewModelTests.swift
|
UTF-8
| 3,825
| 2.515625
| 3
|
[] |
no_license
|
//
// ConvertorViewModelTests.swift
// currencycalculatorTests
//
// Created by Arkady Smirnov on 8/19/18.
// Copyright © 2018 Arkady Smirnov. All rights reserved.
//
import Foundation
import XCTest
@testable import currencycalculator
class ConvertorViewModelTests: XCTestCase {
func testRatesChanged() {
let successExpectation = expectation(description: "expectation of ratesChanged call")
let currencyService = FakeCurrencyService()
let defaultBaseRate = RateModel(currency: "FAKE", value: 100.0)
let viewModel = ConvertorViewModel(currencyService: currencyService, baseRate: defaultBaseRate)
viewModel.ratesChanged = {
successExpectation.fulfill()
}
currencyService.raiseSuccess()
wait(for: [successExpectation], timeout: 1)
}
func testRatesNotChanged() {
let successExpectation = expectation(description: "expectation of not calling ratesChanged ")
successExpectation.isInverted = true
let currencyService = FakeCurrencyService()
let defaultBaseRate = RateModel(currency: "FAKE", value: 100.0)
let viewModel = ConvertorViewModel(currencyService: currencyService, baseRate: defaultBaseRate)
viewModel.ratesChanged = {
successExpectation.fulfill()
}
currencyService.raiseError()
wait(for: [successExpectation], timeout: 1)
}
func testisEditingChanged() {
let successExpectation = expectation(description: "expectation of isEditingChanged call")
successExpectation.expectedFulfillmentCount = 2
let currencyService = FakeCurrencyService()
let viewModel = ConvertorViewModel(currencyService: currencyService)
viewModel.isEditingChanged = {
successExpectation.fulfill()
}
viewModel.isEditing = true
viewModel.isEditing = false
wait(for: [successExpectation], timeout: 1)
}
func testBaseCurrencyChanged() {
let successExpectation = expectation(description: "expectation of baseCurrency update and ratesChanged call")
let expectedCurrency = "currency5"
let currencyService = FakeCurrencyService()
let defaultBaseRate = RateModel(currency: "FAKE", value: 100.0)
let viewModel = ConvertorViewModel(currencyService: currencyService, baseRate: defaultBaseRate)
viewModel.ratesChanged = {
if viewModel.baseCurrency == expectedCurrency {
successExpectation.fulfill()
}
}
currencyService.raiseSuccess()
viewModel.baseCurrency = expectedCurrency
currencyService.raiseSuccess()
wait(for: [successExpectation], timeout: 1)
}
func testRatesOrderingAfterBaseCarrencyChanged() {
let successExpectation = expectation(description: "expectation of baseCurrency update and ratesChanged call")
let expectedCurrency = "currency5"
let currencyService = FakeCurrencyService()
let defaultBaseRate = RateModel(currency: "FAKE", value: 100.0)
let viewModel = ConvertorViewModel(currencyService: currencyService, baseRate: defaultBaseRate)
viewModel.ratesChanged = {
if viewModel.baseCurrency == expectedCurrency, viewModel.rates[1].currency == defaultBaseRate.currency
&& viewModel.rates[1].value == defaultBaseRate.value {
successExpectation.fulfill()
}
}
currencyService.raiseSuccess()
viewModel.baseCurrency = expectedCurrency
currencyService.raiseSuccess()
wait(for: [successExpectation], timeout: 1)
}
}
| true
|
c0e52946bb86954a1df7bf6fe96dd7a922121653
|
Swift
|
anirudhamahale/reactive-architecture
|
/ReactiveX/Sources/Rx/RxAnimatableTableSectionModel.swift
|
UTF-8
| 994
| 2.75
| 3
|
[] |
no_license
|
//
// RxAnimatableTableSectionModel.swift
// ReactiveX
//
// Created by Anirudha Mahale on 13/08/20.
// Copyright © 2020 Anirudha Mahale. All rights reserved.
//
import RxSwift
import RxCocoa
import RxDataSources
struct RxAnimatableTableSectionModel {
var header: String
var rows: [RxAnimatableTableCellModel]
var rowsCount: Int {
return rows.count
}
mutating func append(_ model: RxAnimatableTableCellModel) {
rows.append(model)
}
mutating func removeItems(at indexs: [Int]) {
indexs.forEach({ rows.remove(at: $0) })
}
}
class RxAnimatableTableCellModel: IdentifiableType, Equatable {
var identity: String {
return id
}
var id = ""
typealias Identity = String
static func == (lhs: RxAnimatableTableCellModel, rhs: RxAnimatableTableCellModel) -> Bool {
return lhs.id == rhs.id
}
func getIndex(from constant: String) -> Int? {
let stringIndex = identity.replacingOccurrences(of: constant, with: "")
return Int(stringIndex)
}
}
| true
|
cec3cb0daf35d640cf859a21a88aed65b9a38cb0
|
Swift
|
HarveySun228/swiftDemo
|
/codes/08/8.2/InitOverride.swift
|
UTF-8
| 967
| 3.484375
| 3
|
[] |
no_license
|
class Fruit
{
var name: String
var weight: Double
init()
{
self.name = ""
self.weight = 0.0
}
init(name:String , weight: Double)
{
self.name = name
self.weight = weight
}
convenience init(name: String)
{
self.init(name:name , weight: 0.0)
}
convenience init(_ name: String)
{
self.init(name:name)
}
}
class Apple: Fruit
{
var color: String
// 重写父类的指定构造器
override init(name: String , weight: Double)
{
self.color = "默认色"
// 调用父类构造器
super.init(name:name , weight:weight)
}
// 定义指定构造器
init(name: String)
{
self.color = "默认色"
super.init(name: name, weight: 0.0)
}
// 便利构造器
convenience init(name: String ,weight: Double, color:String)
{
self.init(name:name , weight:weight)
self.weight = weight
}
// 使用便利构造器重写父类的指定构造器
override convenience init()
{
self.init(name:"苹果" , weight:0.0 , color:"粉红" )
}
}
| true
|
e8e40d9919e8f86af63967b649c078ed75fbe24d
|
Swift
|
abdurrahman-90/SwiftAdvanceNEws
|
/SwiftAdvanceNEWS/Model/Channel.swift
|
UTF-8
| 520
| 2.90625
| 3
|
[] |
no_license
|
//
// Channel.swift
// SwiftAdvanceNEWS
//
// Created by Akdag on 2.03.2021.
//
import UIKit
enum sectionType {
case NewsSources , Topics , Domains
}
struct Channel : Hashable {
let identifier: UUID = UUID()
let sectionType: sectionType
var sites: [NewsSource]
var topics: [String]
func hash(into hasher: inout Hasher) {
return hasher.combine(identifier)
}
static func == (lhs:Channel , rhs : Channel ) -> Bool {
return lhs.identifier == rhs.identifier
}
}
| true
|
7517037fe9515f6ba6ce85785304ec093d7d045e
|
Swift
|
gemicn/FityIt
|
/FityIt/Main/AppColors.swift
|
UTF-8
| 1,245
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// AppColors.swift
// FityIt
//
// Created by Txai Wieser on 13/03/18.
// Copyright © 2018 Txai Wieser. All rights reserved.
//
import SpriteKit
extension SKColor {
static let mirageBlack: SKColor = SKColor(red:0.07, green:0.11, blue:0.16, alpha:1)
static let lightBlack: SKColor = SKColor(red:0.29, green:0.35, blue:0.41, alpha:1)
static let darkBlack: SKColor = SKColor(red:0.19, green:0.23, blue:0.27, alpha:1)
static let darkerBlack: SKColor = SKColor(red:0.03, green:0.07, blue:0.12, alpha:1)
static let laranja: SKColor = SKColor(red:0.97, green:0.58, blue:0.31, alpha:1)
static let rosa: SKColor = SKColor(red:0.91, green:0.31, blue:0.42, alpha:1)
static let roxo: SKColor = SKColor(red:0.4, green:0.31, blue:0.82, alpha:1)
static let verde: SKColor = SKColor(red:0.44, green:0.84, blue:0.25, alpha:1)
static let darkerLaranja: SKColor = SKColor(red:0.72, green:0.32, blue:0, alpha:1)
static let darkerRosa: SKColor = SKColor(red:0.67, green:0.06, blue:0.17, alpha:1)
static let darkerRoxo: SKColor = SKColor(red:0.17, green:0.01, blue:0.67, alpha:1)
static let darkerVerde: SKColor = SKColor(red:0.22, green:0.62, blue:0, alpha:1)
static let lightTintColor: SKColor = .white
}
| true
|
1569383b3761de95b20fdcf14a81f73659496eaa
|
Swift
|
miguel-rios-r/Adivina-el-numero-IOS
|
/First App IOS/ViewController.swift
|
UTF-8
| 2,047
| 2.96875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// First App IOS
//
// Created by Miguel Rios R on 12/24/18.
// Copyright © 2018 Miguel Rios R. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var numtxt: UITextField!
@IBOutlet weak var intentoslbl: UILabel!
@IBOutlet weak var smslbl: UILabel!
var random = ""
var intentos = 0
@IBAction func validarbtn(_ sender: Any) {
if numtxt.text == random{
smslbl.text = "Felicidades, Ganaste!"
self.view.backgroundColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1)
showAlert()
} else {
smslbl.text = "Game over"
if intentos == 1{
self.view.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
showAlert()
} else {
intentos = intentos - 1
intentoslbl.text = String(intentos)
smslbl.text = "Intenta de nuevo"
numtxt.text = ""
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setValues()
// Do any additional setup after loading the view, typically from a nib.
}
func showAlert(){
let alert = UIAlertController(title: nil, message: "Intenta de nuevo", preferredStyle: .alert)
let playAgain = UIAlertAction(title: "Juega de nuevo", style: .default){
(UIAlertAction) in self.setValues()
}
alert.addAction(playAgain)
self.present(alert, animated: true, completion: nil)
}
func setValues(){
random = String(arc4random_uniform(10))
print (random)
intentos = 5
intentoslbl.text = String(intentos)
numtxt.text = ""
smslbl.text = "Ingrese un número del 0 - 9"
self.view.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
}
}
| true
|
4805bb1a419f96b10b4d19cca3d66aa5f216bc7f
|
Swift
|
refundr/mvvm-observables
|
/TemplateProject/ViewModel/CurrencyDataSource.swift
|
UTF-8
| 1,055
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// CurrencyDataSource.swift
// TemplateProject
//
// Created by Benoit PASQUIER on 24/01/2018.
// Copyright © 2018 Benoit PASQUIER. All rights reserved.
//
import Foundation
import UIKit
class GenericDataSource<T> : NSObject {
var data: DynamicValue<[T]> = DynamicValue([])
}
class CurrencyDataSource : GenericDataSource<CurrencyRate>, UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: CurrencyCell = tableView.dequeueReusableCell(withIdentifier: "CurrencyCell", for: indexPath as IndexPath) as? CurrencyCell else {
fatalError("CurrencyCell cell is not found")
}
let currencyRate = self.data.value[indexPath.row]
cell.currencyRate = currencyRate
return cell
}
}
| true
|
7c9ed1c75681a153527504992ca2fa653e4eb0ea
|
Swift
|
AndrewSB/Library
|
/Sources/Library/Util/Bool + AllTrue.swift
|
UTF-8
| 623
| 3.578125
| 4
|
[] |
no_license
|
import Foundation
// TODO: this protocol isn't needed in swift 3.1
// remove it then https://github.com/apple/swift/blob/master/CHANGELOG.md#swift-31
public protocol BooleanType {
var boolValue: Bool { get }
}
extension Bool: BooleanType {
public var boolValue: Bool {
return self
}
}
public extension Array where Element: BooleanType {
var allTrue: Bool {
return reduce(true) { (sum, next) in return sum && next.boolValue }
}
var anyTrue: Bool {
return contains { $0.boolValue == true }
}
}
public func allTrue(_ array: [Bool]) -> Bool {
return array.allTrue
}
| true
|
b442471d98c516f1a159369418768f3a8d32b24a
|
Swift
|
ryantstone/squish
|
/Squish/Views/DropzoneView.swift
|
UTF-8
| 2,384
| 2.734375
| 3
|
[] |
no_license
|
import AppKit
final class DropzoneView: NSView {
let NSFilenamesPboardType = NSPasteboard.PasteboardType("NSFilenamesPboardType")
var fileTypeIsOk = false
var droppedFilePath: [URL]! {
didSet {
delegate?.didReceiveFiles(droppedFilePath)
}
}
let acceptedFileExtensions = [ "mp3", "mp4", "m4a", "m4b" ]
let draggableTypes = [
NSPasteboard.PasteboardType(kUTTypeFileURL as String),
NSPasteboard.PasteboardType(kUTTypeItem as String)
]
var delegate: DropzoneViewDelegate?
required init?(coder: NSCoder) {
super.init(coder: coder)
registerForDraggedTypes(draggableTypes)
}
override func awakeFromNib() {
registerForDraggedTypes(draggableTypes)
}
override func draw(_ dirtyRect: NSRect) {
NSColor(red: 0x1d/255, green: 0x16/255, blue: 0x1d/255, alpha: 1).setFill()
dirtyRect.fill()
super.draw(dirtyRect)
}
override public func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if checkExtension(drag: sender) {
fileTypeIsOk = true
return .copy
} else {
fileTypeIsOk = false
return []
}
}
override public func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
return fileTypeIsOk ? .copy : []
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
guard let filePaths = parseDraggingInfo(sender) else { return false }
droppedFilePath = filePaths.compactMap { URL(fileURLWithPath: $0) }
return false
}
func checkExtension(drag: NSDraggingInfo) -> Bool {
guard let filePaths = parseDraggingInfo(drag) else { return false }
return filePaths.map { NSURL(fileURLWithPath: $0).pathExtension?.lowercased() }
.unique
.allSatisfy { acceptedFileExtensions.contains($0!) }
}
private func parseDraggingInfo(_ sender: NSDraggingInfo) -> [String]? {
guard let files = sender.draggingPasteboard.propertyList(forType: NSFilenamesPboardType) as? NSArray,
let filesPaths = files as? [String] else {
return nil
}
return filesPaths
}
}
protocol DropzoneViewDelegate {
func didReceiveFiles(_ files: [URL])
}
| true
|
2aedf7bb0e4779d6058ea2dd4392170cd5ea6b0a
|
Swift
|
josancamon19/iOS12-SwiftBootcamp
|
/1.3 Magic 8 Ball/Magic 8 Ball/ViewController.swift
|
UTF-8
| 662
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Magic 8 Ball
//
// Created by Joan Cabezas on 7/11/19.
// Copyright © 2019 josancamon19. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
answerQuestion()
}
@IBAction func askButtonPressed(_ sender: Any) {
answerQuestion()
}
func answerQuestion(){
image.image = UIImage(named: "ball\(Int.random(in: 1...5))")
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
answerQuestion()
}
}
| true
|
fc414167e93288cf5f6bf88c4ecd08ff2f49e432
|
Swift
|
AhmedAli-IB/CatsPicApp
|
/CatsPicturesApp/Extensions/UIImage+LoadImage.swift
|
UTF-8
| 625
| 2.859375
| 3
|
[] |
no_license
|
//
// UIImage+LoadImage.swift
// CatsPicturesApp
//
// Created by Ahmed Ali on 02/06/2021.
//
import UIKit
import Kingfisher
// MARK: - ImageLoader
//
protocol ImageLoader {
/// Set image using url as string and placeholder image in case of failure to fetch the image
///
func setImage(urlString: String?, placeholder: UIImage?)
}
// MARK: - UIImageView + ImageLoader Conformance
//
extension UIImageView: ImageLoader {
func setImage(urlString: String?, placeholder: UIImage?) {
let url = URL(string: urlString ?? "")
self.kf.setImage(with: url, placeholder: placeholder)
}
}
| true
|
0d0ff52491c70b7a3d92db30497f0c937cc77f33
|
Swift
|
mobLee-arquivo/Coding-Dojo-iOS---13-de-abril-de-2015
|
/TennisKata_coding_dojo/TennisKataTests/TennisKataTests.swift
|
UTF-8
| 1,374
| 2.59375
| 3
|
[] |
no_license
|
import UIKit
import XCTest
class TennisKataTests: XCTestCase {
var jogo : Jogo!
var jogador1 = 1
var jogador2 = 2
override func setUp() {
jogo = Jogo()
}
func testPlacarInicial() {
XCTAssertEqual(jogo.mostrarPlacar(), "LovexLove")
}
func testPrimeiroPontoPrimeiroJogador(){
jogo.pontuar(jogador1)
XCTAssertEqual(jogo.mostrarPlacar(), "15xLove")
}
func testPrimeiroPontoSegundoJogador(){
jogo.pontuar(jogador2)
XCTAssertEqual(jogo.mostrarPlacar(), "Lovex15")
}
func testEmpateQuinzeQuinze() {
pontuarNVezes(1, jogador:jogador1)
pontuarNVezes(1, jogador:jogador2)
XCTAssertEqual(jogo.mostrarPlacar(), "15x15")
}
func testPlacarQuinzeTrinta() {
pontuarNVezes(1, jogador:jogador1)
pontuarNVezes(2, jogador:jogador2)
XCTAssertEqual(jogo.mostrarPlacar(), "15x30")
}
func testEmpateTrintaTrinta() {
pontuarNVezes(2, jogador:jogador1)
pontuarNVezes(2, jogador:jogador2)
XCTAssertEqual(jogo.mostrarPlacar(), "30x30")
}
func testEmpateDeuce() {
pontuarNVezes(3, jogador:jogador1)
pontuarNVezes(3, jogador:jogador2)
XCTAssertEqual(jogo.mostrarPlacar(), "Deuce")
}
func pontuarNVezes(n:Int,jogador:Int){
for _ in 0..<n{
jogo.pontuar(jogador)
}
}
}
| true
|
3bdec65ac01e25505e458d2fe49e50e4749aeda3
|
Swift
|
parumpupum/rs.ios.stage-task6
|
/Swift_Task6/ios.stage-task/Exercises/Exercise-2/Deck.swift
|
UTF-8
| 1,834
| 3.640625
| 4
|
[] |
no_license
|
import Foundation
protocol DeckBaseCompatible: Codable {
var cards: [Card] {get set}
var type: DeckType {get}
var total: Int {get}
var trump: Suit? {get}
}
enum DeckType:Int, CaseIterable, Codable {
case deck36 = 36
}
struct Deck: DeckBaseCompatible {
//MARK: - Properties
var cards = [Card]()
var type: DeckType
var trump: Suit?
var total:Int {
return type.rawValue
}
}
extension Deck {
init(with type: DeckType) {
self.type = type
let suits = Suit.allCases
let values = Value.allCases
cards = createDeck(suits: suits, values: values)
}
public func createDeck(suits:[Suit], values:[Value]) -> [Card] {
var cards = [Card]()
for suit in suits{
for value in values{
cards.append(Card(suit: suit, value: value))
}
}
return cards
}
public mutating func shuffle() {
var newDeck = cards
cards.removeAll()
while let newCard = newDeck.randomElement(){
cards.append(newCard)
let i = newDeck.firstIndex(of: newCard)!
newDeck.remove(at: i)
}
}
public mutating func defineTrump() {
trump = cards.last?.suit
for (index, card) in cards.enumerated(){
if card.suit == trump{
cards[index].isTrump = true
}
}
}
public mutating func initialCardsDealForPlayers(players: [Player]) {
for i in 0..<players.count{
var newHand = [Card]()
for q in 1...6{
newHand.append(cards.first!)
cards.removeFirst()
}
players[i].hand = newHand
}
}
}
| true
|
50a8a0b27b2ab375bd9b99e4168c8857e900b55b
|
Swift
|
iAmNaz/TweeterStreamer
|
/TwitterFeedUI/ViewControllers/RootViewController.swift
|
UTF-8
| 3,475
| 2.640625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TwitterFeedUI
//
// Created by Nazario Mariano on 15/02/2018.
// Copyright © 2018 Nazario Mariano. All rights reserved.
//
import UIKit
enum ContainerView {
case LoginView
case FeedView
}
protocol FeedItemViewModel {
var profileImageURL: URL { get set }
var screenName: String { get set }
var text: String { get set }
}
class RootViewController: UIViewController {
@IBOutlet weak var logoutButton: UIButton!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var feedViewContainer: UIView!
@IBOutlet weak var loginViewContainer: UIView!
@IBOutlet weak var statusLabel: UILabel!
var rootInteractor: RootInteractorProtocol!
var appController: AppControllerProtocol!
var appInteractor: AppInteractorProtocol!
fileprivate var currentKeyword: String?
fileprivate var searchActive : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
appController.didLaunch()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func logoutAction(_ sender: Any) {
loggedOutView()
appInteractor.logout()
}
//MARK - Private
fileprivate func keywordEntered(keyword: String){
currentKeyword = keyword
rootInteractor.loadFeed(forKeyword: currentKeyword!)
}
fileprivate func displayStatus(message: String) {
statusLabel.isHidden = false
view.bringSubview(toFront: statusLabel)
statusLabel.text = message
}
fileprivate func loggedInView() {
hideStatus()
loginViewContainer.isHidden = true
feedViewContainer.isHidden = false
logoutButton.isHidden = false
searchBar.isHidden = false
}
fileprivate func loggedOutView() {
logoutButton.isHidden = true
statusLabel.isHidden = true
searchBar.isHidden = true
feedViewContainer.isHidden = true
loginViewContainer.isHidden = false
searchBar.endEditing(true)
}
}
extension RootViewController: RootDisplayProtocol {
func show(message: String) {
displayStatus(message: message)
}
func showProgress() {
displayStatus(message: "loading...")
}
func hideStatus() {
statusLabel.isHidden = true
}
func showAuthRequiredView() {
loggedOutView()
}
//Called after auth or if authorized
func showFeedView() {
loggedInView()
}
func showKeyword(keyword: String) {
searchBar.text = keyword
}
}
extension RootViewController: UISearchBarDelegate {
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = currentKeyword
self.searchBar.endEditing(true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//dismiss keyboard
self.searchBar.endEditing(true)
//prevent empty text
if (searchBar.text?.isEmpty)! {
searchBar.text = currentKeyword
return
}
let lowerCased = searchBar.text!.lowercased()
currentKeyword = lowerCased
keywordEntered(keyword: lowerCased)
}
}
| true
|
96898313acfcc6e048075b7533b2e062124b681a
|
Swift
|
gsnsg/SimpleSongSearch
|
/MusicSearch/ViewModifiers/LoaderModifier.swift
|
UTF-8
| 605
| 2.953125
| 3
|
[] |
no_license
|
//
// LoaderModifier.swift
// MusicSearch
//
// Created by Sai Nikhit Gulla on 11/06/21.
//
import SwiftUI
extension View {
func showLoader(_ isLoading: Binding<Bool>) -> some View {
self.modifier(LoaderModifier(isLoading: isLoading))
}
}
struct LoaderModifier: ViewModifier {
@Binding var isLoading: Bool
func body(content: Content) -> some View {
ZStack {
content
if isLoading {
Color.black.opacity(0.3)
.edgesIgnoringSafeArea(.bottom)
ProgressView()
}
}
}
}
| true
|
10615ee2e80dc7f015736641057e2ca5c4314eaa
|
Swift
|
JCTec/Movies
|
/Movies/ViewModel/MovieList/MovieListViewModel.swift
|
UTF-8
| 5,172
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// MovieListViewModel.swift
// Movies
//
// Created by Juan Carlos on 21/06/20.
// Copyright © 2020 JCTechnologies. All rights reserved.
//
import Foundation
import UIKit
import ViewAnimator
// MARK: - InteractiveDownloadHandler
public protocol InteractiveDownloadHandler: ErrorHandler {
func nextPage(completed: @escaping ([Movie]) -> Void, error: @escaping (Error) -> Void)
func didSelect(movie: Movie)
func didRefreshView()
}
// MARK: - MovieListViewModel
public class MovieListViewModel: NSObject {
public static let collectionViewTag: Int = 97
public let animations = [AnimationType.from(direction: .bottom, offset: 30.0)]
public weak var delegate: InteractiveDownloadHandler?
public weak var collectionView: UICollectionView!
private var movies: [Movie] = [Movie]()
public init(movies: [Movie]) {
self.movies = movies
}
public func getCollectionView(width: CGFloat, addInfiniteScroll: Bool = true) -> UICollectionView {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.tag = MovieListViewModel.collectionViewTag
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.backgroundColor = .clear
collectionView.register(HorizontalMovieCollectionViewCell.nib, forCellWithReuseIdentifier: HorizontalMovieCollectionViewCell.identifier)
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: width, height: 250.0)
}
if addInfiniteScroll {
collectionView.addInfiniteScroll { (collectionView) in
if let delegate = self.delegate {
delegate.nextPage(completed: { (movies) in
DispatchQueue.main.async {
self.movies += movies
self.collectionView.reloadData()
collectionView.finishInfiniteScroll()
}
}, error: { (error) in
debugPrint(error)
collectionView.finishInfiniteScroll()
})
}else {
collectionView.finishInfiniteScroll()
}
}
}
self.collectionView = collectionView
return collectionView
}
}
// MARK: - Output
extension MovieListViewModel {
func refreshWith(movies: [Movie]) {
DispatchQueue.main.async {
self.movies.removeAll()
self.movies = movies
self.collectionView.reloadData()
self.collectionView.performBatchUpdates({
UIView.animate(views: self.collectionView.orderedVisibleCells,
animations: self.animations, animationInterval: 0.065, completion: nil)
}, completion: nil)
self.delegate?.didRefreshView()
}
}
}
// MARK: - UICollectionViewDelegate
extension MovieListViewModel: UICollectionViewDelegate {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
// MARK: - UICollectionViewDataSource
extension MovieListViewModel: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.didSelect(movie: movies[indexPath.row])
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HorizontalMovieCollectionViewCell.identifier, for: indexPath) as? HorizontalMovieCollectionViewCell else { return UICollectionViewCell() }
cell.movie = movies[indexPath.row]
return cell
}
}
// MARK: - UICollectionViewDelegate
extension MovieListViewModel: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
}
}
| true
|
a0fba229dec712baae0c46b5387619c36ddcc249
|
Swift
|
AhmadKhattab/TableViewDiffableDatasourceAndDI
|
/MoviesDiffableDataSource/Features/Home/MoviesRepo.swift
|
UTF-8
| 757
| 3.046875
| 3
|
[] |
no_license
|
//
// MoviesRepo.swift
// MoviesDiffableDataSource
//
// Created by Ahmad Khattab on 20/06/2021.
//
import Foundation
protocol MoviesRepoProtocol {
var remoteDataSource: RemoteDataSourceProtocol { get set }
func fetchAllMovies(url: String, completionHandler: @escaping (Result<[Movie], Error>) -> Void)
}
class MoviesRepo: MoviesRepoProtocol {
var remoteDataSource: RemoteDataSourceProtocol
init(remoteDataSource: RemoteDataSourceProtocol) {
self.remoteDataSource = remoteDataSource
}
func fetchAllMovies(url: String, completionHandler: @escaping (Result<[Movie], Error>) -> Void) {
print("Hello from movies repo")
remoteDataSource.fetchData(url: url, completionHandler: completionHandler)
}
}
| true
|
4dab3fb0a2bcac700f59e4bdfcd4fb342cec7b30
|
Swift
|
surnan/Time_Manager
|
/Time_Manager/Time_Manager/Extras/PictureViewController.swift
|
UTF-8
| 1,093
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// PictureViewController.swift
// Time_Manager
//
// Created by admin on 6/27/18.
// Copyright © 2018 admin. All rights reserved.
//
import UIKit
class PictureViewController: UIViewController {
var myImageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
guard let myImage = myImageView else {
print("GUARD LET -- set off--")
return
}
myImage.backgroundColor = UIColor.yellow
myImage.contentMode = .scaleAspectFit
myImage.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myImage)
NSLayoutConstraint.activate([
myImage.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
myImage.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
myImage.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor),
myImage.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor),
])
}
}
| true
|
318eec5427a02a5b4a8418f1064c062271e8295d
|
Swift
|
clemwek/appStudy
|
/appStudy/Settings/SettingsViewController.swift
|
UTF-8
| 1,537
| 2.78125
| 3
|
[] |
no_license
|
//
// SettingsViewController.swift
// appStudy
//
// Created by Clement Wekesa on 06/11/2020.
//
import UIKit
@available(iOS 10.0, *)
class SettingsViewController: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let defaults = UserDefaults.standard
var places: [Places]?
let units = ["standard", "metric", "imperial"]
@IBOutlet weak var picker: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func reset(_ sender: Any) {
do {
places = try context.fetch(Places.fetchRequest())
for place in places! {
context.delete(place)
}
try context.save()
} catch {
// There was an error
}
}
}
@available(iOS 10.0, *)
extension SettingsViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return units.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return units[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
defaults.setValue(units[row], forKey: "selectedUnit")
}
}
| true
|
e549634e5b461c4667f49f76951974fa7ecc45ed
|
Swift
|
oguzhankarakuss/movies
|
/Movies/ViewModel/MovieList/HeaderView/MovieListHeaderViewModel.swift
|
UTF-8
| 863
| 2.875
| 3
|
[] |
no_license
|
//
// MovieListHeaderViewModel.swift
// Movies
//
// Created by Oğuzhan Karakuş on 18.04.2020.
// Copyright © 2020 Oğuzhan Karakuş. All rights reserved.
//
import Foundation
struct MovieListHeaderViewModel {
typealias CompletionHandler = (() -> Void)
weak var dataSource : GenericDataSource<NowPlaying>?
init(dataSource : GenericDataSource<NowPlaying>?) {
self.dataSource = dataSource
}
func nowPlaying(with page: Int, completion: CompletionHandler?) {
Service.nowPlaying(page: page) { (result) in
switch result {
case .failure(let error):
print(error)
case .success(let response):
if let nowPlaying = response.results {
self.dataSource?.data.value = nowPlaying
}
}
}
}
}
| true
|
62bbadde3f7415d26342d5910a0c36e15550026e
|
Swift
|
sultana209/Todoey_n
|
/Todoey/Models/Item.swift
|
UTF-8
| 521
| 2.65625
| 3
|
[] |
no_license
|
//
// Item.swift
// Todoey
//
// Created by A K M Saleh Sultan on 1/21/19.
// Copyright © 2019 A K M Saleh Sultan. All rights reserved.
//
import Foundation
import RealmSwift
class Item: Object{
@objc dynamic var id = UUID().uuidString
@objc dynamic var title: String = ""
@objc dynamic var done: Bool = false
@objc dynamic var dateCreated = Date()
var parentCategory = LinkingObjects(fromType: Cetagory.self, property: "items")
override class func primaryKey() -> String? {
return "id"
}
}
| true
|
1e1fec8542606c4d6a948938b3ba3e9b3ea60bf1
|
Swift
|
LucasAgin/XYQuotes
|
/XYQuotes/TestControllerViewController.swift
|
UTF-8
| 1,575
| 2.546875
| 3
|
[] |
no_license
|
//
// TestControllerViewController.swift
// XYQuotes
//
// Created by Lucas Agin on 5/9/17.
// Copyright © 2017 LucasAgin. All rights reserved.
//
import UIKit
import Firebase
class TestControllerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var quoteCount = 0
var quotes = [String]()
@IBOutlet weak var tableView: UITableView!
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return quotes.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("Gettings quotes...\n")
print(quotes)
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "quote")
cell.textLabel?.text = quotes[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
getQuotes()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
}
func getQuotes () {
let quoteRef = FIRDatabase.database().reference(withPath: "Quotes")
quoteRef.observe(.childAdded, with: { (snapshot) in
self.quotes.append(snapshot.childSnapshot(forPath: "Quote").value as! String!)
self.tableView.reloadData()
})
}
}
| true
|
734901ed5dea175a33a5b5277a0985682ff3b010
|
Swift
|
amoltdhage/tableView
|
/tableView/ViewController.swift
|
UTF-8
| 712
| 2.8125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// tableView
//
// Created by Amol Tukaram Dhage on 07/04/18.
// Copyright © 2018 Amol Tukaram Dhage. All rights reserved.
//
import UIKit
let list = ["Milk", "Tea","Coffee", "Bread", "Biscuit" , "Toast" ]
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(list.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = list[indexPath.row]
return cell!
}
}
| true
|
a9ba3147b0e607b2dc22a8a4af1f90ad69cc0e9a
|
Swift
|
neodem/swiftatc
|
/atc/objects/Exit.swift
|
UTF-8
| 7,426
| 2.625
| 3
|
[] |
no_license
|
//
// Exit.swift
// atc
//
// Created by Vincent Fumo on 9/10/20.
// Copyright © 2020 Vincent Fumo. All rights reserved.
//
import SpriteKit
class Exit: BaseSceneAware {
let gateLine: SKSpriteNode
let leftGate: SKSpriteNode
let rightGate: SKSpriteNode
let exitLabel: SKLabelNode
// todo these may change based on gridScale
let gateOffset: CGFloat = 25
let exitBoundOffset: CGFloat = 5
let labelOffset: CGFloat = 30
let gateAlpha: CGFloat = 1.0
let lineAlpha: CGFloat = 0.2
let labelAlpha: CGFloat = 0.4
let boundingBox: BoundingBox
let ident: Character
let boardX: Int
let boardY: Int
let direction: Direction
// outbound direction of the exit is `direction`
init(ident: Character, boardX: Int, boardY: Int, direction: Direction, gridScale: Int) {
self.direction = direction
self.boardX = boardX
self.boardY = boardY
self.ident = ident
let (xOrigin, yOrigin) = Grid.convertToRadarCoords(gridX: boardX, gridY: boardY, gridScale: gridScale)
// the origins of the Left/Right Gates
let leftGateX: CGFloat
let leftGateY: CGFloat
let rightGateX: CGFloat
let rightGateY: CGFloat
// the rotation of the gates
let gateRotation: CGFloat
// the cutoff factor of the gate lines (relevant in the Diagnal exits)
var gateCutoff: CGFloat = 1.0
// label location
var labelXloc: CGFloat
var labelYloc: CGFloat
switch direction {
case Direction.N:
gateRotation = 0
leftGateX = xOrigin - gateOffset
leftGateY = yOrigin
rightGateX = xOrigin + gateOffset
rightGateY = yOrigin
labelXloc = xOrigin
labelYloc = yOrigin - labelOffset
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
case Direction.NE:
gateRotation = 7 * .pi / 4
leftGateX = xOrigin - gateOffset
leftGateY = yOrigin
rightGateX = xOrigin
rightGateY = yOrigin - gateOffset
labelXloc = xOrigin - labelOffset
labelYloc = yOrigin - labelOffset
gateCutoff = 2 / 3
//TODO fix this
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
case Direction.E:
gateRotation = .pi * 3 / 2
leftGateX = xOrigin
leftGateY = yOrigin + gateOffset
rightGateX = xOrigin
rightGateY = yOrigin - gateOffset
labelXloc = xOrigin - labelOffset
labelYloc = yOrigin
//TODO fix this
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
case Direction.SE:
gateRotation = 5 * .pi / 4
leftGateX = xOrigin - gateOffset
leftGateY = yOrigin
rightGateX = xOrigin
rightGateY = yOrigin + gateOffset
labelXloc = xOrigin - labelOffset
labelYloc = yOrigin + labelOffset
gateCutoff = 2 / 3
//TODO fix this
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
case Direction.S:
gateRotation = .pi
leftGateX = xOrigin - gateOffset
leftGateY = yOrigin
rightGateX = xOrigin + gateOffset
rightGateY = yOrigin
labelXloc = xOrigin
labelYloc = yOrigin + labelOffset
//TODO fix this
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
case Direction.SW:
gateRotation = 3 * .pi / 4
leftGateX = xOrigin
leftGateY = yOrigin + gateOffset
rightGateX = xOrigin + gateOffset
rightGateY = yOrigin
labelXloc = xOrigin + labelOffset
labelYloc = yOrigin + labelOffset
gateCutoff = 2 / 3
//TODO fix this
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
case Direction.W:
gateRotation = .pi / 2
leftGateX = xOrigin
leftGateY = yOrigin + gateOffset
rightGateX = xOrigin
rightGateY = yOrigin - gateOffset
labelXloc = xOrigin + labelOffset
labelYloc = yOrigin
//TODO fix this
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
case Direction.NW:
gateRotation = .pi / 4
leftGateX = xOrigin
leftGateY = yOrigin - gateOffset
rightGateX = xOrigin + gateOffset
rightGateY = yOrigin
labelXloc = xOrigin + labelOffset
labelYloc = yOrigin - labelOffset
gateCutoff = 2 / 3
//TODO fix this
boundingBox = BoundingBox(
topLeft: CGPoint(x: xOrigin - gateOffset, y: yOrigin),
bottomRight: CGPoint(x: xOrigin + gateOffset, y: yOrigin - gateOffset)
)
}
leftGate = Gate(len: gateOffset, cutoff: gateCutoff, alpha: gateAlpha, rotation: gateRotation, x: leftGateX, y: leftGateY).gateSprite
rightGate = Gate(len: gateOffset, cutoff: gateCutoff, alpha: gateAlpha, rotation: gateRotation, x: rightGateX, y: rightGateY).gateSprite
gateLine = SKSpriteNode(color: NSColor.systemGreen, size: CGSize(width: 1, height: 100))
gateLine.colorBlendFactor = 1.0
gateLine.alpha = lineAlpha
gateLine.zRotation = gateRotation
gateLine.zPosition = G.ZPos.exit
gateLine.anchorPoint = CGPoint(x: 0.5, y: 1)
gateLine.position = CGPoint(x: xOrigin, y: yOrigin)
exitLabel = SKLabelNode(fontNamed: "Andale Mono")
exitLabel.text = "\(ident)"
exitLabel.fontColor = NSColor.systemGreen
exitLabel.alpha = labelAlpha
exitLabel.fontSize = 34
exitLabel.zRotation = gateRotation
exitLabel.zPosition = G.ZPos.exit
exitLabel.position = CGPoint(x: labelXloc, y: labelYloc)
}
override func initializeScene(scene: SKScene) {
super.initializeScene(scene: scene)
scene.addChild(gateLine)
scene.addChild(leftGate)
scene.addChild(rightGate)
scene.addChild(exitLabel)
}
func inExit(sprite: SKNode) -> Bool {
boundingBox.isInside(point: sprite.position)
}
}
| true
|
5575c0ba762eac7a6bea9d8d473fdc948c4a3d19
|
Swift
|
ryuzmukhametov/QuadroButton
|
/Pod/Classes/QuadroButton.swift
|
UTF-8
| 2,436
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// QuadroButton.swift
// QuadroButton
//
// Created by Rustam Yuzmukhametov on 22/04/2017.
// Copyright © 2017 Rustam Yuzmukhametov. All rights reserved.
//
import UIKit
class QuadroButton: UIView {
var buttons:[UIButton]! = []
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup() {
self.clipsToBounds = true
self.layer.cornerRadius = 10
self.backgroundColor = UIColor.clear
let buttonWidth = self.frame.width / 2
let buttonHeight = self.frame.height / 2
let padding:CGFloat = 1.0
let buttonSize = CGSize(width: buttonWidth - padding, height: buttonHeight - padding)
self.buttons = []
// 01
// 23
for index in 0..<4 {
let buttonX = index % 2 == 0 ? 0 : buttonWidth + padding
let buttonY = index / 2 == 0 ? 0 : buttonHeight + padding
let buttonFrame = CGRect(origin: CGPoint(x:buttonX, y:buttonY), size: buttonSize)
//
let button = UIButton(type: UIButtonType.system)
button.frame = buttonFrame.insetBy(dx: 0.5, dy: 0.5)
button.setTitleColor(UIColor.white , for: UIControlState.normal)
button.backgroundColor = UIColor.gray
self.addSubview(button)
self.buttons.append(button)
button.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
self.buttons[0].autoresizingMask.update(with: [.flexibleRightMargin, .flexibleBottomMargin])
self.buttons[1].autoresizingMask.update(with: [.flexibleLeftMargin, .flexibleBottomMargin])
self.buttons[2].autoresizingMask.update(with: [.flexibleRightMargin, .flexibleTopMargin])
self.buttons[3].autoresizingMask.update(with: [.flexibleLeftMargin, .flexibleTopMargin])
}
func setButtonTitles(_ titles:[String]) {
if titles.count != 4 {
return
}
for (index, button) in buttons.enumerated() {
let title = titles[index]
button.setTitle(title, for: UIControlState.normal)
}
}
func setButtonBackgroundColor(_ buttonBackgroundColor:UIColor) {
for button in buttons {
button.backgroundColor = buttonBackgroundColor
}
}
}
| true
|
b54a7be63937f30384a94acef685f5ec1a416704
|
Swift
|
nathanday/RationalNumeric
|
/RationalNumeric/main.swift
|
UTF-8
| 641
| 3.609375
| 4
|
[
"MIT"
] |
permissive
|
//
// main.swift
// RationalNumeric
//
// Created by Nathaniel Day on 16/07/18.
// Copyright © 2018 Nathaniel Day. All rights reserved.
//
import Foundation
let a = Rational(3,2);
let b = Rational(5,3);
let ra = a + b;
print("\(a) + \(b) = \(ra)")
let rm = a * b;
print("\(a) * \(b) = \(rm)")
let rs = a - b;
print("\(a) - \(b) = \(rs)")
let rd = a/b;
print("\(a) ÷ \(b) = \(rd)")
let d = Double(a)
print("Double(Rational(\(a.numerator,a.denominator))) = \(d)")
let i = Int(a)
print("Double(Rational(\(a.numerator,a.denominator))) = \(i)")
let f = Rational( 0.251, maxDenominator: 16 );
print("Rational( 0.251, maxDenominator: 16 )=\(f)");
| true
|
a90f754f2665258478fa5c0f01aa76851d7825f7
|
Swift
|
durgalokapavani/Awash
|
/AwashiOS/Handlers/AnalyticsHandler.swift
|
UTF-8
| 1,574
| 2.625
| 3
|
[] |
no_license
|
//
// AnalyticsHandler.swift
// AwashiOS
//
// Copyright © 2017 Awashapp. All rights reserved.
//
import Foundation
import Firebase
import Crashlytics
enum AnalyticsType{
case error
case warning
case view
case event
}
class AnalyticsHandler{
public static var shared = AnalyticsHandler()
var enableAnaytics:Bool = true
private init() {
self.setUserId()
}
private func logEvent(withName: String, logLevel: AnalyticsType, additionalData: [String:String]) {
if self.enableAnaytics{
Analytics.logEvent(withName, parameters: additionalData)
}
}
//MARK: Analytics methods
func trackEvent(of type:AnalyticsType, name:String){
self.trackEvent(of: type, name: name, additionalInfo: [:])
}
func trackEvent(of type:AnalyticsType, name:String, additionalInfo:[String:String]){
self.logEvent(withName: name, logLevel: type, additionalData: additionalInfo)
}
func setUserId() {
if self.enableAnaytics {
AwashUser.shared.getUserEmail { userId in
Analytics.setUserProperty(userId, forName: "userId")
Analytics.setUserID(userId)
Crashlytics.sharedInstance().setUserIdentifier(userId)
}
}
}
func resetAnalyticsData(){
Analytics.setUserProperty("", forName: "userId")
Analytics.setUserID("")
Crashlytics.sharedInstance().setUserIdentifier("")
}
}
| true
|
e1c83fbbe2eadf9a5fbe377cbfe0463535aa321b
|
Swift
|
mayur-mahajan/Swiftty
|
/Tests/SwifttyTests/BufferTests.swift
|
UTF-8
| 825
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
@testable import Swiftty
class BufferTests: XCTestCase {
static var allTests : [(String, (BufferTests) -> () throws -> Void)] {
return [
("testEmptyBuffer", testEmptyBuffer),
("testFixedBufferFromArray", testFixedBufferFromArray),
]
}
func testEmptyBuffer() {
let buf: Buffer = DirectBuffer()
XCTAssertEqual(buf.isReadable, false, "Buffer is readable")
XCTAssertEqual(buf.isWriteable, true, "Buffer is not writeable")
}
func testFixedBufferFromArray() {
let array = [Byte]("test string".utf8)
let buf: Buffer = DirectBuffer(from: array)
XCTAssertEqual(buf.isReadable, true, "Buffer is not readable")
XCTAssertEqual(buf.isWriteable, false, "Buffer is writeable")
}
}
| true
|
c512bfb77cbcb149f55621346d655e12bdaba6d6
|
Swift
|
barrylyl09/swift_practice
|
/Swift_Practice/Swift_Practice/Code/21-字典转模型.playground/Contents.swift
|
UTF-8
| 1,407
| 4.25
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
class Stu : NSObject {
var name:String = ""
var age:Int = 0
init(dict:[String:Any]) {
//复习可选类型 和 类型转换。
//as? 代表 系统尝试帮你进行转换,转失败了,值就是 nil。也就是可选类型。只有可选类型才可 为 nil 。
//?? 空合运算 如果可选类型的值为nil,那么则使用默认值。如果有值,直接解包使用
// let name = dict["name"] as? String ?? ""
// let age = dict["age"] as? Int ?? 0
// self.name = name
// self.age = age
//1.这样穿进来一个 字典每个值 都要去解析
//2.使用 KVC 要使用 KVC 就得继承 NSObject
super.init() //先要 调用 super.init() 初始化 self
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
print(key,value ?? "\(key)没有值") // ?? 是空合运算。
}
}
let dict:[String:Any] = ["name":"hahahhah", "age":10]
let p = Stu(dict: dict)
p
//如果 使用 KVC 找不到 key 对应属性,程序就会奔溃 解决方法 setValue:forUndefinedKey 函数
let dict1:[String:Any] = ["name":"hahahah","age":10,"score":20.5]
let p1 = Stu(dict: dict)
p1
| true
|
539c5b51c88de341e574dc07130566c824218314
|
Swift
|
blkbrds/intern16-practice
|
/10_Protocol/TamNguyen/Protocol/Protocol/Bai3/Province/ProvinceViewController.swift
|
UTF-8
| 1,285
| 2.671875
| 3
|
[] |
no_license
|
//
// ProvinceViewController.swift
// Protocol
//
// Created by PCI0001 on 7/25/20.
// Copyright © 2020 PCI0001. All rights reserved.
//
import UIKit
final class ProvinceViewController: UIViewController {
// MARK: - IBOulets
@IBOutlet private weak var provinceButton: UIButton!
// MARK: - Properties
var location: Location = Location()
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
configUI()
}
// MARK: - Private methods
private func configUI() {
title = "Tỉnh"
let districtButton = UIBarButtonItem(title: "Huyện", style: .plain, target: self, action: #selector(pushToViewButtonTouchUpInside))
navigationItem.rightBarButtonItem = districtButton
}
@objc private func pushToViewButtonTouchUpInside() {
let nextViewVC = DistrictViewController()
nextViewVC.location = location
navigationController?.pushViewController(nextViewVC, animated: true)
}
// MARK: - IBActions
@IBAction private func getProvinceButtonTouchUpInside(_ sender: UIButton) {
sender.backgroundColor = .green
guard let titleText = sender.titleLabel?.text else { return }
location.province = titleText
}
}
| true
|
f7123de542b0ad74f5d65bd473f7288bf793e06d
|
Swift
|
Veljko1212/Project_1
|
/Hangman/Controllers/CategoryVC.swift
|
UTF-8
| 4,383
| 2.703125
| 3
|
[] |
no_license
|
//
// CategoryViewController.swift
// Hangman
//
// Created by Veljko Milosevic on 06/04/2020.
// Copyright © 2020 Veljko Milosevic. All rights reserved.
//
import UIKit
class CategoryVC: UIViewController {
let cellIdentifier = "CollectionViewCell"
var selectedStrategy:GuessingStrategy!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let nibCell = UINib(nibName: cellIdentifier, bundle: nil)
collectionView.register(nibCell, forCellWithReuseIdentifier: cellIdentifier)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.backgroundColor = AppSettings.shared.themeColor
}
@IBAction func menuButton(_ sender: UIBarButtonItem) {
navigationController?.popViewController(animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toGame" {
if let gameVC = segue.destination as? GameVC {
if let normalStragy = selectedStrategy as? NormalStrategy {
gameVC.gameStrategy = normalStragy
normalStragy.delegate = gameVC
}
else if let easyStrategy = selectedStrategy as? EasyStrategy {
gameVC.gameStrategy = easyStrategy
easyStrategy.delegate = gameVC
}
}
}
}
}
extension CategoryVC: UICollectionViewDataSource {
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return GameStorage.shared.categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CollectionViewCell
let group = GameStorage.shared.categories[indexPath.row]
cell.imageView.image = UIImage(data: group.image!)
cell.title.text = group.name
return cell
}
}
extension CategoryVC: UICollectionViewDelegate {
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let category = GameStorage.shared.getCategoryFromCategoryCD(indexPath: indexPath)
let alert = UIAlertController(title: "Chose difficulty", message: "", preferredStyle: .alert)
let normal = UIAlertAction(title: "Normal", style: .default) { (_) in
self.selectedStrategy = NormalStrategy(category: category)
self.performSegue(withIdentifier: "toGame", sender: nil)
}
let easy = UIAlertAction(title: "Easy", style: .default) { (_) in
self.selectedStrategy = EasyStrategy(category: category)
self.performSegue(withIdentifier: "toGame", sender: nil)
}
alert.addAction(normal)
alert.addAction(easy)
self.present(alert, animated: true, completion: nil)
}
}
extension CategoryVC: UICollectionViewDelegateFlowLayout {
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let inset:CGFloat = 0
return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if UIDevice.current.userInterfaceIdiom == .pad {
let yourHeight = collectionView.bounds.height / 5.0 - 10
let yourWidth = collectionView.bounds.width / 3.0 - 10
return CGSize(width: yourWidth, height: yourHeight)
}
else {
let yourHeight = collectionView.bounds.height / 6.0 - 10
let yourWidth = collectionView.bounds.width / 3.0 - 10
return CGSize(width: yourWidth, height: yourHeight)
}
}
}
| true
|
7eaca186ae5ea1a07978cd9e4dd32ca57e48ec19
|
Swift
|
iskalinov13/OneLab-2
|
/ContactsApp/ViewModel/ContactVM.swift
|
UTF-8
| 3,731
| 3.0625
| 3
|
[] |
no_license
|
//
// ContactVM.swift
// ContactsApp
//
// Created by Farukh Iskalinov on 7.07.20.
// Copyright © 2020 Farukh Iskalinov. All rights reserved.
//
import Foundation
class ContactVM {
var selectedIndex: Int?
var sectionKeys: [String] = []
var contacts: [[Contact]] = []
var filteredContacts: [Contact] = []
var updateTableContent: (() -> Void)?
func getContactAt(section: Int, row: Int) -> Contact {
return contacts[section][row]
}
func addContact(_ contactObject: Contact) {
//получить первую букву казалось сложным не знаю есть ли легкий способ типо string.uppercased().charAt(0)
let key = "\(contactObject.name.uppercased()[contactObject.name.uppercased().startIndex])" // first char of the name
if sectionKeys.contains(key) {
let index = sectionKeys.firstIndex(of: key)!
contacts[index].append(contactObject)
} else {
sectionKeys.append(key)
contacts.append([contactObject])
}
updateTableContent?()
}
func showSortedContacts(){
if contacts.count > 1 {
sectionKeys = sectionKeys.sorted()
contacts = contacts.sorted(by: { $0[0] < $1[0]})
for i in 0..<contacts.count {
contacts[i] = contacts[i].sorted(by: {$0 < $1})
}
}
updateTableContent?()
}
func searchContact(name: String) {
guard name != "" else {
return
}
let key = "\(name[name.startIndex])".uppercased()
if let index = sectionKeys.firstIndex(of: key) {
selectedIndex = index
filteredContacts = contacts[index]
filteredContacts = filteredContacts.filter { $0.name.uppercased().contains(name.uppercased()) }
} else {
selectedIndex = nil
filteredContacts.removeAll()
}
updateTableContent?()
}
func getSectionTitle() -> String {
if let index = selectedIndex {
return sectionKeys[index]
}
return "Not found"
}
func removeContactAt(section: Int, row: Int) {
contacts[section].remove(at: row)
if contacts[section].count == 0 {
contacts.remove(at: section)
sectionKeys.remove(at: section)
}
updateTableContent?()
}
func contains(_ contact: Contact) -> Bool {
var flag = false
contacts.forEach { arr in
if arr.contains(contact) {
flag = true
}
}
return flag
}
private func indexOf(_ contact: Contact) -> (Int, Int)? {
for i in 0..<contacts.count {
for j in 0..<contacts[i].count {
if contacts[i][j].id == contact.id {
return (i,j)
}
}
}
return nil
}
func updateContact(_ contactObject: Contact) {
if let index = indexOf(contactObject) {
let oldKey = sectionKeys[index.0]
let key = "\(contactObject.name.uppercased()[contactObject.name.uppercased().startIndex])"
if oldKey == key {
contacts[index.0][index.1] = contactObject
} else {
if contacts[index.0].count == 1 {
contacts.remove(at: index.0)
sectionKeys.remove(at: index.0)
addContact(contactObject)
} else {
contacts[index.0].remove(at: index.1)
addContact(contactObject)
}
}
}
updateTableContent?()
}
}
| true
|
71e3bd4a047b8138f335564e227c8c65355be4cf
|
Swift
|
hbyw618/swiftStudy
|
/types/enumerations.playground/section-1.swift
|
UTF-8
| 6,226
| 4.6875
| 5
|
[] |
no_license
|
// Playground - noun: a place where people can play
import UIKit
// * Enumerations
// Enumerations in Swift are much more flexible, and do not have to provide a value for each member of the enumeration. If a value (known as a "raw" value) is provided for each enumeration member, the value can be a string, a character, or a value of any integer or floating-point type.
// Alternatively, enumeration members can specify associated values of any type to be stored along with each different member value, much as unions or variants do in other languages. You can define a common set of related members as part of one enumeration, each of which has a different set of values of appropriate types associated with it.
// Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration's current value, and instance methods to provide functionality related to the values the enumeration represents. Enumerations can also define initializers to provide an initial member value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.
// * Enumeration Syntax
// You introduce enumerations with the enum keyword and place their entire definition within a pair of braces:
enum SomeEnumeration {
// enumeration definition goes here
}
// The values defined in an enumeration are the member values of that enumeration. The case keyword indicates that a new line of member values is about to be defined.
enum CompassPoint {
case North
case South
case East
case West
}
// Unlike C and Objective-C, Swift enumeration members are not assigned a default integer value when they are created. Instead, the different enumeration members are fully-fledged values in their own right, with an explicitly-defined type of CompassPoint.
// Multiple member values can appear on a single line, separated by commas:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
// The type of directionToHead is inferred when it is initialized with one of the possible values of CompassPoint.
var directionToHead = CompassPoint.West
directionToHead = .East
// * Matching Enueration Values with a Switch Statement
directionToHead = .South
switch directionToHead {
case .North:
println("Lots of planets have a north")
case .South:
println("Watch out for penguins")
case .East:
println("Where the sun rises")
case .West:
println("Where the skies are blue")
}
// A switch statement must be exhaustive when considering an enumeration's members.
// * Associated Values
// You can define Swift enumerfations to store associated values of any given type, and the value types can be different for each member of the enumeration if needed. Enumerations similar to these are known as discriminated unions, tagged unions, or variants in other programming languages.
enum Barcode {
// This definition does not provide any actual Int or String values - it just defines the type of associated values that Barcode constants and variables can store when they are equal to Barcode.UPCA or Barcode.QRCode.
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")
// The associated values can be extracted as part of the switch statement, You extract each associated value as a constant ( with the let prefix) or a variable ( with the var prefix ) for use within the switch case's body.
switch productBarcode{
case .UPCA(let numberSystem, let manufacturer, let product, let check):
println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case .QRCode(let productCode):
println("QR Code: \(productCode).")
}
// If all of the associated values for a enumeration member are extracted as constants, or if all are extracted as variables, you can place a single var or let annotation before the member name, for brevity:
switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check):
println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .QRCode(productCode):
println("QR Code: \(productCode).")
}
// * Raw values
// As an alternative to associated values, enumeration members can come prepopulated with default values ( called raw values ), which are all of the same type.
// Here, the raw values for an enumeration called ASCIIControlCharacter are defined to be of type Character, and are set to some of the more common ASCII control characters.
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
// The raw value for a particular enumeration member is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration's members, and can be different each time you do so.
// Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration. When integers are used for raw values, they auto-increment if no value is specified for some of the enumeration members.
enum Planet2:Int{
// Auto-incrementation means that Planet.Venus has raw value of 2, and so on.
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Planet2.Venus.rawValue
// Initializing from a Raw Value
let possiblePlanet = Planet2(rawValue: 7)
// Not all posible Int values will find a matching planet, however. the raw value initializer will always returns an optional enumeration member.
possiblePlanet?.rawValue
let positionToFind = 9
// Use optional binding to try to access a planet with a raw value of 9.
if let somePlanet = Planet2(rawValue: positionToFind){
switch somePlanet {
case .Earth:
println("Mostly harmless")
default:
println("Not a safe place for humans")
}
}else {
println("There isn't a planet at position \(positionToFind)")
}
| true
|
8547633fa0721790435a16427c60b69d1b472a4b
|
Swift
|
matheusberger/PedalBoard
|
/PedalPrototype/Data/Protocols/AuthProtocol.swift
|
UTF-8
| 700
| 2.5625
| 3
|
[] |
no_license
|
//
// AuthProtocol.swift
// PedalPrototype
//
// Created by Matheus Coelho Berger on 17/03/18.
// Copyright © 2018 mcb3. All rights reserved.
//
import Foundation
protocol AuthProtocol {
static func createUser(withEmail: String,
password: String,
andName: String,
withCompletionBlock: @escaping (_ user: PBUser?, Error?) -> Void)
static func singInUser(withEmail: String,
andPassword: String,
withCompletionBlock: @escaping (_ user: PBUser?, Error?) -> Void)
static func signOutUser(withCompletionBlock: @escaping (_ success: Bool) -> Void)
}
| true
|
73beeac1efcf1063a23e441234f201fc2272e0fb
|
Swift
|
FJHitch/Retos
|
/Reto2.playground/Contents.swift
|
UTF-8
| 458
| 3.8125
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
// String de entrada
// Boolean como salida
// Si es palindromo devolvemos True
//Palindromo = se lee igual al derecho que al revés
func reto2 (str:String) -> Bool{
let string_original = Array(str.characters)
let string_invertido = Array(str.reversed())
return string_original == string_invertido
}
assert(reto2(str: "portatil")==false, "El reto 2 tiene un error :(")
| true
|
e1969e1d91617d6b015cf20d258fda5bc476105b
|
Swift
|
tahasallam400/GarmentList
|
/Technical Assessment/Controller/GarmentList/DataSource/GarmentListDataSource.swift
|
UTF-8
| 1,496
| 2.640625
| 3
|
[] |
no_license
|
//
// DataSource11.swift
// Technical Assessment
//
// Created by TAHA SALLAM on 12/20/20.
//
import Foundation
import UIKit
public class GarmentListDataSource:GenericDataSource<GamenList>,UITableViewDelegate,UITableViewDataSource{
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch data.value.count {
case 0:
return 1
default:
return data.value.count
}
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch data.value.count {
case 0:
return tableView.frame.height
default:
return 65
}
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch data.value.count {
case 0:
return tableView.dequeueReusableCell(withIdentifier: "NoDataExistCell") ?? UITableViewCell()
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell")
cell?.textLabel?.text = data.value[indexPath.row].name
return cell ?? UITableViewCell()
}
}
}
| true
|
c33c860010e699a75496324a183e767ca9bf717d
|
Swift
|
dougsuriano/hlthhack
|
/ios/hlthhack/hlthhack/DetailsHeaderView.swift
|
UTF-8
| 2,550
| 2.5625
| 3
|
[] |
no_license
|
//
// DetailsHeaderView.swift
// hlthhack
//
// Created by Doug Suriano on 5/5/18.
// Copyright © 2018 wiestyfbaby. All rights reserved.
//
import UIKit
class DetailsHeaderView: UIView
{
let backgroundView = UIView()
let imageView = UIImageView()
let titleLabel = UILabel(style: .largeTitle)
override init(frame: CGRect)
{
super.init(frame: frame)
backgroundColor = .white
backgroundView.backgroundColor = .hltnYellow
addSubview(backgroundView)
imageView.contentMode = .center
backgroundView.addSubview(imageView)
titleLabel.textColor = .hltnDarkBlue
backgroundView.addSubview(titleLabel)
backgroundView.enableAutoLayout()
backgroundView.topAnchor.constraint(equalTo: topAnchor, constant: .medium).activate()
backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -.medium).activate()
backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -.medium).activate()
backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: .medium).activate()
imageView.enableAutoLayout()
imageView.topAnchor.constraint(equalTo: backgroundView.topAnchor, constant: .medium).activate()
imageView.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor, constant: -.medium).activate()
imageView.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor, constant: .medium).activate()
imageView.widthAnchor.constraint(equalToConstant: 75.0).activate()
titleLabel.enableAutoLayout()
titleLabel.topAnchor.constraint(equalTo: backgroundView.topAnchor, constant: .medium).activate()
titleLabel.trailingAnchor.constraint(equalTo: backgroundView.trailingAnchor, constant: -.medium).activate()
titleLabel.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor, constant: -.medium).activate()
titleLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: .medium).activate()
backgroundView.layer.shadowColor = UIColor.hltnDarkBlue.cgColor
backgroundView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
backgroundView.layer.shadowOpacity = 0.3 * 1.0
backgroundView.layer.shadowRadius = 2
backgroundView.layer.cornerRadius = 5.0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
0ed1cec754ce2340efc492996aae68a5baf78720
|
Swift
|
eMove-app/iOS
|
/eMOVE/Screens/Rides/RidesVC.swift
|
UTF-8
| 1,291
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// RidesVC.swift
// eMOVE
//
// Created by Bogdan Matasaru on 09/09/2018.
// Copyright © 2018 Bogdan Matasaru. All rights reserved.
//
import UIKit
protocol RidesVCDelegate: class {
func ridesVCDidSelect(ride: Direction)
}
class RidesVC: UIViewController {
@IBOutlet var tableView: UITableView!
public weak var delegate: RidesVCDelegate?
public var rides: [Direction]!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerReusableNibs(withClasses: [RideCell.self])
}
}
extension RidesVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rides.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = self.rides[indexPath.row]
let cell = tableView.dequeueReusableCell(withClass: RideCell.self, for: indexPath)
cell.setupWith(item)
return cell
}
}
extension RidesVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = self.rides[indexPath.row]
self.delegate?.ridesVCDidSelect(ride: item)
}
}
| true
|
343765a4f529a7d0b9ad66c427f10eb42a21e951
|
Swift
|
lexxanderdream/laudo
|
/Sources/Laudo/Table View/Temp/Sections/BaseTableViewSection.swift
|
UTF-8
| 914
| 2.78125
| 3
|
[] |
no_license
|
//
// File.swift
//
//
// Created by Alexander Zhuchkov on 03.06.2020.
//
import UIKit
/*
@available(iOS 13.0, *)
public protocol TableViewSectionType: Hashable {
associatedtype Item
func registerCells(in tableView: UITableView)
func cell(for item: Item, at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell?
}
@available(iOS 13.0, *)
open class BaseTableViewSection: TableViewSectionType {
private let id = UUID()
open func registerCells(in tableView: UITableView) {
}
open func cell(for item: AnyHashable, at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell? {
return nil
}
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
public static func == (lhs: BaseTableViewSection, rhs: BaseTableViewSection) -> Bool {
return lhs.id == rhs.id
}
}
*/
| true
|
8739ad33856b8f4f4423c3c2cd2aadd802cb23c4
|
Swift
|
davisbd100/VemeObeme-SwiftUI
|
/VemeObeme/Views/GenericMakeObservation.swift
|
UTF-8
| 750
| 2.84375
| 3
|
[] |
no_license
|
//
// GenericMakeObservation.swift
// VemeObeme
//
// Created by David Bárcenas Duran
//
import SwiftUI
struct GenericMakeObservation: View {
@Binding var comments: String
var body: some View {
VStack(alignment: .leading){
Divider()
HStack{
Image(systemName: "info.circle")
Text("Observaciones")
.font(.custom("Avenir Book", size: 16))
.foregroundColor(.green)
.padding()
}
TextEditor(text: $comments)
.frame(minWidth: 220, idealWidth: 344, minHeight: 200, idealHeight: 233, maxHeight: 250)
.border(Color.green)
Spacer()
}
.padding()
}
}
| true
|
eeeaac37732e4062d21ae35e39c4d51ab15be1dc
|
Swift
|
matteoKuama/iOS-location-listener
|
/LocationListener/ContentView.swift
|
UTF-8
| 2,451
| 2.796875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// LocationListener
//
// Created by Kuama on 29/04/21.
//
import SwiftUI
import CoreLocation
import Combine
struct ContentView: View {
// let locationReader = LocationReader()
// let locationRequest = LocationRequest()
// @State var locationRequest = CLLocationManager.publishLocation()
// var locationPublisher = CLLocationManager.publishLocation()
let stream = StreamLocation()
@State var cancellable: AnyCancellable? = nil
var body: some View {
let publisher = stream.subject
VStack(content: {
Button("Get Location", action:{
stream.startUpdatingLocations()
DispatchQueue.main.async{
self.cancellable = publisher?.sink{
s in
print("\(s.coordinate.latitude),\(s.coordinate.longitude)")
}
}
// locationReader.setupObserver()
// locationRequest.startUpdatingLocation()
}
).padding(.all)
// .onReceive(publisher) {
// s in
// print("\(s.coordinate.latitude)-\(s.coordinate.longitude)")
// }
Button("Stop Location", action:{
stream.stopUpdates()
DispatchQueue.main.async {
self.cancellable?.cancel()
}
}).padding(.all)
// .onReceive(locationPublisher, perform: { location in
// print("lat: \(location.coordinate.latitude), lon: \(location.coordinate.longitude)")
// })
})
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
class LocationReader {
private let notificationCenter = NotificationCenter.default
func setupObserver(){
notificationCenter.addObserver(self, selector: #selector(locationPrinter(_notification:)), name: Notification.Name("Location"), object: LocationRequest.shared)
}
@objc
private func locationPrinter(_notification:Notification){
if let data = _notification.userInfo as? [String:Double]{
for (name, location) in data {
print("\(name): \(location)")
}
}
}
func removeObserver(){
notificationCenter.removeObserver(self)
}
}
| true
|
f4990a5272aecc24f240ddcf60908212230641c1
|
Swift
|
hxx0215/LeetCodeRepo
|
/P350IntersectionofTwoArraysII.swift
|
UTF-8
| 281
| 2.90625
| 3
|
[] |
no_license
|
func intersect(nums1: [Int], _ nums2: [Int]) -> [Int] {
var n1 = nums1
return nums2.filter({ (num) -> Bool in
defer{
if n1.contains(num){
n1.removeAtIndex(n1.indexOf(num)!)
}
}
return n1.contains(num)
})
}
| true
|
792dc18f4117fd17e5c3b3a274481d33e4f1bb8e
|
Swift
|
walkinded/TheStudents
|
/TheStudents/Data/StudentsClass.swift
|
UTF-8
| 810
| 2.890625
| 3
|
[] |
no_license
|
//
// StudentsClass.swift
// TheStudents
//
// Created by Роман Лабунский on 13/12/2019.
// Copyright © 2019 Роман Лабунский. All rights reserved.
//
import Foundation
import UIKit
class Student {
let manager = DataManager.shared
var name: String?
var lastname: String?
var years: Int?
var gender: Gender!
var photo: String?
var position: String?
var coins: Int?
init(index: Int) {
self.gender = manager.getGender()
let tmpName = manager.getFioStudent(gender: gender)
self.name = tmpName.name
self.lastname = tmpName.lastname
self.position = tmpName.position
self.years = manager.getYears(index: index)
self.photo = manager.getPhoto(gender: gender)
self.coins = manager.getCoins(index: index)
}
}
| true
|
ad5dba77fc05cae3ba0fde6ff52e66229914cfe2
|
Swift
|
tiendnuit/555
|
/sourceCode/iOS/NhacCuaTui/API/RestUtils/Features/ResponseSerialization.swift
|
UTF-8
| 6,601
| 3.015625
| 3
|
[] |
no_license
|
//
// ResponseSerialization.swift
// Rest
//
// Created by Delphinus on 6/5/15.
// Copyright (c) 2015 Delphinus. All rights reserved.
//
import Foundation
// MARK: String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public class func stringResponseSerializer(_ encoding: String.Encoding? = nil) -> Serializer {
var encoding = encoding
return { _, response, data in
if data == nil || data?.count == 0 {
return (nil, nil)
}
if encoding == nil {
if let encodingName = response?.textEncodingName {
encoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString)))
}
}
let string = NSString(data: data!, encoding: encoding.map { $0.rawValue } ?? String.Encoding.isoLatin1.rawValue)
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
- returns: The request.
*/
public func responseString(_ encoding: String.Encoding? = nil, completionHandler: @escaping (Foundation.URLRequest, HTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Request.stringResponseSerializer(encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public class func JSONResponseSerializer(_ options: JSONSerialization.ReadingOptions = .allowFragments) -> Serializer {
return { request, response, data in
if data == nil || data?.count == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject?
do {
JSON = try JSONSerialization.jsonObject(with: data!, options: options) as AnyObject
} catch let error as NSError {
serializationError = error
JSON = nil
} catch {
fatalError()
}
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
- returns: The request.
*/
public func responseJSON(_ options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (Foundation.URLRequest, HTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options), completionHandler: { request, response, JSON, error in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `0` by default.
- returns: A property list object response serializer.
*/
public class func propertyListResponseSerializer(_ options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions(rawValue: 0)) -> Serializer {
return { request, response, data in
if data == nil || data?.count == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject?
do {
plist = try PropertyListSerialization.propertyList(from: data!, options: options, format: nil) as AnyObject
} catch let error as NSError {
propertyListSerializationError = error
plist = nil
} catch {
fatalError()
}
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(_ options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions(rawValue: 0), completionHandler: @escaping (Foundation.URLRequest, HTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.propertyListResponseSerializer(options), completionHandler: { request, response, plist, error in
completionHandler(request, response, plist, error)
})
}
}
| true
|
a931cbfc0ca820413f635c4e36ff915e391646d0
|
Swift
|
BrianLitwin/LeetcodeSolutions
|
/leetcode/maximum-depth-of-binary-tree/solution.swift
|
UTF-8
| 1,407
| 3.65625
| 4
|
[] |
no_license
|
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
var md = 0
getMax(root, 1, &md)
return md
}
func getMax(_ n: TreeNode?, _ depth: Int, _ maxDepth: inout Int) {
guard let n = n else { return }
//when you find a leaf, recalc max depth
if n.left == nil && n.right == nil {
maxDepth = max(depth, maxDepth)
}
getMax(n.left, depth + 1, &maxDepth)
getMax(n.right, depth + 1, &maxDepth)
}
}
//Iterative
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
var queue = [root]
var depth = 0
while !queue.isEmpty {
queue.forEach { node in
queue.remove(at: 0)
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
depth += 1
}
return depth
}
}
// Rercursive
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
return getDepth(root, 0)
}
func getDepth(_ node: TreeNode?, _ d: Int) -> Int {
guard let node = node else { return d }
return max(getDepth(node.left, d + 1), getDepth(node.right, d + 1))
}
}
| true
|
65909a0ad5f08223a3cedac9601d62cff56a33f6
|
Swift
|
youlianchun/FGrep
|
/FGrepCTL/Log.swift
|
UTF-8
| 903
| 2.90625
| 3
|
[] |
no_license
|
//
// Log.swift
// FGrepCTL
//
// Created by YLCHUN on 2020/11/7.
//
import Foundation
func log(_ string: String) {
loger.log(string)
}
func relog(_ string:String) {
loger.relog(string)
}
fileprivate let loger = Loger()
fileprivate class Loger {
let lock = NSLock()
var isRelog :Bool = false
func log(_ string: String){
lock.lock()
if isRelog {
print("\u{1B}[1A\u{1B}[K\(string)")//当前光标位置
print("\u{1B}8")//恢复光标状态和位置
isRelog = false
}
else {
print(string)
}
lock.unlock()
}
func relog(_ string:String) {
lock.lock()
if !isRelog {
print("\u{1B}7")//保存光标状态和位置
isRelog = true
}
print("\u{1B}[1A\u{1B}[K\(string)")//当前光标位置
lock.unlock()
}
}
| true
|
7f2186e887f6aa5df8d0f1ef6117a365608d6078
|
Swift
|
jemzza/MyGame
|
/MyGame/Models/Objects/Obstruction.swift
|
UTF-8
| 2,733
| 2.796875
| 3
|
[] |
no_license
|
//
// Obstruction.swift
// MyGame
//
// Created by Alexander Litvinov on 25.08.2020.
// Copyright © 2020 Alexander Litvinov. All rights reserved.
//
import Foundation
import SpriteKit
import GameplayKit
final class Obstruction: SKNode, GameObjectsSpriteable {
static func set(at point: CGPoint?) -> Obstruction {
let obstruction = Obstruction()
guard let point = point else { return Obstruction()}
let scoreNode = SKSpriteNode()
scoreNode.size = CGSize(width: 1, height: UIScreen.main.bounds.height * 2)
scoreNode.position = CGPoint(x: UIScreen.main.bounds.width + point.x, y: point.y + Constants.Land.height)
scoreNode.physicsBody = SKPhysicsBody(rectangleOf: scoreNode.size)
scoreNode.physicsBody?.affectedByGravity = false
scoreNode.physicsBody?.isDynamic = false
scoreNode.physicsBody?.categoryBitMask = BitMaskCategory.Score
scoreNode.physicsBody?.collisionBitMask = 0
scoreNode.physicsBody?.contactTestBitMask = BitMaskCategory.Ball
let landObstruction = SKSpriteNode(color: .red, size: CGSize(width: point.x, height: point.y))
landObstruction.position = CGPoint(x: UIScreen.main.bounds.width + landObstruction.size.width / 2,
y: landObstruction.frame.height / 2 - UIScreen.main.bounds.height + Constants.Land.height)
landObstruction.physicsBody = SKPhysicsBody(rectangleOf: landObstruction.size)
landObstruction.physicsBody?.categoryBitMask = BitMaskCategory.Obstrucion
landObstruction.physicsBody?.collisionBitMask = BitMaskCategory.Ball
landObstruction.physicsBody?.contactTestBitMask = BitMaskCategory.Ball
landObstruction.physicsBody?.isDynamic = false
landObstruction.physicsBody?.affectedByGravity = false
obstruction.addChild(scoreNode)
obstruction.addChild(landObstruction)
return obstruction
}
//MARK: - TODO
/*
fileprivate static func rotateForRandomAngle() -> SKAction {
let distribution = GKRandomDistribution(lowestValue: 0, highestValue: 360)
let randomNumber = CGFloat(distribution.nextInt())
return SKAction.rotate(toAngle: randomNumber * CGFloat(Double.pi / 180), duration: 0)
}
fileprivate static func move(from point: CGPoint, time: TimeInterval) -> SKAction {
let movePoint = CGPoint(x: point.x, y: point.y)
let moveDistance = point.x + 200
let movementSpeed: CGFloat = 100.0 + 5.0 * CGFloat(time)
let duration = moveDistance / movementSpeed
return SKAction.move(to: movePoint, duration: TimeInterval(duration))
}
*/
}
| true
|
bfb9d2be154d7ed19366198f4655b5d3f8ca4f18
|
Swift
|
DS253/FlipBit
|
/FlipBit/Carthage/Checkouts/NetQuilt/NetQuilt/NetQuilt/Extensions/NetQuilt/NetQuilt+NetSessionConfiguration.swift
|
UTF-8
| 3,078
| 2.890625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// NetQuilt+NetSessionConfiguration.swift
// NetQuilt
//
// Created by Daniel Stewart on 9/28/19.
// Copyright © 2019 Daniel Stewart. All rights reserved.
//
import Foundation
public extension NetQuilt {
/// Model object of the NetSession Configuration.
class NetSessionConfiguration {
/// The configuration default value is `.ephemeral`.
internal let configuration: NetQuilt.NetSessionConfiguration.Configuration
/// The JSONDecoder for decoding data into models.
internal let decoder: JSONDecoder
/// The queue to dispatch `Result` object on.
internal let dispatchQueue: DispatchQueue
/// The standardized timeout interval for request and resource.
internal let timeout: NetQuilt.NetSessionConfiguration.Timeout
/// List of supported session configurations.
///
/// The configuration enum is a represents the available options offered
/// by Foundation as clas properties for `URLSessionConfiguration`.
public enum Configuration: Equatable {
/// A session configuration for transferring data files while the app runs in the background.
case background(String)
/// The default session configuration uses a persistent disk-based cache.
case `default`
/// Ephemeral configuration doesn’t store caches, credential stores, or any session-related data on disk (RAM only).
case ephemeral
}
/// Creates a `NetSessionConfiguration` instance given the provided paramter(s).
///
/// - Parameters:
/// - configuration: The `NetQuilt.NetSessionConfiguration` - default value is `.ephemeral`.
/// - decoder: The `JSONDecoder` for decoding data into models.
/// - dispatchQueue: The queue to dispatch `Result` objects on.
public init(configuration: NetQuilt.NetSessionConfiguration.Configuration = .ephemeral, decoder: JSONDecoder = JSONDecoder(), dispatchQueue: DispatchQueue = .main) {
self.configuration = configuration
self.decoder = decoder
self.dispatchQueue = dispatchQueue
self.timeout = Timeout()
}
}
}
// MARK: - Configuration
internal extension NetQuilt.NetSessionConfiguration {
/// Returns `URLSessionConfiguration` for each `NetQuilt.NetSession.Configuration` case.
var sessionConfiguration: URLSessionConfiguration {
let sessionConfiguration: URLSessionConfiguration
switch configuration {
case .background(let identifier):
sessionConfiguration = .background(withIdentifier: identifier)
case .ephemeral:
sessionConfiguration = .ephemeral
case .default:
sessionConfiguration = .default
}
sessionConfiguration.timeoutIntervalForRequest = timeout.request
sessionConfiguration.timeoutIntervalForResource = timeout.resource
return sessionConfiguration
}
}
| true
|
bbfa701d44d469e451ac3c72049047aa5c8504e9
|
Swift
|
ryokuhei/MVVM-Example
|
/MVVM-Example/MVVM-Example/TableViewModel.swift
|
UTF-8
| 973
| 2.59375
| 3
|
[] |
no_license
|
//
// TableViewModel.swift
// MVVM-Example
//
// Created by ryoku on 2017/12/02.
// Copyright © 2017 ryoku. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import RealmSwift
class TableViewModel {
private let getMemoListUseCase = GetMemoListUseCase()
private let addMemoUseCase = AddMemoUseCase()
private let deleteMemoUseCase = DeleteMemoUseCase()
let memoList = Variable<[Memo]>([])
lazy var listObservable: Observable<[Memo]> = {
return self.memoList
.asObservable()
.share(replay: 1)
}()
init() {
self.memoList.value = getMemoListUseCase.invoke()
}
func addMemo() {
addMemoUseCase.invoke()
self.memoList.value = getMemoListUseCase.invoke()
}
func deleteMemo(index: Int) {
let id = memoList.value[index].id
deleteMemoUseCase.ivoke(id: id)
self.memoList.value = getMemoListUseCase.invoke()
}
}
| true
|
c5867682ede0a86bbcc3c74e7f628125cc51b7f1
|
Swift
|
corona-warn-app/cwa-app-ios
|
/src/xcode/ENA/ENA/Source/Scenes/ContactDiary/Model/DiaryDay.swift
|
UTF-8
| 1,315
| 2.65625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MIT",
"Unlicense"
] |
permissive
|
////
// 🦠 Corona-Warn-App
//
import Foundation
struct DiaryDay: Equatable {
// MARK: - Init
init(
dateString: String,
entries: [DiaryEntry],
tests: [DiaryDayTest],
submissions: [DiaryDaySubmission]
) {
self.dateString = dateString
self.entries = entries
self.tests = tests
self.submissions = submissions
}
// MARK: - Internal
let dateString: String
let entries: [DiaryEntry]
let tests: [DiaryDayTest]
let submissions: [DiaryDaySubmission]
var selectedEntries: [DiaryEntry] {
entries.filter { $0.isSelected }
}
var formattedDate: String {
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("EEEEddMMyy")
return dateFormatter.string(from: localMidnightDate)
}
var utcMidnightDate: Date {
let dateFormatter = ISO8601DateFormatter.justUTCDateFormatter
guard let date = dateFormatter.date(from: dateString) else {
Log.error("Could not get date from date string", log: .contactdiary)
return Date()
}
return date
}
// MARK: - Private
private var localMidnightDate: Date {
let dateFormatter = ISO8601DateFormatter.justLocalDateFormatter
guard let date = dateFormatter.date(from: dateString) else {
Log.error("Could not get date from date string", log: .contactdiary)
return Date()
}
return date
}
}
| true
|
2aaaf819ccd7e1b12d69dcdb70129d6f080daba1
|
Swift
|
dontSpeakItAloud/Onboarding
|
/Onboarding/Extension/UIColor.swift
|
UTF-8
| 564
| 2.671875
| 3
|
[] |
no_license
|
//
// UIColor.swift
// Onboarding
//
// Created by Rodion Kuskov on 2/2/20.
// Copyright © 2020 Rodion Kuskov. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
static let mainBackgroundColor = #colorLiteral(red: 0.07607161254, green: 0.07609234005, blue: 0.07606887072, alpha: 1)
static let grayColor = #colorLiteral(red: 0.4391798973, green: 0.4392358363, blue: 0.4391607642, alpha: 1)
}
extension CGColor {
static let mainBorderColor = #colorLiteral(red: 0.8352298141, green: 0.8353305459, blue: 0.8351953626, alpha: 1).cgColor
}
| true
|
e8d98eb96f0f9707b674684ae97f042c32ad04b5
|
Swift
|
Yasumoto/UCSF-Shuttle-Dashboard
|
/SF Shuttle Tracker/ViewController.swift
|
UTF-8
| 1,575
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// SF Shuttle Tracker
//
// Created by Joseph Smith on 1/19/16.
// Copyright © 2016 bjoli. All rights reserved.
//
import UIKit
class ViewController: UIViewController, CountdownDisplay {
@IBOutlet weak var nearestShuttleLabel: UILabel!
@IBOutlet weak var upcomingShuttlesTextView: UITextView!
var shuttleTracker: ShuttleRoute?
override func viewDidLoad() {
super.viewDidLoad()
self.shuttleTracker = ShuttleRoute(delegate: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateCountdown(nextShuttleTimes: [String]) {
dispatch_async(dispatch_get_main_queue()) {
if let nextShuttle = Int(nextShuttleTimes[0]) {
if nextShuttle > 30 {
self.nearestShuttleLabel.textColor = UIColor.greenColor()
}
else if nextShuttle > 20 {
self.nearestShuttleLabel.textColor = UIColor.yellowColor()
} else {
self.nearestShuttleLabel.textColor = UIColor.redColor()
}
self.nearestShuttleLabel.text = String(nextShuttleTimes[0]) + "min"
}
self.upcomingShuttlesTextView.text = nextShuttleTimes.joinWithSeparator("\n")
}
}
func connectionError() {
dispatch_async(dispatch_get_main_queue()) {
self.upcomingShuttlesTextView.text = "Warning- connection error."
}
}
}
| true
|
e3b051625a875a6156c6a8a18d22b89d37b48f66
|
Swift
|
VildanovM/TestTaskToSberbank
|
/TestTaskToSberbank/Services/NetworkService.swift
|
UTF-8
| 1,846
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// NetworkService.swift
// TestTaskToSberbank
//
// Created by Максим Вильданов on 28.08.2020.
// Copyright © 2020 Максим Вильданов. All rights reserved.
//
import Foundation
protocol NetworkServiceProtocol {
func getFilms(completion: @escaping(_ filmsDict: [[String: Any]]?, _ error: Error?) -> ())
var baseURL: URL? { get }
}
final class NetworkService {
// MARK: - Приватные свойства
private let urlSession = URLSession.shared
}
// MARK: - Реализация протокола
extension NetworkService: NetworkServiceProtocol {
var baseURL: URL? {
return URL(string: "https://swapi.dev/api/")
}
func getFilms(completion: @escaping(_ filmsDict: [[String: Any]]?, _ error: Error?) -> ()) {
guard let baseURL = baseURL else { return }
let filmURL = baseURL.appendingPathComponent("films")
urlSession.dataTask(with: filmURL) { (data, response, error) in
if let error = error {
completion(nil, error)
return
}
guard let data = data else {
let error = NSError(domain: dataErrorDomain, code: DataErrorCode.networkUnavailable.rawValue, userInfo: nil)
completion(nil, error)
return
}
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard let jsonDictionary = jsonObject as? [String: Any], let result = jsonDictionary["results"] as? [[String: Any]] else {
throw NSError(domain: dataErrorDomain, code: DataErrorCode.wrongDataFormat.rawValue, userInfo: nil)
}
completion(result, nil)
} catch {
completion(nil, error)
}
}.resume()
}
}
| true
|
3d19cbb1cf909d24d2fc41aba2a2c82baec20ebb
|
Swift
|
exup-cloud/cloudios-sdk
|
/chainup-ios/Chainup/UI/EXTriangleIndicator.swift
|
UTF-8
| 2,049
| 2.609375
| 3
|
[] |
no_license
|
//
// EXTriangleIndicator.swift
// Chainup
//
// Created by liuxuan on 2019/3/21.
// Copyright © 2019 zewu wang. All rights reserved.
//
import UIKit
class EXTriangleIndicator: UIControl {
var fillColor:UIColor = UIColor.ThemeView.bgIcon
var highlight:UIColor = UIColor.ThemeView.highlight
var textNormalColor:UIColor = UIColor.ThemeLabel.colorMedium
var textHighLightColor:UIColor = UIColor.ThemeLabel.colorLite
private var titleLabel :UILabel = UILabel.init()
var triangleWidth :CGFloat = 6
var triangleHeight :CGFloat = 6
var isChecked:Bool = false {
didSet {
titleLabel.textColor = isChecked ? textHighLightColor : textNormalColor
self.setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
config()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
config()
}
func config(){
self.backgroundColor = UIColor.clear
self.addSubview(titleLabel)
titleLabel.secondaryRegular()
titleLabel.textAlignment = .left
self.isChecked = false
titleLabel.snp.makeConstraints { (make ) in
make.left.equalToSuperview()
make.right.equalToSuperview().offset(-10)
make.top.bottom.equalToSuperview()
make.height.equalTo(14)
}
}
func setTitle(content:String) {
titleLabel.text = content
self.setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let path = UIBezierPath()
if isChecked {
highlight .setFill()
}else {
fillColor .setFill()
}
let startX = rect.width
let startY = rect.height
path.move(to: CGPoint(x: startX, y: startY))
path.addLine(to: CGPoint(x: startX, y: startY - triangleHeight))
path.addLine(to: CGPoint(x: startX - triangleWidth, y: startY))
path.close()
path.fill()
}
}
| true
|
bc2b23316d23cc2f4523cf4347d78039b8282397
|
Swift
|
inswag/githubAPIExercise
|
/GitHubAPIExercise/Coordinator/Coordinator.swift
|
UTF-8
| 642
| 2.78125
| 3
|
[] |
no_license
|
//
// Coordinator.swift
// GitHubAPIExercise
//
// Created by 박인수 on 21/08/2019.
// Copyright © 2019 inswag. All rights reserved.
//
import UIKit
enum Coordinator {
case main
case second(id: Int)
}
extension Coordinator {
var viewController: UIViewController {
switch self {
case .main:
let mainTableVC = MainTableVC()
let navMainTableVC = UINavigationController(rootViewController: mainTableVC)
return navMainTableVC
case .second(id: let value):
let secondVC = SecondVC(receivedID: value)
return secondVC
}
}
}
| true
|
0a54836d51a56424418250135398b80ecfc63207
|
Swift
|
e38284/ElectronicMedicalRecord
|
/ElectronicMedicalRecord/ViewController.swift
|
UTF-8
| 3,107
| 2.671875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ElectronicMedicalRecord
//
// Created by 萩原祐太郎 on 2019/05/11.
// Copyright © 2019 Yutaro_Hagiwara. All rights reserved.
//
import UIKit
import ESTabBarController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupTab()
}
func setupTab() {
// 画像のファイル名を指定してESTabBarControllerを作成する
let tabBarController: ESTabBarController! = ESTabBarController(tabIconNames: ["user-7", "file-three-7", "fountain-pen-7", "search-detail-7", "dot-more-7"])
// 選択時のアイコンの色と真ん中のボタンを設定する(オレンジ)
tabBarController.selectedColor = UIColor(red: 1.0, green: 0.44, blue: 0.11, alpha: 1)
// 背景色(薄いオレンジ)
tabBarController.buttonsBackgroundColor = UIColor(red: 0.96, green: 0.91, blue: 0.87, alpha: 1)
// 選択時の下線の太さ
tabBarController.selectionIndicatorHeight = 5
// 作成したESTabBarControllerを親のViewController(=self)に追加する
addChild(tabBarController)
let tabBarView = tabBarController.view!
tabBarView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tabBarView)
let safeArea = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
tabBarView.topAnchor.constraint(equalTo: safeArea.topAnchor),
tabBarView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor),
tabBarView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor),
tabBarView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor),
])
tabBarController.didMove(toParent: self)
// タブをタップした時に表示するViewControllerを設定する
let ownerInfoViewController = storyboard?.instantiateViewController(withIdentifier: "OwnerInfo")
let selectRecordViewController = storyboard?.instantiateViewController(withIdentifier: "SelectRecord")
let searchRecordViewController = storyboard?.instantiateViewController(withIdentifier: "SearchRecord")
let settingViewController = storyboard?.instantiateViewController(withIdentifier: "Setting")
tabBarController.setView(ownerInfoViewController, at: 0)
tabBarController.setView(selectRecordViewController, at: 1)
tabBarController.setView(searchRecordViewController, at: 3)
tabBarController.setView(settingViewController, at: 4)
// 真ん中のタブはボタンとして扱う
tabBarController.highlightButton(at: 2)
tabBarController.setAction({
// ボタンが押されたらImageViewControllerをモーダルで表示する
let describeRecordViewController = self.storyboard?.instantiateViewController(withIdentifier: "DescribeRecord")
self.present(describeRecordViewController!, animated: true, completion: nil)
}, at: 2)
}
}
| true
|
c40ac88ef4e770e0eebae746b5b9815c0d1f67eb
|
Swift
|
senducusin/github-users
|
/Github Users/View Models/GithubUserListViewModel.swift
|
UTF-8
| 953
| 2.703125
| 3
|
[] |
no_license
|
//
// GithubUserListViewModel.swift
// Github Users
//
// Created by Jansen Ducusin on 3/22/21.
//
import Foundation
import RealmSwift
struct GitUserListViewModel {
var appStarted = false
var users = PersistenceService.shared.getUsers().sorted(byKeyPath: "id", ascending: true)
var numberOfrows: Int {
return users.count
}
var pagination: Int {
if let lastUser = users.last {
return lastUser.id
}
return 0
}
func userAtIndex(_ index:Int) -> User{
return users[index]
}
var searchText: String? {
didSet {
guard let searchText = self.searchText else {return}
if searchText.isEmpty {
self.users = PersistenceService.shared.getUsers()
}else{
self.users = PersistenceService.shared.getUsersWithLoginFilter(keyword: searchText)
}
}
}
}
| true
|
c86d4e8c8a05b55b4dffd9d50cb1c1bae2265fce
|
Swift
|
mstkmys/FastChat
|
/FastChat/Classes/Controllres/ChatViewController.swift
|
UTF-8
| 5,273
| 2.671875
| 3
|
[] |
no_license
|
//
// ChatViewController.swift
// FastChat
//
// Created by Miyoshi Masataka on 2018/03/12.
// Copyright © 2018年 Masataka Miyoshi. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
import Chameleon
class ChatViewController: UIViewController {
let chatView: ChatView = {
let chatView = ChatView(frame: UIScreen.main.bounds)
chatView.backgroundColor = .white
return chatView
}()
// MARK: - Properties
var messageArray: [Message] = [Message]()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Add Views
[chatView].forEach{ self.view.addSubview($0) }
setUpNavigation()
// TableView: DatasourceとDelegate
chatView.tableView.dataSource = self
chatView.tableView.delegate = self
// TextFiled: Dategate
chatView.chatTextField.delegate = self
// Recieve Chage Messages
retrieveMessages()
}
// MARK: - Methods
private func setUpNavigation() {
self.navigationController?.title = "Chat"
let logoutButton = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(self.logout))
self.navigationItem.setRightBarButton(logoutButton, animated: true)
}
private func retrieveMessages() {
let messageDB = Database.database().reference().child("Messages")
messageDB.observe(.childAdded) { snapshot in
let value = snapshot.value as! Dictionary<String, String>
guard let text = value["MessageBody"] else { return }
guard let sender = value["Sender"] else { return }
let message = Message()
message.body = text
message.sender = sender
self.messageArray.append(message)
self.chatView.tableView.reloadData()
}
}
// MARK: - Actions
@objc private func logout() {
do {
try Auth.auth().signOut()
self.navigationController?.popToRootViewController(animated: true)
}
catch {
print("Error, there was a problem siging out.")
}
}
}
// MARK: - UITableViewDataSource
/**********************************************************************************************************/
extension ChatViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = chatView.tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(ChatTableViewCell.self), for: indexPath) as! ChatTableViewCell
cell.message.text = self.messageArray[indexPath.row].body
cell.senderUserName.text = self.messageArray[indexPath.row].sender
if cell.senderUserName.text == Auth.auth().currentUser?.email as String! {
cell.iconImageView.backgroundColor = .flatMint()
}
return cell
}
}
// MARK: - UITableViewDelegate
/**********************************************************************************************************/
extension ChatViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - UITextFieldDelegate
/**********************************************************************************************************/
extension ChatViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
UIView.animate(withDuration: 0.5) {
// テキストフィールド上げる
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
UIView.animate(withDuration: 0.5) {
// テキストフィールド下げる
}
chatView.chatTextField.isEnabled = false
let messageDB = Database.database().reference().child("Messages")
let messageDictionary = [
"Sender": Auth.auth().currentUser?.email,
"MessageBody": textField.text!
]
messageDB.childByAutoId().setValue(messageDictionary) {
error, reference in
if error != nil {
print("MessageSavingError: \(String(describing: error))")
}
else {
print("Message Save Success.")
self.chatView.chatTextField.isEnabled = true
self.chatView.chatTextField.text = ""
}
}
return true
}
}
| true
|
ebe84de50f24634b5fe9f1c4c54d33df7d197f12
|
Swift
|
SwiftyCodes/Relations_CoreData
|
/CollegeStudent_CoreData/Serivce File/DatabaseHelper.swift
|
UTF-8
| 4,115
| 3.015625
| 3
|
[] |
no_license
|
//
// DatabaseHelper.swift
// CoreDataProject
//
// Created by Anurag Kashyap on 29/08/19.
// Copyright © 2019 Anurag Kashyap. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class DatabaseHelper : NSObject {
static let sharedInstance = DatabaseHelper()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
private override init(){}
//MARK: Fetch - Generic
func fetchDataFromEntity(fromEntity entity: String) -> [NSManagedObject] {
var allData = [NSManagedObject]()
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entity)
do {
allData = try (context?.fetch(fetchRequest))!
}catch {
print("Not able to fetch data from store")
}
return allData
}
//MARK: Create - College
func createCollege(objectOf object: [String:Any]) -> Bool {
let collegeObject = NSEntityDescription.insertNewObject(forEntityName: "College", into: context!) as! College
collegeObject.name = object["name"] as? String
collegeObject.address = object["address"] as? String
collegeObject.city = object["city"] as? String
collegeObject.university = object["university"] as? String
do{
try context?.save()
print("College Data Saved Successfully")
return true
}catch{
print("Error saving data at College")
return false
}
}
//MARK: Delete - College
func delete(atIndex index: Int, fromEntity entity: String) -> [NSManagedObject] {
var allData = fetchDataFromEntity(fromEntity: entity)
context?.delete(allData[index]) // Remove data from Entity
allData.remove(at: index) // Remove data from Array
do{
try context?.save()
print("Data Deleted Successfully")
}catch{
print("Error Deleting data")
}
return allData
}
//MARK: Update - College
func updateCollege(objectOf object: College, atIndex i: Int) {
var allCollege = fetchDataFromEntity(fromEntity: "College") as! [College]
allCollege[i] = object
do{
try context?.save()
print("College Data Edited Successfully")
}catch{
print("Error Editing data at College")
}
}
//MARK: Update - Student
func createStudent(objectOf object: [String:Any], toCollege college: College) -> Bool {
let studentObject = NSEntityDescription.insertNewObject(forEntityName: "Student", into: context!) as! Student
studentObject.name = object["name"] as? String
studentObject.age = Int16(object["age"] as! Int)
studentObject.number = object["number"] as? String
studentObject.city = object["city"] as? String
studentObject.universities = college
do{
try context?.save()
print("Data Saved Successfully")
return true
}catch{
print("Error saving data")
return false
}
}
//MARK: Delete - Student
func deleteStudent(atIndex index: Int, fromEntity entity: String, fromCollege thisCollege:College) -> [NSManagedObject] {
var allData = thisCollege.students?.allObjects as! [NSManagedObject]
context?.delete(allData[index]) // Remove data from Entity
allData.remove(at: index) // Remove data from Array
do{
try context?.save()
print("Data Deleted Successfully")
}catch{
print("Error Deleting data")
}
return allData
}
//MARK: Update - Student
func updateStudent(objectOf object: Student, atIndex i: Int) {
var allStudent = fetchDataFromEntity(fromEntity: "Student") as! [Student]
allStudent[i] = object
do{
try context?.save()
print("Data Edited Successfully")
}catch{
print("Error Editing data")
}
}
}
| true
|
f459afcaf6dcf22eb0f235cd436f5ba8f6acc75c
|
Swift
|
Zih-Siang-Yue/KKDemo-Rx-Mvvm
|
/KKApiDemo_Sean/Login/ViewModel/LoginViewModel.swift
|
UTF-8
| 2,018
| 2.65625
| 3
|
[] |
no_license
|
//
// LoginViewModel.swift
// KKApiDemo_Sean
//
// Created by Sean.Yue on 2019/1/2.
// Copyright © 2019 Sean.Yue. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import Action
class LoginViewModel: NSObject, ViewModelType {
typealias Input = LoginInput
typealias Output = LoginOutput
struct LoginInput {
var acStr: Driver<String>
var pwStr: Driver<String>
}
struct LoginOutput {
var acValid: Driver<ValidationResult>
var pwValid: Driver<ValidationResult>
var btnValid: Driver<Bool>
var btnAction: Action<(String, String), Bool>
init(ac: Driver<String>, pw: Driver<String>) {
acValid = ac
.flatMapLatest({ (acStr) -> Driver<ValidationResult> in
return LoginService().validateAc(ac: acStr)
.asDriver(onErrorJustReturn: .failed(message: "服務器發生錯誤!"))
})
pwValid = pw
.flatMapLatest({ (pwStr) -> Driver<ValidationResult> in
return LoginService().validatePw(pw: pwStr)
.asDriver(onErrorJustReturn: .failed(message: "服務器發生錯誤!"))
})
btnValid = Driver.combineLatest(acValid, pwValid)
.flatMapLatest {
return Driver.just($0.isValid && $1.isValid)
}
.distinctUntilChanged()
btnAction = Action(workFactory: { (input) -> Observable<Bool> in
let (ac, pw) = input
if (ac == "1234" || ac == "abcd") && (pw == "1234" || pw == "abcd") {
return KKAPI.shared.getToken()
}
else {
return Observable.just(false)
}
})
}
}
func transform(input: Input) -> Output {
return Output(ac: input.acStr, pw: input.pwStr)
}
}
| true
|
bca61309f72c932af51f4f694cb1daf984220f5c
|
Swift
|
sinLuke/EazyFitness
|
/EazyFitness/ViewController/Setting/LocalDataTableViewController.swift
|
UTF-8
| 5,237
| 2.65625
| 3
|
[] |
no_license
|
//
// LocalDataTableViewController.swift
// EazyFitness
//
// Created by Luke on 2018/5/21.
// Copyright © 2018年 luke. All rights reserved.
//
import UIKit
class LocalDataTableViewController: DefaultTableViewController {
var selected:EFData?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
switch section {
case 0:
return DataServer.studentDic.count
case 1:
return DataServer.trainerDic.count
case 2:
return DataServer.courseDic.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
switch indexPath.section {
case 0:
let student = DataServer.studentDic[(Array(DataServer.studentDic.keys))[indexPath.row]]
cell.textLabel?.text = student?.name
cell.detailTextLabel?.text = (Array(DataServer.studentDic.keys))[indexPath.row]
case 1:
let trainer = DataServer.trainerDic[(Array(DataServer.trainerDic.keys))[indexPath.row]]
cell.textLabel?.text = trainer?.name
cell.detailTextLabel?.text = (Array(DataServer.studentDic.keys))[indexPath.row]
case 2:
let course = DataServer.courseDic[(Array(DataServer.courseDic.keys))[indexPath.row]]
cell.textLabel?.text = course?.note
cell.detailTextLabel?.text = (Array(DataServer.studentDic.keys))[indexPath.row]
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
self.performSegue(withIdentifier: "move", sender: self)
selected = DataServer.studentDic[(Array(DataServer.studentDic.keys))[indexPath.row]]
case 1:
self.performSegue(withIdentifier: "move", sender: self)
selected = DataServer.trainerDic[(Array(DataServer.trainerDic.keys))[indexPath.row]]
case 2:
self.performSegue(withIdentifier: "move", sender: self)
selected = DataServer.courseDic[(Array(DataServer.courseDic.keys))[indexPath.row]]
default:
break
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "学生"
case 1:
return "教练"
case 2:
return "课程"
default:
return "学生"
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dvc = segue.destination as? LocalNextDataTableViewController{
dvc.selected = self.selected
}
}
}
| true
|
1bc31700759aa37ab1eee196c7ddf22fc8c94e2a
|
Swift
|
KarimEbrahemAbdelaziz/Foodics
|
/Foodics/Foodics/Core/UI/Views/Product/ProductItemView.swift
|
UTF-8
| 1,488
| 2.75
| 3
|
[] |
no_license
|
//
// ProductItemView.swift
// Foodics
//
// Created by Ahmed Ramy on 11/22/20.
// Copyright © 2020 Ahmed Ramy. All rights reserved.
//
import UIKit
import Nuke
public final class ProductItemView: UIView, Configurable {
let imageView: UIImageView = UIImageView().then {
$0.contentMode = .scaleAspectFit
}
let nameLabel = Label(font: TextStyles.body, color: . black).then {
$0.numberOfLines = 0
$0.textAlignment = .center
}
lazy var vStack = UIStackView(axis: .vertical, alignment: .fill, distribution: .fill, spacing: 8).then {
$0.setArrangedSubview([
self.imageView,
self.nameLabel
])
}
public func configure(with viewModel: ProductItemViewModelProtocol) {
if let imageURL = URL(string: viewModel.image) {
Nuke.loadImage(with: imageURL, into: imageView)
} else {
imageView.isHidden = true
}
nameLabel.text = viewModel.name
self.addGestureRecognizer(UITapGestureRecognizer {
viewModel.onTapAction()
})
}
public init() {
super.init(frame: .zero)
initialize()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initialize()
}
}
private extension ProductItemView {
func initialize() {
setupViews()
setupConstraints()
}
func setupViews() {
addSubview(vStack)
}
func setupConstraints() {
vStack.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
make.height.equalTo(150)
}
}
}
| true
|
25406cb546383e969a9c5d9cea6d16374346bb40
|
Swift
|
IsaacQiao/SportsLFG
|
/SportsLFG/Groups.swift
|
UTF-8
| 1,027
| 2.703125
| 3
|
[] |
no_license
|
//
// File : Group.swift
// Author: Aaron Cheung, Charles Li
// Date created : Oct.30 2015
// Date edited : Nov.05 2015
// Description :
//
import Foundation
class Groups : NSObject{
var name: String? //as unique Kinvey entity _id
var dateCreated: String?
var startTime : String?
var startDate : String?
var sport : String?
var maxSize : String?
var address: String?
var city : String?
var province: String?
var metadata: KCSMetadata? //Kinvey metadata, optional
//This function provided by Kinvey API maps the variables above to the back-end database schema
override func hostToKinveyPropertyMapping() -> [NSObject : AnyObject]! {
return [
"name" : KCSEntityKeyId, //the required _id field
"dateCreated": "dateCreated",
"sport" : "sport",
"startTime": "time",
"startDate": "date",
"maxSize" : "maxSize",
"address" : "address",
"city" : "city",
"province" :"province",
"metadata" : KCSEntityKeyMetadata
]
}
}
| true
|
729b0edc8ca753a1f291fa6665382d6df77cd5b2
|
Swift
|
ameter/SwiftUI
|
/misc/ScaledText.swift
|
UTF-8
| 2,554
| 3.265625
| 3
|
[] |
no_license
|
//
// ScaledText.swift
// Flashable
//
// Created by Chris on 7/9/20.
// Copyright © 2020 CodePika. All rights reserved.
//
import SwiftUI
struct ScaledText: View {
@Environment(\.font) var font
// @Environment(\.self) var env
private var uiFont: UIFont? {
switch font {
case Font.largeTitle:
return .preferredFont(forTextStyle: UIFont.TextStyle.largeTitle)
case Font.title:
return .preferredFont(forTextStyle: UIFont.TextStyle.title1)
case Font.headline:
return .preferredFont(forTextStyle: UIFont.TextStyle.headline)
case Font.subheadline:
return .preferredFont(forTextStyle: UIFont.TextStyle.subheadline)
case Font.body:
return .preferredFont(forTextStyle: UIFont.TextStyle.body)
case Font.callout:
return .preferredFont(forTextStyle: UIFont.TextStyle.callout)
case Font.caption:
return .preferredFont(forTextStyle: UIFont.TextStyle.caption1)
case Font.footnote:
return .preferredFont(forTextStyle: UIFont.TextStyle.footnote)
default:
for size in 1...1000 {
if font == Font.system(size: CGFloat(size)) {
return UIFont.systemFont(ofSize: CGFloat(size))
}
}
}
return nil
}
private let text: String
private let longestWord: String
@State private var newFont = Font.body
@State private var isScaled = false
init(_ text: String) {
self.text = text
self.longestWord = text.components(separatedBy: .whitespacesAndNewlines).max(by: {$1.count > $0.count}) ?? ""
}
var body: some View {
GeometryReader { geometry in
Text(self.text)
.font(self.scaledFont(width: geometry.size.width))
// .minimumScaleFactor(0.01)
}
}
func scaledFont(width: CGFloat) -> Font {
var tmpFont = uiFont ?? .preferredFont(forTextStyle: UIFont.TextStyle.body)
while longestWord.size(withAttributes: [.font: tmpFont]).width > width {
tmpFont = tmpFont.withSize(tmpFont.pointSize - 1)
}
return .system(size: tmpFont.pointSize)
}
}
struct ScaledText_Previews: PreviewProvider {
static var previews: some View {
ScaledText("School Superintendents are super cool.")
.font(.system(size: 100))
.minimumScaleFactor(0.01)
.lineLimit(nil)
}
}
| true
|
0841a40f90dcaac6c5adf0535f53c95df7bfe7e6
|
Swift
|
OpenStack-mobile/aerogear-ios-oauth2
|
/AeroGearOAuth2Tests/Session.swift
|
UTF-8
| 1,737
| 3.0625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Session.swift
// OpenStack Summit
//
// Created by Alsey Coleman Miller on 7/31/16.
// Copyright © 2016 OpenStack. All rights reserved.
//
import Foundation
/// Provides the storage for session values
public protocol SessionStorage {
/// The authenticated member.
var member: Identifier? { get set }
/// Whether the device previously had a passcode.
var hadPasscode: Bool { get set }
}
public extension SessionStorage {
/// Resets the session storage.
mutating func clear() {
self.member = nil
}
}
// MARK: - Implementations
public final class UserDefaultsSessionStorage: SessionStorage {
public let userDefaults: UserDefaults
public init(userDefaults: UserDefaults = UserDefaults.standard) {
self.userDefaults = userDefaults
}
public var member: Identifier? {
get { return (userDefaults.object(forKey: Key.member.rawValue) as? NSNumber)?.int64Value }
set {
guard let member = newValue
else { userDefaults.removeObject(forKey: Key.member.rawValue); return }
userDefaults.set(NSNumber(value: member), forKey: Key.member.rawValue)
userDefaults.synchronize()
}
}
public var hadPasscode: Bool {
get { return userDefaults.bool(forKey: Key.hadPasscode.rawValue) }
set { userDefaults.set(newValue, forKey: Key.hadPasscode.rawValue) }
}
fileprivate enum Key: String {
case member = "CoreSummit.UserDefaultsSessionStorage.Key.Member"
case hadPasscode = "CoreSummit.UserDefaultsSessionStorage.Key.HadPasscode"
}
}
| true
|
8e612ea2cd17047fc2a2cf3fc52d4d872a87ebe0
|
Swift
|
morarivasile/TEST-TASK_Product-list
|
/Morari_Vasile_Test_Task/View/RoundedSelectableButton.swift
|
UTF-8
| 1,307
| 2.75
| 3
|
[] |
no_license
|
//
// RoundedSelectableButton.swift
// Morari_Vasile_Test_Task
//
// Created by Vasile Morari on 12/4/18.
// Copyright © 2018 Vasile Morari. All rights reserved.
//
import UIKit
class RoundedSelectableButton: UIButton {
@IBInspectable var activeTintColor: UIColor = .blue
@IBInspectable var inactiveTintColor: UIColor = .lightGray
@IBInspectable var isOn: Bool = false {
didSet {
onStateChange()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initButton()
}
func initButton() {
onStateChange()
layer.cornerRadius = frame.size.height / 2
addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}
private func onStateChange() {
layer.borderColor = isOn ? activeTintColor.cgColor : UIColor.clear.cgColor
backgroundColor = isOn ? activeTintColor.withAlphaComponent(0.02) : .white
let titleColor: UIColor = isOn ? activeTintColor : inactiveTintColor
setTitleColor(titleColor, for: .normal)
layer.borderWidth = isOn ? 1.0 : 0.0
}
@objc private func buttonPressed() {
isOn = !isOn
}
}
| true
|
156d03123233b6cfef3065f63713aeae566ecfba
|
Swift
|
itman9595/Labyrinth-Explorer
|
/Labyrinth Explorer/BlockingArea.swift
|
UTF-8
| 684
| 2.640625
| 3
|
[] |
no_license
|
//
// BlockingArea.swift
// Labyrinth Explorer
//
// Created by Muratbek Bauyrzhan on 4/16/15.
// Copyright (c) 2015 Dimension. All rights reserved.
//
import SpriteKit
class BlockingArea: SKNode {
init(nodeName:String, position:CGPoint, size:CGSize) {
super.init()
let a = gameScene.childNodeWithName(nodeName)!.copy() as! SKNode
a.physicsBody = SKPhysicsBody(rectangleOfSize: a.frame.size)
a.physicsBody?.dynamic = false
a.physicsBody?.categoryBitMask = PhysicsCategory.Undestroyable
world.addChild(a)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
0d1d4fd012e86bbad7dbc820f5973d14a5cc6c31
|
Swift
|
hp561/iosprojects
|
/Music Player/Music Player/ViewController.swift
|
UTF-8
| 3,258
| 2.96875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Music Player
//
// Created by Harsh Patel on 3/28/17.
// Copyright © 2017 Harsh Patel. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var numberOfLoops = 0
var pause=false
@IBOutlet weak var songPlaying: UILabel!
let sound = URL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "mp3")!)
@IBOutlet weak var loops: UITextField!
var audioPlayer: AVAudioPlayer?
var audioSession = AVAudioSession.sharedInstance()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do{
try
audioPlayer = AVAudioPlayer (contentsOf:self.sound)
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch{
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func songSelector(_ sender: Any) {
if(audioPlayer?.isPlaying)!{
let alert = UIAlertController(title: "Error", message: "Song is playing. Wait until the loop is over or terminate and restart.", preferredStyle:.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
if(pause==true){
audioPlayer?.play()
}
else if(loops.text != "" && loops.text != "0" ){
numberOfLoops = (Int(loops.text!)!)-1
audioPlayer?.numberOfLoops = numberOfLoops
audioPlayer?.play()
}
else{
let alert = UIAlertController(title: "Error", message: "Enter the amount of times you want the song to play. Can't be 0.", preferredStyle:.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
loops.text=""
pause=false
}
@IBAction func stop(_ sender: Any) {
if((audioPlayer?.isPlaying)! || pause==true){
audioPlayer?.stop()
audioPlayer?.currentTime = 0
numberOfLoops = 0
pause=false
}
else{
let alert = UIAlertController(title: "Error", message: "No song is currently playing.", preferredStyle:.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
@IBAction func pauseButton(_ sender: Any) {
if(audioPlayer?.isPlaying)!{
audioPlayer?.pause()
pause=true
}
}
}
| true
|
b156c1a02462d8cfc7b123ee93adb89123572271
|
Swift
|
Rakouga/PocketCampus
|
/PocketCampus/CreatePostViewController.swift
|
UTF-8
| 3,587
| 2.5625
| 3
|
[] |
no_license
|
//
// CreatePostViewController.swift
// PocketCampus
//
// Created by 伽 on 16/4/17.
// Copyright © 2016年 罗浩伽. All rights reserved.
//
import UIKit
class CreatePostViewController: UIViewController {
@IBOutlet weak var postTitleTextField: UITextField!
@IBOutlet weak var postContentTextView: UITextView!
let user = BmobUser.getCurrentUser()
var userID:String!
var userName:String!
var postTitle:String!
var postContent:String!
override func viewDidLoad() {
super.viewDidLoad()
//给帖子内容的textview添加描边
self.postContentTextView.layer.borderWidth = 1
self.postContentTextView.layer.borderColor = UIColor.lightGrayColor().CGColor
self.postContentTextView.layer.cornerRadius = 3
self.postContentTextView.layer.masksToBounds = true
if self.user != nil{
self.userName = self.user.username
self.userID = self.user.objectForKey("objectId") as! String
}else{
self.view.makeToast("请先登录", duration: 2, position: CSToastPositionCenter)
}
}
func checkFormat()->Bool{
self.postTitle = self.postTitleTextField.text
self.postContent = self.postContentTextView.text
if self.user == nil{
return false
}
if self.postTitle == "" || self.postContent == nil{
self.view.makeToast("标题不能为空", duration: 2, position: CSToastPositionCenter)
return false
}
if self.postContent == "" || self.postContent == nil{
self.view.makeToast("内容不能为空", duration: 2, position: CSToastPositionCenter)
return false
}
return true
}
@IBAction func sendPost(sender: AnyObject) {
self.postTitle = nil
self.postContent = nil
if checkFormat(){
let post = BmobObject(className: "Post")
let dic = ["userID":"\(self.userID)","userName":"\(self.userName)","title":"\(self.postTitle)","content":"\(self.postContent)"]
post.saveAllWithDictionary(dic)
post.saveInBackgroundWithResultBlock({ (isSuccessful, error) in
if isSuccessful {
self.view.makeToast("发帖成功", duration: 2, position: CSToastPositionCenter)
//发送通知,刷新帖子列表
NSNotificationCenter.defaultCenter().postNotificationName("getPostListNotification", object: nil)
delay(2, task: { () -> () in
self.dismissViewControllerAnimated(true, completion: nil)
})
}else if (error != nil){
self.view.makeToast("发帖失败", duration: 2, position: CSToastPositionCenter)
print("\(error)")
}else{
self.view.makeToast("发帖失败,原因我也不知道", duration: 2, position: CSToastPositionCenter)
}
})
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.postTitleTextField.resignFirstResponder()
self.postContentTextView.resignFirstResponder()
}
@IBAction func back(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
9e95b119d9227f0e5ea4be1e4fa5173779d4c12b
|
Swift
|
alvesmarcel/ViperExampleProject
|
/ViperExampleProject/Common/NetworkService/NetworkServiceProtocols.swift
|
UTF-8
| 745
| 2.984375
| 3
|
[] |
no_license
|
// Abstract: These protocols and extensions are mainly used to mock the classes that we don't own in a test environment
import Foundation
protocol URLSessionDataTaskProtocol {
func resume()
}
protocol URLSessionProtocol {
func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol
}
extension URLSessionDataTask: URLSessionDataTaskProtocol {}
extension URLSession: URLSessionProtocol {
func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol {
return (dataTask(with: url, completionHandler: completionHandler) as URLSessionDataTask) as URLSessionDataTaskProtocol
}
}
| true
|
1623cfd966731d1c42fa82ed022332d256ee3aa4
|
Swift
|
OyegokeTomisin/NetworkTemplate
|
/NetworkTemplate/Endpoint/Error/NetworkResponseError.swift
|
UTF-8
| 910
| 3
| 3
|
[] |
no_license
|
//
// NetworkResponseError.swift
// EYNetwork
//
// Created by OYEGOKE TOMISIN on 06/04/2020.
// Copyright © 2020 OYEGOKE TOMISIN. All rights reserved.
//
import Foundation
enum NetworkResponse: Error, LocalizedError {
case invalidToken
case serverError
case unknownError
case forbiddenError
case incorrectPassword
case authenticationError
public var errorDescription: String {
switch self {
case .authenticationError:
return "You need to be authenticated first."
case .serverError:
return "internalServerError"
case .unknownError:
return "Oops!! something went wrong"
case .forbiddenError:
return "forbiddenError"
case .incorrectPassword:
return "The password you provided is incorrect."
case .invalidToken:
return "Your token has expired"
}
}
}
| true
|
074ebf9cbb0fad4bcd51f339a80a4cec759dd751
|
Swift
|
Cleverlance/Pyramid
|
/Sources/Common/Core/Domain/Repository.swift
|
UTF-8
| 484
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright © 2016 Cleverlance. All rights reserved.
//
public protocol RepositoryProtocol {
associatedtype Model
func load() throws -> Model?
func save(_ model: Model) throws
func deleteAll() throws
}
open class Repository<Model>: AbstractClass, RepositoryProtocol {
public init() {}
open func load() throws -> Model? { virtualMethod }
open func save(_ model: Model) throws { virtualMethod }
open func deleteAll() throws { virtualMethod}
}
| true
|
e8a4a36c1d3de2d9daaa348d59b610b85bcd00fe
|
Swift
|
balapoq/AnimationLib
|
/Platform_AnimationDemo/PoqPlatform/Sources/Controls/BorderedButton.swift
|
UTF-8
| 8,534
| 3.0625
| 3
|
[] |
no_license
|
//
// BorderedButton.swift
// Poq.iOS
//
// Created by Nikolay Dzhulay on 9/29/16.
//
//
import Foundation
import UIKit
/// Button with white color inside and colored border
/// We will use tint color for it
open class BorderedButton: UIButton {
static let maxHeight: CGFloat = 28
var createButtonWidth: CGFloat?
open var cornerRadius = CGFloat(AppSettings.sharedInstance.navigationBorderedButtonCornerRadius) {
didSet {
updateBorder()
}
}
var borderWidth = CGFloat(AppSettings.sharedInstance.navigationBorderedButtonBorderWidth) {
didSet {
updateBorder()
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
updateButtonStyle()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
updateButtonStyle()
}
/// By default we are using tintColor, which is independed from state.
/// This dictionary should help us provide different colors for different states.
open var colorPerState = [UIControlState: UIColor]() {
didSet {
updateButtonStyle()
}
}
}
// MARK: - convenience API
extension BorderedButton {
/// Create BorderedButton with target and action, after create UIBarButtonItem and return result
open class func createButtonItem(withTitle title: String, target: AnyObject, action: Selector, position: BarButtonPosition = .right, width: CGFloat? = nil) -> UIBarButtonItem {
let button = BorderedButton(frame: CGRect.zero)
button.translatesAutoresizingMaskIntoConstraints = true
button.titleLabel?.font = AppTheme.sharedInstance.borderedBarButtonFont
button.tintColor = AppTheme.sharedInstance.mainColor
let states: [UIControlState] = [.disabled, .highlighted]
for state: UIControlState in states {
button.colorPerState[state] = BarButtonType.color(forPosition: position, state: state)
}
button.setTitle(title, for: UIControlState())
button.addTarget(target, action: action, for: .touchUpInside)
button.sizeToFit()
if let buttonWidth = width {
button.createButtonWidth = buttonWidth
button.frame.size = CGSize(width: buttonWidth, height: button.frame.height)
} else {
// Update the Button Size to avoid small buttons based on small texts.
// Minimum Button Size can be changed in Client through a ClientStyleProvider.
if let size = ResourceProvider.sharedInstance.clientStyle?.adjustBorderedNavigationBarButtonSize(basedOn: button.frame.size) {
button.frame.size = size
}
}
return BorderedBarButtonItem(withButton: button)
}
override open var isEnabled: Bool {
get {
return super.isEnabled
}
set(value) {
super.isEnabled = value
updateBorder()
}
}
override open var isHighlighted: Bool {
didSet {
updateBorder()
}
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
updateButtonStyle()
}
override open func sizeToFit() {
var newFrame = frame
newFrame.size = sutableSize
frame = newFrame
}
override open func sizeThatFits(_ size: CGSize) -> CGSize {
return sutableSize
}
override open var intrinsicContentSize: CGSize {
return sutableSize
}
open override func setTitle(_ title: String?, for state: UIControlState) {
// Store current frame.
let oldFrame = frame
super.setTitle(title, for: state)
// In case the new text needs a bigger button.
self.sizeToFit()
// Use the width provided with the init method.
if let buttonWidth = createButtonWidth {
frame.size.width = buttonWidth
// To avoid having an smaller button.
} else if frame.size.width < oldFrame.size.width {
if let size = ResourceProvider.sharedInstance.clientStyle?.adjustBorderedNavigationBarButtonSize(basedOn: self.frame.size) {
frame.size = size
}
}
}
}
// MARK: - Private
extension BorderedButton {
/**
Draw colored rect
- parameter color: of rect
- returns: resizable image
*/
fileprivate static func createColorImage(_ color: UIColor?) -> UIImage? {
let imageColor = color ?? AppTheme.sharedInstance.mainColor
return UIImage.createResizableColoredImage(imageColor)
}
/// Update title color, background image and border
fileprivate final func updateButtonStyle() {
// Disable specific case, we can't allow the same color, it really will confuse user
if colorPerState[.disabled] == nil {
colorPerState[.disabled] = (colorPerState[UIControlState()] ?? tintColor)?.colorWithAlpha(0.3)
}
// Set AppTheme mainColor as the BorderedButton .normal color.
if colorPerState[.normal] == nil {
colorPerState[.normal] = (colorPerState[UIControlState()] ?? BarButtonType.color(forPosition: .right, state: .normal))
}
// Setup colors already on colorPerState as the tint color of the button
let states: [UIControlState] = [.highlighted, .disabled, .normal]
for state in states {
// Title
setTitleColor((colorPerState[state] ?? tintColor), for: state)
setBackgroundImage(nil, for: state)
}
// Selected state is special case, text here shuld change color, since we will fulfill background
setBackgroundImage(BorderedButton.createColorImage(tintColor), for: .highlighted)
setTitleColor(UIColor.white, for: .highlighted)
updateBorder()
}
fileprivate final func updateBorder() {
var simpleState = UIControlState()
if !isEnabled {
simpleState = .disabled
} else if isHighlighted {
simpleState = .highlighted
}
let borderColor: UIColor? = colorPerState[simpleState]
layer.borderColor = borderColor?.cgColor
layer.masksToBounds = true
layer.cornerRadius = cornerRadius
layer.borderWidth = borderWidth
}
@nonobjc
fileprivate var sutableSize: CGSize {
guard let title = title(for: UIControlState()), let font = titleLabel?.font else {
// Lets make an empty square
return CGSize(width: BorderedButton.maxHeight, height: BorderedButton.maxHeight)
}
let textFrame = (title as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: BorderedButton.maxHeight),
options: [],
attributes: [NSAttributedStringKey.font: font],
context: nil)
let size = CGSize(width: textFrame.size.width + 10, height: BorderedButton.maxHeight)
return size
}
}
/**
We need this class as a wrapper for BorderedButton
In some places we will trying to set title to button - here we should pass it to button
*/
private class BorderedBarButtonItem: UIBarButtonItem {
fileprivate let borderedButton: BorderedButton
init(withButton button: BorderedButton) {
borderedButton = button
super.init()
// For some reason when we assign button to 'customView' it got disable state, so lets save state
let buttonEnabled = borderedButton.isEnabled
customView = borderedButton
borderedButton.isEnabled = buttonEnabled
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var title: String? {
get {
return borderedButton.title(for: UIControlState())
}
set(value) {
borderedButton.setTitle(value, for: UIControlState())
}
}
override var isEnabled: Bool {
get {
return borderedButton.isEnabled
}
set(value) {
borderedButton.isEnabled = value
}
}
}
| true
|
9289da8e6a126a0c0435089c9904e0fbb899c07f
|
Swift
|
robertpankrath/Snake3D
|
/SnakeTests/PointTests.swift
|
UTF-8
| 1,263
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
// Created by Robert Pankrath on 13.03.16.
// Copyright © 2016 Robert Pankrath. All rights reserved.
import XCTest
@testable import Snake
class PointTests: XCTestCase {
func testInitWithArray() {
let indizes = [1, 2, 3, 4, 5]
let point = Point(indizes: indizes)
XCTAssertEqual(indizes, point.indizes)
}
func testInitWithInts() {
let indizes = [1, 2, 3, 4, 5]
let point = Point(indizes: 1, 2, 3, 4, 5)
XCTAssertEqual(indizes, point.indizes)
}
func testEqual() {
let point1 = Point(indizes: 1, 2, 3, 4, 5)
let point2 = Point(indizes: 1, 2, 3, 4, 5)
XCTAssertTrue(point1 == point2)
let point3 = Point(indizes: 5, 4, 3, 2, 1)
XCTAssertFalse(point1 == point3)
}
func testAdd() {
let point1 = Point(indizes: 1, 2, 3)
let point2 = Point(indizes: 4, 5, 6)
let point3 = try! point1 + point2
XCTAssertEqual([5, 7, 9], point3.indizes)
}
func testAddThrows() {
let point1 = Point(indizes: 1, 2, 3)
let point2 = Point(indizes: 4, 5)
do {
try point1 + point2
XCTFail()
} catch {
XCTAssertTrue(true)
}
}
}
| true
|
30aa890f1af93bf119341fb7d7342485361ecb08
|
Swift
|
ponysoloud/sportsgrounds
|
/sportsgrounds/Views/Cells/SGUserCell.swift
|
UTF-8
| 6,453
| 2.625
| 3
|
[] |
no_license
|
//
// SGUserCell.swift
// sportsgrounds
//
// Created by Alexander Ponomarev on 19/05/2019.
// Copyright © 2019 Alexander Ponomarev. All rights reserved.
//
import UIKit
class SGUserCell: UITableViewCell {
// MARK: - Public properties
static var reuseIdentifier: String {
return String(describing: self)
}
// MARK: - Private properties
private static let contentInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
private lazy var avatarImageView: SGAvatarImageView = {
let imageView = SGAvatarImageView.imageView
contentView.addSubview(imageView)
return imageView
}()
private lazy var nameLabel: UILabel = {
let label = UILabel()
label.textColor = .appBlack
label.font = .smallTextFont
label.textAlignment = .left
label.numberOfLines = 1
contentView.addSubview(label)
return label
}()
private lazy var ageLabel: UILabel = {
let label = UILabel()
label.textColor = .appBlack
label.font = .smallTextFont
label.textAlignment = .left
label.numberOfLines = 1
contentView.addSubview(label)
return label
}()
private lazy var ratingButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .clear
button.titleLabel?.font = UIFont.smallTextFont
button.setTitleColor(.appBlack, for: .normal)
button.setImage(UIImage(named: "user.icon.rating.small"), for: .normal)
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: -5)
button.isUserInteractionEnabled = false
contentView.addSubview(button)
return button
}()
private lazy var hostImageView: UIImageView = {
let button = UIImageView(image: UIImage(named: "user.icon.host"))
button.contentMode = .scaleAspectFit
contentView.addSubview(button)
return button
}()
private var tapHandler: ((SGUserCell) -> Void)?
// MARK: - UICollectionView hierarchy
override func prepareForReuse() {
super.prepareForReuse()
self.avatarImageView.image = UIImage(named: "user.avatar.placeholder")
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupSubviewsLayout()
self.setupGestureRecognizer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupSubviewsLayout()
self.setupGestureRecognizer()
}
// MARK: - Public functions
enum Style {
case separate
case grouped
}
static var height: CGFloat {
return 55.0
}
func configure(withUser user: SGUser,
isOwner: Bool,
isYou: Bool,
style: Style,
tapHandler: @escaping (SGUserCell) -> Void) {
if let avatarUrl = user.imageUrl {
self.avatarImageView.load(url: avatarUrl, placeholder: nil)
}
self.hostImageView.isHidden = !isOwner
self.nameLabel.textColor = isYou ? .appBlue : .appBlack
self.nameLabel.text = "\(user.surname) \(user.name)"
self.ageLabel.text = "\(user.birthdate.age) лет"
self.ratingButton.isHidden = !(user.rating > 0)
self.ratingButton.setTitle(user.rating.description, for: .normal)
switch style {
case .separate:
self.backgroundColor = .appWhite
case .grouped:
self.backgroundColor = .appGray
}
self.tapHandler = tapHandler
}
// MARK: - Private functions
private func setupGestureRecognizer() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(contentTouchUpInside(_:)))
self.contentView.addGestureRecognizer(tapGestureRecognizer)
}
private func setupSubviewsLayout() {
avatarImageView.translatesAutoresizingMaskIntoConstraints = false
hostImageView.translatesAutoresizingMaskIntoConstraints = false
nameLabel.translatesAutoresizingMaskIntoConstraints = false
ageLabel.translatesAutoresizingMaskIntoConstraints = false
ratingButton.translatesAutoresizingMaskIntoConstraints = false
let contentInsets = SGUserCell.contentInsets
NSLayoutConstraint.activate([
avatarImageView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: contentInsets.top),
avatarImageView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: contentInsets.left),
avatarImageView.heightAnchor.constraint(equalTo: avatarImageView.widthAnchor),
avatarImageView.widthAnchor.constraint(equalToConstant: 35),
nameLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: contentInsets.top),
nameLabel.leftAnchor.constraint(equalTo: avatarImageView.rightAnchor, constant: 16),
hostImageView.centerYAnchor.constraint(equalTo: nameLabel.centerYAnchor),
hostImageView.leftAnchor.constraint(equalTo: nameLabel.rightAnchor, constant: 10.0),
hostImageView.heightAnchor.constraint(equalTo: hostImageView.widthAnchor),
hostImageView.widthAnchor.constraint(equalToConstant: 10.0),
hostImageView.rightAnchor.constraint(lessThanOrEqualTo: self.contentView.rightAnchor, constant: -contentInsets.right),
ageLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 6),
ageLabel.leftAnchor.constraint(equalTo: avatarImageView.rightAnchor, constant: 16),
ageLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -contentInsets.bottom),
ratingButton.leftAnchor.constraint(equalTo: ageLabel.rightAnchor, constant: 20),
ratingButton.centerYAnchor.constraint(equalTo: ageLabel.centerYAnchor)
])
}
@objc private func contentTouchUpInside(_ sender: UITapGestureRecognizer) {
self.tapHandler?(self)
}
}
| true
|
d7af1708d364579b3ee476fb04626209b3ee8bcc
|
Swift
|
al1020119/SwiftArchitecture
|
/Single_App/Others/Service/TiledMap/TiledScrollView.swift
|
UTF-8
| 21,964
| 2.5625
| 3
|
[] |
no_license
|
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// **************************************************************
// http://www.icocos.cn //
// https://icocos.github.io //
// https://al1020119.github.io //
// **************************************************************
// ************ 😂🤔 曹理鹏(梦工厂@iCocos) 🤔😂 ************ //
// **************************************************************
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// **************************************************************
//
// Single_App
// TiledScrollView
//
// Created by iCocos on 2018/12/24.
// Copyright © 2018年 iCocos. All rights reserved.
//
// @class TiledScrollView.swift
// @abstract 碎片整体ScrollView
// @discussion 用于显示整体碎片ScrollView
//
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// **************************************************************
import UIKit
let kTiledScrollViewAnimationTime = TimeInterval(0.1)
@objc protocol TiledScrollViewDelegate: NSObjectProtocol {
func tiledScrollView(_ scrollView: TiledScrollView, viewForAnnotation annotation: TiledAnnotation) -> TiledAnnotationView
@objc optional func tiledScrollViewDidZoom(_ scrollView: TiledScrollView)
@objc optional func tiledScrollViewDidScroll(_ scrollView: TiledScrollView)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, annotationWillDisappear annotation: TiledAnnotation)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, annotationDidDisappear annotation: TiledAnnotation)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, annotationWillAppear annotation: TiledAnnotation)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, annotationDidAppear annotation: TiledAnnotation)
/**
Whether the annotation view be selected. If not implemented, defaults to `true`
- Parameters:
- scrollView: The tiled scroll view
- view: The annotation view
- Returns: Whether the annotation view be selected
*/
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, shouldSelectAnnotationView view: TiledAnnotationView) -> Bool
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, didSelectAnnotationView view: TiledAnnotationView)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, didDeselectAnnotationView view: TiledAnnotationView)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, didReceiveSingleTap gestureRecognizer: UIGestureRecognizer)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, didReceiveDoubleTap gestureRecognizer: UIGestureRecognizer)
@objc optional func tiledScrollView(_ scrollView: TiledScrollView, didReceiveTwoFingerTap gestureRecognizer: UIGestureRecognizer)
}
@objc protocol TileSource: NSObjectProtocol {
func tiledScrollView(_ scrollView: TiledScrollView, imageForRow row: Int, column: Int, scale: Int) -> UIImage
}
@objc class TiledScrollView: UIView {
//Delegates
weak var tiledScrollViewDelegate: TiledScrollViewDelegate?
weak var dataSource: TileSource?
//internals
var tiledView: TiledView!
var scrollView: UIScrollView!
var canvasView: UIView!
var annotation: TiledAnnotation!
//Default gesture behvaiour
var centerSingleTap: Bool = true
var zoomsInOnDoubleTap: Bool = true
var zoomsToTouchLocation: Bool = false
var zoomsOutOnTwoFingerTap: Bool = true
var _levelsOfZoom: UInt!
var _levelsOfDetail: UInt!
var _muteAnnotationUpdates: Bool = false
var levelsOfZoom: UInt
{
set
{
_levelsOfZoom = newValue
self.scrollView.maximumZoomScale = pow(2.0, max(0.0, CGFloat(levelsOfZoom)))
}
get
{
return _levelsOfZoom
}
}
var levelsOfDetail: UInt
{
set
{
_levelsOfDetail = newValue
if levelsOfDetail == 1 {
print("Note: Setting levelsOfDetail to 1 causes strange behaviour")
}
self.tiledView.numberOfZoomLevels = size_t(levelsOfDetail)
}
get
{
return _levelsOfDetail
}
}
var zoomScale: CGFloat
{
set
{
self.setZoomScale(newValue, animated: false)
}
get
{
return scrollView.zoomScale
}
}
/*private*/
var muteAnnotationUpdates: Bool
{
set
{
// FIXME: Jesse C - I don't like overloading this here, but the logic is in one place
_muteAnnotationUpdates = newValue
self.isUserInteractionEnabled = !self.muteAnnotationUpdates
if !self.muteAnnotationUpdates {
self.correctScreenPositionOfAnnotations()
}
}
get
{
return _muteAnnotationUpdates
}
}
/*private*/
var annotations: Set<TiledAnnotation> = Set()
/*private*/
var recycledAnnotationViews: Set<TiledAnnotationView> = Set()
/*private*/
var visibleAnnotations: Set<TiledVisibleAnnotationTuple> = Set()
/*private*/
var previousSelectedAnnotationTuple: TiledVisibleAnnotationTuple?
/*private*/
var currentSelectedAnnotationTuple: TiledVisibleAnnotationTuple?
/*private*/
var singleTapGestureRecognizer: UITapGestureRecognizer!
/*private*/
var doubleTapGestureRecognizer: UITapGestureRecognizer!
/*private*/
var twoFingerTapGestureRecognizer: UITapGestureRecognizer!
// MARK: -
// MARK: Init method and main methods
init(frame: CGRect, contentSize: CGSize)
{
super.init(frame: frame)
autoresizingMask = [.flexibleHeight, .flexibleWidth]
scrollView = UIScrollView(frame: self.bounds)
scrollView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
scrollView.delegate = self
scrollView.backgroundColor = UIColor.white
scrollView.contentSize = contentSize
scrollView.bouncesZoom = true
scrollView.bounces = true
scrollView.minimumZoomScale = 1.0
levelsOfZoom = 2
let canvasFrame = CGRect(origin: CGPoint.zero, size: scrollView.contentSize)
canvasView = UIView(frame: canvasFrame)
canvasView.isUserInteractionEnabled = false
let tiledLayerClass = type(of: self).tiledLayerClass() as! UIView.Type
tiledView = tiledLayerClass.init(frame: canvasFrame) as? TiledView
tiledView.delegate = self
scrollView.addSubview(tiledView)
addSubview(scrollView)
addSubview(canvasView)
singleTapGestureRecognizer = TiledAnnotationTapGesture(
target: self,
action: #selector(singleTapReceived(_:)))
singleTapGestureRecognizer.numberOfTapsRequired = 1
singleTapGestureRecognizer.delegate = self
tiledView.addGestureRecognizer(singleTapGestureRecognizer)
doubleTapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(doubleTapReceived(_:)))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
tiledView.addGestureRecognizer(doubleTapGestureRecognizer)
singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
twoFingerTapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(twoFingerTapReceived(_:)))
twoFingerTapGestureRecognizer.numberOfTouchesRequired = 2
twoFingerTapGestureRecognizer.numberOfTapsRequired = 1
tiledView.addGestureRecognizer(twoFingerTapGestureRecognizer)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
class func tiledLayerClass() -> AnyClass
{
return TiledView.self
}
// MARK: Position
/*private*/
func correctScreenPositionOfAnnotations()
{
CATransaction.begin()
CATransaction.setAnimationDuration(0.0)
if (scrollView.isZoomBouncing || muteAnnotationUpdates) && !scrollView.isZooming {
for t in visibleAnnotations {
t.view.position = screenPositionForAnnotation(t.annotation)
}
}
else {
for annotation in annotations {
let screenPosition = screenPositionForAnnotation(annotation)
var t = visibleAnnotations.visibleAnnotationTupleForAnnotation(annotation)
if screenPosition.tiled_isWithinBounds(bounds) {
if let t = t {
if t == currentSelectedAnnotationTuple {
canvasView.addSubview(t.view)
}
t.view.position = screenPosition
}
else {
// t is nil
let view = tiledScrollViewDelegate?.tiledScrollView(self, viewForAnnotation: annotation)
if let view = view {
view.position = screenPosition
t = TiledVisibleAnnotationTuple(annotation: annotation, view: view)
if let t = t {
tiledScrollViewDelegate?.tiledScrollView?(self, annotationWillAppear: t.annotation)
visibleAnnotations.insert(t)
canvasView.addSubview(t.view)
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
let animation = CABasicAnimation(keyPath: "opacity")
animation.duration = 0.3
animation.repeatCount = 1
animation.fromValue = 0.0
animation.toValue = 1.0
t.view.layer.add(animation, forKey: "animateOpacity")
tiledScrollViewDelegate?.tiledScrollView?(self, annotationDidAppear: t.annotation)
}
}
else {
// view is nil
continue
}
}
}
else {
if let t = t {
tiledScrollViewDelegate?.tiledScrollView?(self, annotationWillAppear: t.annotation)
if t != currentSelectedAnnotationTuple {
t.view.removeFromSuperview()
recycledAnnotationViews.insert(t.view)
visibleAnnotations.remove(t)
}
else {
// FIXME: Anthony D - I don't like let the view in visible annotations array, but the logic is in one place
t.view.removeFromSuperview()
}
tiledScrollViewDelegate?.tiledScrollView?(self, annotationDidDisappear: t.annotation)
}
} // if screenPosition.tiled_isWithinBounds(bounds)
} // for obj in annotations
}// if (scrollView.zoomBouncing || muteAnnotationUpdates) && !scrollView.zooming
CATransaction.commit()
}
/*private*/
func screenPositionForAnnotation(_ annotation: TiledAnnotation) -> CGPoint
{
var position = CGPoint.zero
position.x = (annotation.contentPosition.x * self.zoomScale) - scrollView.contentOffset.x
position.y = (annotation.contentPosition.y * self.zoomScale) - scrollView.contentOffset.y
return position
}
// MARK: Mute Annotation Updates
func makeMuteAnnotationUpdatesTrueFor(_ time: TimeInterval)
{
self.muteAnnotationUpdates = true
let popTime = DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: popTime, execute: {
self.muteAnnotationUpdates = false
})
}
// MARK: TiledScrollView
func setZoomScale(_ zoomScale: CGFloat, animated: Bool)
{
scrollView.setZoomScale(zoomScale, animated: animated)
}
func setContentCenter(_ center: CGPoint, animated: Bool)
{
scrollView.tiled_setContentCenter(center, animated: animated)
}
// MARK: Annotation Recycling
func dequeueReusableAnnotationViewWithReuseIdentifier(_ reuseIdentifier: String) -> TiledAnnotationView?
{
var viewToReturn: TiledAnnotationView? = nil
for v in self.recycledAnnotationViews {
if v.reuseIdentifier == reuseIdentifier {
viewToReturn = v
break
}
}
if viewToReturn != nil {
self.recycledAnnotationViews.remove(viewToReturn!)
}
return viewToReturn
}
// MARK: Annotations
func refreshAnnotations()
{
self.correctScreenPositionOfAnnotations()
for annotation in self.annotations {
let t = self.visibleAnnotations.visibleAnnotationTupleForAnnotation(annotation)
t?.view.setNeedsLayout()
t?.view.setNeedsDisplay()
}
}
func addAnnotation(_ annotation: TiledAnnotation) {
self.annotations.insert(annotation)
let screenPosition = self.screenPositionForAnnotation(annotation)
if screenPosition.tiled_isWithinBounds(bounds) {
if let view = self.tiledScrollViewDelegate?.tiledScrollView(self, viewForAnnotation: annotation) {
view.position = screenPosition
let t = TiledVisibleAnnotationTuple(annotation: annotation, view: view)
self.visibleAnnotations.insert(t)
self.canvasView.addSubview(view)
}
}
}
func addMainAnnotation(_ annotation: TiledAnnotation) {
self.annotations.insert(annotation)
let screenPosition = self.screenPositionForAnnotation(annotation)
if screenPosition.tiled_isWithinBounds(bounds) {
if let view = self.tiledScrollViewDelegate?.tiledScrollView(self, viewForAnnotation: annotation) {
view.position = screenPosition
let t = TiledVisibleAnnotationTuple(annotation: annotation, view: view)
self.visibleAnnotations.insert(t)
self.canvasView.addSubview(view)
self.annotation = annotation;
}
}
}
func addAnnotations(_ annotations: [TiledAnnotation])
{
for annotation in annotations {
self.addAnnotation(annotation)
}
}
func removeAnnotation(_ annotation: TiledAnnotation?)
{
if let annotation = annotation {
if self.annotations.contains(annotation) {
if let t = self.visibleAnnotations.visibleAnnotationTupleForAnnotation(annotation) {
t.view.removeFromSuperview()
self.visibleAnnotations.remove(t)
}
self.annotations.remove(annotation)
}
}
}
func removeAnnotations(_ annotations: [TiledAnnotation])
{
for annotation in annotations {
self.removeAnnotation(annotation)
}
}
func removeAllAnnotations()
{
for annotation in self.annotations {
self.removeAnnotation(annotation)
}
}
}
// MARK: - UIScrollViewDelegate
extension TiledScrollView: UIScrollViewDelegate
{
func viewForZooming(in scrollView: UIScrollView) -> UIView?
{
return self.tiledView
}
func scrollViewDidZoom(_ scrollView: UIScrollView)
{
self.tiledScrollViewDelegate?.tiledScrollViewDidZoom?(self)
}
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
self.correctScreenPositionOfAnnotations()
self.tiledScrollViewDelegate?.tiledScrollViewDidScroll?(self)
}
}
// MARK: - TiledBitmapViewDelegate
extension TiledScrollView: TiledBitmapViewDelegate {
func tiledView(_ tiledView: TiledView, imageForRow row: Int, column: Int, scale: Int) -> UIImage {
return self.dataSource!.tiledScrollView(self, imageForRow: row, column: column, scale: scale)
}
}
// MARK: - UIGestureRecognizerDelegate
extension TiledScrollView: UIGestureRecognizerDelegate {
@objc func singleTapReceived(_ gestureRecognizer: UITapGestureRecognizer) {
if gestureRecognizer.isKind(of: TiledAnnotationTapGesture.self) {
let annotationGestureRecognizer = gestureRecognizer as! TiledAnnotationTapGesture
previousSelectedAnnotationTuple = currentSelectedAnnotationTuple
currentSelectedAnnotationTuple = annotationGestureRecognizer.tapAnnotation
if nil == annotationGestureRecognizer.tapAnnotation {
if let previousSelectedAnnotationTuple = self.previousSelectedAnnotationTuple {
self.tiledScrollViewDelegate?.tiledScrollView?(self, didDeselectAnnotationView: previousSelectedAnnotationTuple.view)
}
else if self.centerSingleTap {
self.setContentCenter(gestureRecognizer.location(in: self.tiledView), animated: true)
}
self.tiledScrollViewDelegate?.tiledScrollView?(self, didReceiveSingleTap: gestureRecognizer)
}
else {
if let previousSelectedAnnotationTuple = self.previousSelectedAnnotationTuple {
var oldSelectedAnnotationView = previousSelectedAnnotationTuple.view
if oldSelectedAnnotationView == nil {
oldSelectedAnnotationView = self.tiledScrollViewDelegate?.tiledScrollView(self, viewForAnnotation: previousSelectedAnnotationTuple.annotation)
}
self.tiledScrollViewDelegate?.tiledScrollView?(self, didDeselectAnnotationView: oldSelectedAnnotationView!)
}
if currentSelectedAnnotationTuple != nil {
if let tapAnnotation = annotationGestureRecognizer.tapAnnotation {
let currentSelectedAnnotationView = tapAnnotation.view
if (tiledScrollViewDelegate?.tiledScrollView?(self, shouldSelectAnnotationView: currentSelectedAnnotationView!) ?? true) == true {
self.tiledScrollViewDelegate?.tiledScrollView?(self, didSelectAnnotationView: currentSelectedAnnotationView!)
}
else {
self.tiledScrollViewDelegate?.tiledScrollView?(self, didReceiveSingleTap: gestureRecognizer)
}
}
}
}
}
}
@objc func doubleTapReceived(_ gestureRecognizer: UITapGestureRecognizer) {
if self.zoomsInOnDoubleTap {
let newZoom = self.scrollView.tiled_zoomScaleByZoomingIn(1.0)
self.makeMuteAnnotationUpdatesTrueFor(kTiledScrollViewAnimationTime)
if self.zoomsToTouchLocation {
let bounds = scrollView.bounds
let pointInView = gestureRecognizer.location(in: scrollView).applying(CGAffineTransform(scaleX: 1 / scrollView.zoomScale, y: 1 / scrollView.zoomScale)
)
let newSize = bounds.size.applying(CGAffineTransform(scaleX: 1 / newZoom, y: 1 / newZoom)
)
scrollView.zoom(to: CGRect(x: pointInView.x - (newSize.width / 2),
y: pointInView.y - (newSize.height / 2), width: newSize.width, height: newSize.height), animated: true)
}
else {
scrollView.setZoomScale(newZoom, animated: true)
}
}
self.tiledScrollViewDelegate?.tiledScrollView?(self, didReceiveDoubleTap: gestureRecognizer)
}
@objc func twoFingerTapReceived(_ gestureRecognizer: UITapGestureRecognizer) {
if self.zoomsOutOnTwoFingerTap {
let newZoom = self.scrollView.tiled_zoomScaleByZoomingOut(1.0)
self.makeMuteAnnotationUpdatesTrueFor(kTiledScrollViewAnimationTime)
scrollView.setZoomScale(newZoom, animated: true)
}
self.tiledScrollViewDelegate?.tiledScrollView?(self, didReceiveTwoFingerTap: gestureRecognizer)
}
/** Catch our own tap gesture if it is on an annotation view to set annotation.
*Return NO to only recognize single tap on annotation
*/
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool
{
let location = gestureRecognizer.location(in: self.canvasView)
(gestureRecognizer as? TiledAnnotationTapGesture)?.tapAnnotation = nil
for t in self.visibleAnnotations {
if t.view.frame.contains(location) {
(gestureRecognizer as? TiledAnnotationTapGesture)?.tapAnnotation = t
return true
}
}
// Deal with all tap gesture
return true
}
}
| true
|
e3e45cf29c6cfec0a568b8f85382cc7982052524
|
Swift
|
eran3d/WWDC-tvOS
|
/WWDC/PlayerBuilder.swift
|
UTF-8
| 1,510
| 2.71875
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
//
// PlayerBuilder.swift
// WWDC
//
// Created by Guilherme Rambo on 22/11/15.
// Copyright © 2015 Guilherme Rambo. All rights reserved.
//
import UIKit
import AVFoundation
import AVKit
class PlayerBuilder {
class func buildPlayerViewController(videoURL: String, title: String?, description: String?) -> (AVPlayerViewController, AVPlayer) {
// build playerItem and It's metadata
let playerItem = AVPlayerItem(URL: NSURL(string: videoURL)!)
if let title = title {
let titleMeta = AVMutableMetadataItem()
titleMeta.locale = NSLocale.currentLocale()
titleMeta.keySpace = AVMetadataKeySpaceCommon
titleMeta.key = AVMetadataCommonKeyTitle
titleMeta.value = title
playerItem.externalMetadata.append(titleMeta)
}
if let description = description {
let descriptionMeta = AVMutableMetadataItem()
descriptionMeta.locale = NSLocale.currentLocale()
descriptionMeta.keySpace = AVMetadataKeySpaceCommon
descriptionMeta.key = AVMetadataCommonKeyDescription
descriptionMeta.value = description
playerItem.externalMetadata.append(descriptionMeta)
}
// build player and playerController
let player = AVPlayer(playerItem: playerItem)
let playerController = AVPlayerViewController()
playerController.player = player
return (playerController, player)
}
}
| true
|
5d6308d56dad7db6584cc6353b3393c2b51df66e
|
Swift
|
Caz-person/guessGuessGuess
|
/guessGuessGuess/GuessTableViewCell.swift
|
UTF-8
| 2,660
| 2.65625
| 3
|
[] |
no_license
|
//
// GuessTableViewCell.swift
// guessGuessGuess
//
// Created by Rebecca Cullimore on 5/28/16.
// Copyright © 2016 Cullimore Family. All rights reserved.
//
import UIKit
private var kAssociationKeyNextField: UInt8 = 0
//private var kFirstAlreadyInitialized: Bool = false
extension UITextField {
var nextField: UITextField? {
get {
return objc_getAssociatedObject(self, &kAssociationKeyNextField) as? UITextField
}
set(newField) {
objc_setAssociatedObject(self, &kAssociationKeyNextField, newField, .OBJC_ASSOCIATION_RETAIN)
}
}
}
class GuessTableViewCell: UITableViewCell, UITextFieldDelegate {
let limitLength = 1
@IBOutlet weak var correctNumbers: UILabel!
@IBOutlet weak var correctPlaces: UILabel!
@IBOutlet weak var rowLabel: UILabel!
@IBOutlet weak var input1: UITextField!
@IBOutlet weak var input2: UITextField!
@IBOutlet weak var input3: UITextField!
@IBOutlet weak var input4: UITextField!
@IBOutlet weak var youWin: UILabel!
@IBOutlet weak var goButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// if kFirstAlreadyInitialized == true {
// input1.becomeFirstResponder()
// }
input1.delegate = self
input2.delegate = self
input3.delegate = self
input4.delegate = self
self.input1.nextField = self.input2
self.input2.nextField = self.input3
self.input3.nextField = self.input4
self.input4.nextField = self.input1
//self.input1.chan
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// kFirstAlreadyInitialized = true
guard let text = textField.text else { return true }
if text.characters.count == limitLength {
textField.nextField?.becomeFirstResponder()
}
return text.characters.count < limitLength
// let newLength = text.characters.count + string.characters.count - range.length
// return newLength <= limitLength
}
// func textFieldShouldReturn(textField: UITextField) -> Bool {
// // Hide the keyboard.
//// textField.resignFirstResponder()
//// textField.nextField?.becomeFirstResponder()
// return false
// }
// func textFieldDidEndEditing(textField: UITextField) {
// print(textField.text)
// }
}
| true
|
348d06cb6c055bcad4cac46c1d23386ad8ed6dbd
|
Swift
|
lizlyon/lLyon_357_Project02
|
/lLyon_357_Project02_/lLyon_357_Project02_/main.swift
|
UTF-8
| 8,675
| 3.453125
| 3
|
[] |
no_license
|
// main.swift
// lLyon_Project02
// Created by Elizabeth Lyon on 2/15/21.
import Foundation
var myDictionary = [String:String]() //can be anything
class Program {
init(){ //drives the code
var reply = ""
var keepRunning = true
while (keepRunning) {
reply = Ask.AskQuestions(questionText: "Hello, Please select from the options below: \n1) View all passwords \n2) View a single password \n3) Delete a password \n4) Add a password \nType '1', '2', '3', or '4' : ", acceptedReply: ["1", "2", "3", "4"])
if (reply == "1") {
//calls the all function
all()
}
else if (reply == "2"){
//calls the single function
single()
}
else if (reply == "3"){
//calls the delete function
delete()
}
else if (reply == "4"){
//calls the add function
add()
}
else if (reply == "5" || reply == "0") {
keepRunning = false
break
}
}
func all(){
//outputs all keys and values
for key in myDictionary.keys{
print("Key: \(key)")
}
}
func single() {
//output single password based on the valid key
print("You have selected SINGLE \nPlease enter a key: ")
let userKey = readLine()
//if key exists ask for passphrase
if myDictionary.keys.contains(userKey!){
print("Now enter a passphrase: ")
let userPassphrase = readLine()
myDictionary[userKey!] = passwordDecrypt(passEncrypt : userPassphrase!)
print("The password is: " + passwordDecrypt(passEncrypt : userPassphrase!)) //force unwrap
}
else{
print("Error. Invalid input.")
}
}
}
//fucntion that outputs all keys with their cooresponding value
func all(){
for key in myDictionary.keys{
print("Key: \(key)")
}
}
//function that outputs a single password for the cooresponding key
func single() {
//ask for key
print("You have selected SINGLE \nPlease enter a key: ")
let userKey = readLine()
//if key exists ask for passphrase
if myDictionary.keys.contains(userKey!){
print("Now enter a passphrase: ")
let userPassphrase = readLine()
myDictionary[userKey!] = passwordDecrypt(passEncrypt : userPassphrase!)
print("The password is: " + passwordDecrypt(passEncrypt : userPassphrase!)) //force unwrap
}
//if doesnt exist
else{
print("Error. Invalid input.")
}
}
//function that deletes a specified object given a key
func delete() {
//ask for key
print("You have selected DELETE \nPlease enter a key: ")
let userKey = readLine()
//if exists then delete
if myDictionary.keys.contains(userKey!){
myDictionary.removeValue(forKey: userKey!)
print("YAY! You have successfully deleted that password")
}
//else doesnt exists
else{
print("Error. Invalid input.")
}
}
//function that adds a password to the dictionary
func add() {
//ask for name to add
print("You have selected ADD \nPlease enter a name to add: ")
let userKey = readLine()
//ask for passowrd
print("Now eneter a password: ")
let userPassword = readLine()
//ask for passphrase
print("Now eneter a passphrase: ")
let userPassphrase = readLine()
let add = userPassword! + userPassphrase!
myDictionary[userKey!] = passwordEncrypt(passEncrypt: add)
}
//function to reverse user input
func reverse(reverseStr input : String) -> String{
//returns the users string input as reveresed
return String(input.reversed())
}
//function to translate
func translate(i : Character, intToTranslate : Int) -> Character {
if let ascii = i.asciiValue{
var intFinal = ascii
if (ascii >= 97 && ascii <= 122){
intFinal = ((ascii - 97) + UInt8(intToTranslate) % 26) + 97
}
else if (ascii >= 65 && ascii <= 98){
intFinal = ((ascii - 65) + UInt8(intToTranslate) % 26) + 65
}
return Character(UnicodeScalar(intFinal))
}
return Character("")
}
//function to unscramble the cipher code
func unscrambleTranslator(i : Character, intToTranslate : Int) -> Character {
if let ascii = i.asciiValue {
var intFinal = ascii
if (ascii >= 97 && ascii <= 122) {
let temp = ascii - UInt8(intToTranslate)
if(temp < 97){
intFinal += 26
}
else if (temp > 122){
intFinal -= 26
}
intFinal = (((intFinal - 97) - UInt8(intToTranslate)) % 26) + 65
}
else if (ascii >= 65 && ascii <= 90) {
let temp = ascii - UInt8(intToTranslate)
if (temp < 65){
intFinal += 26
}
else if ( temp > 90){
intFinal -= 26
}
intFinal = (((intFinal - 65) - UInt8(intToTranslate)) % 26) + 65
}
return Character(UnicodeScalar(intFinal))
}
print(i)
return Character("")
}
//function for passowrd encryption
func passwordEncrypt(passEncrypt : String) -> String {
var encypted = ""
let shift = passEncrypt.count
for letter in passEncrypt{
encypted += String(translate(i : letter, intToTranslate : shift))
}
return encypted
}
//function for passowrd decryption
func passwordDecrypt(passEncrypt : String) -> String {
var strUnscramble = ""
let shift = passEncrypt.count
for letter in passEncrypt{
strUnscramble += String(unscrambleTranslator(i : letter, intToTranslate: shift))
}
return strUnscramble
}
}
//recursive class
class Ask {
static func AskQuestions(questionText output: String, acceptedReply inputArr: [String], caseSen: Bool = false) -> String {
print(output) //ask question
guard let response = readLine() else{
//if they didnt type anything at all
print("Invalid input")
//recursive function call
return AskQuestions(questionText: output, acceptedReply: inputArr)
}
//verify that the response is acceptable or empty
if (inputArr.contains(response) || inputArr.isEmpty) {
return response
}
else{
print("Error. Invalid input")
return AskQuestions(questionText: output,
acceptedReply: inputArr)
}
}
}
//creates instance of object p and store it in the Program class
let p = Program()
//write to JSON
func writeJSON(myDictionary : Dictionary<String,String>) -> Void {
do{
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, //file path within your computer
appropriateFor: nil,
create: true)
.appendingPathComponent("mySimplePasswordManager.json")
try JSONSerialization.data(withJSONObject: myDictionary)
.write(to: fileURL) //writing to the object we created
}
catch{
print(error)
}
}
//read from JSON
func readJSON() -> Dictionary<String,String> {
do
{
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, //file path within your computer
appropriateFor: nil,
create: false)
.appendingPathComponent("mySimplePasswordManager.json")
let data = try Data(contentsOf: fileURL)
let dictionary = try JSONSerialization.jsonObject(with: data)
}
catch
{
print(error)
}
return myDictionary
}
| true
|
567afef34f0305450ddd019bf1c6e17e4f10f6b0
|
Swift
|
jbeoris/RxPlayground
|
/RxPlayground/Playgrounds/Message/MessageSection.swift
|
UTF-8
| 976
| 2.796875
| 3
|
[] |
no_license
|
//
// MessageSection.swift
// RxPlayground
//
// Created by Jack Beoris on 1/30/19.
// Copyright © 2019 Jack Beoris. All rights reserved.
//
import Foundation
import RxDataSources
struct MessageSection {
var header: String
var messages: [Message]
var updated: Date
init(header: String, messages: [Message], updated: Date) {
self.header = header
self.messages = messages
self.updated = updated
}
}
extension MessageSection:
Equatable,
AnimatableSectionModelType {
typealias Item = Message
typealias Identity = String
var identity: String {
return header
}
var items: [Message] {
return messages
}
init(original: MessageSection, items: [Item]) {
self = original
self.messages = items
}
}
func == (lhs: MessageSection, rhs: MessageSection) -> Bool {
return lhs.header == rhs.header && lhs.items == rhs.items && lhs.updated == rhs.updated
}
| true
|
aba4df2845382b512bc753bc6a554d08fd568e70
|
Swift
|
Umar-M-Haroon/WWDC2020
|
/Template/PlaygroundBook/Modules/BookCore.playgroundmodule/Sources/VirusContentView.swift
|
UTF-8
| 9,474
| 2.828125
| 3
|
[] |
no_license
|
//
// VirusContentView.swift
// BookCore
//
// Created by Umar Haroon on 5/15/20.
//
import SwiftUI
import UIKit
import SceneKit
public struct VirusContentView: View {
@State var instructionText = Text("")
@State var sceneView: SceneKitView!
@State var shouldPlay = false
@State var showingNotice = false
@State var cellSteps = [
CellStep(step: "Viral RNA uses cell machinery to make copies"),
CellStep(step: "Virus attaches to cell"),
CellStep(step: "Virus gets assembled and leaves cell"),
CellStep(step: "Virus inserts RNA")
]
var correctSteps = [
CellStep(step: "Virus attaches to cell"),
CellStep(step: "Virus inserts RNA"),
CellStep(step: "Viral RNA uses cell machinery to make copies"),
CellStep(step: "Virus gets assembled and leaves cell")
]
public init() {}
private func shouldShowUpButton(step: CellStep) -> Bool {
return self.cellSteps.firstIndex(where: {$0.step == step.step})! != 0
}
private func shouldShowDownButton(step: CellStep) -> Bool {
return self.cellSteps.firstIndex(where: {$0.step == step.step})! != 3
}
public var body: some View {
ZStack {
SceneKitView(shouldPlay: $shouldPlay)
if showingNotice {
FloatingNotice(showingNotice: $showingNotice)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.showingNotice.toggle()
withAnimation {
self.shouldPlay = true
self.instructionText =
Text("Congrats! You finished this playground! Thank you for your time!")
.foregroundColor(.green)
}
}
}
.animation(.easeInOut)
}
GeometryReader { geometry in
VStack(alignment: .center, spacing: 0.0) {
Text("Arrange the steps in the correct order")
.font(.headline)
self.instructionText
.font(.headline)
HStack {
if self.cellSteps[0].step != self.correctSteps[0].step {
Text(self.cellSteps[0].step)
} else {
Text(self.cellSteps[0].step).foregroundColor(.green)
}
Button(action: {
withAnimation {
self.cellSteps.swapAt(0, 1)
}
self.confirmAnswers()
}, label: {
if self.cellSteps[0].step != self.correctSteps[0].step {
Image(systemName: "arrow.down")
.frame(width: 44.0, height: 44.0, alignment: .center)
}
})
}
HStack {
if self.cellSteps[1].step != self.correctSteps[1].step {
Text(self.cellSteps[1].step)
} else {
Text(self.cellSteps[1].step).foregroundColor(.green)
}
Button(action: {
withAnimation {
self.cellSteps.swapAt(1, 0)
self.confirmAnswers()
}
}, label: {
if self.cellSteps[1].step != self.correctSteps[1].step {
Image(systemName: "arrow.up")
.frame(width: 44.0, height: 44.0, alignment: .center)
}
})
Button(action: {
withAnimation {
self.cellSteps.swapAt(1, 2)
self.confirmAnswers()
}
}, label: {
if self.cellSteps[1].step != self.correctSteps[1].step {
Image(systemName: "arrow.down")
.frame(width: 44.0, height: 44.0, alignment: .center)
}
})
}
HStack {
if self.cellSteps[2].step != self.correctSteps[2].step {
Text(self.cellSteps[2].step)
} else {
Text(self.cellSteps[2].step).foregroundColor(.green)
}
Button(action: {
withAnimation {
self.cellSteps.swapAt(2, 1)
self.confirmAnswers()
}
}, label: {
if self.cellSteps[2].step != self.correctSteps[2].step {
Image(systemName: "arrow.up")
.frame(width: 44.0, height: 44.0, alignment: .center)
}
})
Button(action: {
withAnimation {
self.cellSteps.swapAt(2, 3)
}
self.confirmAnswers()
}, label: {
if self.cellSteps[2].step != self.correctSteps[2].step {
Image(systemName: "arrow.down")
.frame(width: 44.0, height: 44.0, alignment: .center)
}
})
}
HStack {
if self.cellSteps[3].step != self.correctSteps[3].step {
Text(self.cellSteps[3].step)
} else {
Text(self.cellSteps[3].step).foregroundColor(.green)
}
Button(action: {
withAnimation {
self.cellSteps.swapAt(3, 2)
}
self.confirmAnswers()
}, label: {
if self.cellSteps[3].step != self.correctSteps[3].step {
Image(systemName: "arrow.up")
.frame(width: 44.0, height: 44.0, alignment: .center)
}
})
}
}
.position(x: geometry.size.width * 0.5, y: geometry.size.height * 0.8)
}
}
}
func confirmAnswers() {
if self.cellSteps == correctSteps {
withAnimation {
showingNotice = true
}
} else {
self.instructionText = Text("Keep going! For a virus to infect a cell, what must it do first?")
showingNotice = false
}
}
}
struct FloatingNotice: View {
@Binding var showingNotice: Bool
var body: some View {
VStack (alignment: .center, spacing: 8) {
Image(systemName: "checkmark")
.foregroundColor(.white)
.font(.system(size: 48, weight: .regular))
.padding(EdgeInsets(top: 20, leading: 5, bottom: 5, trailing: 5))
Text("Correct!")
.foregroundColor(.white)
.font(.callout)
.padding(EdgeInsets(top: 0, leading: 10, bottom: 5, trailing: 10))
}
.background(Color.gray.opacity(0.8))
.cornerRadius(5)
.transition(.scale)
}
}
public struct CellStep: Identifiable, Equatable {
public var step: String
public var id = UUID()
}
extension CellStep {
public static func ==(lhs: CellStep, rhs: CellStep) -> Bool {
return lhs.step == rhs.step
}
}
struct SceneKitView : UIViewRepresentable {
@Binding var shouldPlay: Bool
let scene = SCNScene(named: "Final.scn")!
func makeUIView(context: Context) -> SCNView {
let scnView = SCNView()
return scnView
}
func updateUIView(_ scnView: SCNView, context: Context) {
scnView.scene = scene
scnView.isPlaying = shouldPlay
scnView.scene?.isPaused = !shouldPlay
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
// configure the view
scnView.backgroundColor = UIColor.black
}
}
struct VirusContentView_Previews: PreviewProvider {
static var previews: some View {
VirusContentView()
}
}
| true
|
805b286d5066a5aa6c28dbf02c6ec54e92f5d7d8
|
Swift
|
hirooka/kippoui-ios
|
/kippoui-ios/search/SearchedPlaceView.swift
|
UTF-8
| 312
| 2.765625
| 3
|
[] |
no_license
|
import SwiftUI
struct SearchedPlaceView: View {
var name: String
var address: String
var body: some View {
GeometryReader { geometry in
VStack {
Text(name).font(.largeTitle)
//Text(address).font(.subheadline)
}
}
}
}
| true
|
0d049bd1778cb7ffd27ad63230069f50b982ccab
|
Swift
|
EthanDoan/ImageCoordinateSpace
|
/Unit Tests/CGAffineTransform+Scale_Spec.swift
|
UTF-8
| 1,054
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
import Quick
import Nimble
@testable import ImageCoordinateSpace
class CGAffineTransform_Scale_Spec: QuickSpec {
override func spec() {
describe(CGAffineTransform.self) {
context(CGAffineTransform.scale) {
it("should pass X and Y to block and return block result") {
let transform = CGAffineTransform(scaleX: 2, y: 3)
expect(transform.scale(using: {
expect($0) == 2
expect($1) == 3
return 5
})) == 5
}
}
context(CGAffineTransform.init(scaleTo:from:)) {
it("should create tranform that will scale from one size to another") {
let from = CGSize.nextRandom()
let to = CGSize.nextRandom()
let transform = CGAffineTransform(scaleTo: to, from: from)
expect(from.applying(transform)) ≈ to ± 0.0001
}
}
}
}
}
| true
|
206ddb61b8cfc7ba0f4dabd3bb284356069ca5b4
|
Swift
|
thanhan123/PracticeSwift
|
/SwiftPractice/ViewController/Controller/InsertTodoViewController.swift
|
UTF-8
| 1,872
| 2.5625
| 3
|
[] |
no_license
|
//
// InsertTodoViewController.swift
// SwiftPractice
//
// Created by Dinh Thanh An on 4/4/17.
// Copyright © 2017 Dinh Thanh An. All rights reserved.
//
import Foundation
import UIKit
import RealmSwift
import ReactiveCocoa
import ReactiveSwift
class InsertTodoViewController: UIViewController{
@IBOutlet weak var itemNameTextField: UITextField!
@IBOutlet weak var detailTextView: UITextView!
@IBOutlet weak var addButton: UIButton!
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Insert Item"
detailTextView.layer.borderColor = UIColor.gray.cgColor
detailTextView.layer.borderWidth = 1.0
bindingUI()
}
func bindingUI() {
self.addButton.isEnabled = false
Signal.combineLatest(itemNameTextField.reactive.continuousTextValues, detailTextView.reactive.continuousTextValues)
.observeValues{ itemNameString, itemDetailString in
if (itemNameString?.characters.count)! > 0 && (itemDetailString?.characters.count)! > 0 {
self.addButton.isEnabled = true
} else {
self.addButton.isEnabled = false
}
}
addButton.reactive.controlEvents(.touchUpInside)
.observe{ sender in
let item = Item()
item.itemDetail = self.detailTextView.text
item.itemName = self.itemNameTextField.text!
self.addObjectToRealm(item)
}
}
func addObjectToRealm(_ object: Object) {
try! self.realm.write {
self.realm.add(object)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
[unowned self] in
_ = self.navigationController?.popViewController(animated: true)
}
}
}
}
| true
|
4c574f88ca2adff020a210dffc3794a93ddae25d
|
Swift
|
SantiLorenzana/Iosmusicaentregar
|
/Reproductor Musical/Listas/ListTableViewController.swift
|
UTF-8
| 2,313
| 2.859375
| 3
|
[] |
no_license
|
//
// RegisterViewController.swift
// Reproductor Musical
//
// Created by alumnos on 14/3/18.
// Copyright © 2018 santi. All rights reserved.
//
import UIKit
import Toast_Swift
class ListTableViewController: UITableViewController{
let dataManager = DataManager()
var songs = NSArray()
var songsParsed = [Song]()
override func viewDidLoad() {
super.viewDidLoad()
obtainSongs(parameters: ["data": "nil"])
}
func obtainSongs(parameters: [String: Any]){
//Se hace la llamada a la API y se filtran los códigos de respuesta
dataManager.getSongs(params: parameters) { (json) in
if json.code == 200 {
self.songs = json.data["songs"] as! NSArray
for songR in json.data["songs"] as! [[String : Any]]{
self.songsParsed.append(Song(Song:songR))
}
self.tableView.reloadData()
self.view.makeToast(json.message , duration: 3.0, position: .top)
} else if json.code == 401 || json.code == 419{
self.view.makeToast(json.message , duration: 3.0, position: .top)
} else if json.code == 400 || json.code == 500 {
print(String(describing:json))
}
}
}
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 self.songsParsed.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : DataInTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Songcell", for: indexPath) as! DataInTableViewCell
cell.SongName.text = self.songsParsed[indexPath.item].songName
cell.Artist.text = self.songsParsed[indexPath.item].Artist
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(songsParsed[indexPath.item].urlSong)
}
}
| true
|
a73fa22ea77e6ed0d3e14933a7562ff508f02ae2
|
Swift
|
polurezov8/DataStructures
|
/DataStructures/HashTable/HashTable.swift
|
UTF-8
| 4,860
| 3.734375
| 4
|
[
"MIT"
] |
permissive
|
//
// HashTable.swift
// HashTable
//
// Created by Dmitry Polurezov on 22.09.2021.
//
import XCTest
/// Hash Table: A symbol table of generic key-value pairs.
public struct HashTable<Key: Hashable, Value> {
private typealias Element = (key: Key, value: Value)
private typealias Bucket = [Element]
private var buckets: [Bucket]
/// The number of key-value pairs in the hash table.
private(set) var count: Int = .zero
/// A Boolean value that indicates whether the hash table is empty.
public var isEmpty: Bool { return count == .zero }
/// Create a hash table with the given capacity.
public init(capacity: Int) {
assert(capacity > .zero)
buckets = Array<Bucket>(repeatElement([], count: capacity))
}
/// Accesses the value associated with
/// the given key for reading and writing.
public subscript(key: Key) -> Value? {
get {
value(forKey: key)
}
set {
if let value = newValue {
updateValue(value, forKey: key)
} else {
removeValue(forKey: key)
}
}
}
/// Returns the value for the given key.
public func value(forKey key: Key) -> Value? {
let index = self.index(forKey: key)
for element in buckets[index] {
if element.key == key {
return element.value
}
}
return nil // key not in hash table
}
/// Updates the value stored in the hash table for the given key,
/// or adds a new key-value pair if the key does not exist.
@discardableResult
public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
let index = self.index(forKey: key)
// Do we already have this key in the bucket?
for (i, element) in buckets[index].enumerated() {
if element.key == key {
let oldValue = element.value
buckets[index][i].value = value
return oldValue
}
}
// This key isn't in the bucket yet; add it to the chain.
buckets[index].append((key: key, value: value))
count += 1
return nil
}
/// Removes the given key and its associated value from the hash table.
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
let index = self.index(forKey: key)
// Find the element in the bucket's chain and remove it.
for (i, element) in buckets[index].enumerated() {
if element.key == key {
buckets[index].remove(at: i)
count -= 1
return element.value
}
}
return nil // key not in hash table
}
/// Removes all key-value pairs from the hash table.
public mutating func removeAll() {
buckets = Array<Bucket>(repeatElement([], count: buckets.count))
count = .zero
}
/// Returns the given key's array index.
private func index(forKey key: Key) -> Int {
abs(key.hashValue % buckets.count)
}
}
extension HashTable: CustomStringConvertible {
/// A string that represents the contents of the hash table.
public var description: String {
let pairs = buckets.flatMap { b in b.map { e in "\(e.key) = \(e.value)" } }
return pairs.joined(separator: ", ")
}
/// A string that represents the contents of
/// the hash table, suitable for debugging.
public var debugDescription: String {
var string = ""
for (index, bucket) in buckets.enumerated() {
let pairs = bucket.map { e in "\(e.key) = \(e.value)" }
string += "bucket \(index): " + pairs.joined(separator: ", ") + "\n"
}
return string
}
}
class HashTableTests: XCTestCase {
func testIsEmpty() {
var hashTable = HashTable<Int, String>(capacity: 3)
hashTable[1] = "First element"
XCTAssertFalse(hashTable.isEmpty)
hashTable.removeValue(forKey: 1)
XCTAssertTrue(hashTable.isEmpty)
}
func testValueForKey() {
let element = "First element"
var hashTable = HashTable<Int, String>(capacity: 3)
hashTable[1] = element
let value = hashTable.value(forKey: 1)
XCTAssertEqual(value, element)
}
func testUpdateValue() {
let element = "First element"
var hashTable = HashTable<Int, String>(capacity: 3)
hashTable[1] = element
XCTAssertEqual(hashTable.value(forKey: 1), element)
let newValue = "New first value"
hashTable[1] = newValue
XCTAssertEqual(hashTable.value(forKey: 1), newValue)
}
func testRemoveValue() {
let element = "First element"
var hashTable = HashTable<Int, String>(capacity: 3)
hashTable[1] = element
XCTAssertFalse(hashTable.isEmpty)
let removedValue = hashTable.removeValue(forKey: 1)
XCTAssertNotNil(removedValue)
XCTAssertEqual(removedValue, element)
XCTAssertTrue(hashTable.isEmpty)
}
func testDebugDescription() {
let element = "First element"
var hashTable = HashTable<Int, String>(capacity: 3)
hashTable[1] = element
XCTAssertEqual("1 = First element", hashTable.description)
}
}
| true
|
e313ab0b04a1152225a273e98d2a43e33b15f454
|
Swift
|
casal033/StoryBuilder
|
/MultiViews/GameViewController.swift
|
UTF-8
| 21,708
| 2.796875
| 3
|
[] |
no_license
|
//
// GameViewController.swift
// MultiViews
//
// Created by Administrator on 7/15/14.
// Copyright (c) 2014 Administrator. All rights reserved.
//
import UIKit
import SpriteKit
import Foundation
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks")
var sceneData = NSData(contentsOfFile: path!, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData!)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
}
}
class GameViewController: UIViewController {
let panRec = UIPanGestureRecognizer()
let tapRec = UITapGestureRecognizer()
var toolbar:UIToolbar!
var toolbarAlpha:UIToolbar!
var scrollView: UIScrollView!
var wordSelectionView: UIImageView! = UIImageView(image: UIImage(named: "purpleRectangle"));
//allWords contains all of the words related to the current student
var allWords = [String]()
//Max word length in allWords used to set Scrol Width
var maxWordLength = Int()
//Max word length in allWords used to set tile width
var maxWordLengthWord = Int()
//_wordPackIDs has an array of the student's contextpacksIDs they're assigned
var studentWordPackIDs = [String]()
//_looseWordsIDs has an array of the student's individually assigned words
var studentWordIDs = [String]()
//_looseWordsIDs has an array of the student's individually assigned words
var studentWordPackWordIDs = [String]()
//_wordPacks has a dictionary with all of the <contextIDs, contextTitle> in the word river system
var studentWordPacks = [String: [String]]()
var studentContextPacks = [String: [String]]()
//_words has a dictionary with all of the contextIDs and a nested dictionary <wordIDs, <name:wordName, type:wordType> in the word river system
var studentWords = [String: [String]]()
var contextPackNames = [String]()
var _alphaDictionary = [String: [String]]()
let alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
override func viewDidLoad() {
super.viewDidLoad()
//Generate helpful objects of related student information
getStudentInfo()
//Dictionary of categories and associated arrays
getStudentWords()
setWidth(maxWordLength)
setWordWidth(maxWordLengthWord)
/////////* Section for Scroll View */////////
/* Populate the scroll bar with all of the words related to the student (Their assigned category words and inidviudally assigned words) */
populateSelector(sortArray(allWords))
//Add word view to scroll
scrollView.addSubview(wordSelectionView)
let scrollViewFrame = scrollView.frame
//Scale/Zoom information
let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
let minScale = min(scaleWidth, scaleHeight);
scrollView.minimumZoomScale = minScale;
scrollView.maximumZoomScale = 1.0
scrollView.zoomScale = minScale;
/////////* Section for Toolbar */////////
//Array of category names assigned to student
contextPackNames = getWordPackNames(studentContextPacks)
var sorted:[String] = sortArray(contextPackNames)
/*Array of buttons to add to toolbar
Currently includes "All" and each category the student is assigned */
var items = [AnyObject]()
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action:"refreshWords:"))
items.append (UIBarButtonItem(title: "All", style: UIBarButtonItemStyle.Plain, target: self, action: "allButtonPressed:"))
for index in 0...sorted.count-1 {
items.append(UIBarButtonItem(title: sorted[index], style: UIBarButtonItemStyle.Plain, target: self, action: "showCategories:"))
}
//Making a toolbar programatically
toolbar = UIToolbar()
//Add buttons to toolbar
toolbar.items = items
//Add toolbat to view
view.addSubview(toolbar)
/////////* Section for Toolbar 2 */////////
/* Array of buttons to add to toolbar */
var letters = [AnyObject]()
var alphaSorted = sortArray(alpha)
for position in 0...alphaSorted.count-1 {
letters.append(UIBarButtonItem(title: alphaSorted[position], style: UIBarButtonItemStyle.Plain, target: self, action: "showAlphaWords:"))
}
//Making a toolbar programatically
toolbarAlpha = UIToolbar()
//Add buttons to toolbar
toolbarAlpha.items = letters
//Add toolbat to view
view.addSubview(toolbarAlpha)
//////////Testing buttons
let button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
button.frame = CGRectMake(CGFloat(view.bounds.width - 115), 20, 110, 80)
button.backgroundColor = UIColor.redColor()
button.setTitle("Clear Tiles", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
button.titleLabel!.font = UIFont(name: "Thonburi", size: 18)
button.addTarget(self, action: "ResetButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
tapRec.addTarget(self, action: "tappedView")
panRec.addTarget(self, action: "draggedView")
let skView = self.view as! SKView
scene = GameScene(size: skView.bounds.size)
scene.backgroundColor = UIColor.darkGrayColor()
skView.addGestureRecognizer(tapRec)
skView.presentScene(scene)
}
var setScrollWidth = CGFloat()
var setScrollWidthText = CGFloat()
var setScrollWidthButton = CGFloat()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Set scrollView bounds "size"
//If scroll width is breaking use 150
scrollView.frame = CGRectMake(0, 105, setScrollWidth, view.bounds.height-115)
//Set toolbar bounds "size"
toolbar.frame = CGRectMake(10, 20, CGFloat(view.bounds.width-130), 40)
//Set toolbar bounds "size"
toolbarAlpha.frame = CGRectMake(10, 60, CGFloat(view.bounds.width-130), 40)
}
//Brings scroll to start of words when each category is selected
func toBegining(scrollView: UIScrollView) {
scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
}
//Get names of categories from a dictionary where [name: array] to make buttons for toolbar
func getWordPackNames(dict: [String: [String]]) -> [String]{
var toReturn = [String]()
for (key, value) in dict {
toReturn.append(key)
}
return toReturn
}
var y: CGFloat = 50
func populateSelector(_words: [String]) {
//Allows scroll to move when needed, and stay still when list of words is short
self.scrollView = UIScrollView()
self.scrollView.contentSize = CGSizeMake(wordSelectionView.frame.size.width, CGFloat(count(_words) * 30))
view.addSubview(scrollView)
//Brings scroll to start of words when each category is selected
toBegining(scrollView)
//Formatting words to be displayed in scroll
y = 0
for word in _words {
var wordButton = UIButton()
var wordLabel = UILabel()
wordLabel.text = word
wordLabel.font = UIFont(name: "Thonburi", size: 20)
wordLabel.textAlignment = .Left
wordLabel.frame = CGRectMake(10, 0, setScrollWidthText, 25)
//If scroll width is breaking use 100
wordButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
// 3rd is is width, 4th is height
//If scroll width is breaking use 120
wordButton.frame = CGRectMake(10, y, setScrollWidthButton, 30)
wordButton.backgroundColor = UIColor(red: 0.7, green: 0.5, blue: 0.9, alpha: 1.0)
//adjust y position for the next word
y += 30
wordButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
scrollView.addSubview(wordButton)
wordButton.addSubview(wordLabel)
}
}
//Function adds words from populateSelector() into the game scene as a tile
func pressed(sender: UIButton!) {
let word = sender.subviews[0] as! UILabel
scene.addTile([word.text!, getWordType(word.text!)])
}
//Function to grab word type so the word can be made into a tile
func getWordType(word: String) -> String {
var toReturn = String()
for (key, value) in studentWords {
let tileName:String = value[0]
let tileType:String = value[1]
if tileName == word {
toReturn = tileType
}
}
return toReturn
}
//Function filters to show all words assigned to the child
func allButtonPressed(sender: AnyObject) {
let subViews: Array = scrollView.subviews
for subview in subViews
{
subview.removeFromSuperview()
}
populateSelector(sortArray(allWords))
}
//Function filters to show category-specific words assigned to the child
func showCategories(sender: AnyObject) {
var holder:[String: [String]] = studentContextPacks
var categoryName = sender.title
let subViews: Array = scrollView.subviews
for subview in subViews
{
subview.removeFromSuperview()
}
populateSelector(sortArray(getArrayToDisplay(categoryName, dict: holder)))
}
//Function filters to show alpha-specific words assigned to the child
func showAlphaWords(sender: AnyObject) {
var holder:[String: [String]] = _alphaDictionary
var letterName = sender.title
let subViews: Array = scrollView.subviews
for subview in subViews
{
subview.removeFromSuperview()
}
populateSelector(sortArray(getArrayToDisplay(letterName, dict: holder)))
}
//Function refreshes our current words whenever the button is pressed in scene
//So a teacher can add a word, and a child can refresh and get it right away
func refreshWords(sender: AnyObject){
allWords = []
setScrollWidth = CGFloat()
setScrollWidthText = CGFloat()
setScrollWidthButton = CGFloat()
let subViews: Array = scrollView.subviews
for subview in subViews
{
subview.removeFromSuperview()
}
viewDidLoad()
viewDidLayoutSubviews()
}
//Sets the appropriate scroll width based on lengths of given words
func setWidth(int:Int) {
var hold = Int()
if int > 18 {
hold = 18
} else {
hold = int
}
for index in 0...hold {
setScrollWidth += 12
}
//println(setScrollWidth)
}
//Sets the appropriate word width based on lengths of given words
func setWordWidth(int:Int) {
var hold = Int()
//println("Count check tile: \(int > 18)")
if int > 18 {
hold = 18
} else {
hold = int
}
for index in 0...hold {
setScrollWidthText += 10
setScrollWidthButton += 11
}
//println(setScrollWidthButton)
}
//Parses dictionaries to get associated arrays with given names for alpha & categories currently
func getArrayToDisplay(category: String?!, dict: [String:[String]]) -> [String] {
var toReturn = [String]()
for (key, value) in dict {
if key == category {
toReturn = value
}
}
return toReturn
}
//Alpha sorting function for arrays
func sortArray(toSort: [String]) -> [String]{
return toSort.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
}
//Get all related information about student (words & categories their assigned)
func getStudentInfo() {
//_looseWordPackIDs has an array of the student's individual word pack IDs they're assigned
studentWordPackIDs = WordList(urlStudents: "https://teacherwordriver.herokuapp.com/api/students").looseStudentWordPackIDs
//_looseWordsIDs has an array of the student's individual word IDs they're assigned
studentWordIDs = WordList(urlStudents: "https://teacherwordriver.herokuapp.com/api/students").looseStudentWordIDs
//studentWordPacks is a dictionary with all of the [wordPackID: [wordPackName, list of word IDs]]
studentWordPacks = WordList(urlWordPacks: "https://teacherwordriver.herokuapp.com/api/wordPacks", wpIDs: studentWordPackIDs).wordPack
//studentWordPackWordIDs has an array of the student's word IDs they're assigned from the assigned word packs
studentWordPackWordIDs = WordList(urlWordPacks: "https://teacherwordriver.herokuapp.com/api/wordPacks", wpIDs: studentWordPackIDs).wordIDs
//studentWords is a dictionary with all of the [wordID: [wordName, wordType]]
studentWords = WordList(urlWords: "https://teacherwordriver.herokuapp.com/api/words", wdIDs: studentWordPackWordIDs).words
//Combine word IDs from word packs and individually assigned word IDs
for index in 0...studentWordIDs.count-1{
if(!(contains(studentWordPackWordIDs, studentWordIDs[index]))){
studentWordPackWordIDs.append(studentWordIDs[index])
}
}
//Start the alphabet filter sorting
createAlphaDictionary()
//Go through all grabbed student words
for (id, arr) in studentWords {
if(contains(studentWordPackWordIDs, id)){
//Add each word to allWords
allWords.append(arr[0])
//Check the size of each word for the scroll bar width
var wordLength = count(arr[0])
checkMaxWord(wordLength)
//Add each word to the alphabet dictionary
addToAlphaDictionary(arr[0])
}
}
//studentContextPacks is a dictionary with all of the [contextPackName: [wordPackIDs]]
studentContextPacks = WordList(urlContextPacks: "https://teacherwordriver.herokuapp.com/api/contextPacks", wpIDs: studentWordPackIDs).contextPack
//Print staetment to check speed of gathering student info
println("Got api info!")
}
//Helper to initialize the alphaDictionary with empty arrays
func createAlphaDictionary(){
for i in 0...alpha.count-1 {
_alphaDictionary[alpha[i]] = []
}
}
//Parse all word information from getStudentInfo into usable objects
func getStudentWords() {
var wpsInCPs = [String]()
//Loop through dictionary of known assigned context packs
for (contextName, wordPackIDs) in studentContextPacks {
var wordIDs = [String]()
//If contextPack has assigned wordPacks
if (wordPackIDs.count > 0) {
//Loop through assigned wordPacks in contextPack
for index in 0...wordPackIDs.count-1 {
//Loop through dictionary of known assigned wordPacks
for (wpID, wpWordIDs) in studentWordPacks {
//If ID from contextPack matches ID of current wordPack
if(wordPackIDs[index] == wpID){
//Helper for getting wordPacks not assigned to contextPacks
if (!(contains(wpsInCPs, wpID))){
wpsInCPs.append(wpID)
}
//Holder for matched words from wordPack
var wpWords = wpWordIDs
//Loop through word IDs in current wordPack and add them to all word IDs in current contextPack
for index2 in 1...wpWordIDs.count-1{
if (!(contains(wordIDs, wpWordIDs[index2]))) {
wordIDs.append(wpWordIDs[index2])
}
}
}
}
}
//Assigning all word IDs from wordPacks in current contextPack to the name of the current contextPack
//Essentially replacing wordPack IDs with all of the word IDs from those previous wordPack IDs
studentContextPacks[contextName] = wordIDs
}
}
//Loop through dictionary of known assigned wordPacks again to check if not in a contextPack
for (wpIDnonContext, wpWordIDnonContext) in studentWordPacks {
var nonContextWordIDs = [String]()
//If the current wordPack ID is not in the helper list of wordPack IDs in a contextPack
if(!(contains(wpsInCPs, wpIDnonContext))){
var wpWordsNonContext = [String]()
wpWordsNonContext = wpWordIDnonContext
//Loop through word IDs in current wordPack and add them to all word IDs in current wordPack
for index3 in 1...wpWordIDnonContext.count-1{
if (!(contains(nonContextWordIDs, wpWordIDnonContext[index3]))) {
nonContextWordIDs.append(wpWordIDnonContext[index3])
}
}
//Make wordPack a "contextPack" by adding name and it's assigned word IDs
//wpWordIDnonContext[0] is the wordPackName
studentContextPacks[wpWordIDnonContext[0]] = nonContextWordIDs
}
}
//Loop through all words assigned to the student
for (wordID, wordArr) in studentWords {
//Loop through all contextPacks with their assigned word IDs
for (contName, contWordIDs) in studentContextPacks {
//If contextPack has words assigned
if(contWordIDs.count > 0){
//Loop through word IDs assigned to contextPack
for i in 0...contWordIDs.count-1 {
//If current word ID in contextPack matches the current student word
if (wordID == contWordIDs[i]) {
var wordsHold = contWordIDs
wordsHold[i] = wordArr[0]
//Replace the word ID with the word name
studentContextPacks[contName] = wordsHold
}
}
}
}
}
}
//Helper for setting scroll width based on the maxword length
func checkMaxWord(int: Int) {
if int > maxWordLength {
maxWordLength = int
maxWordLengthWord = maxWordLength
}
}
//Helper to organize all assigned words, with no doubles into alphabet filters
func addToAlphaDictionary(word: String) {
let currentWord = word.lowercaseString
let index = advance(currentWord.startIndex, 0)
var letterToGet = currentWord[index]
var currentLetter = String()
currentLetter = String(letterToGet)
var holderArr = [String]()
//key is the letter, value is the array of associated words
for (key, value) in _alphaDictionary {
if key == currentLetter {
holderArr = value
holderArr.append(word)
holderArr = sortArray(holderArr)
_alphaDictionary[key] = holderArr
}
}
}
var skView: SKView!
var scene: GameScene!
@IBOutlet var Word1: UITextField?
//Resets all tiles in playing field
func ResetButtonPressed(sender: AnyObject) {
scene.resetTiles()
}
@IBAction func NextButtonPressed(sender: AnyObject) {
scene.addTileFromWordList()
}
func tappedView() {
}
func showTag(sender: UIBarButtonItem!) {
let subViews: Array = scrollView.subviews
for subview in subViews
{
subview.removeFromSuperview()
}
let tag = sender.title
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| true
|
eb209a40d2da08f78eba6aa08de6eeedf16a1762
|
Swift
|
kcourtois/KataBank
|
/KataBank/main.swift
|
UTF-8
| 395
| 2.78125
| 3
|
[] |
no_license
|
//
// main.swift
// KataBank
//
// Created by Kévin Courtois on 15/12/2019.
// Copyright © 2019 Kévin Courtois. All rights reserved.
//
import Foundation
let account = Account()
account.deposit(amount: 1000, date: Date(dateString: "10/01/2012")!)
account.deposit(amount: 2000, date: Date(dateString: "13/01/2012")!)
account.withdrawal(amount: 500, date: Date(dateString: "14/01/2012")!)
print(account)
| true
|
e4de2c8147f1ba0e7f3438b1c8f27ee59839f6f8
|
Swift
|
seepal/seepal
|
/SeePal/SeePal/Model/PDFPageData.swift
|
UTF-8
| 1,492
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// PDFPageData.swift
// SeePal
//
// Created by Gi Soo Hur on 16/01/2019.
// Copyright © 2019 Gi Soo Hur. All rights reserved.
//
import UIKit
import CoreGraphics.CGPDFDocument
class PDFPageData : PageData {
override func binary() -> Data? {
let a = archive as! CGPDFDocument
let e = entry as! CGPDFPage
var ret:Data?
lock(obj: a) {
let s = UIScreen.main.scale
let orgRect = e.getBoxRect(CGPDFBox.cropBox)
var rect = orgRect
rect.size.width *= s
rect.size.height *= s
let size = rect.size
UIGraphicsBeginImageContext(size)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.saveGState()
let rotate = e.rotationAngle
let transform = e.getDrawingTransform(CGPDFBox.cropBox, rect: orgRect, rotate: rotate, preserveAspectRatio: true)
context.concatenate(transform)
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: CGFloat(s), y: CGFloat(-s))
context.drawPDFPage(e)
context.restoreGState()
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
UIGraphicsEndImageContext()
return
}
ret = image.pngData()
UIGraphicsEndImageContext()
}
return ret
}
}
| true
|
d353cadd709d5c415130131ec096455a1a06b330
|
Swift
|
thanhvv-ios-tl/Ominext-MVVM
|
/Ominext-MVVM/MVVM/CustomViews/OMButton.swift
|
UTF-8
| 1,244
| 2.84375
| 3
|
[] |
no_license
|
//
// OMButton.swift
//
// Copyright © 2019 Ominext. All rights reserved.
//
import Foundation
import UIKit
class OMButton: UIButton {
@IBInspectable var localizationKey: String = ""
override func awakeFromNib() {
self.localization()
self.adjustFont()
}
func localization() {
self.setTitle(localizationKey.localized, for: .normal)
}
func adjustFont() {
guard let currentFont = self.titleLabel?.font else {
return
}
let currentFontSize = currentFont.pointSize
if currentFont.familyName == UIFont.systemFont(ofSize: 12).familyName
{
self.titleLabel?.font = UIFont.fontWithSize(currentFontSize, fontWeight: self.fontWeightFromSystemFont(currentFont))
}
}
func fontWeightFromSystemFont(_ font: UIFont) -> UIFont.Weight {
let fontName = font.fontName
if fontName.hasSuffix("-Bold") {
return UIFont.Weight.bold
}
if fontName.hasSuffix("-Semibold") {
return UIFont.Weight.semibold
}
if fontName.hasSuffix("-Medium") {
return UIFont.Weight.medium
}
return UIFont.Weight.regular
}
}
| true
|
0eb7e85e1a33c035fa47155693a0a6f2e264ee25
|
Swift
|
nakatakau/e2voice
|
/e2voice/Model/ComponentsAndColor/RegisterAllergyCollectionViewCell.swift
|
UTF-8
| 851
| 2.515625
| 3
|
[] |
no_license
|
import UIKit
final class RegisterAllergyCollectionViewCell: UICollectionViewCell {
//CollectionView内のcellに描画するUIImageViewの作成
private let menuImg : UIImageView = {
let img = UIImageView()
return img
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
contentView.addSubview(menuImg)
}
//UILabelのセットアップ
func setupContents(image:UIImage) {
menuImg.image = image
menuImg.frame.size = CGSize(width: contentView.frame.width, height: contentView.frame.width)
menuImg.center = CGPoint(x: contentView.frame.width/2, y: contentView.frame.height/2)
}
}
| true
|
93733f6b3d0905ed15d9d9ddd4e8c194449b95ff
|
Swift
|
Whiffer/SwiftUI-Core-Data-Test
|
/CodeExamples.swift
|
UTF-8
| 7,437
| 3.40625
| 3
|
[] |
no_license
|
//
// CodeExamples.swift
// Shared
//
// Created by Chuck Hartman on 7/4/20.
//
import SwiftUI
import CoreData
// MARK: CoreDataDataSource Examples of Common Usage Patterns
// MARK: Examples that use an NSFetchedResultsController
// Using State to control sort order
struct ItemsView : View {
// Data source with a default fetch request for all Item's
@ObservedObject private var dataSource = CoreDataDataSource<Item>()
// State var to control the sort order of the fetch request
@State private var sortAscending: Bool = true
var body: some View {
List {
// List shows all Item objects using current sort state
ForEach(self.dataSource
.sortAscending1(self.sortAscending)
.objects) { item in
Text("\(item.name)")
}
}
}
}
struct ItemAttributesView : View {
// Object passed in to be used as predicateObject
var item: Item
// Data source to fetch all Attribute's related to the Item passed in
@ObservedObject private var dataSource = CoreDataDataSource<Attribute>(predicateKey: "item")
var body: some View {
Form {
Text("\(item.name)")
Section(header: Text("Attributes")) {
// List shows all Attribute objects related to Item
ForEach(self.dataSource
.predicateObject(item)
.objects) { attribute in
Text("\(attribute.name)")
}
}
}
}
}
struct AllAttributesByItemView: View {
// Data source to fetch All Attribute's and group them by Item
@ObservedObject private var dataSource = CoreDataDataSource<Attribute>(sortKey1: "item.order",
sortKey2: "order",
sectionNameKeyPath: "item.name")
var body: some View {
List {
// The sections outer ForEach loop provides the section (i.e. Item) names
ForEach(self.dataSource.sections, id: \.name) { section in
Section(header: Text("Attributes for: \(section.name)")) {
// The objects inner ForEach loop provides all of the Attribute objects for the section's Item
ForEach(self.dataSource.objects(inSection: section)) { attribute in
Text("\(attribute.name)")
}
}
}
}
.listStyle(GroupedListStyle())
}
}
struct DynamicPredicate: View {
// Data source with a default fetch request for all Attribute's
@ObservedObject private var dataSource = CoreDataDataSource<Attribute>()
// State var for TextField input
@State private var searchText = ""
var body: some View {
VStack {
TextField("Enter Search Text", text: self.$searchText)
List {
Section(header: Text("Search Results for: '\(self.searchText)'"))
{
// Rebuilds the NSPredicate each time self.searchText changes
ForEach(self.dataSource
.predicate(NSPredicate(format: "name contains[c] %@", self.searchText))
.objects) { attribute in
Text("\(attribute.name)")
}
}
}
}
}
}
struct ChangingSortKey: View {
// Data source with a default fetch request for all Attribute's
@ObservedObject private var dataSource = CoreDataDataSource<Attribute>()
// State var to specify searching by name or by order
@State private var sortByOrder = true
var body: some View {
List {
Section(header: Text("Search Results by: '\(self.sortByOrder ? "order" : "name")'"))
{
// List shows all Attribute objects related to Item sorted by order or name
ForEach(self.dataSource
.sortKey1(self.sortByOrder ? "order" : "name")
.objects) { attribute in
Text("\(attribute.name)")
}
}
}
}
}
struct CoreDataViewer: View {
// Object passed in to be used as predicateObject
var entityDescription: NSEntityDescription
// Data source with a default fetch request for all Attribute's
@ObservedObject private var dataSource = CoreDataDataSource<NSManagedObject>()
var body: some View {
List {
Section(header: Text("All of: \(self.entityDescription.name!)")) {
// List shows all objects related to the entity description that was passed in
ForEach(self.dataSource
.entity(self.entityDescription)
.objects, id: \.self) { managedObject in
Text("\(managedObject.objectID)")
}
}
}
}
}
// MARK: Examples that do not use an NSFetchedResultsController
extension Item {
// Return a simple count of all Item objects
class func countItems() -> Int {
return CoreDataDataSource<Item>().count
}
// Return an array of all Item objects
class func allItemsInOrder() -> [Item] {
return CoreDataDataSource<Item>().fetch()
}
// Return an array of all Item objects where 'selected' is true
class func selectedItems() -> [Item] {
return CoreDataDataSource<Item>(predicate: NSPredicate(format:"selected = true")).fetch()
}
}
// MARK: Example that uses both NSFetchedResultsController methods and non-NSFetchedResultsController methods
struct ItemAttributesListView: View {
// Item passed in to be used as predicateObject
var target: Item
// Data source to fetch all Attribute's related to the Item passed in
// Group Attribute's for the Item by attributeGroupType
@ObservedObject private var dataSource =
CoreDataDataSource<Attribute>(sortKey1: "attributeType.attributeGroupType.order",
sortKey2: "attributeType.order",
sectionNameKeyPath: "attributeGroupTypeName",
predicateKey: "item")
var body: some View {
List {
// count will provide the number of objects that would be returned to the dataSource
if self.dataSource
.predicateObject(self.target)
.count > 0 {
// Should use the same datasource modifiers as used by the count
ForEach(self.dataSource
.predicateObject(self.target)
.sections, id: \.name) { section in
Section(header: Text(section.name)) {
// The inner ForEach loop provides the Attribute objects for the given AtteributeGroup
ForEach(self.dataSource.objects(inSection: section)) { attribute in
Text("\(attribute.name)")
}
}
}
} else {
Section(header: Text("There are no Attributes.")) {
EmptyView()
}
}
}
.listStyle(GroupedListStyle())
}
}
| true
|
c50bc4648cd4215b31575abc6f7254f2176ffcda
|
Swift
|
MFunZero/TasteStories
|
/CTDemo/CTView.swift
|
UTF-8
| 4,578
| 2.765625
| 3
|
[] |
no_license
|
//
// CTView.swift
// TasteStories
//
// Created by fanzz on 16/6/26.
// Copyright © 2016年 fanzz. All rights reserved.
//
import UIKit
import CoreText
/**
*使用时需要通过setter方法对texts进行赋值,默认是字体为竖直方向,文本较多时应该设置文本数组为一个,文本首行缩进的话需要在文本首行敲进去4个空格。
*/
class CTView: UIView {
private var isVertical:Bool = false
private var texts:[NSString] = ["岁月凝涵香,佛渡慈航","焚香祈愿,轻诉卷章","回望间,溢彷徨","诗意涟漪,纵生芸芸","前世今生,焉能忘?"]
private var font = UIFont(name: "Arial", size: 40)
func setIsVertical(flag:Bool){
self.isVertical = flag
}
func setTexts(flag:[NSString]){
self.texts = flag
}
func setFont(flag:UIFont){
self.font = flag
}
func insertEnterToString(text:String,index:Int)
{
let char = text.characters
var newchar:String = ""
for item in char{
newchar+="\(item)\n"
}
self.texts[index] = newchar
}
private var dataArr:NSMutableArray = NSMutableArray()
private var numArr:NSMutableArray = NSMutableArray()
private var textLayers:[CATextLayer] = [CATextLayer]()
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let textsCount = texts.count
for index in 0..<textsCount{
let delta = Double(NSEC_PER_SEC)*Double(index)*2.0
let dtime = dispatch_time(DISPATCH_TIME_NOW, Int64(delta))
dispatch_after(dtime,dispatch_get_main_queue() , {
Void in
print("1111:::延迟2秒执行")
let textLayer = CATextLayer()
self.textLayers.append(textLayer)
if self.isVertical {
self.insertEnterToString(self.texts[index] as String,index: index)
let width = self.frame.width/CGFloat(textsCount)
textLayer.frame = CGRect(x: self.frame.width-width*CGFloat(index+1), y:0, width: width, height: self.frame.height)
textLayer.alignmentMode = kCAAlignmentCenter
}else{
let height = self.frame.height/CGFloat(textsCount)
textLayer.frame = CGRect(x: 0, y:CGFloat(index)*height, width: self.frame.width, height: height)
textLayer.alignmentMode = kCAAlignmentJustified
}
self.layer.addSublayer(textLayer)
textLayer.wrapped = true
let str = self.texts[index]
let string = NSMutableAttributedString(string: str as String)
let fontName = self.font!.fontName
let fontSize = self.font!.pointSize
let fontRef = CTFontCreateWithName(fontName, fontSize, nil)
let attribs:[String:AnyObject] = [kCTForegroundColorAttributeName as String:UIColor.clearColor().CGColor,kCTFontAttributeName as String:fontRef]
string.addAttributes(attribs, range: NSMakeRange(0, str.length))
let arr = NSMutableArray(objects: fontRef,attribs,string,str,textLayer)
self.dataArr.addObject(arr)
let nums = NSMutableArray()
self.numArr.addObject(nums)
for i in 0..<str.length{
self.numArr[index].addObject(i)
self.performSelector(#selector(CTView.changeToBack(_:)), withObject:"\(index)",afterDelay: 0.1*Double(i))
}
})
}
}
func changeToBack(index:NSString)
{
let attr = dataArr[index.integerValue] as! NSMutableArray
let fontRef = attr[0]
let string = attr[2] as! NSMutableAttributedString
let num = numArr[index.integerValue].firstObject
let y = num as! Int
var attribs = attr[1] as! [String:AnyObject]
attribs = [kCTForegroundColorAttributeName as String:UIColor.blackColor().CGColor,kCTFontAttributeName as String:fontRef]
string.addAttributes(attribs , range: NSMakeRange(y, 1))
if numArr[index.integerValue].count > 1 {
numArr[index.integerValue].removeObjectAtIndex(0)
}
let textLayer:CATextLayer = dataArr[index.integerValue].lastObject as! CATextLayer
textLayer.string = string
}
}
| true
|
7f5f6561e5a70d515cfb3581c15efdf346c34593
|
Swift
|
timmybea/Advanced_iOS_Frameworks
|
/9_Protocol_Oriented_Programming/Real_World_POP/Real_World_POP/ViewController.swift
|
UTF-8
| 715
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Real_World_POP
//
// Created by Tim Beals on 2017-09-15.
// Copyright © 2017 Tim Beals. All rights reserved.
//
import UIKit
//The goal: We want to make some UI items 'shakeable'. That is to say, we want to choose which UI items have the animation, and we want to avoid repeating the same animation code.
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var shakeTextField: ShakeTextField!
override func viewDidLoad() {
super.viewDidLoad()
shakeTextField.delegate = self
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
shakeTextField.shake()
return true
}
}
| true
|
8f108c962845f62d1446e6be65d63b1cfb290204
|
Swift
|
coolryze/LeetCode
|
/Swift/powerful-integers.swift
|
UTF-8
| 615
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
class Solution {
func powerfulIntegers(_ x: Int, _ y: Int, _ bound: Int) -> [Int] {
var res = Set<Int>()
let logX = x != 1 ? Int((log(Double(bound)) / log(Double(x)))) + 1 : 1
let logY = y != 1 ? Int((log(Double(bound)) / log(Double(y)))) + 1 : 1
var powX = 1
for _ in 0..<logX {
var powY = 1
for _ in 0..<logY {
let val = powX + powY
if val <= bound {
res.insert(val)
}
powY *= y
}
powX *= x
}
return Array(res)
}
}
| true
|
615a84a78ee566e0db32dc8d744249b19922f73c
|
Swift
|
Toshiyana/Agora
|
/Algora/DashboardMainCell.swift
|
UTF-8
| 1,408
| 2.953125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Algora
//
// Created by Abdalla Elsaman on 3/4/20.
// Copyright © 2020 Dumbies. All rights reserved.
//
import SwiftUI
import UIKit.UIColor
struct DashboardMainCell: View {
var iconName: String
var status: String
var count: Int
var iconColor: Color
var body: some View {
// Button (action: {
//
// }) {
VStack(alignment: .leading) {
HStack {
Image(systemName: iconName)
.resizable()
.foregroundColor(iconColor)
.aspectRatio(contentMode: .fit)
.frame(width: 35)
Spacer()
Text("\(count)")
.font(.system(size: 30))
.fontWeight(.medium)
.foregroundColor(Color.init(.label))
}
Spacer()
Text(status)
.font(.system(size: 18))
.fontWeight(.medium)
.foregroundColor(Color.init(.systemGray))
}.padding()
// }
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
DashboardMainCell(iconName: "tray", status: "Today", count: 2, iconColor: Color.blue).previewLayout(.fixed(width: 200, height: 90))
}
}
| true
|
a3f392afd35ea8d66dce4feccc756920aceca219
|
Swift
|
lbatr3s/UnitConversion
|
/Unit Conversion/ContentView.swift
|
UTF-8
| 2,330
| 3.375
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Unit Conversion
//
// Created by Lester Batres on 1/23/20.
// Copyright © 2020 lester. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var inputUnit = 0
@State private var outputUnit = 1
@State private var length = "0"
let unitsDescription = ["Meters", "Kilometers", "Feet", "Yards", "Miles"]
let units = [UnitLength.meters, UnitLength.kilometers, UnitLength.feet, UnitLength.yards, UnitLength.miles]
var sourceLength: Measurement<UnitLength> {
let length = Double(self.length) ?? 0
let sourceUnit = units[inputUnit]
let sourceLenght = Measurement(value: length, unit: sourceUnit)
return sourceLenght
}
var destinationLength: Measurement<UnitLength> {
let destinationUnit = units[outputUnit]
let destinationLength = sourceLength.converted(to: destinationUnit)
return destinationLength
}
var body: some View {
NavigationView {
Form {
Section(header: Text("Source Unit")) {
Picker("Source unit", selection: $inputUnit) {
ForEach(0 ..< units.count) {
Text("\(self.unitsDescription[$0])")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Output Unit")) {
Picker("Output unit", selection: $outputUnit) {
ForEach(0 ..< units.count) {
Text("\(self.unitsDescription[$0])")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Enter length")) {
TextField("0", text: $length)
.keyboardType(.decimalPad)
}
Section(header: Text("Converted length")) {
Text("\(destinationLength.description)")
}
}
.navigationBarTitle("Unit Conversion")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
3804ef37bc853c64acd3c9d9b8a69a5e287d6b4b
|
Swift
|
DONGSHUER/InfoDay-SwiftUI
|
/InfoDaySwiftUI/MapView.swift
|
UTF-8
| 909
| 3.0625
| 3
|
[] |
no_license
|
//
// MapView.swift
// InfoDaySwiftUI
//
// Created by DONG SHUER on 28/11/2020.
//
import SwiftUI
import MapKit
struct MapView: View {
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 22.33787,
longitude: 114.18131
),
span: MKCoordinateSpan(
latitudeDelta: 0.005,
longitudeDelta: 0.005
)
)
var body: some View {
ZStack(alignment:.bottom){
Map(coordinateRegion: $region, showsUserLocation: true)
.edgesIgnoringSafeArea(.all)
Button("Move") {
withAnimation {
region.center = CLLocationCoordinate2D(
latitude: 22.33787,
longitude: 114.18131
)
}
}
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.