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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
383c1db62b6123a5558110a50128271955c11eba
|
Swift
|
tarshadesouza/RecipePuppy
|
/RecipePuppyTest/Model/Recipe.swift
|
UTF-8
| 526
| 2.6875
| 3
|
[] |
no_license
|
//
// Recipe.swift
// RecipePuppyTest
//
// Created by Tarsha De Souza on 06/08/2019.
// Copyright © 2019 Tarsha De Souza. All rights reserved.
//
import Foundation
import SwiftyJSON
struct Recipe {
public private(set) var ingredients : String?
public private(set) var title: String?
public private(set) var thumbnailUrl: String?
init(result: [String:String]) {
self.ingredients = result["ingredients"]
self.title = result["title"]
self.thumbnailUrl = result["thumbnail"]
}
}
| true
|
a6d4e33bcc3daef1ca20278d09a62e9984cfc869
|
Swift
|
stampcjw/YelloShut
|
/YelloShuttle/Structure/DriverInfo.swift
|
UTF-8
| 778
| 2.84375
| 3
|
[] |
no_license
|
//
// DriverInfo.swift
// YelloShuttle
//
// Created by Chadoli on 2020/11/05.
//
import UIKit
//struct DriverInfo {
// var driverPicture: UIImage
// var driverName: String
// var driverNumber: String
// var driverCarNumber: String
// var academy: String
//}
class DriverInfo {
var driverPicture: UIImage!
var driverName: String!
var driverNumber: String!
var driverCarNumber: String!
var academy: String!
init(driverPicture: UIImage, driverName: String, driverNumber: String, driverCarNumber: String, academy: String) {
self.driverPicture = driverPicture
self.driverName = driverName
self.driverNumber = driverNumber
self.driverCarNumber = driverCarNumber
self.academy = academy
}
}
| true
|
07c4092c4c64edbd0e0a00896db524ad6bf91d7b
|
Swift
|
lawrenceherman/sort-gauge
|
/sort/DataStructures/DoublyLL.swift
|
UTF-8
| 4,315
| 3.765625
| 4
|
[] |
no_license
|
//
// linkedlist.swift
// sort
//
// Created by Lawrence Herman on 11/13/18.
// Copyright © 2018 Lawrence Herman. All rights reserved.
//
// class DoublyLLNode<T> where T: Equatable {
class DoublyLLNode<T: Comparable> {
var value: T
var next: DoublyLLNode?
var previous: DoublyLLNode?
init(value: T) {
self.value = value
}
}
extension DoublyLLNode: Comparable {
static func == (lhs: DoublyLLNode<T>, rhs: DoublyLLNode<T>) -> Bool {
return lhs.value == rhs.value
}
static func < (lhs: DoublyLLNode<T>, rhs: DoublyLLNode<T>) -> Bool {
return lhs.value < rhs.value
}
}
//// struct vs class for iterator
//class DoublyLLIterator<T: Comparable> : IteratorProtocol {
//
// typealias Element = DoublyLLNode<T>
// var currentNode: Element?
//
// init(startNode: Element?) {
// print("DoubleLLIterator init" )
// currentNode = startNode
// }
//
// func next() -> DoublyLLIterator.Element? {
// print("DoublyLLNext")
// let node = currentNode
// currentNode = currentNode?.next
// return node
// }
//}
//extension DoublyLL : Sequence {
// typealias Iterator = DoublyLLIterator<T>
//
// func makeIterator() -> DoublyLLIterator<T> {
// return DoublyLLIterator(startNode: head)
// }
//}
class DoublyLL<T: Comparable> {
typealias Node = DoublyLLNode<T>
//see of typealias works better
var head: Node?
var tail: Node?
//addTo Head
func prepend(value: T) {
let newNode = Node(value: value)
if let currentHead = head {
newNode.next = currentHead
currentHead.previous = newNode
} else {
tail = newNode
}
head = newNode
}
//addTo Tail
func append(value: T) {
let newNode = Node(value: value)
if let currentTail = tail {
newNode.previous = currentTail
currentTail.next = newNode
} else {
head = newNode
}
tail = newNode
}
var first: Node? {
print("first")
return head
}
//
// // need last?
//
// var count: Int {
//
// //possible O(1) by keeping track with adds and removes
// print("count")
// guard var currentHead = head else { return 0 }
//
// var count = 1
// while let next = currentHead.next {
// count += 1
// currentHead = next
// }
//
// return count
// }
//
// var isEmpty: Bool {
// print("isEmpty")
// return head == nil
// }
}
extension DoublyLL : Collection {
typealias Element = DoublyLLNode<T>
// public typealias Index = Int
// make value the Element?
var startIndex: Int {
print("start index")
return 0
}
//check if isEmpty accounts for no items
var endIndex: Int {
print("end index")
return count
}
subscript(position: Int) -> Node {
// trouble working with any unwrapping condition here without optional return
// does it matter which error? subscript out of range causes runtime anyways
if position == 0 {
print("subscript = 0")
return first!
} else {
var node = first!.next
for _ in 1..<position {
print("subscript cycle")
node = node?.next
if node == nil {
break
}
}
return node!
}
}
//could change above with this to return a value instead of a node
// public subscript(index: Int) -> T {
// let node = node(atIndex: index)
// return node.value
// }
func index(after i: Int) -> Int {
print("index after")
return i + 1
}
}
// source
//@inlinable
//public var isEmpty: Bool {
// return startIndex == endIndex
//}
//@inlinable
//public var first: Element? {
// let start = startIndex
// if start != endIndex { return self[start] }
// else { return nil }
//}
//@inlinable
//public var count: Int {
// return distance(from: startIndex, to: endIndex)
//}
//@inlinable
//public func map<T>(
// _ transform: (Element) throws -> T
// ) rethrows -> [T] {
// // TODO: swift-3-indexing-model - review the following
// let n = self.count
// if n == 0 {
// return []
// }
//
// var result = ContiguousArray<T>()
// result.reserveCapacity(n)
//
// var i = self.startIndex
//
// for _ in 0..<n {
// result.append(try transform(self[i]))
// formIndex(after: &i)
// }
//
// _expectEnd(of: self, is: i)
// return Array(result)
//}
| true
|
aff6e2ac1186f71583c0b62af12ec5bf0a2187bb
|
Swift
|
azuredark/RxFeedExample
|
/RxFeedExample/Models/FeedItem.swift
|
UTF-8
| 679
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
import RxDataSources
struct FeedItem: IdentifiableType, Equatable {
let id: Int
let title: String
let image: URL
let author: String
let whenCreated: String
let distance: String
let address: String
let avatar: URL
let liked: Bool
var identity: Int {
return id
}
}
extension FeedItem {
func copy(liked: Bool) -> FeedItem {
return FeedItem(
id: id,
title: title,
image: image,
author: author,
whenCreated: whenCreated,
distance: distance,
address: address,
avatar: avatar,
liked: liked
)
}
}
| true
|
db4050439751c871ca1e5e35ac8e84886eac1717
|
Swift
|
AtchuChitri/Array-Data-Structure-
|
/StringDataStructure/FizzBuzz.playground/Contents.swift
|
UTF-8
| 629
| 3.84375
| 4
|
[] |
no_license
|
import UIKit
//main idea behind this is to handle multple of 3 and multiple of 5 spapartely but handaling of both 3 and 5 before them idiviually if n is less or equal to 0 the return
//method 1
func getFizBuzz(n:Int){
for i in 1...n{//loop till n
if i%3 == 0 && i%5 == 0 {//check module devide by 3 & 5
print("Fizz Buzz")
}
else if i%3 == 0 { //check module devide by 3
print("Fizz")
}
else if i%5 == 0 {//check module devide by 5
print("Buzz")
}
else{
print(i)
}
}
}
getFizBuzz(n: 15)
| true
|
cf7a35f34f56fd358ee3c80be8e6f6516e4c79df
|
Swift
|
btc/allegro
|
/allegro/Audio.swift
|
UTF-8
| 9,915
| 3.15625
| 3
|
[] |
no_license
|
//
// Audio.swift
// allegro
//
// Created by Brian Tiger Chow on 1/27/17.
// Copyright © 2017 gigaunicorn. All rights reserved.
//
import AudioKit
import Rational
import MusicKit
import SwiftyTimer
protocol AudioObserver: class {
func audioPlaybackChanged(playing: Bool)
func audioPositionChanged(measure: Int, position: Rational)
}
extension AudioObserver {
func audioPlaybackChanged(playing: Bool) {
// default impl
}
func audioPositionChanged(measure: Int, position: Rational) {
// default impl
}
}
private class Weak {
private(set) weak var value: AudioObserver?
init(_ value: AudioObserver?) {
self.value = value
}
}
fileprivate struct TrackElem {
var measureIndex: Int
var measurePosition: Rational // may be freepace or note
var midiPitch: UInt8? // if nil don't play anything
var waitTime: TimeInterval // seconds
}
// Takes the Part and builds a MIDI track just like a sequencer
// Each TrackElem is played according to the timing using the sampler
class Audio {
// minimum step with 1/64 notes (leftover from double-dotted 1/16 note)
private static let minimumDuration: Rational = 1/64
var isPlaying: Bool = false {
didSet {
if !isPlaying {
currentMeasure = nil
currentPosition = nil
}
notifyPlaybackChanged()
}
}
private var currentMeasure: Int? {
didSet {
notifyPositionChanged()
}
}
private var currentPosition: Rational? {
didSet {
notifyPositionChanged()
}
}
private let sampler: AKMIDISampler = AKMIDISampler()
private let mixer: AKMixer
private var observers: [Weak] = [Weak]()
init() {
self.sampler.name = "piano"
self.mixer = AKMixer(sampler)
mixer.volume = 1.0
// TODO audio engineering to make it sound better
AudioKit.output = mixer
// load the sample
guard let _ = try? self.sampler.loadWav("FM Piano") else {
Log.error?.message("Unable to load FM Piano wav from bundle")
return
}
}
func start() {
AudioKit.start()
}
func subscribe(_ observer: AudioObserver) {
observers.append(Weak(observer))
}
func unsubscribe(_ observer: AudioObserver) {
observers = observers.filter { observer in
guard let value = observer.value else { return false } // prune released objects
return value !== observer
}
}
// general notification must always be sent to observers
private func notifyPlaybackChanged() {
// prunes released objects as it iterates
observers = observers.filter { observer in
guard let value = observer.value else { return false }
value.audioPlaybackChanged(playing: self.isPlaying)
return true
}
}
private func notifyPositionChanged() {
observers = observers.filter { observer in
guard let value = observer.value else { return false }
guard let measure = self.currentMeasure else { return true }
guard let position = self.currentPosition else { return true }
value.audioPositionChanged(measure: measure, position: position)
return true
}
}
// convert duration into the amount to time we have to wait
// eg.
// 1/4 note in 4/4 time -> 1/4 * 4 -> 1 beat
// 120 bpm / 60 = 2 beats per second -> 0.5 seconds per beat
func calcWaitTime(duration: Rational, tempo: Double, beat: Int) -> TimeInterval {
return (duration * Rational(beat)).double / (tempo / 60)
}
// play just this note
private func playPitch(pitch: UInt8) {
// TODO investigate channels
sampler.play(noteNumber: MIDINoteNumber(pitch), velocity: 100, channel: 0)
}
// loop and play each note
// tempo is in beats per minute
// beat the note that gets the beat (denominator of time signature)
private func play(track: [TrackElem], tempo: Double, beat: Int) {
self.isPlaying = true
var trackElemIterator = track.makeIterator()
var currStartTime = Date.distantPast // time that curr note was played
var currWait: TimeInterval = 0 // time to wait until next note
let step = calcWaitTime(duration: Audio.minimumDuration, tempo: tempo, beat: beat)
Timer.every(step.seconds) { (timer: Timer) -> Void in
if !self.isPlaying {
Log.info?.message("Audio playback interrupted, stopping timer")
timer.invalidate()
return
}
if (Date().timeIntervalSince(currStartTime) >= currWait) {
// pop next track elem
guard let trackElem = trackElemIterator.next() else {
Log.info?.message("Audio playback done, stopping timer")
timer.invalidate()
self.isPlaying = false
return
}
// update state
self.currentMeasure = trackElem.measureIndex
self.currentPosition = trackElem.measurePosition
if let midiPitch = trackElem.midiPitch {
// play unless nil (for rests and freespace)
self.playPitch(pitch: midiPitch)
}
currStartTime = Date()
currWait = trackElem.waitTime
}
}
}
// load all notes and freespaces into the track
private func build(part: Part, startMeasureIndex: Int, tempo: Double, beat: Int) -> [TrackElem] {
var track = [TrackElem]()
let endMeasure = findEndMeasure(part: part)
for index in stride(from: startMeasureIndex, to: endMeasure, by: 1) {
let m = part.measures[index]
var currPos: Rational = 0
while currPos < m.timeSignature {
var duration: Rational = 0
var midiPitch: UInt8?
if let note = m.note(at: currPos) {
duration = note.duration
if !note.rest {
midiPitch = note.midiPitch
}
} else if let freePos = m.freespace(at: currPos) {
duration = freePos.duration
} else {
Log.error?.message("building audio track: current position is neither a note nor free!")
}
// convert duration into the amount to time we have to wait
let waitTime = calcWaitTime(duration: duration, tempo: tempo, beat: beat)
// add this note to the track without pitch so we don't play it
track.append(TrackElem(measureIndex: index,
measurePosition: currPos,
midiPitch: midiPitch, // nil for rest or freespace
waitTime: waitTime))
currPos = currPos + duration
}
}
return track
}
// find the last non-empty measure
private func findEndMeasure(part: Part) -> Int {
var endMeasure = part.measures.count - 1
for index in stride(from: part.measures.count - 1, through: 0, by: -1) {
if part.measures[index].notes.count > 0 {
return endMeasure
} else {
endMeasure = index
}
}
return endMeasure
}
// play a single note
func playNote(part: Part, measure: Int, position: Rational) {
if let note = part.measures[measure].note(at: position) {
playPitch(pitch: note.midiPitch)
}
}
// build the track and play from the current measure
// the block is called on current measure and current note position
func playFromCurrentMeasure(part: Part, measure: Int) {
let tempo = Double(part.tempo)
let beat = part.timeSignature.denominator
let track = build(part: part, startMeasureIndex: measure, tempo: tempo, beat: beat)
play(track: track, tempo: tempo, beat: beat)
}
}
fileprivate extension Note {
var midiPitch: UInt8 {
var chroma: Chroma = .c
var octave = self.octave
switch self.accidental {
case .sharp:
switch self.letter {
case .A:
chroma = .as
case .B:
chroma = .c
octave = self.octave + 1
case .C:
chroma = .cs
case .D:
chroma = .ds
case .E:
chroma = .f
case .F:
chroma = .fs
case .G:
chroma = .gs
}
case .flat:
switch self.letter {
case .A:
chroma = .gs
case .B:
chroma = .as
case .C:
chroma = .b
octave = self.octave - 1
case .D:
chroma = .cs
case .E:
chroma = .ds
case .F:
chroma = .e
case .G:
chroma = .fs
}
case .natural:
switch self.letter {
case .A:
chroma = .a
case .B:
chroma = .b
case .C:
chroma = .c
case .D:
chroma = .d
case .E:
chroma = .e
case .F:
chroma = .f
case .G:
chroma = .g
}
default: break // doubles
}
return UInt8(Pitch(chroma: chroma, octave: UInt(octave)).midi)
}
}
| true
|
39cbf014de4baa0fa04b2295c3704d7d08e9b294
|
Swift
|
Henrikh91/RaketaSampleCode
|
/RaketaSampleCode/Common/RequestDataProvider.swift
|
UTF-8
| 806
| 2.828125
| 3
|
[] |
no_license
|
//
// RequestDataProvider.swift
// RaketaSampleCode
//
// Created by hvk on 18.02.2021.
//
import Foundation
public typealias Parameters = [String: String]
public protocol RequestDataProvider {
var baseUrl: URL { get }
var path: String { get }
var method: HTTP.Method { get }
var parameters: Parameters? { get }
}
public extension RequestDataProvider {
var baseUrl: URL {
URLComponents.reddit.url!
}
var method: HTTP.Method {
return .get
}
var parameters: Parameters? {
return nil
}
var url: URL {
return baseUrl.absoluteURL.appendingPathComponent(path)
}
func request() -> URLRequest? {
URLComponents(url: url, resolvingAgainstBaseURL: false)?.request(by: method, parameters: parameters)
}
}
| true
|
448bb7c5d66bc767a2ef594fb1fbfb12c19da9b2
|
Swift
|
labman010/Mydays
|
/MyDay/KindController.swift
|
UTF-8
| 4,378
| 2.859375
| 3
|
[] |
no_license
|
//
// KindController.swift
// demo1
//
// Created by kurisu on 2017/12/20.
// Copyright © 2017年 Apple Inc. All rights reserved.
//
import UIKit
@IBDesignable class KindController: UIStackView {
private var KindButtons = [UIButton]()
var kind = -1 {
didSet {
updateButtonSelectionStates()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupButtons()
}
private func setupButtons() {
for button in KindButtons {
removeArrangedSubview(button)
button.removeFromSuperview()
}
KindButtons.removeAll()
let bundle = Bundle(for: type(of: self))
let face0 = UIImage(named: "smile", in: bundle, compatibleWith: self.traitCollection)
let face1 = UIImage(named: "cry", in: bundle, compatibleWith: self.traitCollection)
let face2 = UIImage(named: "feelnothing", in: bundle, compatibleWith: self.traitCollection)
let face3 = UIImage(named: "sweet", in: bundle, compatibleWith: self.traitCollection)
let face4 = UIImage(named: "angry", in: bundle, compatibleWith: self.traitCollection)
let downface = UIImage(named: "too-cry", in: bundle, compatibleWith: self.traitCollection)
let too_face0 = UIImage(named: "too-smile", in: bundle, compatibleWith: self.traitCollection)
let too_face1 = UIImage(named: "too-cry", in: bundle, compatibleWith: self.traitCollection)
let too_face2 = UIImage(named: "too-feelnothing", in: bundle, compatibleWith: self.traitCollection)
let too_face3 = UIImage(named: "too-sweet", in: bundle, compatibleWith: self.traitCollection)
let too_face4 = UIImage(named: "too-angry", in: bundle, compatibleWith: self.traitCollection)
var x=0
for _ in 0..<5{
let button = UIButton()
switch x
{
case 0: button.setImage(face0 , for: .normal)
case 1: button.setImage(face1 , for: .normal)
case 2: button.setImage(face2 , for: .normal)
case 3: button.setImage(face3 , for: .normal)
case 4: button.setImage(face4 , for: .normal)
default:
print("error!")
}
switch x
{
case 0: button.setImage(too_face0, for: .selected)
case 1: button.setImage(too_face1 , for: .selected)
case 2: button.setImage(too_face2 , for: .selected)
case 3: button.setImage(too_face3 , for: .selected)
case 4: button.setImage(too_face4 , for: .selected)
default:
print("error!")
}
// button.setImage(downface, for: .highlighted)
// button.setImage(downface, for: [.highlighted, .selected])
// button.backgroundColor = UIColor.brown
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
button.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
button.addTarget(self, action: #selector(KindController.KindButtonTapped(button:)), for: .touchUpInside)
addArrangedSubview(button)
KindButtons.append(button)
x=x+1
}
updateButtonSelectionStates()
}
//action
func KindButtonTapped(button: UIButton) {
guard let index = KindButtons.index(of: button) else {
fatalError("The button, \(button), is not in the kindButtons array: \(KindButtons)")
}
switch index {
case 0:
print("0 pressed ");kind=0
case 1:
print("1 pressed ");kind=1
case 2:
print("2 pressed ");kind=2
case 3:
print("3 pressed ");kind=3
case 4:
print("4 pressed ");kind=4
default:
print(" face error ");
}
}
private func updateButtonSelectionStates() {
for (index, button) in KindButtons.enumerated()
{
button.isSelected=index==kind
}
}
}
| true
|
cd3447400270021158d636f9721531c762aa863b
|
Swift
|
igniti0n/iOS-WeatherApp-SwiftUI
|
/WeatherAppSwitUI/Models/Weather.swift
|
UTF-8
| 1,899
| 3.234375
| 3
|
[] |
no_license
|
//
// Weather.swift
// WeatherAppSwitUI
//
// Created by Ivan Stajcer on 06.10.2021..
//
import Foundation
import Foundation
struct Weather: Codable {
var temperature: Double
var minTemperature: Double
var maxTemperature: Double
var humidity: Double
var pressure: Double
var windSpeed: Double
var conditionId: Int
var name: String
static let dummyWeather = Weather(temperature: 44, minTemperature: 10, maxTemperature: 10, humidity: 10, pressure: 10, windSpeed: 10, conditionId: 800, name: "London")
static func fromJson(map: [String:Any]) -> Weather? {
guard
let weatherDictonaryArray = map["weather"] as? [Any],
let weatherDictonary = weatherDictonaryArray.first as? [String:Any],
let mainDictonary = map["main"] as? [String: Any],
let windDictonary = map["wind"] as? [String: Any],
let name = map["name"] as? String
else{
return nil
}
guard
let temp = mainDictonary["temp"] as? Double,
let minTemp = mainDictonary["temp_min"] as? Double,
let maxTemp = mainDictonary["temp_max"] as? Double,
let pressure = mainDictonary["pressure"] as? Double,
let humidity = mainDictonary["humidity"] as? Double,
let id = weatherDictonary["id"] as? Int,
let wind = windDictonary["speed"] as? Double
else{
return nil
}
return Weather(temperature: temp, minTemperature: minTemp, maxTemperature: maxTemp, humidity: humidity, pressure: pressure, windSpeed: wind, conditionId: id, name: name)
}
static func fromData(data: Data) -> Weather? {
let encoder = JSONDecoder()
return try? encoder.decode(Weather.self, from: data)
}
func toData() -> Data?{
let encoder = JSONEncoder()
return try? encoder.encode(self)
}
}
| true
|
22d7a2bfd51e59fc0fe8bef0f6c7d0bc384cacf2
|
Swift
|
tienan-git/bukuma-ios
|
/Bukuma_ios_swift/BarButtonItem.swift
|
UTF-8
| 4,431
| 2.671875
| 3
|
[] |
no_license
|
//
// BKMBarButtonItem.swift
// Bukuma_ios_swift
//
// Created by Hiroshi Chiba on 2016/03/07.
// Copyright © 2016年 Hiroshi Chiba. All rights reserved.
//
// ButtonItem クラス。基本的にこれを使う
private let BarButtonItemButtonBoldFontSize = UIFont.boldSystemFont(ofSize: 16)
private let BarButtonItemStartButtonBoldFontSize = UIFont.boldSystemFont(ofSize: 15)
private let BarButtonItemButtonNormalFontSize = UIFont.systemFont(ofSize: 16)
private let BarButtonItemMargin: CGFloat = 10
private let BarButtonItemStartButtonHeight: CGFloat = 30
private class BarButtonItemButton : UIButton{
override init(frame: CGRect) {
super.init(frame: CGRect.zero)
self.setTitleColor(UIColor.white, for: UIControlState.normal)
self.setTitleColor(UIColor.white, for: UIControlState.highlighted)
self.setTitleColor(UIColor.white.withAlphaComponent(0.5), for: UIControlState.disabled)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
open class BarButtonItem: UIBarButtonItem {
open class func barButtonItemWithText(_ text:String, isBold:Bool, isLeft:Bool, target:AnyObject, action:Selector) ->BarButtonItem {
let font = isBold ? BarButtonItemButtonBoldFontSize : BarButtonItemButtonNormalFontSize
let button: BarButtonItemButton = BarButtonItemButton.init(frame: CGRect.zero)
button.frame = CGRect(x: 0, y: 0, width: text.getTextWidthWithFont(font, viewHeight: 20) + 20, height: kCommonNavigationBarHeight)
button.titleLabel!.font = font
button.setTitle(text, for: UIControlState.normal)
button.titleLabel!.textAlignment = isLeft ? NSTextAlignment.left : NSTextAlignment.right
button.isExclusiveTouch = true
button.titleEdgeInsets = UIEdgeInsetsMake(0, 25 * (isLeft ? -1 : 0), 0, 25 * (isLeft ? 0 : -1))
button.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
return BarButtonItem.init(customView: button)
}
open class func barButtonItemWithText(_ text:String, s_text:String, isBold:Bool, isLeft:Bool, target:AnyObject, action:Selector) ->BarButtonItem {
let font = isBold ? BarButtonItemButtonBoldFontSize : BarButtonItemButtonNormalFontSize
let button: BarButtonItemButton = BarButtonItemButton.init(frame: CGRect.zero)
button.frame = CGRect(x: 0, y: 0, width: text.getTextWidthWithFont(font, viewHeight: 20) + 20, height: kCommonNavigationBarHeight)
button.titleLabel!.font = font
button.setTitle(text, for: UIControlState.normal)
button.setTitle(s_text, for: UIControlState.selected)
button.titleLabel!.textAlignment = isLeft ? NSTextAlignment.left : NSTextAlignment.right
button.isExclusiveTouch = true
button.titleEdgeInsets = UIEdgeInsetsMake(0, 25 * (isLeft ? -1 : 0), 0, 25 * (isLeft ? 0 : -1))
button.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
return BarButtonItem.init(customView: button)
}
open class func barButtonItemWithImage(_ image:UIImage, isLeft:Bool, target:AnyObject, action:Selector) ->BarButtonItem {
let button: BarButtonItemButton = BarButtonItemButton.init(frame: CGRect.zero)
button.frame = CGRect(x: 0, y: 0, width: image.size.width + 20 , height: image.size.height + 20)
button.setImage(image, for: UIControlState.normal)
button.isExclusiveTouch = true
button.imageEdgeInsets = UIEdgeInsetsMake(0, 44 * (isLeft ? -1 : 0), 0, 44 * (isLeft ? 0 : -1))
button.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
return BarButtonItem.init(customView: button)
}
open class func backButton(_ image:UIImage, target:AnyObject, action:Selector) ->BarButtonItem {
let button: BarButtonItemButton = BarButtonItemButton.init(frame: CGRect.zero)
button.frame = CGRect(x: 0, y: 0, width: image.size.width + 20 , height: image.size.height + 20)
button.setImage(image, for: UIControlState.normal)
button.isExclusiveTouch = true
button.imageEdgeInsets = UIEdgeInsetsMake(0, 34 * -1, 0, 44 * 0 )
button.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
return BarButtonItem.init(customView: button)
}
}
| true
|
01394d42bcd7d13d2ac714de860171c8fd59e4d4
|
Swift
|
aepryus/Acheron
|
/Sources/Acheron/Interface/Screen.swift
|
UTF-8
| 6,934
| 2.53125
| 3
|
[] |
no_license
|
//
// Screen.swift
// Acheron
//
// Created by Joe Charlier on 10/15/20.
// Copyright © 2020 Aepryus Software. All rights reserved.
//
#if canImport(UIKit)
import UIKit
public class Screen {
static let current: Screen = Screen()
public enum Model {
case iPhone, iPad, mac, other
}
public enum Dimensions {
case dim320x480, // 0.67 - original
dim320x568, dim375x667, dim414x736, // 0.56 - iPhone 5
dim360x780, dim375x812, dim390x844, dim393x852, dim414x896, dim428x926, dim430x932, // 0.46 - iPhone X
dim1024x768, dim1080x810, dim1112x834, dim1366x1024, // 1.33 - original iPad
dim1180x820, dim1194x834, // 1.43 - iPad 11"
dim1133x744, // 1.52 - iPad Mini 6th gen
dimOther
}
public enum Ratio: CaseIterable {
case rat067, rat056, rat046, rat133, rat143, rat152, other
var ratio: CGFloat {
switch self {
case .rat067: return 0.67
case .rat056: return 0.56
case .rat046: return 0.46
case .rat133: return 1.33
case .rat143: return 1.43
case .rat152: return 1.52
case .other: return 1.00
}
}
}
let model: Model
let dimensions: Dimensions
let ratio: Ratio
let width: CGFloat
let height: CGFloat
let s: CGFloat
let scaler: CGFloat
init() {
#if targetEnvironment(macCatalyst)
if UIScreen.main.bounds.width <= 1800 {
scaler = 1
} else {
scaler = 0.77
}
model = .mac
dimensions = .dim1194x834
ratio = .rat143
width = UIApplication.shared.windows.first?.width ?? 1194 / scaler
height = UIApplication.shared.windows.first?.height ?? 834 / scaler
s = 790 / 748 / scaler
#else
scaler = 1
if UIDevice.current.userInterfaceIdiom == .phone {
model = .iPhone
} else if UIDevice.current.userInterfaceIdiom == .pad {
model = .iPad
} else {
model = .other
}
let dw: CGFloat = UIScreen.main.bounds.size.width
let dh: CGFloat = UIScreen.main.bounds.size.height
let w: CGFloat = model == .iPhone ? min(dw, dh) : max(dw, dh)
let h: CGFloat = model == .iPhone ? max(dw, dh) : min(dw, dh)
if w == 320 && h == 480 { dimensions = .dim320x480; ratio = .rat067 }
else if w == 320 && h == 568 { dimensions = .dim320x568; ratio = .rat056 }
else if w == 375 && h == 667 { dimensions = .dim375x667; ratio = .rat056 }
else if w == 414 && h == 736 { dimensions = .dim414x736; ratio = .rat056 }
else if w == 360 && h == 780 { dimensions = .dim360x780; ratio = .rat046 }
else if w == 375 && h == 812 { dimensions = .dim375x812; ratio = .rat046 }
else if w == 390 && h == 844 { dimensions = .dim390x844; ratio = .rat046 }
else if w == 414 && h == 896 { dimensions = .dim414x896; ratio = .rat046 }
else if w == 428 && h == 926 { dimensions = .dim428x926; ratio = .rat046 }
else if w == 1024 && h == 768 { dimensions = .dim1024x768; ratio = .rat133 }
else if w == 1080 && h == 810 { dimensions = .dim1080x810; ratio = .rat133 }
else if w == 1112 && h == 834 { dimensions = .dim1112x834; ratio = .rat133 }
else if w == 1366 && h == 1024 { dimensions = .dim1366x1024; ratio = .rat133 }
else if w == 1180 && h == 820 { dimensions = .dim1180x820; ratio = .rat143 }
else if w == 1194 && h == 834 { dimensions = .dim1194x834; ratio = .rat143 }
else if w == 1133 && h == 744 { dimensions = .dim1133x744; ratio = .rat152 }
else {
dimensions = .dimOther
let r: CGFloat = w/h
var minDelta: CGFloat = 9
var closest: Ratio = .rat067
Ratio.allCases.forEach {
let delta: CGFloat = abs(1 - r/$0.ratio)
if delta < minDelta {
minDelta = delta
closest = $0
}
}
ratio = closest
}
width = w
height = h
s = model == .iPhone ? width / 375 : height / 768
#endif
}
// Static ==========================================================================================
public static var model: Model { current.model }
public static var dimensions: Dimensions { current.dimensions }
public static var ratio: Ratio { current.ratio }
public static var width: CGFloat { current.width }
public static var height: CGFloat { current.height }
public static var size: CGSize { CGSize(width: width, height: height) }
public static var s: CGFloat { current.s }
public static var scaler: CGFloat { current.scaler }
public static var scale: CGFloat { UIScreen.main.scale}
public static func snapToPixel(_ x: CGFloat) -> CGFloat { ceil(x*scale)/scale }
public static var iPhone: Bool { current.model == .iPhone }
public static var iPad: Bool { current.model == .iPad }
public static var mac: Bool { current.model == .mac }
public static var bounds: CGRect { CGRect(x: 0, y: 0, width: width, height: height) }
public static var safeTop: CGFloat {
guard let window = Screen.keyWindow else { fatalError() }
return window.safeAreaInsets.top
}
public static var safeBottom: CGFloat {
guard let window = Screen.keyWindow else { fatalError() }
return window.safeAreaInsets.bottom
}
public static var safeLeft: CGFloat {
guard let window = Screen.keyWindow else { fatalError() }
return window.safeAreaInsets.left
}
public static var safeRight: CGFloat {
guard let window = Screen.keyWindow else { fatalError() }
return window.safeAreaInsets.right
}
public static var navBottom: CGFloat { Screen.safeTop + 44 }
public static var keyWindow: UIWindow? {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
#endif
| true
|
dd5d45f34fcad3315928b05c370adaef1f55eb22
|
Swift
|
evrimfeyyaz/ah-guest-client-ios
|
/Guest Client/Views/RSItemDetailView.swift
|
UTF-8
| 2,988
| 2.5625
| 3
|
[] |
no_license
|
//
// RSItemDetailView.swift
// Guest Client
//
// Created by Evrim Persembe on 4/22/17.
// Copyright © 2017 Automated Hotel. All rights reserved.
//
import UIKit
import TagListView
class RSItemDetailView: UIView {
// MARK: - Public properties
let itemTitleLabel = StyledLabel(withStyle: .title1)
let tagListView = TagListView()
let tagCellIdentifier = "TagCell"
let itemPriceLabel = StyledLabel(withStyle: .price)
let itemDescriptionLabel = StyledLabel(withStyle: .body)
// MARK: - Private properties
private let centerStackView = UIStackView()
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View configuration
private func configureView() {
configureTitleLabel()
configureDescriptionLabel()
configureTagListView()
configureCenterStackView()
configureOuterStackView()
}
private func configureTagListView() {
tagListView.textFont = ThemeFonts.dynamicEquivalent(ofFont: ThemeFonts.oswaldRegular, withSize: 14)
tagListView.textColor = ThemeColors.darkBlue
tagListView.tagBackgroundColor = .white
tagListView.paddingX = 10
tagListView.paddingY = 5
tagListView.marginX = 5
tagListView.marginY = 10
tagListView.cornerRadius = tagListView.textFont.pointSize / 1.5
tagListView.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
}
private func configureCenterStackView() {
centerStackView.addArrangedSubview(tagListView)
centerStackView.addArrangedSubview(itemPriceLabel)
centerStackView.distribution = .fill
centerStackView.alignment = .center
}
private func configureOuterStackView() {
let outerStackView = UIStackView(arrangedSubviews: [itemTitleLabel, centerStackView, itemDescriptionLabel])
outerStackView.axis = .vertical
outerStackView.spacing = 6
addSubview(outerStackView)
outerStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
outerStackView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor, constant: 10),
outerStackView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor, constant: -10),
outerStackView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor, constant: 15),
outerStackView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor, constant: -30)
])
}
private func configureTitleLabel() {
itemTitleLabel.numberOfLines = 0
}
private func configureDescriptionLabel() {
itemDescriptionLabel.numberOfLines = 0
}
}
| true
|
89a239a90f97a40d94cd6ab317d567a16fbd57c1
|
Swift
|
artemmakaroff/NodeKitPlayground
|
/NodeKitPlayground.playground/Contents.swift
|
UTF-8
| 2,298
| 3.21875
| 3
|
[] |
no_license
|
import NodeKit
import UIKit
// MARK: - Constants
enum Constants {
static let url = "https://sentim-api.herokuapp.com/api/v1/"
static let text = "We have been through much darker times than these, and somehow each generation of Americans carried us through to the other side, he said."
}
enum RequestKeys {
static let text = "text"
}
// MARK: - Errors
enum CustomError: Error {
case badURL
}
// MARK: - Extensions
extension URL {
static func from(string: String) throws -> URL {
guard let url = URL(string: string) else {
throw CustomError.badURL
}
return url
}
}
// MARK: - Entities
struct SentimEntity: DTODecodable {
let result: TextScanEntity
let sentences: [SentenceEntity]
static func from(dto: SentimEntry) throws -> SentimEntity {
return try .init(result: .from(dto: dto.result), sentences: dto.sentences.map { try .from(dto: $0) })
}
}
struct TextScanEntity: DTODecodable {
let polarity: Double
let type: String
static func from(dto: TextScanEntry) throws -> TextScanEntity {
return .init(polarity: dto.polarity, type: dto.type)
}
}
struct SentenceEntity: DTODecodable {
let sentence: String
let sentiment: TextScanEntity
static func from(dto: SentenceEntry) throws -> SentenceEntity {
return try .init(sentence: dto.sentence, sentiment: .from(dto: dto.sentiment))
}
}
// MARK: - Entries
struct SentimEntry: Codable, RawMappable {
typealias Raw = Json
let result: TextScanEntry
let sentences: [SentenceEntry]
}
struct TextScanEntry: Codable, RawMappable {
typealias Raw = Json
let polarity: Double
let type: String
}
struct SentenceEntry: Codable, RawMappable {
typealias Raw = Json
let sentence: String
let sentiment: TextScanEntry
}
// MARK: - Provider
enum TextScanProvider: UrlRouteProvider {
case text
func url() throws -> URL {
return try .from(string: Constants.url)
}
}
// MARK: - Request
func scan() -> Observer<SentimEntity> {
let params = [RequestKeys.text: Constants.text]
return UrlChainsBuilder()
.route(.post, TextScanProvider.text)
.build()
.process(params)
}
scan().onError { error in
print("Error - \(error.localizedDescription)")
}.onCompleted { model in
print("Model - \(model)")
}.onCanceled {
print("Cancel")
}
| true
|
f8167202d83dc16c1694a1b59ddf5454edb03f95
|
Swift
|
KendallWillard/blackjack-swift
|
/Bank.swift
|
UTF-8
| 708
| 3.078125
| 3
|
[] |
no_license
|
//
// Bank.swift
// BlackJack
//
// Created by James Tyner on 3/4/17.
// Copyright © 2017 James Tyner. All rights reserved.
//
import SpriteKit
import UIKit
import Foundation
let youloseText = SKLabelNode(text: "Sorry, you are out of money. Trashcan")
class Bank {
var balance = 500
init() {
}
func resetBalance(){
balance = 500
}
func addMoney(amount: Int){
balance += amount
}
func subtractMoney(amount: Int){
balance -= amount
if(balance <= 0){
// this is a cheap way lets see what else we can do ->resetBalance()
}
}
func getBalance()->Int{
return balance
}
}
| true
|
7c3d573a33b4e7f10fe81c298c82fbd5d3f90ce3
|
Swift
|
Guru7373/Dozee-Vital
|
/dozeevital/Controller/ProfileViewController.swift
|
UTF-8
| 5,632
| 2.546875
| 3
|
[] |
no_license
|
//
// ProfileViewController.swift
// dozeevital
//
// Created by Guru Raj R on 20/09/20.
//
import UIKit
class ProfileViewController: UIViewController {
lazy var backdropView: UIView = {
let bdView = UIView(frame: self.view.bounds)
bdView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
return bdView
}()
let menuView = UIView()
let menuHeight = UIScreen.main.bounds.height/2.2
var isPresenting = false
var profileLabel = UILabel()
var userDetailTV = UITextView()
init() {
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .custom
transitioningDelegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
view.addSubview(backdropView)
view.addSubview(menuView)
menuView.backgroundColor = UIColor(hexString: "#303376")
menuView.layer.cornerRadius = 10
menuView.layer.masksToBounds = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissVC))
backdropView.addGestureRecognizer(tapGesture)
menuView.addSubview(profileLabel)
profileLabel.text = "My Profile"
profileLabel.textAlignment = .center
profileLabel.font = .nunitoExtraBold(ofSize: 24)
profileLabel.textColor = .white
menuView.addSubview(userDetailTV)
userDetailTV.isEditable = false
userDetailTV.isSelectable = false
userDetailTV.backgroundColor = .clear
userDetailTV.showsVerticalScrollIndicator = false
let style = NSMutableParagraphStyle()
style.lineSpacing = 15
userDetailTV.attributedText = NSAttributedString(string: "Name", attributes: [NSAttributedString.Key.paragraphStyle : style])
userDetailTV.font = .nunitoRegular(ofSize: 18)
userDetailTV.text = "Name : \(userDetail?.name ?? "-") \n" + "Phone : \(userDetail?.phone.countryCode ?? "-") - \(userDetail?.phone.number ?? "") \n" + "DOB : \(userDetail?.dob ?? "-")"
userDetailTV.textColor = .white
}
override func viewWillLayoutSubviews() {
menuView.translatesAutoresizingMaskIntoConstraints = false
menuView.heightAnchor.constraint(equalToConstant: menuHeight).isActive = true
menuView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
menuView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
menuView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
profileLabel.translatesAutoresizingMaskIntoConstraints = false
profileLabel.topAnchor.constraint(equalTo: menuView.topAnchor, constant: 30).isActive = true
profileLabel.leadingAnchor.constraint(equalTo: menuView.leadingAnchor, constant: 20).isActive = true
profileLabel.trailingAnchor.constraint(equalTo: menuView.trailingAnchor, constant: -20).isActive = true
userDetailTV.translatesAutoresizingMaskIntoConstraints = false
userDetailTV.topAnchor.constraint(equalTo: profileLabel.bottomAnchor, constant: 20).isActive = true
userDetailTV.leadingAnchor.constraint(equalTo: menuView.leadingAnchor, constant: 20).isActive = true
userDetailTV.trailingAnchor.constraint(equalTo: menuView.trailingAnchor, constant: -20).isActive = true
userDetailTV.bottomAnchor.constraint(equalTo: menuView.bottomAnchor, constant: -20).isActive = true
}
@objc func dismissVC() {
dismiss(animated: true, completion: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ProfileViewController: UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
guard let toVC = toViewController else { return }
isPresenting = !isPresenting
if isPresenting == true {
containerView.addSubview(toVC.view)
menuView.frame.origin.y += menuHeight
backdropView.alpha = 0
UIView.animate(withDuration: 0.4, delay: 0, options: [.curveEaseOut], animations: {
self.menuView.frame.origin.y -= self.menuHeight
self.backdropView.alpha = 1
}, completion: { (finished) in
transitionContext.completeTransition(true)
})
} else {
UIView.animate(withDuration: 0.4, delay: 0, options: [.curveEaseOut], animations: {
self.menuView.frame.origin.y += self.menuHeight
self.backdropView.alpha = 0
}, completion: { (finished) in
transitionContext.completeTransition(true)
})
}
}
}
| true
|
b6a5c03b7a31cb5f645a717a4b0cd21c426d1f37
|
Swift
|
BlayckPanthers/OnTheMap
|
/OnTheMap/Controllers/MapVC.swift
|
UTF-8
| 2,770
| 2.65625
| 3
|
[] |
no_license
|
//
// MapVC.swift
// OnTheMap
//
// Created by Fabien Lebon on 18/05/2020.
// Copyright © 2020 Fabien Lebon. All rights reserved.
//
import UIKit
import MapKit
class MapVC: UIViewController {
@IBOutlet weak var map: MKMapView!
var annotations = [MKPointAnnotation]()
override func viewDidLoad() {
super.viewDidLoad()
populatePointsMap(params: "limit=10&order=-updatedAt")
map.delegate = self
}
func populatePointsMap(params: String){
OTMClient.getStudentLocation(params: params, completion: {
(results, error) in
PinModel.pins = results
DispatchQueue.main.async {
self.annotations = self.getMKAnnotations(PinModel.pins)
self.map.addAnnotations(self.annotations)
}
})
}
func getMKAnnotations(_ pins: [Pin]) -> [MKPointAnnotation] {
var annotationsExtract = [MKPointAnnotation]()
for pin in pins {
let lat = CLLocationDegrees(pin.latitude!)
let long = CLLocationDegrees(pin.longitude!)
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
let first = pin.firstName!
let last = pin.lastName!
let mediaURL = pin.mediaURL ?? ""
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "\(first) - \(last)"
annotation.subtitle = mediaURL
annotationsExtract.append(annotation)
}
return annotationsExtract
}
}
extension MapVC: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "AnnotationView"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.pinTintColor = .blue
pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
let app = UIApplication.shared
if let toOpen = view.annotation?.subtitle! {
app.open(URL(string: toOpen)!)
}
}
}
}
| true
|
50bd9feac6f734ce85da36d958db10cc8506cab9
|
Swift
|
jorge3pp/international-business-example
|
/international-business-example/Data/Transaction.swift
|
UTF-8
| 685
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
//
// Transaction.swift
// international-business-example
//
// Created by Jorge Poveda on 20/9/21.
//
import Foundation
struct Transaction: Decodable {
public var sku: String
public var amount: String
public var currency: String
public init(sku: String, amount: String, currency: String) {
self.sku = sku
self.amount = amount
self.currency = currency
}
}
extension Transaction: Equatable {
public static func == (lhs: Transaction, rhs: Transaction) -> Bool {
lhs.sku == rhs.sku && lhs.amount == rhs.amount && lhs.currency == rhs.currency
}
}
extension Transaction: Identifiable {
var id: UUID {
UUID()
}
}
| true
|
018adc1f1ec0ccc08430cbeea56b3aa5b844181c
|
Swift
|
AnfisaKlisho/Investments
|
/Investments/UIColor_Hex.swift
|
UTF-8
| 881
| 3.203125
| 3
|
[] |
no_license
|
//
// UIColor_Hex.swift
// Yandex Investments
//
// Created by Anfisa Klisho on 14.04.2021.
//
import UIKit
public extension UIColor {
class func fromHex(_ hex: String, alpha: CGFloat = 1) -> UIColor {
var colorHexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if colorHexString.hasPrefix("#") {
colorHexString.remove(at: colorHexString.startIndex)
}
if (colorHexString.count) != 6 {
return UIColor.gray.withAlphaComponent(alpha)
}
var rgbValue: UInt64 = 0
Scanner(string: colorHexString).scanHexInt64(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha
)
}
}
| true
|
12d68ab9a53efc02aa67bc4fc74f852e10e36867
|
Swift
|
xsu11/iit-cs442-summer-2016
|
/mp/05/Simon/Simon/ViewController.swift
|
UTF-8
| 4,299
| 2.921875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Simon
//
// Created by Michael Lee on 6/27/16.
// Copyright © 2016 Michael Lee. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet var buttons: [UIButton]!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var label: UILabel!
var sequence = [Int]()
var guessidx = 0
var currentLevel: Int?
override func viewDidLoad() {
super.viewDidLoad()
messageLabel.text = "Double tap to start!"
label.text = String(Int(slider.value))
}
func flashSequence(level: Int) {
let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
self.messageLabel.text = "Watch carefully... (Level \(level))"
dispatch_async(queue) {
NSThread.sleepForTimeInterval(1.0)
self.generateSequence(level)
for btnidx in self.sequence {
dispatch_async(dispatch_get_main_queue()) {
self.buttons[btnidx].highlighted = true
}
NSThread.sleepForTimeInterval(1.0)
dispatch_async(dispatch_get_main_queue()) {
self.buttons[btnidx].highlighted = false
}
}
dispatch_async(dispatch_get_main_queue()) {
self.messageLabel.text = "Tap out the sequence!"
}
}
}
func generateSequence(level: Int) -> Bool {
self.sequence = []
while self.sequence.count < level {
let newValue = Int(arc4random_uniform(4))
if (self.sequence.count == 0 || (self.sequence.count > 0 && newValue != self.sequence[sequence.count - 1])) {
self.sequence.append(newValue)
}
}
return true
}
@IBAction func buttonTapped(sender: UIButton) {
if self.buttons[self.sequence[self.guessidx]] == sender {
self.guessidx += 1
let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
if self.guessidx == self.currentLevel {
if self.currentLevel < Int(self.slider.value) {
self.messageLabel.text = "You win! Next Level!"
self.guessidx = 0
self.currentLevel = self.currentLevel! + 1
dispatch_async(queue) {
dispatch_async(dispatch_get_main_queue()) {
self.flashSequence(self.currentLevel!)
}
NSThread.sleepForTimeInterval(1.0)
}
} else {
self.messageLabel.text = "BIG WIN! (Double tap to start!)"
self.guessidx = 0
}
} else {
dispatch_async(queue) {
dispatch_async(dispatch_get_main_queue()) {
self.messageLabel.text = "Good guess \(self.guessidx)"
}
}
}
} else {
self.messageLabel.text = "Wrong!"
self.guessidx = 0
let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
dispatch_async(queue) {
// blink all buttons and restart game
dispatch_async(dispatch_get_main_queue()) {
for btn in self.buttons {
btn.highlighted = true
}
}
NSThread.sleepForTimeInterval(1.0)
dispatch_async(dispatch_get_main_queue()) {
for btn in self.buttons {
btn.highlighted = false
}
}
NSThread.sleepForTimeInterval(1.0)
dispatch_async(dispatch_get_main_queue()) {
self.flashSequence(self.currentLevel!)
}
}
}
}
@IBAction func startGame(sender: AnyObject) {
guessidx = 0
currentLevel = Int(self.slider.minimumValue)
flashSequence(currentLevel!)
}
@IBAction func sliderValueChanged(sender: UISlider) {
label.text = String(Int(sender.value))
}
}
| true
|
70a0a75fb474e25028fd9761067315a70dffb40e
|
Swift
|
Brun41v35/Movie
|
/Movie Tracker/MovieDetail.swift
|
UTF-8
| 2,420
| 3.328125
| 3
|
[] |
no_license
|
//
// MovieDetail.swift
// Movie Tracker
//
// Created by Bruno Alves da Silva on 13/06/20.
// Copyright © 2020 Bruno Alves da Silva. All rights reserved.
//
import SwiftUI
struct MovieDetail: View {
@State var movie: Movie
@Environment(\.presentationMode) var presentationMode
let newMovie : Bool
@EnvironmentObject var movieStorage : MovieStorage
var body: some View {
List {
Section {
SectionTitle(title: "Titulo")
TextField("Titulo do Filme", text:$movie.title)
}
Section {
SectionTitle(title: "Avaliacao")
HStack {
Spacer()
Text(String(repeating: "★", count: Int(movie.rating))).foregroundColor(.yellow).font(.title)
Spacer()
}
Slider(value: $movie.rating, in: 1...5, step: 1)
}
Section {
SectionTitle(title: "Visto")
Toggle(isOn: $movie.seen) {
if movie.title == "" {
Text("Eu assisti esse filme")
} else {
Text("Eu assisti \(movie.title)")
}
}
}
Section {
Button(action:{
if self.newMovie {
self.movieStorage.movies.append(self.movie)
} else {
for x in 0..<self.movieStorage.movies.count {
if self.movieStorage.movies[x].id == self.movie.id {
self.movieStorage.movies[x] = self.movie
}
}
}
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Spacer()
Text("Salvar")
Spacer()
}
}.disabled(movie.title.isEmpty)
}
}.listStyle(GroupedListStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
MovieDetail(movie: Movie(), newMovie: true)
}
}
struct SectionTitle: View {
var title : String
var body: some View {
Text(title).font(.caption).foregroundColor(.green)
}
}
| true
|
f70cd5ed339bc56e96b689b017a6732830bbfd41
|
Swift
|
hughbe/SwiftMAPI
|
/Sources/MAPI/MS-OXCDATA/AddressBookEntryType.swift
|
UTF-8
| 1,269
| 2.734375
| 3
|
[] |
no_license
|
//
// AddressBookEntryType.swift
//
//
// Created by Hugh Bellamy on 08/10/2020.
//
/// Type (4 bytes): An integer representing the type of the object. It MUST be one of the values from the following table.
public enum AddressBookEntryType: UInt32 {
/// 0x00000000 %x00.00.00.00 Local mail user
case localMailUser = 0x00000000
/// 0x00000001 %x01.00.00.00 Distribution list
case distributionList = 0x00000001
/// 0x00000002 %x02.00.00.00 Bulletin board or public folder
case bulletinBoardOrPublicFolder = 0x00000002
/// 0x00000003 %x03.00.00.00 Automated mailbox
case automatedMailbox = 0x00000003
/// 0x00000004 %x04.00.00.00 Organizational mailbox
case organizationalMailbox = 0x00000004
/// 0x00000005 %x05.00.00.00 Private distribution list
case privateDistributionList = 0x00000005
/// 0x00000006 %x06.00.00.00 Remote mail user
case remoteMailUser = 0x00000006
/// 0x00000100 %x00.01.00.00 Container
case container = 0x00000100
/// 0x00000101 %x01.01.00.00 Template
case template = 0x00000101
/// 0x00000102 %x02.01.00.00 One-off user
case oneOffUser = 0x00000102
/// 0x00000200 %x00.02.00.00 Search
case search = 0x00000200
}
| true
|
6a89a9f0a89512773451c41164f1c95a2e6a40ff
|
Swift
|
skaunited/VeeWeather
|
/VeeWeather/AppFlow/DefaultUtils/DefaultUtils.swift
|
UTF-8
| 510
| 2.8125
| 3
|
[] |
no_license
|
//
// DefaultUtils.swift
// VeeWeather
//
// Created by Skander Bahri on 18/09/2021.
//
import Foundation
struct DefaultUtils {
//Singleton Pattern
static var sharedInstance = DefaultUtils()
let userDefaults = UserDefaults.standard
// token
var token: String? {
get { return userDefaults.string(forKey: "token") }
set(newValue) {
userDefaults.set(newValue, forKey: "token") }
}
func syncronise() {
userDefaults.synchronize()
}
}
| true
|
897dbd30c15fd22f511c8c11c300b416fb1f4840
|
Swift
|
calonso/SwiftKickstart
|
/Functions2.playground/section-1.swift
|
UTF-8
| 862
| 3.828125
| 4
|
[] |
no_license
|
func hello() {
print("Hello, ")
println("World!")
println("Glad to be in London.")
}
func hello(name: String) {
println("Hello, \(name).")
}
func hello(name: String,
numberOfTimes: Int) {
for i in 1 ... numberOfTimes {
hello(name)
}
}
func helloWorld3(name: String = "World") {
println("Hello, \(name)")
}
func helloWorld4(toPersonWithName name: String,
numberOfTimes:Int = 1) {
for i in 1 ... numberOfTimes {
helloWorld3(name: name)
}
}
func helloWorld5(#toPersonWithName: String) {
println("Hello \(toPersonWithName)")
}
helloWorld3( name: "Kim")
helloWorld3()
helloWorld4(toPersonWithName:"Maggie", numberOfTimes: 5)
helloWorld4(toPersonWithName: "Anabelle")
helloWorld5(toPersonWithName: "My friend")
//hello()
//hello("London")
//hello("London again ", 5)
| true
|
310b0e4f36333adf558ad0ef78e49dd1b09202ce
|
Swift
|
angierao/parse-tagram
|
/parsetagram/Comment.swift
|
UTF-8
| 3,041
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Comment.swift
// parsetagram
//
// Created by Angeline Rao on 6/23/16.
// Copyright © 2016 Angeline Rao. All rights reserved.
//
import UIKit
import Parse
class Comment: NSObject {
/*
var creationString: String?
var text: String?
var user: PFUser?
init(content: String) {
super.init()
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour , .Minute, .Second], fromDate:date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let min = components.minute
let sec = components.second
let currentDate = NSDateComponents()
currentDate.year = year
currentDate.month = month
currentDate.day = day
currentDate.hour = hour
currentDate.minute = min
currentDate.second = sec
let today = NSCalendar.currentCalendar().dateFromComponents(currentDate)!
let dateFormatter = NSDateFormatter()
//let date = NSDate()
dateFormatter.dateFormat = "MMM d, H:mm a"
let dateString = dateFormatter.stringFromDate(today)
self.creationString = dateString
self.text = content
self.user = PFUser.currentUser()
}*/
class func newMessage(content: UITextField?, id: Int?, withCompletion completion: PFBooleanResultBlock?) -> PFObject {
let comment = PFObject(className: "Comment")
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour , .Minute, .Second], fromDate:date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let min = components.minute
let sec = components.second
let currentDate = NSDateComponents()
currentDate.year = year
currentDate.month = month
currentDate.day = day
currentDate.hour = hour
currentDate.minute = min
currentDate.second = sec
let today = NSCalendar.currentCalendar().dateFromComponents(currentDate)!
let dateFormatter = NSDateFormatter()
//let date = NSDate()
dateFormatter.dateFormat = "MMM d, H:mm a"
let dateString = dateFormatter.stringFromDate(today)
comment["creationString"] = dateString
comment["text"] = content?.text
comment["user"] = PFUser.currentUser()
comment["postID"] = id
comment.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success {
print(comment["text"])
print("not error")
}
else {
print(error)
print("error")
}
}
return comment
}
}
| true
|
b058604e7a77f9bf6a43b1058bcae52a0337cbbc
|
Swift
|
javiermanzo/SeriesHub
|
/SeriesHub/Core/Extension/UIViewController-Extension.swift
|
UTF-8
| 713
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// UIViewController-Extension.swift
// SeriesHub
//
// Created by Javier Manzo on 4/23/17.
// Copyright © 2017 Javier Manzo. All rights reserved.
//
import UIKit
extension UIViewController {
static internal func instanceWithDefaultNib() -> Self {
let className = NSStringFromClass(self as AnyClass).components(separatedBy: ".").last
return self.init(nibName: className, bundle: nil)
}
}
extension UIViewController: StoryboardIdentifiable { }
protocol StoryboardIdentifiable {
static var storyboardIdentifier: String { get }
}
extension StoryboardIdentifiable where Self: UIViewController {
static var storyboardIdentifier: String {
return String(describing: self)
}
}
| true
|
ed7e73bd2559d8f8ff54d2509b7107263e18926f
|
Swift
|
jozecuervo/Codepath-01-RottenTomatoes
|
/tomatoes/MoviesViewController.swift
|
UTF-8
| 6,594
| 2.546875
| 3
|
[] |
no_license
|
//
// MoviesViewController.swift
// tomatoes
//
// Created by Gabe Kangas on 4/14/15.
// Copyright (c) 2015 Gabe Kangas. All rights reserved.
//
// http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=dagqdghwaq3e3mxyrp7kmmj5&q=star+wars
import UIKit
import SDWebImage
import JGProgressHUD
import AFNetworking
class MoviesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var movies = NSMutableArray()
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
collectionView.addSubview(refreshControl)
refresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieCell", forIndexPath: indexPath) as! MovieCollectionViewCell
if let movie = movies.objectAtIndex(indexPath.row) as? Movie {
cell.movieName.text = movie.name
cell.movieImageView.sd_setImageWithURL(movie.imageUrl, placeholderImage: UIImage(named:"placeholder.jpg"))
cell.ratingImageFilename = movie.rating > 50 ? "rebel.png" : "empire.png"
if !movie.displayed {
movie.displayed = true
var delay = Double(indexPath.item % 2) * 0.1
UIView.transitionWithView(cell.movieImageView, duration: 0.4, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in
cell.animate(delay: delay)
}, completion: { (completed) -> Void in
//
})
} else {
cell.layout()
}
}
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies.count
}
func parseData(dataArray: NSArray) {
dataArray.enumerateObjectsUsingBlock { (movieDictionary, index, complete) -> Void in
let singleMovie = Movie(dictionary: movieDictionary as! NSDictionary)
self.movies.addObject(singleMovie)
}
collectionView.reloadData()
}
func refresh() {
movies.removeAllObjects()
let apiUrlString = "http://api.rottentomatoes.com/api/public/v1.0/movies.json"
var params = NSMutableDictionary()
params["apikey"] = "dagqdghwaq3e3mxyrp7kmmj5"
params["q"] = "star wars"
let manager = AFHTTPRequestOperationManager()
manager.GET(apiUrlString,
parameters: params,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
//Complete
if let movies = responseObject.objectForKey("movies") as? NSArray {
self.parseData(movies)
self.refreshControl.endRefreshing()
}
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
self.showError("Network Error")
self.refreshControl.endRefreshing()
}
)
}
func showError(errorText: String) {
let errorView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) as UIVisualEffectView
errorView.tintColor = UIColor.redColor()
errorView.frame = CGRectMake(0, 0, view.frame.size.width, 50)
let errorViewLabel = UILabel(frame: errorView.frame)
errorViewLabel.backgroundColor = UIColor.clearColor()
errorViewLabel.textColor = UIColor.whiteColor()
errorViewLabel.textAlignment = NSTextAlignment.Center
errorViewLabel.adjustsFontSizeToFitWidth = true
errorViewLabel.minimumScaleFactor = 0.3
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "crossed-lightsabers.png")
attachment.bounds = CGRectMake(5, -2, 15, 15)
var attributedStringAttachment = NSAttributedString(attachment: attachment)
let attributedString = NSMutableAttributedString(string: errorText)
attributedString.appendAttributedString(attributedStringAttachment)
errorViewLabel.attributedText = attributedString
errorView.addSubview(errorViewLabel)
view.insertSubview(errorView, aboveSubview: collectionView)
UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.3, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
errorView.frame.origin.y = 60
}) { (completed) -> Void in
// Move error out
UIView.animateWithDuration(1.0, delay: 3.0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
errorView.frame.origin.y = 0
}, completion: { (completed) -> Void in
errorView.removeFromSuperview()
})
}
}
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
let cell = sender as! UICollectionViewCell
let index = collectionView.indexPathForCell(cell)
let movie = movies.objectAtIndex(index!.item) as! Movie
if movie.cast.count == 0 {
showError("We have no cast information for this movie to display.")
return false
}
return true
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let cell = sender as! UICollectionViewCell
let index = collectionView.indexPathForCell(cell)
let movie = movies.objectAtIndex(index!.item) as! Movie
let destinationVC = segue.destinationViewController as! MovieDetailViewController
destinationVC.movie = movie
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
| true
|
fc8cd87d5ed896f6c5a09afc85db9716aecffe6b
|
Swift
|
Fedor117/WeatherSwiftUIApp
|
/WeatherSwiftUIApp/Model/OpenWeatherMapService.swift
|
UTF-8
| 1,797
| 3.171875
| 3
|
[] |
no_license
|
//
// OpenWeatherMapService.swift
// WeatherSwiftUIApp
//
// Created by Fedor Valiavko on 28/08/2020.
// Copyright © 2020 Fedor Valiavko. All rights reserved.
//
import Foundation
final class OpenWeatherMapService: WeatherServicing {
private let decoder = JSONDecoder()
func fetchWeatherData(for city: String, completionHandler: @escaping (Result<String, WeatherServicingError>) -> Void) {
let endPoint = "https://api.openweathermap.org/data/2.5/find?q=\(city)&units=metric&appid=\(APIKeys.openWeatherMap.rawValue)"
guard let safeUrlString = endPoint.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let endPointUrl = URL(string: safeUrlString) else {
completionHandler(.failure(.invalidUrl(endPoint)))
return
}
let dataTask = URLSession.shared.dataTask(with: endPointUrl) {
[weak self] data, response, error in
guard let self = self else { return }
guard error == nil else {
completionHandler(.failure(.forwarded(error!)))
return
}
guard let responseData = data else {
completionHandler(.failure(.invalidPayload(endPointUrl)))
return
}
do {
let weatherList = try self.decoder.decode(OpenWeatherMapContainer.self, from: responseData)
guard let weatherInfo = weatherList.list.first else {
completionHandler(.failure(.invalidPayload(endPointUrl)))
return
}
let weather = weatherInfo.weather.first!.main
let weatherDescription = "\(String(describing: weather)) \(weatherInfo.main.temp)"
completionHandler(.success(weatherDescription))
} catch let error {
completionHandler(.failure(.forwarded(error)))
}
}
dataTask.resume()
}
}
| true
|
9da5c4329321625b051c05b4e5895b13cf694f52
|
Swift
|
JFerrer95/Voice-Changer
|
/Fenamenal Voice Changer/View Controllers/RecordAudioViewController.swift
|
UTF-8
| 7,623
| 2.546875
| 3
|
[] |
no_license
|
//
// StopWatch.swift
// Fenamenal Voice Changer
//
// Created by Jonathan Ferrer on 2/18/20.
// Copyright © 2020 Jonathan Ferrer. All rights reserved.
//
import UIKit
import AVFoundation
import AudioKit
import AudioKitUI
enum State {
case readyToRecord
case recording
case readyToPlay
case playing
}
class RecordAudioViewController: UIViewController{
var micMixer: AKMixer!
var recorder: AKNodeRecorder!
var player: AKPlayer!
var tape: AKAudioFile!
var micBooster: AKBooster!
var reverb: AKReverb!
var delay: AKDelay!
var pitchShifter: AKPitchShifter!
var mainMixer: AKMixer!
var didPlay = false
let mic = AKMicrophone()
var state = State.readyToRecord
var effectsPanel = EffectsPanel()
var preset = Preset()
@IBOutlet weak var outputPlot: AKNodeOutputPlot?
@IBOutlet weak var recordPlayButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
outputPlot?.node = mic
setupUIForRecording()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Clean tempFiles !
AKAudioFile.cleanTempDirectory()
// Session settings
AKSettings.bufferLength = .medium
do {
try AKSettings.setSession(category: .playAndRecord, with: .allowBluetoothA2DP)
} catch {
AKLog("Could not set session category.")
}
AKSettings.defaultToSpeaker = true
// Patching
let monoToStereo = AKStereoFieldLimiter(mic, amount: 1)
micMixer = AKMixer(monoToStereo)
micBooster = AKBooster(micMixer)
// Will set the level of microphone monitoring
micBooster.gain = 0
recorder = try? AKNodeRecorder(node: micMixer)
if let file = recorder.audioFile {
player = AKPlayer(audioFile: file)
}
player.isLooping = true
player.completionHandler = playingEnded
reverb = AKReverb(player)
reverb.stop()
delay = AKDelay(reverb)
delay.stop()
pitchShifter = AKPitchShifter(delay)
pitchShifter.stop()
mainMixer = AKMixer(pitchShifter, micBooster)
AudioKit.output = mainMixer
do {
try AudioKit.start()
} catch {
AKLog("AudioKit did not start!")
}
}
@IBAction func recordPlayButtonPressed(_ sender: UIButton) {
switch state {
case .readyToRecord :
navigationController?.title = "Recording"
recordPlayButton.setBackgroundImage(UIImage(systemName: "stop.fill"), for: .normal)
state = .recording
// microphone will be monitored while recording
// only if headphones are plugged
if AKSettings.headPhonesPlugged {
micBooster.gain = 1
}
do {
try recorder.record()
} catch { AKLog("Errored recording.") }
case .recording :
// Microphone monitoring is muted
micBooster.gain = 0
tape = recorder.audioFile!
player.load(audioFile: tape)
if let _ = player.audioFile?.duration {
recorder.stop()
tape.exportAsynchronously(name: "TempTestFile.m4a",
baseDir: .documents,
exportFormat: .m4a) {_, exportError in
if let error = exportError {
AKLog("Export Failed \(error)")
} else {
AKLog("Export succeeded")
}
}
setupUIForPlaying()
}
case .readyToPlay :
player.play()
navigationController?.title = "Playing..."
recordPlayButton.setBackgroundImage(UIImage(systemName: "stop"), for: .normal)
state = .playing
outputPlot?.node = player
print(tape.url.absoluteString)
case .playing :
player.stop()
if didPlay {
setupUIForPlaying()
didPlay = false
}
playingEnded()
outputPlot?.node = mic
}
}
func playingEnded() {
DispatchQueue.main.async {
let recordedDuration = self.player != nil ? self.player.audioFile?.duration : 0
self.recordPlayButton.setBackgroundImage(UIImage(systemName: "play"), for: .normal)
self.state = .readyToPlay
self.navigationController?.title = String(recordedDuration!)
}
}
func setupUIForPlaying () {
playingEnded()
// navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .redo, target: self, action: nil)
self.effectsPanel.preset = self.preset
UIView.animate(withDuration: 0.5, animations: {
self.recordPlayButton.translatesAutoresizingMaskIntoConstraints = false
self.outputPlot?.translatesAutoresizingMaskIntoConstraints = false
self.effectsPanel.translatesAutoresizingMaskIntoConstraints = false
self.recordPlayButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20).isActive = true
self.outputPlot?.bottomAnchor.constraint(equalTo: self.recordPlayButton.topAnchor, constant: -20).isActive = true
self.view.backgroundColor = .black
self.effectsPanel.reverbDelegate = self
self.effectsPanel.reverbView.delegate = self
self.effectsPanel.delayDelegate = self
self.effectsPanel.pitchShiftDelegate = self
self.view.layoutIfNeeded()
})
}
func setupUIForRecording () {
state = .readyToRecord
navigationController?.title = "Ready to record"
recordPlayButton.setBackgroundImage(UIImage(systemName: "circle.fill"), for: .normal)
micBooster.gain = 0
effectsPanel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(effectsPanel)
effectsPanel.bottomAnchor.constraint(equalTo: outputPlot?.topAnchor ?? view.bottomAnchor, constant: -20).isActive = true
effectsPanel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
effectsPanel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
effectsPanel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch: UITouch = touches.first
else { return }
let location = touch.location(in: view)
if !effectsPanel.frame.contains(location) {
effectsPanel.reverbView.isHidden = true
effectsPanel.delayView.isHidden = true
effectsPanel.pitchShiftView.isHidden = true
}
}
}
| true
|
cc8d50822fe50294caea360f07cb375dbaa1b122
|
Swift
|
glnygl/PokeMoon
|
/PokeMoon/Scenes/PokeList/PokeListWorker.swift
|
UTF-8
| 628
| 2.953125
| 3
|
[] |
no_license
|
//
// PokeListWorker.swift
// PokeMoon
//
// Created by Gülenay Gül on 22.01.2020.
// Copyright © 2020 Gülenay Gül. All rights reserved.
//
import Foundation
typealias PokeListHandler = ([Pokemon]?) -> Void
protocol PokeListWorkingLogic {
func fetchPokemons(completion: @escaping PokeListHandler)
}
final class PokeListWorker: PokeListWorkingLogic {
func fetchPokemons(completion: @escaping PokeListHandler) {
PokeApi.getPokeList { (result) in
if let data = result?.data {
completion(data)
} else {
completion(nil)
}
}
}
}
| true
|
7602ee1f0a0c25af7d52e4adeb7f8a428460c8eb
|
Swift
|
rmelian2014/XCalendar
|
/XCalendar/Files/App/XCalendar.swift
|
UTF-8
| 607
| 2.671875
| 3
|
[] |
no_license
|
//
// XCalendar.swift
// XCalendar
//
// Created by Mohammad Yasir on 07/10/21.
//
import SwiftUI
struct XCalendar: View {
var body: some View {
TabView {
ForEach(Key.calendar.getAllMonths(forDate: Date()), id:\.self) { day in
CalendarView(forDate: day, selectionSize: .large)
.padding(.vertical)
}
}
.tabViewStyle(.page(indexDisplayMode: .never))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)).edgesIgnoringSafeArea(.all))
}
}
| true
|
4dfbd5dbdbc6a1b4d33e4b09a16fd0163bf50bad
|
Swift
|
lugearma/LAMenuBar
|
/LAMenuBar/Classes/LAMenuBar.swift
|
UTF-8
| 5,112
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// LAMenuBar.swift
// Pods
//
// Created by Luis Arias on 6/11/17.
//
//
import UIKit
protocol LAMenuBarDelegate: class {
func didSelectItemAt(indexPath: IndexPath)
}
@available(iOS 9.0, *)
final class LAMenuBar: UIView {
fileprivate var model: LAMenuModel
weak var delegate: LAMenuBarDelegate?
fileprivate var leftAnchorContraint: NSLayoutConstraint?
fileprivate lazy var sectionsBarView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
let selectedIndexPath = IndexPath(row: 0, section: 0)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(MenuBarCell.self, forCellWithReuseIdentifier: MenuBarCell.identifier)
collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: [])
return collectionView
}()
private lazy var sectionIndicatorBar: UIView = {
let view = UIView()
view.backgroundColor = self.model.sectionIndicatorBarColor
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
init(frame: CGRect, model: LAMenuModel) {
self.model = model
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
setupView()
if !model.isCurrentSectionBarHidden {
setupSectionIndicatorBar()
}
}
private func setupSectionIndicatorBar() {
addSubview(sectionIndicatorBar)
leftAnchorContraint = sectionIndicatorBar.leftAnchor.constraint(equalTo: leftAnchor)
let bottomAnchorContraint = sectionIndicatorBar.bottomAnchor.constraint(equalTo: bottomAnchor)
let anchorConstraintForBotton = sectionIndicatorBar.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1/CGFloat(model.sections))
let anchorConstraintForHeight = sectionIndicatorBar.heightAnchor.constraint(equalToConstant: 4)
guard let leftAnchorContraint = leftAnchorContraint else {
preconditionFailure()
}
NSLayoutConstraint.activate([leftAnchorContraint, bottomAnchorContraint, anchorConstraintForBotton, anchorConstraintForHeight])
}
private func setupView() {
addSubview(sectionsBarView)
sectionsBarView.topAnchor.constraint(equalTo: topAnchor).isActive = true
sectionsBarView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
sectionsBarView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
sectionsBarView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
}
func updateWhenScrollView(_ scrollView: UIScrollView) {
let sections = model.sections
leftAnchorContraint?.constant = scrollView.contentOffset.x / CGFloat(sections)
}
func updateWhenFinishScrollAtIndex(_ index: IndexPath) {
self.sectionsBarView.selectItem(at: index, animated: true, scrollPosition: .centeredHorizontally)
}
}
// MARK: - UICollectionViewDataSource
@available(iOS 9.0, *)
extension LAMenuBar: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model.sections
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: MenuBarCell = collectionView.dequeCell(identifier: MenuBarCell.identifier, indexPath: indexPath)
let imageForCell = iconImageForCellAt(indexPath)
let cellModel = MenuBarCellModel(colorWhenSelected: model.colorWhenSelected, colorWhenDiselected: model.colorWhenDiselected, image: imageForCell, cellIndex: indexPath.item)
cell.model = cellModel
cell.configure()
return cell
}
private func iconImageForCellAt(_ indexPath: IndexPath) -> UIImage {
guard let image = model.images[indexPath.item] else {
preconditionFailure("Can not load image for cell")
}
return image
}
}
// MARK: UICollectionViewDelegateFlowLayout
@available(iOS 9.0, *)
extension LAMenuBar: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sections = model.sections
let width = frame.width / CGFloat(sections)
return CGSize(width: width, height: frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
// MARK: - UICollectionViewDelegate
@available(iOS 9.0, *)
extension LAMenuBar: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let index = IndexPath(item: indexPath.item, section: 0)
delegate?.didSelectItemAt(indexPath: index)
}
}
| true
|
312ee442e66e391541aff44e70a8d8af46c89b7c
|
Swift
|
felipe-zg/Swift-clean-architecture
|
/Data/UseCases/RemoteAddAccount.swift
|
UTF-8
| 1,123
| 2.71875
| 3
|
[] |
no_license
|
import Foundation
import Domain
public class RemoteAddAccount: AddAccount{
private let url: URL
private let httpPostClient: HttpPostClient
public init(url: URL, httpPostClient: HttpPostClient) {
self.url = url
self.httpPostClient = httpPostClient
}
public func add(addAccountModel: AddAccountModel, completion: @escaping (AddAccount.Result) -> Void){
httpPostClient.post(to: url, with: addAccountModel.toData()) { [weak self] result in
guard self != nil else {return}
let _ = self?.url
switch result {
case .failure(let error):
switch error {
case .forbidden:
completion(.failure(.emailInUse))
default:
completion(.failure(.unexpected))
}
case .success(let data):
if let model: AccountModel = data?.toModel() {
completion(.success(model))
} else {
completion(.failure(.unexpected))
}
}
}
}
}
| true
|
2bcf6f1235ad897f239ce0c5310c67a75702a272
|
Swift
|
toonbertier/badget-native
|
/Badget/CrowdSurfingView.swift
|
UTF-8
| 3,049
| 2.625
| 3
|
[] |
no_license
|
//
// CrowdSurfingView.swift
// Badget
//
// Created by Toon Bertier on 11/06/15.
// Copyright (c) 2015 Toon Bertier. All rights reserved.
//
import UIKit
protocol CrowdSurfinViewDelegate:class {
func showBadge()
}
class CrowdSurfingView: UIView {
var phone:UIImageView!
var distanceImage:UIImageView!
var distanceLabel:UILabel!
var titleLabel:UILabel!
var descrLabel:UILabel!
weak var delegate:CrowdSurfinViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(UIImageView(image: UIImage(named: "white-bg")!))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showExplanation() {
let image = UIImage(named: "phone")
self.phone = UIImageView(image: image!)
self.phone.center = CGPointMake(self.center.x, self.center.y - 90)
self.addSubview(self.phone)
self.titleLabel = BadgetUI.makeTitle("HOU JE IPHONE TEGEN JE BORST")
self.titleLabel.center = CGPointMake(self.center.x, self.center.y + 70)
self.addSubview(self.titleLabel)
self.descrLabel = BadgetUI.makeDescription("Telkens wanneer je in de juiste positie zit, zal je iPhone trillen. Op het einde van de rit kan je je afgelegde afstand in meter zien.", width:250 ,highlights: [])
self.descrLabel.center = CGPointMake(self.center.x, self.center.y + 160)
self.addSubview(self.descrLabel)
}
func removeExplanation() {
self.phone.removeFromSuperview()
self.titleLabel.removeFromSuperview()
self.descrLabel.removeFromSuperview()
}
func showDistance() {
let image = UIImage(named: "distance")
self.distanceImage = UIImageView(image: image!)
self.distanceImage.center = CGPointMake(self.center.x, self.center.y)
self.addSubview(self.distanceImage)
self.distanceLabel = UILabel(frame: CGRectMake(0, 0, 100, 44))
self.distanceLabel.font = UIFont(name: "Dosis-SemiBold", size: 40)
self.distanceLabel.textAlignment = .Center
self.distanceLabel.center = CGPointMake(self.center.x + 85, self.center.y + 40)
self.addSubview(self.distanceLabel)
}
func updateDistanceLabel(distance:Double) {
self.distanceLabel.text = String(format:"%.0f", distance)
}
func showBadgeButton() {
let stopButton = BadgetUI.makeButton("NAAR BADGE", center: CGPointMake(self.center.x, self.center.y + 180), width: 160)
stopButton.addTarget(self, action: "showBadgeController:", forControlEvents: .TouchUpInside)
self.addSubview(stopButton)
}
func showBadgeController(sender:UIButton) {
self.delegate?.showBadge()
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| true
|
218767d6efd394d5ccb19c408b983f1487ec1561
|
Swift
|
urielbattanoli/R6-Plus
|
/R6-Plus/Models/RankedStats.swift
|
UTF-8
| 1,936
| 3.046875
| 3
|
[] |
no_license
|
//
// RankedStats.swift
// R6-Plus
//
// Created by Uriel Battanoli on 07/09/18.
// Copyright © 2018 Mocka. All rights reserved.
//
import Foundation
struct RankedStats: Codable {
let deaths: Int
let kills: Int
let lost: Int
let played: Int
let timePlayed: Int
let won: Int
var winRate: Double {
guard played != 0 else { return 0 }
return Double(won) / Double(played) * 100
}
var kdRatio: Double {
guard deaths != 0 else { return 0 }
return Double(kills) / Double(deaths)
}
enum CodingKeys: String, CodingKey {
case kills = "rankedpvp_kills:infinite"
case won = "rankedpvp_matchwon:infinite"
case deaths = "rankedpvp_death:infinite"
case played = "rankedpvp_matchplayed:infinite"
case timePlayed = "rankedpvp_timeplayed:infinite"
case lost = "rankedpvp_matchlost:infinite"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
kills = try values.decodeIfPresent(Int.self, forKey: .kills) ?? 0
won = try values.decodeIfPresent(Int.self, forKey: .won) ?? 0
deaths = try values.decodeIfPresent(Int.self, forKey: .deaths) ?? 0
played = try values.decodeIfPresent(Int.self, forKey: .played) ?? 0
timePlayed = try values.decodeIfPresent(Int.self, forKey: .timePlayed) ?? 0
lost = try values.decodeIfPresent(Int.self, forKey: .lost) ?? 0
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(kills, forKey: .kills)
try container.encode(won, forKey: .won)
try container.encode(deaths, forKey: .deaths)
try container.encode(played, forKey: .played)
try container.encode(timePlayed, forKey: .timePlayed)
try container.encode(lost, forKey: .lost)
}
}
| true
|
b9d43080d05c1f3f73132fdc91a63c65a17b3024
|
Swift
|
luoboding/sagittarius-swift
|
/sagittarius-swift/common/util/RequestHelper.swift
|
UTF-8
| 3,950
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// RequestHelper.swift
// sagittarius-swift
//
// Created by bonedeng on 4/17/16.
// Copyright © 2016 xingdongyou. All rights reserved.
//
import UIKit
typealias SuccessedHttpRequestHandler = (data: AnyObject?, response: NSHTTPURLResponse)->Void
typealias FailureHttpRequestHandler = (response: NSHTTPURLResponse)->Void
class RequestHelper : NSObject{
var successedHandler: SuccessedHttpRequestHandler!
var failureHandler: FailureHttpRequestHandler!
var httpRequest : NSMutableURLRequest!
var task : NSURLSessionDataTask!
var session : NSURLSession!
override init() {
super.init()
}
convenience init(url: String, params: AnyObject?, success: SuccessedHttpRequestHandler, failure: FailureHttpRequestHandler) {
self.init()
successedHandler = success
failureHandler = failure
session = NSURLSession.sharedSession()
httpRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
do {
if let params = params {
httpRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
}
} catch {
print("JSON serialization failed")
}
session.configuration.HTTPAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/json",
"Accept-Language" : "zh",
"Device-Type" : "IOS"
]
let userDefault = NSUserDefaults.standardUserDefaults()
let token = userDefault.stringForKey("token")
if (token != nil) {
session.configuration.HTTPAdditionalHeaders!["x-auth-token"] = token
}
}
func configTask() {
print("start here")
task = session.dataTaskWithRequest(httpRequest) { (data, response, error) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
let statusCode = httpResponse.statusCode
print("status code is \(statusCode)")
switch statusCode {
case 500:
self.handleServerAndNormalError(httpResponse)
case 200:
self.handleSuccess(data, response: httpResponse)
case 401:
self.handleUnauthorizedError(httpResponse)
default:
self.handleServerAndNormalError(httpResponse)
}
return;
}
}
}
func sendPostRequest() {
httpRequest.HTTPMethod = "POST"
configTask()
task.resume()
}
func sendGetRequest() {
httpRequest.HTTPMethod = "GET"
configTask()
task.resume()
}
func sendPutRequest() {
httpRequest.HTTPMethod = "PUT"
configTask()
task.resume()
}
func sendDeleteRequest() {
httpRequest.HTTPMethod = "DELETE"
configTask()
task.resume()
}
func handleSuccess(data: AnyObject?, response: NSHTTPURLResponse) {
var result: AnyObject?
if let responseData = data {
do {
result = try NSJSONSerialization.JSONObjectWithData(responseData as! NSData, options: .MutableContainers)
} catch {
}
}
dispatch_async(dispatch_get_main_queue(),{ ()->() in
self.successedHandler(data: result, response: response)
})
}
func handleServerAndNormalError (response: NSHTTPURLResponse)->Void {
dispatch_async(dispatch_get_main_queue(),{ ()->() in
self.failureHandler(response: response)
})
}
func handleUnauthorizedError (response: NSHTTPURLResponse)->Void {
dispatch_async(dispatch_get_main_queue(),{ ()->() in
self.failureHandler(response: response)
})
}
}
| true
|
4027fc9fe8ba1e8b2f7cf1779a1de47a53d4fd1e
|
Swift
|
doc22940/learn.bulletinboard.ios
|
/Example/Swift/Bulletin/PetSelectorBulletinPage.swift
|
UTF-8
| 6,611
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
/**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
import BLTNBoard
/**
* An item that displays a choice with two buttons.
*
* This item demonstrates how to create a page bulletin item with a custom interface, and changing the
* next item based on user interaction.
*/
class PetSelectorBulletinPage: FeedbackPageBLTNItem {
private var catButtonContainer: UIButton!
private var dogButtonContainer: UIButton!
private var selectionFeedbackGenerator = SelectionFeedbackGenerator()
// MARK: - BLTNItem
/**
* Called by the manager when the item is about to be removed from the bulletin.
*
* Use this function as an opportunity to do any clean up or remove tap gesture recognizers /
* button targets from your views to avoid retain cycles.
*/
override func tearDown() {
catButtonContainer?.removeTarget(self, action: nil, for: .touchUpInside)
dogButtonContainer?.removeTarget(self, action: nil, for: .touchUpInside)
}
/**
* Called by the manager to build the view hierachy of the bulletin.
*
* We need to return the view in the order we want them displayed. You should use a
* `BulletinInterfaceFactory` to generate standard views, such as title labels and buttons.
*/
override func makeViewsUnderDescription(with interfaceBuilder: BLTNInterfaceBuilder) -> [UIView]? {
let favoriteTabIndex = BulletinDataSource.favoriteTabIndex
// Pets Stack
// We add choice cells to a group stack because they need less spacing
let petsStack = interfaceBuilder.makeGroupStack(spacing: 16)
// Cat Button
let catButtonContainer = createChoiceCell(dataSource: .cat, isSelected: favoriteTabIndex == 0)
catButtonContainer.addTarget(self, action: #selector(catButtonTapped), for: .touchUpInside)
petsStack.addArrangedSubview(catButtonContainer)
self.catButtonContainer = catButtonContainer
// Dog Button
let dogButtonContainer = createChoiceCell(dataSource: .dog, isSelected: favoriteTabIndex == 1)
dogButtonContainer.addTarget(self, action: #selector(dogButtonTapped), for: .touchUpInside)
petsStack.addArrangedSubview(dogButtonContainer)
self.dogButtonContainer = dogButtonContainer
return [petsStack]
}
// MARK: - Custom Views
/**
* Creates a custom choice cell.
*/
func createChoiceCell(dataSource: CollectionDataSource, isSelected: Bool) -> UIButton {
let emoji: String
let animalType: String
switch dataSource {
case .cat:
emoji = "🐱"
animalType = "Cats"
case .dog:
emoji = "🐶"
animalType = "Dogs"
}
let button = UIButton(type: .system)
button.setTitle(emoji + " " + animalType, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
button.contentHorizontalAlignment = .center
button.accessibilityLabel = animalType
if isSelected {
button.accessibilityTraits.insert(.selected)
} else {
button.accessibilityTraits.remove(.selected)
}
button.layer.cornerRadius = 12
button.layer.borderWidth = 2
button.setContentHuggingPriority(.defaultHigh, for: .horizontal)
let heightConstraint = button.heightAnchor.constraint(equalToConstant: 55)
heightConstraint.priority = .defaultHigh
heightConstraint.isActive = true
let buttonColor = isSelected ? appearance.actionButtonColor : .lightGray
button.layer.borderColor = buttonColor.cgColor
button.setTitleColor(buttonColor, for: .normal)
button.layer.borderColor = buttonColor.cgColor
if isSelected {
next = PetValidationBLTNItem(dataSource: dataSource, animalType: animalType.lowercased())
}
return button
}
// MARK: - Touch Events
/// Called when the cat button is tapped.
@objc func catButtonTapped() {
// Play haptic feedback
selectionFeedbackGenerator.prepare()
selectionFeedbackGenerator.selectionChanged()
// Update UI
let catButtonColor = appearance.actionButtonColor
catButtonContainer?.layer.borderColor = catButtonColor.cgColor
catButtonContainer?.setTitleColor(catButtonColor, for: .normal)
catButtonContainer?.accessibilityTraits.insert(.selected)
let dogButtonColor = UIColor.lightGray
dogButtonContainer?.layer.borderColor = dogButtonColor.cgColor
dogButtonContainer?.setTitleColor(dogButtonColor, for: .normal)
dogButtonContainer?.accessibilityTraits.remove(.selected)
// Send a notification to inform observers of the change
NotificationCenter.default.post(name: .FavoriteTabIndexDidChange,
object: self,
userInfo: ["Index": 0])
// Set the next item
next = PetValidationBLTNItem(dataSource: .cat, animalType: "cats")
}
/// Called when the dog button is tapped.
@objc func dogButtonTapped() {
// Play haptic feedback
selectionFeedbackGenerator.prepare()
selectionFeedbackGenerator.selectionChanged()
// Update UI
let catButtonColor = UIColor.lightGray
catButtonContainer?.layer.borderColor = catButtonColor.cgColor
catButtonContainer?.setTitleColor(catButtonColor, for: .normal)
catButtonContainer?.accessibilityTraits.remove(.selected)
let dogButtonColor = appearance.actionButtonColor
dogButtonContainer?.layer.borderColor = dogButtonColor.cgColor
dogButtonContainer?.setTitleColor(dogButtonColor, for: .normal)
dogButtonContainer?.accessibilityTraits.insert(.selected)
// Send a notification to inform observers of the change
NotificationCenter.default.post(name: .FavoriteTabIndexDidChange,
object: self,
userInfo: ["Index": 1])
// Set the next item
next = PetValidationBLTNItem(dataSource: .dog, animalType: "dogs")
}
override func actionButtonTapped(sender: UIButton) {
// Play haptic feedback
selectionFeedbackGenerator.prepare()
selectionFeedbackGenerator.selectionChanged()
// Ask the manager to present the next item.
manager?.displayNextItem()
}
}
| true
|
b73d1718dd3e073d63bb39d3b0c2ed6b327b6cad
|
Swift
|
ayite1207/Reciplease_P10_openClassrooms_IOS
|
/P10_01_Xcode/Reciplease/Reciplease/Controller/DetailRecipeViewController.swift
|
UTF-8
| 3,020
| 2.765625
| 3
|
[] |
no_license
|
//
// DetailRecipeViewController.swift
// Reciplease
//
// Created by ayite on 26/01/2021.
//
import UIKit
class DetailRecipeViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var recipeImage: UIImageView!
@IBOutlet weak var titleRecipeLabel: UILabel!
@IBOutlet weak var showRecipeButton: UIButton!
// MARK: Properties
var detailRecipe : InfoRecipe?
var star : String = "star"
private var coreDataManager: CoreDataManager?
override func viewDidLoad() {
super.viewDidLoad()
guard let appdelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let coreDataRecipe = appdelegate.coreDataRecipe
coreDataManager = CoreDataManager(coreDataRecipe: coreDataRecipe)
displayRecipe()
configRightButtonNavBar()
}
// MARK: Methodes
private func displayRecipe(){
if let recipe = detailRecipe {
let stringPicture = recipe.image
let urlPicture = URL(string: stringPicture )
recipeImage.load(url: urlPicture!)
titleRecipeLabel.text = recipe.title
}
}
private func configRightButtonNavBar(){
star = checkIfEntityExist() ? "starFill" : "star"
let starImage = UIImage(named: star)
navigationItem.rightBarButtonItem = UIBarButtonItem(image: starImage, style: .plain, target: self, action: #selector(addFavorite))
}
@objc private func addFavorite(){
print("addFavorite")
guard let label = detailRecipe?.title,let image = detailRecipe?.image, let ingredients = detailRecipe?.ingredients,let url = detailRecipe?.url else { return }
print("someEntityExists :: \(coreDataManager?.someEntityExists(tilte: label))")
if !checkIfEntityExist() {
coreDataManager?.createFavoriteRecipe(label: label, image: image, ingredients: ingredients, url: url)
configRightButtonNavBar()
} else {
guard let titleRecipe = detailRecipe?.title else { return }
coreDataManager?.deleteRecipe(title: titleRecipe)
configRightButtonNavBar()
}
}
private func checkIfEntityExist() -> Bool{
guard let label = detailRecipe?.title, let checkIfEntityExist = coreDataManager?.someEntityExists(tilte: label)else { return false}
return checkIfEntityExist
}
}
extension DetailRecipeViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return detailRecipe?.ingredients.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ingredientsCell", for: indexPath)
cell.textLabel?.text = detailRecipe?.ingredients[indexPath.row]
return cell
}
}
| true
|
b6c849327b1038b71758e2f20e242fd22cdeeda0
|
Swift
|
zzheads/Aquatic-Saver
|
/Aquatic Saver/Model/Traccar/Extensible.swift
|
UTF-8
| 832
| 3.203125
| 3
|
[] |
no_license
|
//
// Extensible.swift
// Aquatic Saver
//
// Created by Алексей Папин on 31.08.2018.
// Copyright © 2018 Алексей Папин. All rights reserved.
//
import Foundation
protocol Extensible: Equatable {
var id : Int? { get set }
static func ==(lhs: Self, rhs: Self) -> Bool
}
extension Extensible {
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.id == rhs.id
}
}
extension Sequence where Iterator.Element: Extensible {
func findBy(id: Int) -> Iterator.Element? {
guard let found = self.filter({$0.id == id}).first else {
return nil
}
return found
}
func index(where id: Int) -> Int? {
var index = 0
for element in self {
if (element.id == id) { return index }
index += 1
}
return nil
}
}
| true
|
c0d13d3fe96972e6a370bdfc40f36689ec738cc8
|
Swift
|
cyw1843008835/savePhotoTodb
|
/SavePhotoToApp/ContentView.swift
|
UTF-8
| 2,641
| 2.828125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// SavePhotoToApp
//
// Created by yw c on 2020/01/18.
// Copyright © 2020 yw c. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var showImagePicker: Bool = false
@State var image:Image? = nil
var body: some View {
NavigationView {
VStack{
image?.resizable()
.scaledToFit()
.clipShape(Circle())
Button(action: {
self.showImagePicker = true
}) {
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
}
NavigationLink(destination: SecondView(showImagePicker: self.$showImagePicker,image: self.$image)) {
Text("Placeholder1")
}
NavigationLink(destination: SecondView1(showImagePicker: self.$showImagePicker,image: self.$image)) {
Text("Placeholder2")
}
}.sheet(isPresented: self.$showImagePicker){
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
}
}.navigationViewStyle(StackNavigationViewStyle()) }
}
struct SecondView: View {
@Binding var showImagePicker: Bool
@Binding var image:Image?
var body: some View {
VStack{
image?.resizable()
.scaledToFit()
.clipShape(Circle())
Button(action: {
self.showImagePicker = true
}) {
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
.background(Color.red)
.font(.system(size: 40))
.foregroundColor(Color.white)
.cornerRadius(90)
.padding(20)
}
Text("画面遷移できました")
}.sheet(isPresented: self.$showImagePicker){
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
}
}
}
struct SecondView1: View {
@Binding var showImagePicker: Bool
@Binding var image:Image?
var body: some View {
VStack{
image?.resizable()
.scaledToFit()
.clipShape(Circle())
Button(action: {
self.showImagePicker = true
}) {
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
}
Text("画面遷移できました1")
}.sheet(isPresented: self.$showImagePicker){
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
af012a27f90ce4d3a736c2e86207f26ae4850064
|
Swift
|
hyazel/activity
|
/CoreActivity/ML/MLManager.swift
|
UTF-8
| 3,113
| 2.8125
| 3
|
[] |
no_license
|
//
// MLManager.swift
// Activity
//
// Created by laurent.droguet on 15/07/2019.
// Copyright © 2019 laurent.droguet. All rights reserved.
//
import Foundation
import CoreML
public final class MLManager {
struct Constants {
static let numOfFeatures: Int = 6
static let predictionWindowSize = 30
static let sensorsUpdateInterval = 1.0 / 30.0
static let hiddenInLength = 200
static let hiddenCellInLength = 200
static let textErrorClassification = "N/A"
}
private let activityModel = MyActivityClassifier()
private var currentIndexInPredictionWindow: Int
private let predictionWindowDataArray = try? MLMultiArray(shape: [1,
NSNumber(value: Constants.predictionWindowSize),
NSNumber(value: Constants.numOfFeatures)],
dataType: MLMultiArrayDataType.double)
private var lastHiddenOutput = try? MLMultiArray(shape:[Constants.hiddenInLength as NSNumber],
dataType: MLMultiArrayDataType.double)
private var lastHiddenCellOutput = try? MLMultiArray(shape:[Constants.hiddenCellInLength as NSNumber],
dataType: MLMultiArrayDataType.double)
public init() {
currentIndexInPredictionWindow = 0
}
public func handleMotionDataAndPredict(motionData: MotionData, classification: (String) -> Void) {
guard let dataArray = predictionWindowDataArray else { return }
dataArray[[0, currentIndexInPredictionWindow, 0] as [NSNumber]] = motionData.rotationX as NSNumber
dataArray[[0, currentIndexInPredictionWindow, 1] as [NSNumber]] = motionData.rotationY as NSNumber
dataArray[[0, currentIndexInPredictionWindow, 2] as [NSNumber]] = motionData.rotationZ as NSNumber
dataArray[[0, currentIndexInPredictionWindow, 3] as [NSNumber]] = motionData.accelerationX as NSNumber
dataArray[[0, currentIndexInPredictionWindow, 4] as [NSNumber]] = motionData.accelerationY as NSNumber
dataArray[[0, currentIndexInPredictionWindow, 5] as [NSNumber]] = motionData.accelerationZ as NSNumber
currentIndexInPredictionWindow += 1
if (currentIndexInPredictionWindow == Constants.predictionWindowSize) {
currentIndexInPredictionWindow = 0
classification(performPrediction())
}
}
public func performPrediction() -> String {
guard let dataArray = predictionWindowDataArray else { return "Error"}
let modelPrediction = try? activityModel.prediction(features: dataArray,
hiddenIn: lastHiddenOutput,
cellIn: lastHiddenCellOutput)
lastHiddenOutput = modelPrediction?.hiddenOut
lastHiddenCellOutput = modelPrediction?.cellOut
return modelPrediction?.activity ?? Constants.textErrorClassification
}
}
| true
|
c49bdc154fa4c2ffa18a534b11015587a95d84da
|
Swift
|
Hipo/macaroon
|
/macaroon/Classes/Views/Configuration/Styling/StyleElements/Border.swift
|
UTF-8
| 901
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
// Copyright © 2019 hipolabs. All rights reserved.
import Foundation
import UIKit
public struct Border {
public let color: UIColor
public let width: CGFloat
public init(
color: UIColor,
width: CGFloat
) {
self.color = color
self.width = width
}
}
public struct GradientBorder {
public var isRounded: Bool {
return
!cornerRadii.isEmpty &&
!corners.isEmpty
}
public let colors: [CGColor]
public let width: CGFloat
public let cornerRadii: CGSize
public let corners: UIRectCorner
public init(
colors: [UIColor],
width: CGFloat,
cornerRadii: LayoutSize = (0, 0),
corners: UIRectCorner = []
) {
self.colors = colors.map(\.cgColor)
self.width = width
self.cornerRadii = CGSize(cornerRadii)
self.corners = corners
}
}
| true
|
6a5f551debbebf8acbe0a6f411983e2d576fab5b
|
Swift
|
cyang/Insta-G
|
/Insta G/PhotosViewController.swift
|
UTF-8
| 7,924
| 2.578125
| 3
|
[] |
no_license
|
//
// PhotosViewController.swift
// Insta G
//
// Created by Christopher Yang on 2/10/16.
// Copyright © 2016 Christopher Yang. All rights reserved.
//
import UIKit
import AFNetworking
import SVPullToRefresh
class PhotosViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
@IBOutlet weak var tableView: UITableView!
var photos: [NSDictionary]?
var isMoreDataLoading = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 320
// Do any additional setup after loading the view.
getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let photos = photos {
return photos.count;
} else {
return 0;
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
headerView.backgroundColor = UIColor(white: 1, alpha: 0.9)
let profileView = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
profileView.clipsToBounds = true
profileView.layer.cornerRadius = 15;
profileView.layer.borderColor = UIColor(white: 0.7, alpha: 0.8).CGColor
profileView.layer.borderWidth = 1;
// Use the section number to get the right URL
let photo = photos![section]
let profilePhotoUrl = NSURL(string: photo["user"]!["profile_picture"] as! String)
profileView.setImageWithURL(profilePhotoUrl!)
headerView.addSubview(profileView)
// Add a UILabel for the username here
let usernameLabel = UILabel(frame: CGRect(x: 50, y: 15, width: 100, height: 30))
let username = photo["user"]!["username"] as! String!
usernameLabel.text = username
usernameLabel.sizeToFit()
headerView.addSubview(usernameLabel)
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PhotoCell", forIndexPath: indexPath) as! PhotoCell;
let photo = photos![indexPath.section]
let photoUrl = NSURL(string: photo["images"]!["standard_resolution"]!!["url"] as! String!)
cell.pictureImageView.setImageWithURL(photoUrl!)
return cell;
}
func getData(){
let clientId = "e05c462ebd86446ea48a5af73769b602"
let url = NSURL(string:"https://api.instagram.com/v1/media/popular?client_id=\(clientId)")
let request = NSURLRequest(URL: url!)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate:nil,
delegateQueue:NSOperationQueue.mainQueue()
)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
self.photos = responseDictionary["data"] as? [NSDictionary]
self.tableView.reloadData();
}
}
});
task.resume()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let vc = segue.destinationViewController as! PhotoDetailsViewController
let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
let photo = photos![(indexPath?.section)!]
let photoUrl = NSURL(string: photo["images"]!["standard_resolution"]!!["url"] as! String!)
vc.photoUrl = photoUrl
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
tableView.deselectRowAtIndexPath(indexPath, animated:true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func scrollViewDidScroll(scrollView: UIScrollView) {
// Handle scroll behavior here
if (!isMoreDataLoading) {
// Calculate the position of one screen length before the bottom of the results
let scrollViewContentHeight = tableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height
// When the user has scrolled past the threshold, start requesting
if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.dragging) {
isMoreDataLoading = true
// ... Code to load more results ...
loadMoreData()
}
}
}
func loadMoreData() {
// ... Create the NSURLRequest (myRequest) ...
// Configure session so that completion handler is executed on main UI thread
let clientId = "e05c462ebd86446ea48a5af73769b602"
let url = NSURL(string:"https://api.instagram.com/v1/media/popular?client_id=\(clientId)")
let request = NSURLRequest(URL: url!)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate:nil,
delegateQueue:NSOperationQueue.mainQueue()
)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
let dataSet = responseDictionary["data"] as? [NSDictionary]
for element in dataSet! {
self.photos?.append(element)
}
// Update flag
self.isMoreDataLoading = false
// ... Use the new data to update the data source ...
// Reload the tableView now that there is new data
self.tableView.reloadData()
}
}
});
task.resume()
}
}
| true
|
40306f2ecd55ce6909ad6eb7a5c657725fcc81df
|
Swift
|
cedricbahirwe/DOIT
|
/Mobile/Mobile/SubViews/TasksList.swift
|
UTF-8
| 2,140
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// TasksList.swift
// Mobile
//
// Created by Cédric Bahirwe on 21/02/2021.
//
import SwiftUI
struct TasksList: View {
@EnvironmentObject var vm: MainViewModel
var body: some View {
List(
vm.isSearching ?
vm.searchedEvents :
vm.filteredTasks
)
{ task in
HStack(alignment: .top) {
Image(systemName: task.isDone ? "checkmark.square.fill" : "checkmark.square")
.imageScale(.large)
.foregroundColor(.darkBlue)
VStack(alignment: .leading, spacing: 5) {
HStack {
Text(task.title)
.font(.montSerrat(.bold))
.lineLimit(2)
.minimumScaleFactor(0.8)
Spacer()
Image(systemName: "ellipsis")
.rotationEffect(.radians(.pi/2))
}
Text(task.priority.rawValue)
.font(.montSerrat(.bold, size: 8))
.padding(.vertical, 4)
.frame(width: 60)
.foregroundColor(.white)
.background(task.priorityColor)
.clipShape(Capsule())
HStack {
Text("Created " + task.createDate.formatted)
Text("Modified " + task.modifiedDate.formatted)
}
.font(.montSerrat(.regular, size: 10))
.foregroundColor(.darkBlue)
}
}
.blur(radius: task.isDone ? 0.5 : 0.0)
.opacity(task.isDone ? 0.5 : 1.0)
.contentShape(Rectangle())
.onTapGesture {
vm.selectedTask = task
vm.goToTaskDetails.toggle()
}
}.listStyle(PlainListStyle())
}
}
struct TasksList_Previews: PreviewProvider {
static var previews: some View {
TasksList()
.environmentObject(MainViewModel())
}
}
| true
|
72577ac21ad2298fa3204d873593eca8114e6fc9
|
Swift
|
jjones-jr/AUHost
|
/Vendor/mc/mcFoundation/Sources/Sources/Time.swift
|
UTF-8
| 516
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// Time.swift
// WaveLabs
//
// Created by Vlad Gorlov on 11/03/2017.
// Copyright © 2017 Vlad Gorlov. All rights reserved.
//
import Foundation
public struct Time {
public struct Interval {
public static let ThreeMinutes = TimeInterval(3 * 60)
public static let FiveMinutes = TimeInterval(5 * 60)
public static let OneHour = TimeInterval(60 * 60)
public static let OneDay = OneHour * 24
public static let OneWeek = OneDay * 7
public static let ThirtyDays = OneDay * 30
}
}
| true
|
149f230134480f12d2c85e86330592af0c41d247
|
Swift
|
r00b/DukePerson-manager
|
/ECE564_F17_HOMEWORK/DEPRECATEDDukePersonViewController.swift
|
UTF-8
| 11,395
| 2.71875
| 3
|
[] |
no_license
|
////
//// DukePersonViewController.swift
//// ECE564_F17_HOMEWORK
////
//// Created by Robert Steilberg on 9/19/17.
//// Copyright © 2017 ece564. All rights reserved.
////
//
//import UIKit
//import os.log
//
//class DukePersonViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
//
// // MARK: Properties
//
// // either passed by `DukeTableViewController` in `prepare(for:sender:)` or constructed as part of adding a new DukePerson
// var dukePerson: DukePerson?
//
// // define enums, since we can't just create an array from an enum class
// let genders: [String] = ["Male", "Female"]
// let roles: [String] = ["Student", "Teaching Assistant", "Professor"]
// let degrees: [String] = ["MS", "BS", "MENG", "Ph.D", "N/A", "Other"]
//
// var textFields = [UITextField]()
//
// // MARK: View components
//
// @IBOutlet weak var leftBarButton: UIBarButtonItem!
// @IBOutlet weak var rightBarButton: UIBarButtonItem!
//
// @IBOutlet weak var firstNameTextField: UITextField!
// @IBOutlet weak var lastNameTextField: UITextField!
// @IBOutlet weak var genderTextField: UITextField!
// @IBOutlet weak var roleTextField: UITextField!
// @IBOutlet weak var teamTextField: UITextField!
// @IBOutlet weak var fromTextField: UITextField!
// @IBOutlet weak var schoolTextField: UITextField!
// @IBOutlet weak var degreeTextField: UITextField!
// @IBOutlet weak var language1TextField: UITextField!
// @IBOutlet weak var language2TextField: UITextField!
// @IBOutlet weak var language3TextField: UITextField!
// @IBOutlet weak var hobby1TextField: UITextField!
// @IBOutlet weak var hobby2TextField: UITextField!
// @IBOutlet weak var hobby3TextField: UITextField!
//
// var activeField: UITextField?
//
// @IBOutlet weak var profilePicImageView: UIImageView!
//
// let genderPickerView = UIPickerView()
// let rolePickerView = UIPickerView()
// let degreePickerView = UIPickerView()
//
//
// // MARK: ViewController functions
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// // put TextFields in an array so we can loop to do batch-actions
// textFields.append(firstNameTextField)
// textFields.append(lastNameTextField)
// textFields.append(genderTextField)
// textFields.append(roleTextField)
// textFields.append(teamTextField)
// textFields.append(fromTextField)
// textFields.append(schoolTextField)
// textFields.append(degreeTextField)
// textFields.append(language1TextField)
// textFields.append(language2TextField)
// textFields.append(language3TextField)
// textFields.append(hobby1TextField)
// textFields.append(hobby2TextField)
// textFields.append(hobby3TextField)
//
// // set up delegates
// genderPickerView.delegate = self
// rolePickerView.delegate = self
// degreePickerView.delegate = self
// for textField in textFields {
// textField.delegate = self
// }
// genderTextField.inputView = genderPickerView
// roleTextField.inputView = rolePickerView
// degreeTextField.inputView = degreePickerView
//
// // see if we are being provided an existing DukePerson
// if let dukePerson = dukePerson {
//
// navigationItem.title = dukePerson.getFullName()
// leftBarButton.title = "Back"
// rightBarButton.title = "Edit"
// rightBarButton.isEnabled = true
//
// // getting properties of existing DukePerson
// firstNameTextField.text = dukePerson.getFirstName()
// lastNameTextField.text = dukePerson.getLastName()
// genderTextField.text = dukePerson.getGender()
// roleTextField.text = dukePerson.getRole()
// teamTextField.text = dukePerson.getTeam()
// fromTextField.text = dukePerson.whereFrom
// schoolTextField.text = dukePerson.getSchool()
// degreeTextField.text = dukePerson.getDegree()
// language1TextField.text = dukePerson.getLanguage(index: 0)
// language2TextField.text = dukePerson.getLanguage(index: 1)
// language3TextField.text = dukePerson.getLanguage(index: 2)
// hobby1TextField.text = dukePerson.getHobby(index: 0)
// hobby2TextField.text = dukePerson.getHobby(index: 1)
// hobby3TextField.text = dukePerson.getHobby(index: 2)
//
// for textField in textFields {
// textField.isUserInteractionEnabled = false
// }
// }
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
//
// // MARK: Navigation
//
// // Handle leftBarButton
// @IBAction func cancelAdd(_ sender: UIBarButtonItem) {
// // Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways
// let isPresentingInAddDukePersonMode = presentingViewController is UINavigationController
//
// if isPresentingInAddDukePersonMode {
// // cancel adding new DukePerson
// dismiss(animated: true, completion: nil)
// } else if let owningNavigationController = navigationController {
// // go back to list of DukePersons
// owningNavigationController.popViewController(animated: true)
// } else {
// fatalError("The DukePersonViewController is not inside a navigation controller")
// }
// }
//
// override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// guard let button = sender as? UIBarButtonItem, button === rightBarButton else {
// // Edit button not pressed, execute the segue
// return true
// }
// if rightBarButton.title! == "Edit" {
// enableTextFieldEditing()
// rightBarButton.title = "Save"
// // cancel the segue
// return false
// }
// return true
// }
//
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// super.prepare(for: segue, sender: sender)
//
// // configure the destination view controller only when the save button is pressed.
// guard let button = sender as? UIBarButtonItem, button === rightBarButton else {
// os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
// return
// }
//
// // let photo = profilePicImageView.image
//
// // creating a new DukePerson
// dukePerson = DukePerson()
// dukePerson?.setFirstName(firstName: firstNameTextField.text ?? "")
// dukePerson?.setLastName(lastName: lastNameTextField.text ?? "")
// dukePerson?.setGender(gender: genderTextField.text ?? "")
// dukePerson?.setRole(role: roleTextField.text ?? "")
// dukePerson?.setTeam(team: teamTextField.text ?? "")
// dukePerson?.setWhereFrom(whereFrom: fromTextField.text ?? "")
// dukePerson?.setSchool(school: schoolTextField.text ?? "")
// dukePerson?.setDegree(degree: degreeTextField.text ?? "")
// dukePerson?.addLanguages(languages: [language1TextField.text ?? "", language2TextField.text ?? "", language3TextField.text ?? ""])
// dukePerson?.addHobbies(hobbies: [hobby1TextField.text ?? "", hobby2TextField.text ?? "", hobby3TextField.text ?? ""])
// }
//
//
// // MARK: Actions
//
// @IBAction func rightBarButton(_ sender: UIBarButtonItem) {
// if sender.title == "Edit" {
// enableTextFieldEditing()
// }
// }
//
//
// // MARK: UIPickerViewDelegate / UIPickerViewDataSource functions
//
// func numberOfComponents(in pickerView: UIPickerView) -> Int {
// return 1
// }
//
// func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// switch pickerView {
// case genderPickerView:
// return genders.count
// case rolePickerView:
// return roles.count
// case degreePickerView:
// return degrees.count
// default:
// fatalError("Invalid Picker View used in controller.")
// }
// }
//
// func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
// switch pickerView {
// case genderPickerView:
// return genders[row]
// case rolePickerView:
// return roles[row]
// case degreePickerView:
// return degrees[row]
// default:
// fatalError("Invalid Picker View used in controller.")
// }
// }
//
// func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// switch pickerView {
// case genderPickerView:
// genderTextField.text = genders[row]
// case rolePickerView:
// roleTextField.text = roles[row]
// case degreePickerView:
// degreeTextField.text = degrees[row]
// default:
// fatalError("Invalid Picker View used in controller.")
// }
// }
//
//
// //MARK: UITextFieldDelegate functions
//
// func textFieldDidBeginEditing(_ textField: UITextField) {
// // Disable the Save button while editing.
// rightBarButton.isEnabled = false
// }
//
// // Check to see if all fields are valid, update modal title
// func textFieldDidEndEditing(_ textField: UITextField) {
// updateRightBarButtonState()
// let isPresentingInDukePersonDetailMode = !(presentingViewController is UINavigationController)
// if (isPresentingInDukePersonDetailMode) {
// navigationItem.title = dukePerson?.getFullName()
// }
// }
//
// // Dismiss keyboard when focus leaves TextField
// override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// view.endEditing(true)
// }
//
// // Dismiss keyboard when "Done" is pressed
// func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
// self.view.endEditing(true)
// return true
// }
//
//
// // MARK: Private functions
//
// private func updateRightBarButtonState() {
// // Disable the Save button if any of the following TextFields are empty
// let firstName = firstNameTextField.text ?? ""
// let lastName = lastNameTextField.text ?? ""
// let gender = genderTextField.text ?? ""
// let role = roleTextField.text ?? ""
// let from = fromTextField.text ?? ""
// let school = schoolTextField.text ?? ""
// rightBarButton.isEnabled = !firstName.isEmpty && !lastName.isEmpty && !gender.isEmpty && !role.isEmpty && !from.isEmpty && !school.isEmpty
// }
//
// private func enableTextFieldEditing() {
// for textField in textFields {
// textField.isUserInteractionEnabled = true
// }
// }
//}
| true
|
cce2a44b433717aa9223be65fbed8ff403fbd66a
|
Swift
|
omar9369/WelcomeB27
|
/MyPlayground.playground/Contents.swift
|
UTF-8
| 2,897
| 3.984375
| 4
|
[] |
no_license
|
import UIKit
let unsortedArray = [4,3,8,1,7,0]
func bubbleSort(arr: [Int]) -> [Int]{
var array = arr
for _ in 0..<array.count - 1{
for j in 0..<array.count - 1{
if(array [j] > array[j+1]){
let temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
}
}
}
return array
}
func mergeSort(array: [Int]) -> [Int]{
guard array.count > 1 else{
return array
}
let leftArray = Array(array[0..<array.count/2])
let rightArray = Array(array[array.count/2..<array.count])
return merge(left: mergeSort(array: leftArray), right: mergeSort(array: rightArray))
}
func merge(left: [Int], right: [Int]) -> [Int]{
var mergedArray: [Int] = []
var left = left
var right = right
while left.count > 0 && right.count > 0 {
if left.first! < right.first! {
mergedArray.append(left.removeFirst())
}else{
mergedArray.append(right.removeFirst())
}
}
return mergedArray + left + right
}
struct MinHeap{
var items: [Int] = []
private func getLeftChildIndex(_ parentIndex: Int) -> Int{
return 2 * parentIndex + 1
}
private func getRightChildIndex(_ parentIndex: Int) -> Int{
return 2 * parentIndex + 2
}
private func getParentIndex(_ childIndex: Int) -> Int{
return (childIndex - 1) / 2
}
private func hasLeftChild(_ index: Int) -> Bool{
return getLeftChildIndex(index) < items.count
}
private func hasRightChild(_ index: Int) -> Bool{
return getRightChildIndex(index) < items.count
}
private func hasParent(_ index: Int) -> Bool{
return getParentIndex(index) >= 0
}
private func leftChild(_ index: Int) -> Int {
return items[getLeftChildIndex(index)]
}
private func rightChild(_ index: Int) -> Int {
return items[getRightChildIndex(index)]
}
private func parent(_ index: Int) -> Int {
return items[getParentIndex(index)]
}
mutating private func swap(indexOne: Int, indexTwo: Int){
let placeholder = items[indexOne]
items[indexOne] = items[indexTwo]
items[indexTwo] = placeholder
}
public func peek() -> Int{
if items.count != 0{
return items[0]
}else{
fatalError()
}
}
mutating public func poll() -> Int {
if items.count != 0 {
let item = items[0]
items[0] = items[items.count - 1]
heapifyDown()
return item
}else{
fatalError()
}
}
mutating public func add(_ item: Int){
items.append(item)
heapifyUp()
}
}
print(bubbleSort(arr: unsortedArray))
print(mergeSort(array: unsortedArray))
| true
|
815b4328b1c573017aec2edab99b9a1ed2a8ce3e
|
Swift
|
kuotinyen/RainKit
|
/RainKit/Classes/UIButton + Extensions.swift
|
UTF-8
| 1,287
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// UIButton + Extensions.swift
// ChainsKit
//
// Created by TING YEN KUO on 2018/12/20.
//
import UIKit
extension UIButton {
@discardableResult
public func image(_ image: UIImage, for state: UIControl.State) -> Self {
self.setImage(image, for: state)
self.setTitle(nil, for: state)
return self
}
@discardableResult
public func backgroundImage(_ image: UIImage?, for state: UIControl.State) -> Self {
self.setBackgroundImage(image, for: state)
return self
}
@discardableResult
public func title(_ title: String, for state: UIControl.State) -> Self {
self.setImage(nil, for: state)
self.setTitle(title, for: state)
return self
}
@discardableResult
public func attributedTitle(_ title: NSAttributedString?, for state: UIControl.State) -> Self {
self.setAttributedTitle(title, for: state)
return self
}
@discardableResult
public func titleColor(_ color: UIColor, for state: UIControl.State = .normal) -> Self {
self.setTitleColor(color, for: state)
return self
}
@discardableResult
public func font(_ font: UIFont) -> Self {
self.titleLabel?.font(font)
return self
}
}
| true
|
7ce2f6a6a578c800e2cc9498c8df9ef3bfad95cc
|
Swift
|
sudox-history/sudox-ios
|
/sudox/views/Messages/dialogView.swift
|
UTF-8
| 2,578
| 2.90625
| 3
|
[] |
no_license
|
//
// dialog.swift
// Sudox-ios
//
// Created by Никита Казанцев on 22.03.2020.
// Copyright © 2020 Sudox. All rights reserved.
//
import SwiftUI
struct Dialog: View {
let name: String
let image: String
let last_message: String
let was_read: Bool
let last_message_time: String
let count_unread_messages: Int
let online: Bool
var body: some View {
HStack(alignment: .top){
Image(image)
.renderingMode(.original)
.resizable()
.frame(width: 56, height: 56)
.clipShape(Circle())
VStack(alignment: .leading)
{
Text(name).bold()
Text(last_message)
.font(.system(size: 14))
.padding(.leading,0)
.multilineTextAlignment(.leading)
}
Spacer()
VStack(alignment: .trailing){
HStack
{
Image(systemName: "checkmark")
.resizable()
.frame(width: 14, height: 11)
.foregroundColor(.green)
.padding(.top, 2)
Text(last_message_time)
.font(.system(size: 14))
.opacity(0.5)
}
if (String(count_unread_messages).count == 1 && count_unread_messages != 0 )
{
Text(String(count_unread_messages))
.foregroundColor(.white)
.font(.system(size: 14))
.padding(.leading,5)
.padding(.trailing,5)
.background(Color.green)
.clipShape(Circle())
}
else if (String(count_unread_messages).count > 1)
{
Text(String(count_unread_messages))
.foregroundColor(.white)
.font(.system(size: 12))
.fixedSize()
.padding(.leading,5)
.padding(.trailing,5)
.background(Color.green)
.cornerRadius(25.0)
}
}
}.padding(.leading,16).padding(.trailing,16)
}
}
| true
|
0d4b76b609552052f07071f63f2cc6d58355dd01
|
Swift
|
ekyawthan/CFSmartIOS2
|
/Smart CF/SurveyViewController.swift
|
UTF-8
| 4,299
| 2.515625
| 3
|
[] |
no_license
|
//
// SurveyViewController.swift
// Smart CF
//
// Created by Kyaw Than Mong on 10/3/15.
// Copyright © 2015 Meera Solution Inc. All rights reserved.
//
import UIKit
import MaterialKit
import Magic
class SurveyViewController: UIViewController {
let SurveyQuestions : [String] = [
" In the past week have you had worsening sputum volume or colour?",
"In the past week have you had new or increased blood in your sputum?",
"In the past week have you had increased cough?",
"In the past week have you had new or increased chest pain?",
"In the past week have you had new or increased wheeze?",
"In the past week have you had new or increased chest tightness?",
"In the past week have you had increased shortness of breath or difficulty breathing?",
"In the past week have you had increased fatigue or lethargy?",
"In the past week have you had a fever?",
"In the past week have you had loss of appetite or weight?",
"In the past week have you had sinus pain or tenderness?",
"In the past week do you feel that your health has worsened? ",
"In the past week have you felt low in mood?",
"In the past week have you felt worried?"
]
var collectedAnswer : [Int] = [Int]()
@IBOutlet weak var currentQuestionBar: UILabel!
@IBOutlet weak var currentQuestion: UILabel!
@IBOutlet weak var NoButton: MKButton!
@IBOutlet weak var yesButton: MKButton!
@IBOutlet weak var dismissSurvey: MKButton!
var counter : Int = 0 {
didSet {
magic(counter)
currentQuestion.text = SurveyQuestions[counter]
currentQuestionBar.text = "Question \(counter + 1) of 14 "
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupMKButton(NoButton)
setupMKButton(yesButton)
setupMKButton(dismissSurvey)
dismissSurvey.layer.borderWidth = 1.0
dismissSurvey.layer.borderColor = UIColor.MKColor.Orange.CGColor
currentQuestion.userInteractionEnabled = false
currentQuestion.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
currentQuestion.numberOfLines = 0
currentQuestion.text = SurveyQuestions[0]
self.NoButton.tag = 10
self.NoButton.addTarget(self, action: "didAnswer:", forControlEvents: UIControlEvents.TouchUpInside)
self.yesButton.tag = 20
self.yesButton.addTarget(self, action: "didAnswer:", forControlEvents: UIControlEvents.TouchUpInside)
}
private func setupMKButton(button : MKButton) {
button.cornerRadius = button.bounds.height / 2
button.backgroundLayerCornerRadius = button.bounds.height / 2
button.maskEnabled = false
button.ripplePercent = 1.75
button.rippleLocation = .Center
}
func didAnswer(button : MKButton) {
if (button.tag == 10){
collectedAnswer.append(0)
}
else {
collectedAnswer.append(1)
}
if(counter == 13){
yesButton.userInteractionEnabled = false
NoButton.userInteractionEnabled = false
SwiftSpinner.show("Posting ", animated: true)
User.postSurvey(collectedAnswer, completeHandler: {(res, error)
in
if let _ = error {
// something went wrong
SwiftSpinner.hide()
}else {
SwiftSpinner.hide()
NSNotificationCenter.defaultCenter().postNotificationName("justCompleteSurvey", object: nil)
SurveyHandler.cancelAllNotification()
self.dismissViewControllerAnimated(true, completion: nil)
}
})
return
}
else
{
counter = counter + 1
}
}
}
extension SurveyViewController {
@IBAction func didClickDismiss(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| true
|
4ac8f2acd92bb21fc524a6ae1f01907edadfef79
|
Swift
|
p4rtiz4n/sats-tracker
|
/SatsTracker/Modules/Assets/AssetInteractor.swift
|
UTF-8
| 2,777
| 2.546875
| 3
|
[
"WTFPL"
] |
permissive
|
//
// Created by p4rtiz4n on 20/12/2020.
//
import Foundation
protocol AssetsInteractor {
typealias AssetsPageHandler = ([Asset])->()
typealias AssetsHandler = (Result<[Asset], Error>)->()
typealias CandlesHandler = (Result<[Candle], Error>)->()
func load(
pageLoadedHandler: @escaping AssetsPageHandler,
completionHandler: @escaping AssetsHandler
)
func candles(for asset: Asset, lim: Int?, handler: @escaping CandlesHandler)
func candlesCancel(_ assetId: String?, _ idHash: Int?)
func candlesClearCache()
func favoriteAssets() -> [FavouriteAsset]
func toggleFavourite(_ asset: Asset)
}
// MARK: - DefaultAssetsService
class DefaultAssetsInteractor: AssetsInteractor {
private let assetsService: AssetsService
private let candleCacheService: CandlesCacheService
private let favoriteAssetsService: FavouriteAssetsService
init(
assetsService: AssetsService,
candleCacheService: CandlesCacheService,
favoriteAssetsService: FavouriteAssetsService
) {
self.assetsService = assetsService
self.candleCacheService = candleCacheService
self.favoriteAssetsService = favoriteAssetsService
}
// MARK: - Asset handling
func load(
pageLoadedHandler: @escaping ([Asset]) -> (),
completionHandler: @escaping (Result<[Asset], Error>) -> ()
) {
assetsService.assets(
pageHandler: pageLoadedHandler,
completionHandler: completionHandler
)
}
// MARK: - Candles handling
func candles(for asset: Asset, lim: Int?, handler: @escaping CandlesHandler) {
var (start, end): (Date?, Date?) = (nil, nil)
if let lim = lim {
start = Date().addingTimeInterval(-TimeInterval.days(lim))
end = Date()
}
candleCacheService.candles(
assetId: asset.id,
interval: .d1,
start: start,
end: end,
handler: handler
)
}
func candlesCancel(_ assetId: String?, _ idHash: Int?) {
candleCacheService.cancel(assetId, idHash)
}
func candlesClearCache() {
candleCacheService.clear()
}
// MARK: - Favourite handling
func favoriteAssets() -> [FavouriteAsset] {
favoriteAssetsService.favouriteAssets()
}
func toggleFavourite(_ asset: Asset) {
guard let fav = favoriteAssets().first(where: { $0.id == asset.id}) else {
favoriteAssetsService.addToFavorite(FavouriteAsset(asset: asset))
return
}
favoriteAssetsService.removerFromFavorite(fav)
}
}
// MARK: - AssetsServiceError
enum AssetsInteractorError: Error {
case network
case selectedQuoteMarketNotFound
}
| true
|
298f1e7ce5fa487ba73f23a0aa485fb20c7854cd
|
Swift
|
XmasRights/GraveyardSwift
|
/OReilly/GraveyardSwift/Extensions.swift
|
UTF-8
| 579
| 2.828125
| 3
|
[] |
no_license
|
//
// Extensions.swift
// GraveyardSwift
//
// Created by ChrisHome on 29/03/2015.
// Copyright (c) 2015 ChristmasHouse. All rights reserved.
//
import UIKit
extension UIColor
{
class func randomColour() -> UIColor
{
func random() -> CGFloat
{
return CGFloat(arc4random()) / CGFloat(UINT32_MAX)
}
return UIColor(red: random(), green: random(), blue: random(), alpha: 1.0)
}
class func darkTurquoiseColour() -> UIColor
{
return UIColor(red: 0, green: 153/255.0, blue: 76/255.0, alpha: 1.0)
}
}
| true
|
545158d91b1609d4c8666dd77f29353472c57be1
|
Swift
|
yujiahaol68/Recite_Word_Alpha_Version
|
/Recite_Word_Alpha_Version/TViewController.swift
|
UTF-8
| 4,566
| 2.640625
| 3
|
[] |
no_license
|
//
// TViewController.swift
// Recite_Word_Alpha_Version
//
// Created by xiaobo on 15-2-13.
// Copyright (c) 2015年 Sherlock.Yu. All rights reserved.
//
import UIKit
import CoreData
class TViewController: UIViewController,UITableViewDataSource {
var ewords = [String]()
var cwords = [String]()
var Delaterow :Int!
var Words = [Word]()
@IBOutlet weak var img: UIImageView!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.navigationItem.rightBarButtonItem = self.editButtonItem()
tableView.reloadData()
self.tableView.backgroundView = self.img
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.fetchData()
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: true)
tableView.setEditing(editing, animated: true)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete{
ewords.removeAtIndex(indexPath.row)
cwords.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top) //删除单词所在TV中的那一行,并且将数组中对应的中英文删除
Delaterow = indexPath.row
self.delateData(Delaterow)
self.tableView.reloadData()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return ewords.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
cell.textLabel?.font = UIFont.systemFontOfSize(16)
cell.detailTextLabel?.textColor = UIColor(red:0.0 ,green:122.0/255.0, blue:1.0, alpha:1.0)
cell.textLabel?.text = ewords[indexPath.row]
cell.detailTextLabel?.text = cwords[indexPath.row]
cell.backgroundColor = UIColor.clearColor()
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetchData(){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Word")
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [Word]?
if let results = fetchedResults {
Words = results
for i in 0..<self.Words.count{
cwords.append(self.Words[i].cexplaination)
ewords.append(self.Words[i].orialE)
}
}else{
println("获取失败 \(error), \(error!.userInfo)")
}
self.tableView.reloadData()
}
func delateData(row :Int){
let wordToRemove = Words[row] as Word
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Word")
managedContext.deleteObject(wordToRemove)
var error: NSError?
if !managedContext.save(&error) {
println( "Could not save: \(error) " )
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
a717a6530a69b65bac3e8c3113b8b923b1298edd
|
Swift
|
kotalina/Coins-iOS
|
/iOS-test/Presentation/CryptocurrencyList/CryptocurrencyListViewController.swift
|
UTF-8
| 4,141
| 2.546875
| 3
|
[] |
no_license
|
//
// CryptocurrencyListViewController.swift
// iOS-test
//
// Created by Алина Кошманова on 13.07.2020.
// Copyright © 2020 Алина Кошманова. All rights reserved.
//
import Foundation
import UIKit
class CryptocurrencyListViewController: UITableViewController {
//MARK: - Properties
var cryptocurrencyList: [CryptocurrencyElement] = []
var manager: CryptocurrencyListTableViewManager?
var service = CryptocurrencyService()
var factory = CryptocurrencyListFactory()
var currentPage = 1
//MARK: - Outlets
var activiryIndicator: UIActivityIndicatorView!
//MARK: - Lifecycle functions
override func viewDidLoad() {
super.viewDidLoad()
self.configureView()
self.needToShowLoading(isNeedToShow: true)
self.updateCurrencyList(page: self.currentPage)
}
//MARK: - Private functions
private func updateCurrencyList(page: Int, needRefresh: Bool = false) {
self.service.getCryptocurrencyList(page: page, success: { (currenciesList) in
if let list = currenciesList?.data {
if needRefresh {
self.cryptocurrencyList = list
} else {
self.cryptocurrencyList.append(contentsOf: list)
}
DispatchQueue.main.async {
self.updateCells()
self.needToShowLoading(isNeedToShow: false)
}
}
}) { (errorMessage) in
DispatchQueue.main.async {
self.needToShowLoading(isNeedToShow: false)
self.showErrorAlert(message: errorMessage)
}
}
}
private func updateCells() {
let cellObjects = self.factory.cryptocurrencyCellObject(cryptocurrencyList: self.cryptocurrencyList)
self.manager?.updateWith(cellObjects: cellObjects)
}
private func showErrorAlert(message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: String.Alerts.Actions.ok, style: .cancel, handler: nil)
alert.addAction(okAction)
present(alert, animated: true)
}
private func needToShowLoading(isNeedToShow: Bool) {
if isNeedToShow {
self.activiryIndicator.startAnimating()
} else {
self.activiryIndicator.stopAnimating()
}
}
@objc func refresh(_ sender: AnyObject) {
self.updateCurrencyList(page: 1, needRefresh: true)
self.tableView.refreshControl?.endRefreshing()
}
//MARK: - Configurations functions
private func configureView() {
self.configureTableViewManager()
self.configureRefreshControl()
self.configureActivityIndicator()
}
private func configureTableViewManager() {
self.manager = CryptocurrencyListTableViewManager()
self.manager?.set(tableView: self.tableView)
self.manager?.set(delegate: self)
self.tableView.delegate = self.manager
self.tableView.dataSource = self.manager
}
private func configureRefreshControl() {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
self.tableView.refreshControl = refreshControl
}
private func configureActivityIndicator() {
self.activiryIndicator = UIActivityIndicatorView(frame: self.view.bounds)
self.activiryIndicator.center = self.view.center
self.activiryIndicator.hidesWhenStopped = true
self.tableView.addSubview(self.activiryIndicator)
self.tableView.bringSubviewToFront(self.activiryIndicator)
}
}
//MARK: - CryptocurrencyListTableViewManagerDelegate
extension CryptocurrencyListViewController: CryptocurrencyListTableViewManagerDelegate {
func loadCurrenciesForNextPage() {
self.currentPage += 1
self.updateCurrencyList(page: self.currentPage)
}
}
| true
|
b73d140d4c29422ad44755d540e3913f80f997cb
|
Swift
|
AdrianoSong/iOS-MyExtensions
|
/Sources/MyExtensions/Float+Extension.swift
|
UTF-8
| 522
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
//
// File.swift
//
//
// Created by Song on 24/09/20.
//
import Foundation
public extension Float {
/**
Currency formatter
- Parameter locale: `Locale`
- Returns: `String`
*/
func currencyFormatter(locale: Locale) -> String? {
let formatter = NumberFormatter()
formatter.usesGroupingSeparator = true
formatter.numberStyle = .currencyAccounting
formatter.locale = locale
return formatter.string(from: NSNumber(value: self))
}
}
| true
|
9a514f3b9ac2e72c691ab7ab0fc8ba6aad2d6d82
|
Swift
|
pnalvarez/TesteiOSv2
|
/Accenture-Challenge/Accenture-Challenge/Common/Extensions/String+.swift
|
UTF-8
| 1,334
| 3.203125
| 3
|
[] |
no_license
|
//
// String+.swift
// Accenture-Challenge
//
// Created by Pedro Alvarez on 05/07/20.
// Copyright © 2020 Pedro Alvarez. All rights reserved.
//
import Foundation
extension String {
static var empty: String { return ""}
func isValidEmail() -> Bool {
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
func hasUppercaseLetter() -> Bool {
return contains(where: {
$0 >= "A" && $0 <= "Z"
})
}
func hasNumber() -> Bool {
return contains(where: {
$0 >= "0" && $0 <= "9"
})
}
func hasSpecialCharacters() -> Bool {
do {
let regex = try NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: .caseInsensitive)
if let _ = regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, self.count)) {
return true
}
} catch {
debugPrint(error.localizedDescription)
return false
}
return false
}
}
| true
|
3d9224ca0df962cfc741f2c6418a6fb2164e0309
|
Swift
|
MaxiJunkie/WaveAnimation-
|
/WaveAnimation/ViewController.swift
|
UTF-8
| 3,728
| 3.015625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// WaveAnimation
//
// Created by Максим Стегниенко on 13.06.17.
// Copyright © 2017 Максим Стегниенко. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var testView: UIImageView!
var divider: CGFloat = 500
var degree: Double = 0
let animateDuration:TimeInterval = 0.5
override func viewDidLoad() {
super.viewDidLoad()
self.waveAnimation(view: testView)
}
@IBAction func repeatButton(_ sender: Any) {
self.waveAnimation(view: testView)
}
/*
Мне не нравится, то что я использую DispatchQueue.main.asyncAfter, и по идее есть другой вариант через cabasicanimation, но там свои камни
*/
func transformWaveAnimation(rotateAngle: Double,scaleX: CGFloat,scaleY: CGFloat,scaleZ: CGFloat) -> CATransform3D {
if rotateAngle < 0 && (scaleX > 0 || scaleY > 0 || scaleZ > 0) {
var transform = CATransform3DIdentity
transform.m34 = -1.0/divider
let angle = CGFloat((rotateAngle * Double.pi) / 180.0)
let transform1 :CATransform3D
let transform2 :CATransform3D
transform1 = CATransform3DRotate(transform, angle, 1, 0, 0)
transform2 = CATransform3DScale(transform, scaleX, scaleY, scaleZ)
return CATransform3DConcat(transform1, transform2)
}else if rotateAngle < 0 {
var transform = CATransform3DIdentity
transform.m34 = -1.0/divider
let rotateAngle = CGFloat((rotateAngle * Double.pi) / 180.0)
return CATransform3DRotate(transform, rotateAngle, 1, 0, 0)
}else if scaleX > 0 || scaleY > 0 || scaleZ > 0 {
var transform = CATransform3DIdentity
transform.m34 = -1.0/divider
return CATransform3DScale(transform, scaleX, scaleY, scaleZ)
}
return CATransform3DIdentity
}
/*
Здесь можно настроить кастомно почти любую деталь анимации например угол поворот или масштаб увелечения
*/
func waveAnimation(view: UIView) {
UIView.animate(withDuration: animateDuration) {
view.layer.transform = self.transformWaveAnimation(rotateAngle: 0, scaleX: 1.4, scaleY: 1.4, scaleZ: 1.4)
}
DispatchQueue.main.asyncAfter(deadline: .now() + animateDuration)
{
UIView.animate(withDuration: self.animateDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState, animations: {
view.layer.transform = self.transformWaveAnimation(rotateAngle: -15, scaleX: 1.15, scaleY: 1.15, scaleZ: 1.15)
}, completion: nil)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2*animateDuration)
{
UIView.animate(withDuration: self.animateDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState, animations: {
view.layer.transform = self.transformWaveAnimation(rotateAngle: 0, scaleX: 1, scaleY: 1, scaleZ: 1)
}, completion: nil)
}
}
}
| true
|
bb6822994d0b66c9782d5bbd7180ed1792351b4f
|
Swift
|
denizmersinlioglu/SwiftCommonPractices
|
/Codeable.playground/Contents.swift
|
UTF-8
| 1,363
| 3.671875
| 4
|
[] |
no_license
|
import UIKit
struct Employee {
var name: String
var id: Int
var favoriteToy: Toy
enum CodingKeys: String, CodingKey{
case id = "employeeId"
case name = "employeeName"
case gift = "giftName"
}
}
extension Employee: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(id, forKey: .id)
try container.encode(favoriteToy.name, forKey: .gift)
}
}
extension Employee: Decodable {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
id = try values.decode(Int.self, forKey: .id)
let gift = try values.decode(String.self, forKey: .gift)
favoriteToy = Toy(name: gift)
}
}
struct Toy: Codable {
var name: String
}
let toy1 = Toy(name: "Teddy")
let employee = Employee(name: "Deniz", id: 1, favoriteToy: toy1)
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(employee)
let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonData)
print(jsonString)
let jsonDecoder = JSONDecoder()
let employee2 = try jsonDecoder.decode(Employee.self, from: jsonData)
print(employee2)
| true
|
381dc44082202433feae4b3c6f0c1e6a001c0199
|
Swift
|
diegokamiha/movile-up
|
/MovileProject/Models/Episode.swift
|
UTF-8
| 364
| 3.078125
| 3
|
[] |
no_license
|
//
// Episode.swift
// MovileProject
//
// Created by iOS on 7/16/15.
//
//
import Foundation
struct Episode {
let title : String
let number: Int
static func allEpisodes() -> [Episode] {
let episodes = [("Episode ", 1), ("Episode ", 2), ("Episode ", 3)]
return episodes.map{ Episode(title: $0.0, number: $0.1)}
}
}
| true
|
3ab96b5dffecddc01dff3304f1b43880acf3a79c
|
Swift
|
MinaFujisawa/iOSAssignments
|
/Assignments/ProgrammaticView/ProgrammaticView/ViewController.swift
|
UTF-8
| 10,180
| 2.515625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ProgrammaticView
//
// Created by Derrick Park on 2017-05-24.
// Copyright © 2017 Derrick Park. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let framingView: UIView = UIView(frame: CGRect.zero)
let squareButton: UIButton = UIButton(type: .system)
let portraitButton: UIButton = UIButton(type: .system)
let landscapeButton: UIButton = UIButton(type: .system)
var framingViewHeightConstraint: NSLayoutConstraint = NSLayoutConstraint.init()
var framingViewWidthConstraint: NSLayoutConstraint = NSLayoutConstraint.init()
let purpleBox = UIView(frame: CGRect.zero)
let yellowBox = UIView()
let toggleBtn = UIButton()
// var purpleConstraintBottomToYellow : NSLayoutConstraint? = nil
var purpleConstraintBottomToYellow = NSLayoutConstraint()
var purpleConstraintBottomToParent = NSLayoutConstraint()
override func viewDidLoad() {
super.viewDidLoad()
squareButton.setTitle("Square", for: .normal)
squareButton.addTarget(self, action: #selector(resizeFramingView), for: .touchUpInside)
view.addSubview(squareButton)
squareButton.translatesAutoresizingMaskIntoConstraints = false
portraitButton.setTitle("Portrait", for: .normal)
portraitButton.addTarget(self, action: #selector(resizeFramingView), for: .touchUpInside)
view.addSubview(portraitButton)
portraitButton.translatesAutoresizingMaskIntoConstraints = false
landscapeButton.setTitle("Landscape", for: .normal)
landscapeButton.addTarget(self, action: #selector(resizeFramingView), for: .touchUpInside)
view.addSubview(landscapeButton)
landscapeButton.translatesAutoresizingMaskIntoConstraints = false
framingView.translatesAutoresizingMaskIntoConstraints = false
framingView.backgroundColor = UIColor.green
view.addSubview(framingView)
let buttonsHorizontalContraintsFormat = "|[squareButton(==portraitButton)][portraitButton(==landscapeButton)][landscapeButton]|"
let buttonsHorizontalContraints = NSLayoutConstraint.constraints(withVisualFormat: buttonsHorizontalContraintsFormat, options: .alignAllCenterY, metrics: nil, views: ["squareButton": squareButton, "portraitButton": portraitButton, "landscapeButton": landscapeButton])
NSLayoutConstraint.activate(buttonsHorizontalContraints)
let squareButtonBottomConstraint = NSLayoutConstraint.init(item: squareButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: -50.0)
squareButtonBottomConstraint.isActive = true
let framingViewCenterXContraint = NSLayoutConstraint.init(item: framingView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0)
framingViewCenterXContraint.isActive = true
let framingViewCenterYContraint = NSLayoutConstraint.init(item: framingView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0.0)
framingViewCenterYContraint.isActive = true
framingViewHeightConstraint = NSLayoutConstraint.init(item: framingView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 500.0)
framingViewHeightConstraint.isActive = true
framingViewWidthConstraint = NSLayoutConstraint.init(item: framingView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 500.0)
framingViewWidthConstraint.isActive = true
// PurpleBox
purpleBox.translatesAutoresizingMaskIntoConstraints = false
purpleBox.backgroundColor = UIColor.purple
framingView.addSubview(purpleBox)
// BlueBoxes
let blueParent = UIView()
let blueBox1 = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let blueBox2 = UIView(frame: CGRect(x: 0, y: 100, width: 50, height: 50))
let blueBox3 = UIView(frame: CGRect(x: 0, y: 200, width: 50, height: 50))
blueBox1.backgroundColor = UIColor.blue
blueBox2.backgroundColor = UIColor.blue
blueBox3.backgroundColor = UIColor.blue
blueParent.addSubview(blueBox1)
blueParent.addSubview(blueBox2)
blueParent.addSubview(blueBox3)
blueParent.translatesAutoresizingMaskIntoConstraints = false
framingView.addSubview(blueParent)
// SAME
// NSLayoutConstraint( item: blueParent, attribute: .centerX, relatedBy: .equal, toItem: framingView,
// attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
blueParent.centerXAnchor.constraint(equalTo: framingView.centerXAnchor).isActive = true
blueParent.centerYAnchor.constraint(equalTo: framingView.centerYAnchor).isActive = true
NSLayoutConstraint(item: blueParent, attribute: .width, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 50).isActive = true
NSLayoutConstraint(item: blueParent, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 250).isActive = true
// OrangeBoxes
let orangeBox1 = UIView(frame: CGRect.zero)
let orangeBox2 = UIView(frame: CGRect.zero)
orangeBox1.backgroundColor = UIColor.orange
orangeBox2.backgroundColor = UIColor.orange
orangeBox1.layer.borderWidth = 8
orangeBox2.layer.borderWidth = 8
orangeBox1.layer.borderColor = UIColor.red.cgColor
orangeBox2.layer.borderColor = UIColor.red.cgColor
orangeBox1.translatesAutoresizingMaskIntoConstraints = false
orangeBox2.translatesAutoresizingMaskIntoConstraints = false
framingView.addSubview(orangeBox1)
framingView.addSubview(orangeBox2)
NSLayoutConstraint(item: orangeBox1, attribute: .width, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 80).isActive = true
NSLayoutConstraint(item: orangeBox2, attribute: .width, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 100).isActive = true
NSLayoutConstraint(item: orangeBox1, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 50).isActive = true
NSLayoutConstraint(item: orangeBox2, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 50).isActive = true
NSLayoutConstraint(item: orangeBox1, attribute: .right, relatedBy: .equal, toItem: framingView,
attribute: .right, multiplier: 1.0, constant: -20).isActive = true
NSLayoutConstraint(item: orangeBox1, attribute: .top, relatedBy: .equal, toItem: framingView,
attribute: .top, multiplier: 1.0, constant: 20).isActive = true
NSLayoutConstraint(item: orangeBox2, attribute: .right, relatedBy: .equal, toItem: orangeBox1,
attribute: .left, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: orangeBox2, attribute: .top, relatedBy: .equal, toItem: framingView,
attribute: .top, multiplier: 1.0, constant: 20).isActive = true
// Yellow
yellowBox.backgroundColor = UIColor.yellow
yellowBox.translatesAutoresizingMaskIntoConstraints = false
framingView.addSubview(yellowBox)
NSLayoutConstraint(item: yellowBox, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 150).isActive = true
NSLayoutConstraint(item: yellowBox, attribute: .width, relatedBy: .equal, toItem: framingView,
attribute: .width, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: yellowBox, attribute: .bottom, relatedBy: .equal, toItem: framingView,
attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: yellowBox, attribute: .left, relatedBy: .equal, toItem: framingView,
attribute: .left, multiplier: 1.0, constant: 0).isActive = true
// purple constraint
purpleConstraintBottomToYellow = NSLayoutConstraint(item: purpleBox, attribute: .bottom, relatedBy: .equal, toItem: yellowBox, attribute: .top, multiplier: 1.0, constant: 0)
purpleConstraintBottomToParent = NSLayoutConstraint(item: purpleBox, attribute: .bottom, relatedBy: .equal, toItem: framingView, attribute: .bottom, multiplier: 1.0, constant: -20)
purpleConstraintBottomToYellow.isActive = true
purpleConstraintBottomToParent.isActive = false
NSLayoutConstraint(item: purpleBox, attribute: .right, relatedBy: .equal, toItem: framingView,
attribute: .right, multiplier: 1.0, constant: -20).isActive = true
NSLayoutConstraint(item: purpleBox, attribute: .width, relatedBy: .equal, toItem: framingView,
attribute: .width, multiplier: (305.0 / 500.0), constant: 0).isActive = true
NSLayoutConstraint(item: purpleBox, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1.0, constant: 50).isActive = true
// Button
toggleBtn.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
toggleBtn.backgroundColor = UIColor.green
toggleBtn.setTitle("Click Me", for: .normal)
toggleBtn.isSelected = true
// yellowBox.isHidden = true
toggleBtn.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
toggleBtn.tag = 1
view.addSubview(toggleBtn)
}
func btnAction(sender: UIButton!) {
let btnsendtag: UIButton = sender
if btnsendtag.tag == 1 {
if (toggleBtn.isSelected) {
yellowBox.isHidden = true
toggleBtn.isSelected = false
purpleConstraintBottomToYellow.isActive = false
purpleConstraintBottomToParent.isActive = true
} else {
yellowBox.isHidden = false
toggleBtn.isSelected = true
purpleConstraintBottomToYellow.isActive = true
purpleConstraintBottomToParent.isActive = false
}
}
}
func resizeFramingView(_ sender: UIButton) {
var newWidth: CGFloat = 0.0
var newHeight: CGFloat = 0.0
if (sender == self.squareButton) {
newWidth = 500.0
newHeight = 500.0
} else if (sender == self.portraitButton) {
newWidth = 350.0
newHeight = 550.0
} else if (sender == self.landscapeButton) {
newWidth = 900.0
newHeight = 300.0
}
UIView.animate(withDuration: 2.0) {
self.framingViewHeightConstraint.constant = newHeight
self.framingViewWidthConstraint.constant = newWidth
self.view.layoutIfNeeded()
}
}
}
| true
|
c227977db33d9309f0e5b0391a802d5dca7a747e
|
Swift
|
chaitanyasanoriya/Todo-iOS-App
|
/todo_Chaitanya_C0777253/NoteDueViewController.swift
|
UTF-8
| 1,685
| 2.921875
| 3
|
[] |
no_license
|
//
// NoteDueViewController.swift
// todo_Chaitanya_C0777253
//
// Created by Chaitanya Sanoriya on 26/06/20.
// Copyright © 2020 Chaitanya Sanoriya. All rights reserved.
//
import UIKit
import CoreData
class NoteDueViewController: UIViewController
{
var mNotesString = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
/// Action Function for Done Button, dismisses this view
/// - Parameter sender: Done Button
@IBAction func doneClicked(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
/// Extension for Table Data Source and Delegate
extension NoteDueViewController: UITableViewDataSource, UITableViewDelegate
{
/// Sets the number of rows in a section
/// - Parameters:
/// - tableView: TableView for which this function is being called
/// - section: Index of Section
/// - Returns: Number of rows in this section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mNotesString.count
}
/// Gives the TableView cell for each indexpath
/// - Parameters:
/// - tableView: TableView for which this function is being called
/// - indexPath: IndexPath for the Cell
/// - Returns: Cell for IndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "notecell")
if cell == nil
{
cell = UITableViewCell(style: .default, reuseIdentifier: "notecell")
}
cell?.textLabel?.text = mNotesString[indexPath.row]
return cell!
}
}
| true
|
f05a7c2ba21c1c9f57fb9c7bf5f10ccaee8fb2f2
|
Swift
|
betabonsebas/GorillaRecipes
|
/Recipes/Model/APIManager.swift
|
UTF-8
| 745
| 2.875
| 3
|
[] |
no_license
|
//
// APIManager.swift
// Recipes
//
// Created by Sebastian Bonilla on 6/28/19.
// Copyright © 2019 bonsebas. All rights reserved.
//
import Foundation
import Alamofire
class APIManager {
static func getResponse<T: Codable> (url: String, completion: @escaping (_ result: T?, _ error: Error?) -> Void) {
Alamofire.request(url).responseData { data in
guard let responseData = data.data else { return }
do {
let decoder = JSONDecoder()
let recipes = try decoder.decode(T.self, from: responseData)
completion(recipes, nil)
} catch let error {
print(error)
completion(nil, error)
}
}
}
}
| true
|
bfb64256b11ca797fac08ac0520877c4e78bb285
|
Swift
|
CocoaHeadsConference/CHConferenceApp
|
/NSBrazilConf/Views/HomeTabBar.swift
|
UTF-8
| 3,158
| 2.875
| 3
|
[] |
no_license
|
import SwiftUI
struct HomeTabBar: View {
init(model: FeedViewModel) {
UITabBar.appearance().backgroundColor = UIColor(hexString: "#1D3115")
viewModel = model
}
enum SelectedMenu: Int {
case home
case schedule
}
@ObservedObject var viewModel: FeedViewModel
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
@State var currentlySelectedMenu: Int? = 0
var body: some View {
ZStack {
switch viewModel.isLoading {
case .loading:
ActivityIndicatorView()
case .loaded:
loadedBody
case .failed:
errorBody
}
}
}
@ViewBuilder
var loadedBody: some View {
if horizontalSizeClass == .regular, #available(iOS 14.0, *) {
largeScreenView
} else {
smallScreenView
}
}
@available(iOS 14.0, *)
var largeScreenView: some View {
NavigationView {
List {
NavigationLink(
destination: homeListView,
tag: 0,
selection: $currentlySelectedMenu,
label: {
Label("Home", systemImage: "house.fill")
})
NavigationLink(
destination: scheduleListView,
tag: 1,
selection: $currentlySelectedMenu,
label: {
Label("Agenda", systemImage: "calendar")
})
}
.listStyle(SidebarListStyle())
.navigationTitle("NSBrazil")
}
}
var smallScreenView: some View {
TabView {
homeListView
scheduleListView
}
.navigationBarTitle("NSBrazil")
.accentColor(Color(UIColor.label))
}
var homeListView: some View {
HomeList(feedViewModel: self.viewModel).tabItem ({
VStack {
Image(systemName: "house.fill")
.imageScale(.large)
.accentColor(Color(UIColor.label))
Text("Home")
}
})
.tag(1)
}
var scheduleListView: some View {
ScheduleListView(viewModel: self.viewModel).tabItem({
VStack {
Image(systemName: "calendar")
.imageScale(.large).accentColor(Color(UIColor.label))
Text("Schedule")
}
})
.tag(2)
}
var errorBody: some View {
VStack(spacing: 20) {
Text("Algo deu errado")
.font(Font.title.bold())
Button(action: {
self.viewModel.fetchInfo()
}, label: {
Text("Tentar novamente")
})
}
}
}
struct HomeTabBar_Previews: PreviewProvider {
static var previews: some View {
Group {
HomeTabBar(model: FeedViewModel())
HomeTabBar(model: FeedViewModel()).environment(\.colorScheme, .dark)
}
}
}
| true
|
4fc1e1597f75eaa8180f127ed77349a022240b3e
|
Swift
|
sherboo96/MVVM-Example
|
/MVVM/Scenes/ProductDetails/ProductDetailsViewModel.swift
|
UTF-8
| 750
| 3
| 3
|
[] |
no_license
|
//
// ProductDetailsViewModel.swift
// MVVM
//
// Created by Mahmoud Sherbeny on 30/09/2021.
//
import Foundation
import RxSwift
import RxCocoa
protocol ProductDetailsViewModelOutput {
var productToDispaly: PublishSubject<ProductViewModel> { get set }
}
protocol ProductDetailsViewModelInput {
func viewDidLoad()
}
class ProductDetailsViewModel: ViewModelProtocal, ProductDetailsViewModelInput, ProductDetailsViewModelOutput {
var prodcut: Product!
//Output
var productToDispaly: PublishSubject<ProductViewModel> = .init()
init(prodcut: Product) {
self.prodcut = prodcut
}
func viewDidLoad() {
let _product = ProductViewModel(prodcut)
productToDispaly.onNext(_product)
}
}
| true
|
4596c3c096d5bd6ea5e4d9d1421372e9f9e68d86
|
Swift
|
artyombatura/PurchasingDepartment
|
/PurchasingDepartment/PresentationLayer/JobRequestsModule/JobDetails/SupplierSubview.swift
|
UTF-8
| 5,346
| 2.75
| 3
|
[] |
no_license
|
import UIKit
class SupplierSubview: UIView {
enum ViewState {
case canBeRemoved
case notSelected
case selected(price: Double)
}
// MARK: - Subviews
private lazy var containerView: UIView = {
let v = UIView(frame: .zero)
v.backgroundColor = .white
return v
}()
private lazy var supplierNameTitleLabel: UILabel = {
let l = UILabel()
l.font = UIFont.app16Font
return l
}()
private lazy var supplierEmailTitleLabel: UILabel = {
let l = UILabel()
l.font = UIFont.app14Font
return l
}()
private lazy var removeButton: AccessoryButtonItem = {
let a = AccessoryButtonItem()
a.action = { [weak self] in
guard let self = self else {
return
}
self.removeAction?(self)
}
a.displayType = .remove
a.availability = .active
return a
}()
private lazy var viewStateInfoView: UIView = {
let v = UIView()
v.backgroundColor = UIColor.appGrayColor
v.isHidden = true
return v
}()
private lazy var priceTitleLabel: UILabel = {
let l = UILabel()
l.font = UIFont.app14Font
l.isHidden = true
return l
}()
// MARK: - Variables
var supplier: Supplier
var viewState: ViewState = .canBeRemoved {
didSet {
switch viewState {
case .canBeRemoved:
removeButton.isHidden = false
viewStateInfoView.isHidden = true
priceTitleLabel.isHidden = true
case .notSelected:
removeButton.isHidden = true
viewStateInfoView.isHidden = false
priceTitleLabel.isHidden = true
viewStateInfoView.backgroundColor = UIColor.appGrayColor
case let .selected(price):
removeButton.isHidden = true
viewStateInfoView.isHidden = false
priceTitleLabel.isHidden = false
viewStateInfoView.backgroundColor = UIColor.appDefaultColor
priceTitleLabel.text = "\(String(price))р."
}
}
}
var tapAction: ((SupplierSubview) -> Void)?
var removeAction: ((SupplierSubview) -> Void)?
init(supplier: Supplier) {
self.supplier = supplier
super.init(frame: .zero)
setupUI()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
self.addGestureRecognizer(tapGesture)
update(for: supplier, viewState: viewState)
}
override func layoutSubviews() {
super.layoutSubviews()
layer.backgroundColor = UIColor.clear.cgColor
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 1.0)
layer.shadowOpacity = 0.2
layer.shadowRadius = 4.0
layer.cornerRadius = 14
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Actions
@objc private func onTap() {
tapAction?(self)
}
@objc private func onRemoveTap() {
removeAction?(self)
}
// MARK: - Public methods
public func update(for supplier: Supplier, viewState: SupplierSubview.ViewState) {
self.viewState = viewState
self.supplier = supplier
supplierNameTitleLabel.text = supplier.name
supplierEmailTitleLabel.text = supplier.email
}
// MARK: - Private methods
private func setupUI() {
addSubview(containerView)
containerView.addSubview(supplierNameTitleLabel)
containerView.addSubview(supplierEmailTitleLabel)
containerView.addSubview(viewStateInfoView)
containerView.addSubview(removeButton)
containerView.addSubview(priceTitleLabel)
containerView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
viewStateInfoView.snp.makeConstraints {
$0.trailing.equalToSuperview().inset(10)
$0.height.width.equalTo(20)
$0.centerY.equalToSuperview()
}
removeButton.snp.makeConstraints {
$0.trailing.equalTo(viewStateInfoView)
$0.height.width.equalTo(viewStateInfoView)
$0.centerY.equalToSuperview()
}
priceTitleLabel.snp.makeConstraints {
$0.trailing.equalTo(viewStateInfoView.snp.leading).inset(4)
$0.centerY.equalToSuperview()
$0.width.equalTo(60)
}
supplierNameTitleLabel.snp.makeConstraints {
$0.top.equalToSuperview().offset(2)
$0.leading.equalToSuperview().offset(6)
$0.trailing.equalTo(removeButton.snp.leading).inset(20)
$0.height.equalTo(14)
}
supplierEmailTitleLabel.snp.makeConstraints {
$0.top.equalTo(supplierNameTitleLabel).offset(20)
$0.leading.trailing.height.equalTo(supplierNameTitleLabel)
}
viewStateInfoView.layer.cornerRadius = 10
removeButton.layer.cornerRadius = 10
}
}
| true
|
f3fda09a4d8f79b62eb920d669d89e0372bb8b9d
|
Swift
|
dnikolic98/weatherApp
|
/weatherApp/App/UI/Views/UserWarningView.swift
|
UTF-8
| 570
| 2.65625
| 3
|
[] |
no_license
|
//
// UserWarningView.swift
// weatherApp
//
// Created by Dario Nikolic on 14/09/2020.
// Copyright © 2020 Dario Nikolic. All rights reserved.
//
import UIKit
class UserWarningView: UIView {
static let height: CGFloat = 50
var warningInfo: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
buildViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
buildViews()
}
func setWarning(warningText: String) {
warningInfo.text = warningText
}
}
| true
|
74092e596b50fe7a1f05dc2094b785f95af0b3fe
|
Swift
|
mohsinalimat/Dodo
|
/Dodo/Animators/DodoAnimationsHide.swift
|
UTF-8
| 2,341
| 3
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
/// Collection of animation effects use for hiding the notification bar.
struct DodoAnimationsHide {
/**
Animation that rotates the bar around X axis in perspective with spring effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func rotate(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.rotate(duration, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar from to the left with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideLeft(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: false, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar to the right with fade-out effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideRight(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: true, showView: false, view: view, completed: completed)
}
/**
Animation that fades the bar out.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func fade(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.fade(duration, showView: false, view: view, completed: completed)
}
/**
Animation that slides the bar vertically out of view.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideVertically(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slideVertically(duration, showView: false, view: view,
locationTop: locationTop, completed: completed)
}
}
| true
|
c30027e989733b5f2ed797d5a0110b18d84001a1
|
Swift
|
JohnSlug/oisSwift
|
/CoinsAltarix/Coins/Coins/ViewController.swift
|
UTF-8
| 1,876
| 2.75
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Coins
//
// Created by Данил on 20.07.17.
// Copyright © 2017 Данил. All rights reserved.
//
import UIKit
import Alamofire
import Foundation
import SwiftyJSON
struct Coins {
let volumeUsd: Double
let availableSupply: Double
let id: String
let lastUpdated: String
let marketCapUsd: Double
let name: String
let percentChange1h: Double
let percentChange24h: Double
let percentChange7d: Double
let priceBtc: Double
let priceUsd: Double
let rank: Int
let symbol: String
let totalSupply: Double
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request("https://api.coinmarketcap.com/v1/ticker/?limit=10").responseJSON {
(response) -> Void in
if let jsonValue = response.result.value{
let json = JSON(jsonValue)
for item in json[].arrayValue {
print(item["name"].stringValue)
self.model.append(item["name"].stringValue)
}
}
}
}
var model = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let MyCellTable = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "MyCellTable")
MyCellTable.textLabel?.text = model[indexPath.row]
return (MyCellTable)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
0a0b52a5d4184e37b21dc5f84aac7a955a639b8f
|
Swift
|
p-larson/Mapiful-iOS
|
/Mapiful/Model/PrintModel.swift
|
UTF-8
| 3,469
| 3.296875
| 3
|
[] |
no_license
|
//
// PrintModel.swift
// Mapiful
//
// Created by Peter Larson on 11/4/20.
//
import SwiftUI
import CoreLocation
public class PrintModel: ObservableObject {
@Published public var size: PrintSize
@Published public var orientation: Orientation
@Published public var price: Int
public init(
size: PrintSize,
orientation: PrintOrientation,
price: Int = 0
) {
self.size = size
self.orientation = orientation
self.price = price
}
}
extension PrintModel {
public enum Orientation: String {
case portait = "Portait"
case landscape = "Landscape"
}
}
extension PrintModel {
public enum Size: RawRepresentable, Hashable {
public typealias RawValue = CGSize
case centimeters(width: Int, height: Int)
case inches(width: Int, height: Int)
public static let w30h40: Size = .centimeters(width: 30, height: 40) // 30x40cm
public static let w50h70: Size = .centimeters(width: 50, height: 70) // 50x70cm
public static let w70h100: Size = .centimeters(width: 70, height: 100) // 70x100cm
public static let w11h17: Size = .inches(width: 11, height: 17) // 11×17″
public static let w18h24: Size = .inches(width: 18, height: 24) // 18×24″
public static let w24h36: Size = .inches(width: 24, height: 36) // 24×36″
public static let allCases: [Size] = [
w30h40,
w50h70,
w70h100,
w11h17,
w18h24,
w24h36
]
public static var inches: [Size] {
Self.allCases.filter {
switch $0 {
case .centimeters:
return false
case .inches:
return true
}
}
}
// swiftlint:disable:next identifier_name
public static var cm: [Size] {
Self.allCases.filter {
switch $0 {
case .centimeters:
return true
case .inches:
return false
}
}
}
public var string: String {
switch self {
case .centimeters(let width, let height):
return "\(width)x\(height)cm"
case .inches(let width, let height):
return "\(width)x\(height)\""
}
}
public func hash(into hasher: inout Hasher) {
switch self {
case .centimeters(let width, let height):
hasher.combine(width)
hasher.combine(height)
return
case .inches(let width, let height):
hasher.combine(width)
hasher.combine(height)
return
}
}
public var rawValue: CGSize {
switch self {
case .centimeters(let width, let height):
return CGSize(width: width, height: height)
case .inches(let width, let height):
return CGSize(width: width, height: height)
}
}
public init?(rawValue: CGSize) {
return nil
}
static var magnitude: Size {
return w24h36
}
}
}
public typealias PrintSize = PrintModel.Size
public typealias PrintOrientation = PrintModel.Orientation
| true
|
78a2b58c148a47a476de4fd44831011d820b9bb5
|
Swift
|
uts-ios-dev/uts-ios-2019-project3-Group-145
|
/CurrencyExchange/AccountTableViewCell.swift
|
UTF-8
| 1,996
| 2.5625
| 3
|
[] |
no_license
|
//
// AccountTableViewCell.swift
// CurrencyExchange
//
// Created by UTS on 2019/5/29.
// Copyright © 2019 apple. All rights reserved.
//
import UIKit
class AccountTableViewCell: UITableViewCell {
var icon:UIImageView!
var nameLabel:UILabel!
var fullNameLabel:UILabel!
var reccord:RecordModel!{
didSet {
self.nameLabel.text = reccord.tcur
self.fullNameLabel.text = reccord.num
self.icon.image = UIImage.init(named: reccord.image)
self.setNeedsLayout()
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.icon = UIImageView.init()
self.contentView.addSubview(self.icon)
self.nameLabel = UILabel.init()
self.nameLabel.font = UIFont.systemFont(ofSize: 16)
self.contentView.addSubview(self.nameLabel)
self.fullNameLabel = UILabel.init()
self.fullNameLabel.font = UIFont.systemFont(ofSize: 16)
self.contentView.addSubview(self.fullNameLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
self.icon.frame = CGRect.init(x: 15, y: (self.contentView.height - 30) * 0.5, width: 30, height: 30)
self.nameLabel.sizeToFit()
self.nameLabel.frame = CGRect.init(x: self.icon.right + 15, y: (self.contentView.frame.height - self.nameLabel.frame.height) * 0.5, width: self.nameLabel.frame.width, height: self.nameLabel.frame.height)
self.fullNameLabel.sizeToFit()
self.fullNameLabel.frame = CGRect.init(x: self.contentView.width - self.fullNameLabel.width - 15, y: (self.contentView.frame.height - self.fullNameLabel.frame.height) * 0.5, width: self.fullNameLabel.frame.width, height: self.fullNameLabel.frame.height)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
675d6ec0eb2a77e1cd780609580ca88fa7c96c52
|
Swift
|
Falways/IOSFuture
|
/SwiftEasyApp/SwiftEasyApp/LandmarkDetail.swift
|
UTF-8
| 891
| 2.859375
| 3
|
[] |
no_license
|
//
// ContentView.swift
// SwiftEasyApp
//
// Created by 徐航 on 2019/9/25.
// Copyright © 2019 falways. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
MapView().edgesIgnoringSafeArea(.top).frame(height:300)
CircleImage().offset(y:-130).padding(.bottom, -130)
VStack(alignment:.leading,spacing: CGFloat(15)){
Text("Turtle Rock").font(.title).foregroundColor(.green)
HStack(alignment: .top){
Text("Joshua Tree National Park").font(.subheadline)
Spacer()
Text("Another Text").font(Font.subheadline)
}
}.padding()
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
1b3eed2a28938b192882b58cc376a6728d36e990
|
Swift
|
iamhspatel2160419/LBTAYouTubeTutorial
|
/LBTAYouTubeTutorial/App flow/Home/HomeController.swift
|
UTF-8
| 3,649
| 2.515625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// LBTAYouTubeTutorial
//
// Created by Kevin Quisquater on 19/10/2017.
// Copyright © 2017 Kevin Quisquater. All rights reserved.
//
import UIKit
class HomeController: UICollectionViewController {
let menuBar: MenuBar = {
let menuBar = MenuBar()
return menuBar
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
registerCells()
}
private func setupViews() {
collectionView?.backgroundColor = .white
collectionView?.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
setupNavigationBar()
setupMenuBar()
}
private func setupMenuBar() {
view.addSubview(menuBar)
menuBar.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
}
private func setupNavigationBar() {
navigationController?.navigationBar.isTranslucent = false
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 20, height: view.frame.height))
titleLabel.text = "Home"
titleLabel.textColor = .white
titleLabel.font = .systemFont(ofSize: 20)
navigationItem.titleView = titleLabel
let searchIcon = #imageLiteral(resourceName: "search_icon").withRenderingMode(.alwaysOriginal)
let searchBarButtonItem = UIBarButtonItem(image: searchIcon, style: .plain, target: self, action: #selector(handleSearch))
let settingsIcon = #imageLiteral(resourceName: "nav_more_icon").withRenderingMode(.alwaysOriginal)
let settingsBarButtonItem = UIBarButtonItem(image: settingsIcon, style: .plain, target: self, action: #selector(handleOpenSettings))
navigationItem.rightBarButtonItems = [settingsBarButtonItem, searchBarButtonItem]
}
private func registerCells() {
collectionView?.register(VideoCell.self, forCellWithReuseIdentifier: VideoCell.reuseIdentifier)
}
@objc private func handleSearch() {
}
let settingsLauncher = SettingsLauncher()
@objc private func handleOpenSettings() {
settingsLauncher.openSettings()
}
}
extension HomeController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VideoCell.reuseIdentifier, for: indexPath)
return cell
}
}
extension HomeController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellHeight = VideoCellMetrics.cellHeight(viewWidth: view.frame.width)
return CGSize(width: view.frame.width, height: cellHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
collectionView?.collectionViewLayout.invalidateLayout()
view.setNeedsDisplay()
}
}
| true
|
ec02188f0cfb013c4121fcde06978e2ad01c8f06
|
Swift
|
6zz/lab5
|
/lab5/DraggableImageView.swift
|
UTF-8
| 1,824
| 2.859375
| 3
|
[] |
no_license
|
//
// DraggableImageView.swift
// lab5
//
// Created by Shawn Zhu on 9/23/15.
// Copyright © 2015 Shawn Zhu. All rights reserved.
//
import UIKit
class DraggableImageView: UIView {
@IBOutlet weak var cardImageView: UIImageView!
@IBOutlet var contentView: UIView!
var image: UIImage? {
get {
return cardImageView.image
}
set {
cardImageView.image = newValue
}
}
var originalCenter: CGPoint!
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func initSubviews() {
let nib = UINib(nibName: "DraggableImageView", bundle: nil)
nib.instantiateWithOwner(self, options: nil)
contentView.frame = bounds
addSubview(contentView)
}
@IBAction func onCardPanGestureRecognizer(sender: UIPanGestureRecognizer) {
switch sender.state {
case UIGestureRecognizerState.Began:
originalCenter = cardImageView.center
case UIGestureRecognizerState.Changed:
let translation = sender.translationInView(superview)
cardImageView.center = CGPoint(
x: self.originalCenter.x + translation.x,
y: self.originalCenter.y + translation.y
)
case UIGestureRecognizerState.Ended:
print("ended")
default:
print("do nothing")
}
}
}
| true
|
62f40f2b82f907216da11bb0e2fc74a196c38508
|
Swift
|
todun/WeatherApp
|
/WeatherAppBasic/WeatherApp/API/Model/Coordinate.swift
|
UTF-8
| 515
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
//
// Coordinate.swift
// WeatherApp
//
// Created by emile on 11/04/2019.
// Copyright © 2019 emile. All rights reserved.
//
import Foundation
import CoreLocation
struct Coordinate: Codable {
// Custom property names
enum CodingKeys: String, CodingKey {
case latitude = "lat", longitude = "lon"
}
let latitude: Double
let longitude: Double
}
extension Coordinate {
init(_ coordinate: CLLocationCoordinate2D) {
self = .init(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
}
| true
|
066173dbbb63ed44dc0cc4ef3a74da316102c582
|
Swift
|
mofashy/ShiKe
|
/ShiKe/Classes/Modules/Cart/View/OrderAppendCell.swift
|
UTF-8
| 3,165
| 2.65625
| 3
|
[] |
no_license
|
//
// OrderAppendCell.swift
// ShiKe
//
// Created by 沈永聪 on 2018/6/13.
// Copyright © 2018年 沈永聪. All rights reserved.
//
import UIKit
enum AccessoryType {
case none
case indicator
}
class OrderAppendCell: UICollectionViewCell {
//MARK:- Members
lazy var titleLabel = UILabel()
lazy var detailsLabel = UILabel()
private lazy var indicatorView = UIImageView()
var accessoryType: AccessoryType = .none {
didSet {
indicatorView.isHidden = accessoryType == .none
}
}
//MARK:- Life cycle
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
setupSubviews()
configLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- Setup
func setupSubviews() {
titleLabel.font = shike_mediumFont(14)
titleLabel.textColor = shike_color_black
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
detailsLabel.font = shike_mediumFont(14)
detailsLabel.textColor = shike_color_darkGray
indicatorView.image = UIImage(named: "right_30")
indicatorView.contentMode = .scaleAspectFit
indicatorView.isHidden = true
self.contentView.addSubview(titleLabel)
self.contentView.addSubview(detailsLabel)
self.contentView.addSubview(indicatorView)
}
//MARK:- Layout
func configLayout() {
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.contentView.snp.left).offset(20)
make.centerY.equalTo(self.contentView.snp.centerY)
}
detailsLabel.snp.makeConstraints { (make) in
make.left.greaterThanOrEqualTo(titleLabel.snp.right).offset(20)
make.centerY.equalTo(titleLabel.snp.centerY)
make.right.equalTo(indicatorView.snp.left).offset(-10)
}
indicatorView.snp.makeConstraints { (make) in
make.right.equalTo(self.contentView.snp.right).offset(-20)
make.centerY.equalTo(titleLabel.snp.centerY)
make.height.equalTo(14)
make.width.equalTo(indicatorView.snp.height).multipliedBy(32.0 / 62.0)
}
}
func maskTop() {
mask(edge: .top)
}
func maskBottom() {
mask(edge: .bottom)
}
private func mask(edge: MaskEdge) {
let maskLayer = CAShapeLayer()
if edge == .top {
maskLayer.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadii: CGSize(width: 5, height: 5)).cgPath
} else {
maskLayer.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue), cornerRadii: CGSize(width: 5, height: 5)).cgPath
}
self.layer.mask = maskLayer
self.layer.masksToBounds = true
}
}
| true
|
3fe2e51326310a50f9d2b64db47798605678a539
|
Swift
|
diepnn01/42Events
|
/42Events/Routing/Route.swift
|
UTF-8
| 631
| 2.53125
| 3
|
[] |
no_license
|
//
// Route.swift
// Carival
//
// Created by Điệp Nguyễn on 8/13/18.
// Copyright © 2018 Crystal. All rights reserved.
//
import UIKit
import Alamofire
final class Route {
fileprivate(set) var method: HTTPMethod
fileprivate(set) var path: String
fileprivate(set) var queryParams: [String: Any]?
fileprivate(set) var jsonParams: [String: Any]?
public init(method: HTTPMethod,
path: String,
queryParams: [String: Any]? = nil,
jsonParams: [String: Any]? = nil) {
self.method = method
self.path = path
self.queryParams = queryParams
self.jsonParams = jsonParams
}
}
| true
|
b7e784313598b0ba2c485dca7f5c359f1ced2b11
|
Swift
|
amarildolucas/RepoStars
|
/RepoStars/Services/Network/APIClient.swift
|
UTF-8
| 1,716
| 3.0625
| 3
|
[] |
no_license
|
//
// APIClient.swift
// RepoStars
//
// Created by Amarildo Lucas on 23/09/20.
//
import Foundation
// MARK: - APIClient
struct APIClient<APIEndpoint: Endpoint> {
func getData(from endpoint: APIEndpoint, completion: @escaping (Result<Data, Error>) -> Void) {
guard let request = performRequest(for: endpoint) else {
completion(.failure(APIClientError.invalidURL))
return
}
loadData(with: request) { result in
switch result {
case .success(let data):
completion(.success(data))
case .failure(let error):
completion(.failure(error))
}
}
}
// MARK: - Request building
private func performRequest(for endpoint: APIEndpoint) -> URLRequest? {
guard var urlComponents = URLComponents(string: endpoint.absoluteURL) else {
return nil
}
urlComponents.queryItems = endpoint.parameters.compactMap({ parameter -> URLQueryItem in
return URLQueryItem(name: parameter.key, value: parameter.value)
})
guard let url = urlComponents.url else { return nil }
let urlRequest = URLRequest(url: url,
cachePolicy: .reloadRevalidatingCacheData,
timeoutInterval: 15)
return urlRequest
}
// MARK: - Getting data
private func loadData(with request: URLRequest, completion: @escaping (Result<Data, Error>) -> Void) {
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
guard let response = response as? HTTPURLResponse else {
completion(.failure(APIClientError.dataNil))
return
}
completion(.failure(APIError(rawValue: response.statusCode) ??
APIClientError.unknownError))
return
}
completion(.success(data))
}
task.resume()
}
}
| true
|
12f29af4dc27b7f4d99dcc9cf191c721f754c6e3
|
Swift
|
xiaoqiangheye/Card-Note
|
/Card Note/Structure/Card/VoiceCard.swift
|
UTF-8
| 1,962
| 2.71875
| 3
|
[] |
no_license
|
//
// VoiceCard.swift
// Card Note
//
// Created by 强巍 on 2018/4/27.
// Copyright © 2018年 WeiQiang. All rights reserved.
//
import Foundation
import UIKit
class VoiceCard:Card{
var voicepath = Constant.Configuration.url.Audio.absoluteString
var voiceManager:RecordManager?
init(id:String,title:String,parent:Card) {
super.init(title: title, tag: nil, description: "", id: id, definition: "", color: UIColor.white, cardType: "voice", modifytime: "")
voicepath.append(contentsOf: "/\(id).wav")
print(voicepath)
voiceManager = RecordManager(fileName: "\(id).wav")
self.setParent(card: parent)
}
init(id:String,title:String) {
super.init(title: title, tag: nil, description: "", id: id, definition: "", color: UIColor.white, cardType: "voice", modifytime: "")
voicepath.append(contentsOf: "/\(id).wav")
print(voicepath)
voiceManager = RecordManager(fileName: "\(id).wav")
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
// aCoder.encode(voicepath, forKey: "voicePath")
aCoder.encode(voiceManager?.state.rawValue, forKey: "state")
}
private enum CodingKeys:String,CodingKey{
case state = "state"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// self.voicepath = (aDecoder.decodeObject(forKey: "voicePath") as? String)!
self.voiceManager = RecordManager(fileName: "\(self.getId()).wav")
voicepath.append(contentsOf: "/\(self.getId()).wav")
let state = aDecoder.decodeObject(forKey: "state") as? String
if state != nil{
self.voiceManager?.state = RecordManager.State(rawValue:state!)!
}else{
self.voiceManager?.state = RecordManager.State.willRecord
}
// fatalError("init(coder:) has not been implemented")
}
}
| true
|
f8a78162c83682366d8d9124ad69d2bec868932e
|
Swift
|
burhanshakir/meditation-app-ios
|
/Meditation App/View/InstructionsCell.swift
|
UTF-8
| 810
| 2.8125
| 3
|
[] |
no_license
|
//
// InstructionsCell.swift
// Meditation App
//
// Created by Burhanuddin Shakir on 27/09/18.
// Copyright © 2018 meditation-app. All rights reserved.
//
import UIKit
class InstructionsCell: UITableViewCell {
@IBOutlet weak var meditationName : UILabel!
@IBOutlet weak var meditationDescription : UILabel!
var onViewButtonTapped : (() -> Void)? = nil
// Setting instruction data
func updateViews(instructions : MeditationInstructions)
{
meditationName.text = instructions.name
meditationDescription.text = instructions.description
}
//Onclick for view button
@IBAction func viewButtonClicked(_ sender: Any) {
if let onViewButtonTapped = self.onViewButtonTapped
{
onViewButtonTapped()
}
}
}
| true
|
4d74acb8ecab63c57e6e659a80945969282b9f8a
|
Swift
|
daniel-legler/SpitcastSwift
|
/SpitcastSwift/Classes/Model/SCModel.swift
|
UTF-8
| 145
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
typealias SCModel = Codable & SCModelProtocol
protocol SCModelProtocol {
static var dateFormatter: DateFormatter { get }
}
| true
|
76d32231e80906781aba6e07dc81368c6de6f32a
|
Swift
|
sniffapp/iOS
|
/Sniff/Classes/Extensions/StringExtension.swift
|
UTF-8
| 2,513
| 3.0625
| 3
|
[] |
no_license
|
//
// StringExtension.swift
// Sniff
//
// Created by Andrea Ferrando on 29/09/2016.
// Copyright © 2016 Matchbyte. All rights reserved.
//
import Foundation
extension String {
func toBool() -> Bool {
switch self {
case "True", "true", "yes", "YES","1":
return true
case "False", "false", "no", "NO", "0":
return false
default:
return false
}
}
func toDate(format : String) -> NSDate? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if dateFormatter.date(from: self) != nil {
return dateFormatter.date(from: self) as NSDate?
} else if format == "yyyy-mm-dd hh:mm"{
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
return dateFormatter.date(from: self) as NSDate?
}
return nil
}
var isEmailValid: Bool {
do {
let regex = try NSRegularExpression(pattern: "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: .caseInsensitive)
return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
func isPasswordValid() -> Bool {
return self.characters.count > 6
}
func toURL() -> NSURL {
return NSURL(string:self)!
}
func toNumber() -> NSNumber {
return NSNumber(value:Int(self)!)
}
static func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for _ in 0..<len {
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}
return randomString
}
}
| true
|
979c9df374d14d6fdd2bc4e23268bb77083c64c6
|
Swift
|
wentilin/CompilerStudy
|
/CompilerStudy/Parser/LRParser/LRAnalyticTable.swift
|
UTF-8
| 3,055
| 3.03125
| 3
|
[] |
no_license
|
//
// LRAnalyticTable.swift
// CompilerStudy
//
// Created by wentilin on 2020/7/11.
// Copyright © 2020 wentilin. All rights reserved.
//
import Foundation
enum LRAnalyticActionType: CustomStringConvertible {
case shift(order: Int)
case reduce(production: Production)
case accept
var description: String {
switch self {
case .shift(let order):
return "shift \(order)"
case .reduce(let order):
return "reduce \(order)"
case .accept:
return "accept"
}
}
}
struct LRAnalyticActionKey: Hashable, CustomStringConvertible {
let collectionOrder: Int
let node: Node
func hash(into hasher: inout Hasher) {
hasher.combine(collectionOrder)
hasher.combine(node.value)
}
static func == (lhs: LRAnalyticActionKey, rhs: LRAnalyticActionKey) -> Bool {
lhs.collectionOrder == rhs.collectionOrder && lhs.node.value == rhs.node.value
}
var description: String {
return "ActionKey<\(collectionOrder), \(node.value)>"
}
}
struct LRAnalyticGotoKey: Hashable, CustomStringConvertible {
let collectionOrder: Int
let node: NonterminalNode
func hash(into hasher: inout Hasher) {
hasher.combine(collectionOrder)
hasher.combine(node.value)
}
static func == (lhs: LRAnalyticGotoKey, rhs: LRAnalyticGotoKey) -> Bool {
lhs.collectionOrder == rhs.collectionOrder && lhs.node.value == rhs.node.value
}
var description: String {
return "<\(collectionOrder), \(node.value)>"
}
}
struct LRAnalyticActionCollection: CustomStringConvertible {
private var actions: [LRAnalyticActionKey: LRAnalyticActionType] = [:]
subscript(collectionOrder: Int, node: Node) -> LRAnalyticActionType? {
get {
actions[.init(collectionOrder: collectionOrder, node: node)]
} set {
actions[.init(collectionOrder: collectionOrder, node: node)] = newValue
}
}
var description: String {
return "\(actions)"
}
public func map<T>(_ transform: (LRAnalyticActionKey, LRAnalyticActionType) throws -> T) rethrows -> [T] {
return try actions.map(transform)
}
}
struct LRAnalyticGotoCollection: CustomStringConvertible {
private var gotos: [LRAnalyticGotoKey: Int] = [:]
subscript(collectionOrder: Int, node: NonterminalNode) -> Int? {
get {
gotos[.init(collectionOrder: collectionOrder, node: node)]
} set {
gotos[.init(collectionOrder: collectionOrder, node: node)] = newValue
}
}
var description: String {
return "\(gotos)"
}
}
struct LRAnalyticTable: CustomStringConvertible {
var actionCollection: LRAnalyticActionCollection = .init()
var gotos: LRAnalyticGotoCollection = .init()
var description: String {
return """
LRAnalyticTable:
actions: \(actionCollection) \n
gotos: \(gotos)
"""
}
}
| true
|
dc7e865fe95e18200ef296517d90dd531ac92782
|
Swift
|
metoSimka/FireBrick
|
/FireBrick/UI/EmployeesViewController/EmployeesViewController.swift
|
UTF-8
| 3,309
| 2.65625
| 3
|
[] |
no_license
|
//
// EmployeesViewController.swift
// FireBrick
//
// Created by metoSimka on 03/06/2019.
// Copyright © 2019 metoSimka. All rights reserved.
//
import UIKit
import Firebase
class EmployeesViewController: UIViewController {
// MARK: - Public variables
var users: [User] = []
// MARK: - IBOutlets
@IBOutlet weak var tableView: UITableView!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
fetchUsers()
}
// MARK: - Private methods
private func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.alwaysBounceVertical = false
let techCell = UINib(nibName: Constants.cellsID.employeesTableViewCell, bundle: nil)
tableView.register(techCell, forCellReuseIdentifier: Constants.cellsID.employeesTableViewCell)
self.tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableView.automaticDimension
}
private func fetchUsers() {
self.startLoader()
Firestore.firestore().collection(Constants.mainFireStoreCollections.users).getDocuments(completion: { (snapShot, error) in
guard error == nil else {
print("error Here", error ?? "Unkown error")
self.stopLoader()
return
}
guard let snapShot = snapShot else {
self.stopLoader()
return
}
guard let firebaseUsers = self.getUsers(from: snapShot) else {
self.stopLoader()
return
}
self.users = firebaseUsers
self.tableView.reloadData()
self.stopLoader()
})
}
private func getUsers(from snapShot: QuerySnapshot) -> [User]? {
var firebaseUsers: [User] = []
for data in snapShot.documents {
guard let name = data[Constants.fireStoreFields.users.name] as? String,
let iconLink = data[Constants.fireStoreFields.users.icon] as? String,
let busy = data[Constants.fireStoreFields.users.busy] as? Int,
let skills = data[Constants.fireStoreFields.users.skills] as? [[String:AnyObject]] else {
return nil
}
var user = User()
user.name = name
user.busy = busy
user.imageLink = iconLink
user.skills = skills
firebaseUsers.append(user)
}
return firebaseUsers
}
func startLoader() {
}
func stopLoader() {
}
}
// MARK: - Protocol Conformance
extension EmployeesViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = self.tableView.dequeueReusableCell(withIdentifier: Constants.cellsID.employeesTableViewCell) as? EmployeesTableViewCell else {
return UITableViewCell()
}
cell.user = users[indexPath.row]
cell.setupCell()
return cell
}
}
| true
|
08a72c444fc5ad2289f5f54d392a9ad2077ae203
|
Swift
|
noppefoxwolf/SwiftTask-Animation
|
/SwiftTaskAnimation/Classes/SwiftTaskAnimation.swift
|
UTF-8
| 1,744
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// SwiftTaskAnimation.swift
// Pods
//
// Created by Tomoya Hirano on 2016/11/04.
//
//
import UIKit
import SwiftTask
public typealias AnimationTask = Task<Progress, Bool, Error?>
public extension UIView {
public class func animateTask(with duration: TimeInterval,
delay: TimeInterval? = nil,
usingSpringWithDamping: CGFloat? = nil,
initialSpringVelocity: CGFloat? = nil,
options: UIViewAnimationOptions? = nil,
animations: (() -> Void)?,
completion: ((Bool) -> Void)? = nil) -> AnimationTask {
return AnimationTask(paused: true) { progress, fulfill, reject, configure in
DispatchQueue.main.async {
if let usingSpringWithDamping = usingSpringWithDamping, let initialSpringVelocity = initialSpringVelocity {
UIView.animate(withDuration: duration, delay: delay ?? 0.0, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options ?? [], animations: { () -> Void in
animations?()
}, completion: { finish in
completion?(finish)
if finish {
fulfill(finish)
} else {
reject(nil)
}
})
} else {
UIView.animate(withDuration: duration, delay: delay ?? 0.0, options: options ?? [], animations: { () -> Void in
animations?()
}, completion: { finish in
completion?(finish)
if finish {
fulfill(finish)
} else {
reject(nil)
}
})
}
}
}
}
}
| true
|
b173219d21d9d908d65ee5892a70d60adff4fdc9
|
Swift
|
bairuitech/anychat
|
/ios/src/AnyChat4Swfit/HelloAnyChatCloudSwift/HelloAnyChatSwift/UserViewController.swift
|
UTF-8
| 4,290
| 2.515625
| 3
|
[] |
no_license
|
//
// UserViewController.swift
// HelloAnyChatSwift
//
// Created by bairuitech on 15/11/2.
// Copyright © 2015年 bairuitech. All rights reserved.
// 在线用户列表
import UIKit
class UserViewController: UITableViewController, UIAlertViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
var allUserIDs :[Int32]? = [Int32]() {
didSet {
self.getAllUser(allUserIDs)
}
}
var allUser = [User]() // 所有用户(User对象数组)
var remoteUserId: Int32 = 0
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.emptyDataSetSource = self;
self.tableView.emptyDataSetDelegate = self;
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if allUserIDs == nil {
return 0
}else {
return allUser.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserList", forIndexPath: indexPath) as UITableViewCell
let user = allUser[indexPath.row] as User
cell.textLabel?.text = user.name // 用户名
cell.detailTextLabel?.text = String(user.uid) // 用户ID
let imageName = "face\((arc4random() % 5) + 1)" // 随机头像
cell.imageView?.image = UIImage(named: imageName)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectUser = self.allUser[indexPath.row]
self.remoteUserId = selectUser.uid
self.performSegueWithIdentifier("Video", sender: self)
// 取消选中状态
self.tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Video" {
let videoVC = segue.destinationViewController as! VideoViewController;
videoVC.remoteUserId = self.remoteUserId
}
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
// 离开本房间
AnyChatPlatform.LeaveRoom(-1)
// 注销
AnyChatPlatform.Logout()
self.navigationController?.popViewControllerAnimated(true)
}
}
// MARK: - EmptyData
func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! {
return UIImage(named: "empty_bg")
}
func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(14), NSForegroundColorAttributeName:UIColor.lightGrayColor()]
return NSAttributedString(string:"用户列表为空", attributes: attrs)
}
func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
paragraph.alignment = NSTextAlignment.Center
let attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(12), NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSParagraphStyleAttributeName: paragraph]
return NSAttributedString(string: "此用户列表自动刷新,请稍后", attributes: attrs)
}
// MARK: - Custom
func getAllUser(uids: [Int32]?) {
allUser.removeAll()
if uids != nil {
for uid in uids! {
let userName = AnyChatPlatform.GetUserName(uid)
allUser.append(User(name: userName, uid: uid))
}
}
}
// 退出
@IBAction func Logout() {
self.showLogoutAlert()
}
func showLogoutAlert() {
let alertView = UIAlertView(title: "你真的要退出AnyChat系统吗?", message: "", delegate: self, cancelButtonTitle: "按错了", otherButtonTitles: "是的")
alertView.show()
}
}
| true
|
ff55b3877868f1bb265cf70be0dd274d5fe06b5c
|
Swift
|
aquariuslt/sw-webview
|
/ServiceWorker/ServiceWorkerTests/Events/EventTargetTests.swift
|
UTF-8
| 2,003
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
import JavaScriptCore
@testable import ServiceWorker
import XCTest
class EventTargetTests: XCTestCase {
func testShouldFireEvents() {
let sw = ServiceWorker.createTestWorker(id: name)
return sw.evaluateScript("""
var didFire = false;
self.addEventListener('test', function() {
didFire = true;
});
self.dispatchEvent(new Event('test'));
didFire;
""")
.map { (didFire: Bool?) -> Void in
XCTAssertEqual(didFire, true)
}
.assertResolves()
}
func testShouldRemoveEventListeners() {
let testEvents = EventTarget()
let sw = ServiceWorker.createTestWorker(id: name)
let expect = expectation(description: "Code ran")
sw.withJSContext { context in
context.globalObject.setValue(testEvents, forProperty: "testEvents")
}
.then {
sw.evaluateScript("""
var didFire = false;
function trigger() {
didFire = true;
}
testEvents.addEventListener('test', trigger);
testEvents.removeEventListener('test', trigger);
testEvents.dispatchEvent(new Event('test'));
didFire;
""")
}
.compactMap { (didFire: Bool?) -> Void in
XCTAssertEqual(didFire, false)
expect.fulfill()
}
.catch { error -> Void in
XCTFail("\(error)")
}
wait(for: [expect], timeout: 1)
}
func testShouldFireSwiftEvents() {
let testEvents = EventTarget()
var fired = false
let testEvent = ConstructableEvent(type: "test")
testEvents.addEventListener("test") { (ev: ConstructableEvent) in
XCTAssertEqual(ev, testEvent)
fired = true
}
testEvents.dispatchEvent(testEvent)
XCTAssertTrue(fired)
}
}
| true
|
1fa4ec087e9dd9f8381d8084167fca92b58e0027
|
Swift
|
cdeerinck/Animal
|
/Animal/Node.swift
|
UTF-8
| 4,379
| 3.1875
| 3
|
[] |
no_license
|
//
// Node.swift
// Animal
//
// Created by Chuck Deerinck on 12/14/19.
// Copyright © 2019 Chuck Deerinck. All rights reserved.
//
class Node: Codable {
private enum NodeType: String, Codable {
case question
case answer
}
private var nodeType:NodeType
private var str:String
private var yesNode:Node?
private var noNode:Node?
private var yesIsNewer:Bool?
var animalCount:Int {
get {
switch self.nodeType {
case .answer:
return 1
case .question:
return self.yesNode!.animalCount + self.noNode!.animalCount
}
}
}
init(answer theAnswer:String) {
self.nodeType = .answer
self.str = theAnswer
}
init(question theQuestion:String, yesAnswer:String, noAnswer:String) {
self.nodeType = .question
self.str = theQuestion
self.yesNode = Node(answer: yesAnswer)
self.noNode = Node(answer: noAnswer)
}
func ask() {
switch self.nodeType {
case .question:
print("\(self.str) ? ", terminator:"")
if gotYesAnswer(node:self) {
if self.yesNode == nil { return } //This can only happen on a Kill command.
self.yesNode?.ask()
} else {
self.noNode?.ask()
}
case .answer:
print("Is it \(assignPrefix(self.str)) ? ", terminator:"")
if gotYesAnswer() {
print("I win!")
} else {
addBranch()
}
}
}
func addBranch() {
print("What was your animal ? ", terminator:"")
let animal = getFixedQuestion()
print("Please type a question that would distinguish between \(assignPrefix(animal)) and \(assignPrefix(self.str)) : ", terminator:"")
let question = getFixedQuestion()
print("And for \(assignPrefix(animal)) the answer would be : ", terminator:"")
self.yesIsNewer = gotYesAnswer()
if self.yesIsNewer! {
self.nodeType = .question
self.yesNode = Node(answer: animal)
self.noNode = Node(answer: self.str) //Do this before we step on the missed animal.
self.str = question //Now we can step on the missed animal answer.
} else {
self.nodeType = .question
self.yesNode = Node(answer: self.str) //Do this before we step on the missed animal.
self.noNode = Node(answer: animal)
self.str = question //Now we can step on the missed animal answer.
}
print("I have learned.")
}
func removeBranch() {
if self.yesIsNewer == nil {
print("You can't remove the root.")
return
}
let nodeToMove = self.yesIsNewer! ? self.noNode! : self.yesNode!
self.nodeType = nodeToMove.nodeType
self.str = nodeToMove.str
self.yesNode = nodeToMove.yesNode
self.noNode = nodeToMove.noNode
self.yesIsNewer = nodeToMove.yesIsNewer
}
func dump(_ indent:Int=0) {
print(String(repeating: " ", count: indent), terminator:"")
if let x = self.yesIsNewer {
print(x ? "Y " : "N ", terminator:"")
} else {
print(" ", terminator:"")
}
print(self.str, self.animalCount)
self.yesNode?.dump(indent+1)
self.noNode?.dump(indent+1)
}
func flatten(list: inout [Node]) {
list.append(self)
self.yesNode?.flatten(list: &list)
self.noNode?.flatten(list: &list)
}
func analyzeOne() -> Double {
if let y = self.yesNode, let n = self.noNode {
var ratio = Double(y.animalCount) / Double(n.animalCount)
if ratio < 1 { ratio = 1/ratio }
return ratio
}
return 0.0
}
func analyze() {
var nodeList: [Node] = []
self.flatten(list: &nodeList)
var maxRatio = 0.0
var maxNode = self
for node in nodeList {
let ratio = node.analyzeOne()
if ratio > maxRatio {
maxRatio = ratio
maxNode = node
}
}
print("The worst imbalance in the tree is :", maxRatio, "for the question", maxNode.str)
}
}
| true
|
2f997ccf9a537d865222b71594c5f1aa60395f7c
|
Swift
|
Binsabbar/iBOfficeBeacon
|
/iBOfficeBeacon/ParserHelpers.swift
|
UTF-8
| 1,914
| 2.96875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
//
// Parser.swift
// SwiftCSV
//
// Created by Will Richardson on 11/04/16.
// Copyright © 2016 JavaNut13. All rights reserved.
//
extension CSV {
/// List of dictionaries that contains the CSV data
public var rows: [[String: String]] {
if _rows == nil {
parse()
}
return _rows!
}
/// Dictionary of header name to list of values in that column
/// Will not be loaded if loadColumns in init is false
public var columns: [String: [String]] {
if !loadColumns {
return [:]
} else if _columns == nil {
parse()
}
return _columns!
}
/// Parse the file and call a block for each row, passing it as a dictionary
public func enumerateAsDict(_ block: @escaping ([String: String]) -> ()) {
let enumeratedHeader = header.enumerated()
enumerateAsArray { fields in
var dict = [String: String]()
for (index, head) in enumeratedHeader {
dict[head] = index < fields.count ? fields[index] : ""
}
block(dict)
}
}
/// Parse the file and call a block on each row, passing it in as a list of fields
public func enumerateAsArray(_ block: @escaping ([String]) -> ()) {
self.enumerateAsArray(block, limitTo: nil, startAt: 1)
}
fileprivate func parse() {
var rows = [[String: String]]()
var columns = [String: [String]]()
if loadColumns {
for field in header {
columns[field] = []
}
}
enumerateAsDict { dict in
rows.append(dict)
if self.loadColumns {
for key in self.header {
columns[key]?.append(dict[key] ?? "")
}
}
}
_columns = columns
_rows = rows
}
}
| true
|
47d5c139b84510119347061743fdd853a0cba5fe
|
Swift
|
alexvelikotckiy/Taskem
|
/Taskem/Screens/Calendar/CalendarControl/CalendarControlRouter.swift
|
UTF-8
| 1,193
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// CalendarControlRouter.swift
// Taskem
//
// Created by Wilson on 4/10/18.
// Copyright © 2018 Wilson. All rights reserved.
//
import Foundation
import PainlessInjection
import TaskemFoundation
class CalendarControlStandardRouter: CalendarControlRouter {
weak var controller: CalendarControlViewController!
init(calendarcontrolController: CalendarControlViewController) {
self.controller = calendarcontrolController
}
func dismiss() {
controller.dismiss(animated: true, completion: nil)
}
func alert(title: String, message: String, _ completion: @escaping ((Bool) -> Void)) {
let cancelTitle = "Cancel"
let confirmTitle = "Confirm"
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { _ in completion(false) }
let deleteAction = UIAlertAction(title: confirmTitle, style: .destructive) { _ in completion(true) }
let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
actionSheet.addAction(cancelAction)
actionSheet.addAction(deleteAction)
controller.present(actionSheet, animated: true, completion: nil)
}
}
| true
|
c0415dea8e2931742de0dde216e82f74c0216540
|
Swift
|
boboloo/Event-Em
|
/TestMultipleStoryboards/View Controllers/SettingsTableViewController.swift
|
UTF-8
| 4,173
| 2.578125
| 3
|
[] |
no_license
|
//
// SettingsTableViewController.swift
// TestMultipleStoryboards
//
// Created by Robert Liu on 10/31/17.
// Copyright © 2017 Summer Moon Solutions. All rights reserved.
//
import UIKit
class SettingsTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Settings"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.backgroundColor = Style.backgroundColor
self.navigationController?.navigationBar.barTintColor = Style.barTintColor
self.navigationController?.navigationBar.tintColor = Style.textColor
self.navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName : Style.textColor]
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = Style.backgroundColor
}
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 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 7
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "profileCell", for: indexPath) as! ProfileTableViewCell
cell.selectionStyle = .none
cell.profileName.text = DataStore.shared.getUser().email
cell.profileName.textColor = Style.textColor
self.tableView.rowHeight = 130
cell.profileImage.image = DataStore.shared.profileImage
return cell
}
else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "myEventsCell", for: indexPath) as! MyEventsTableViewCell
cell.myEvents.textColor = Style.textColor
self.tableView.rowHeight = 50
return cell
}
else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventHistoryCell", for: indexPath) as! EventHistoryTableViewCell
cell.eventHistory.textColor = Style.textColor
self.tableView.rowHeight = 50
return cell
}
else if indexPath.row == 3 {
let cell = tableView.dequeueReusableCell(withIdentifier: "TouchIDCell", for: indexPath) as! TouchIDTableViewCell
cell.touchID.textColor = Style.textColor
self.tableView.rowHeight = 50
return cell
}
else if indexPath.row == 4 {
let cell = tableView.dequeueReusableCell(withIdentifier: "toggleEventsCell", for: indexPath) as! ToggleEventsTableViewCell
cell.toggleEvents.textColor = Style.textColor
self.tableView.rowHeight = 50
return cell
}
else if indexPath.row == 5 {
let cell = tableView.dequeueReusableCell(withIdentifier: "myThemesCell", for: indexPath) as! MyThemesTableViewCell
cell.myThemes.textColor = Style.textColor
self.tableView.rowHeight = 50
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "logoutCell", for: indexPath) as! LogoutTableViewCell
cell.logout.textColor = Style.textColor
self.tableView.rowHeight = 50
return cell
}
}
}
| true
|
b3f65b1fbe2099e73d161aa2536f744551a45490
|
Swift
|
ioschoi89/ChoiHyunHo_iOS_School6
|
/Project/ChoiHyunHo/ChoiHyunHo/ViewController.swift
|
UTF-8
| 4,905
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ChoiHyunHo
//
// Created by choi hyunho on 2018. 2. 7..
// Copyright © 2018년 choi hyunho. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var priceList: [String] = ["1000원", "800원", "1500원", "500원", ]
var imgName: [String] = ["콜라.png", "사이다.png", "칸타타.png", "삼다수.png"]
var statusLb: UILabel?
var resultLb: UILabel?
var price1000Btn: UIButton?
var price500Btn: UIButton?
var exchangeBtn: UIButton?
var exchangeTemp: Int = 0
var inputTemp: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
makeDrinkList(with: 4)
resultLb = UILabel()
resultLb?.frame = CGRect(x: 30, y: 380, width: 330, height: 50)
resultLb?.backgroundColor = .black
resultLb?.textColor = .white
resultLb?.textAlignment = .right
view.addSubview(resultLb!)
statusLb = UILabel()
statusLb?.frame = CGRect(x: 30, y: 430, width: 330, height: 50)
statusLb?.backgroundColor = .gray
statusLb?.textColor = .white
statusLb?.textAlignment = .right
view.addSubview(statusLb!)
price1000Btn = UIButton()
price1000Btn?.layer.borderWidth = 2
price1000Btn?.setTitle("1000원", for: .normal)
price1000Btn?.setTitleColor(.black, for: .normal)
price1000Btn?.addTarget(self, action: #selector(self.inputPriceBtn(_:)), for: .touchUpInside)
price1000Btn?.frame = CGRect(x: 30, y: 510, width: 120, height: 50)
view.addSubview(price1000Btn!)
price500Btn = UIButton()
price500Btn?.layer.borderWidth = 2
price500Btn?.setTitle("500원", for: .normal)
price500Btn?.setTitleColor(.black, for: .normal)
price500Btn?.frame = CGRect(x: 170, y: 510, width: 120, height: 50)
price500Btn?.addTarget(self, action: #selector(self.inputPriceBtn(_:)), for: .touchUpInside)
view.addSubview(price500Btn!)
exchangeBtn = UIButton()
exchangeBtn?.layer.borderWidth = 2
exchangeBtn?.setTitle("반환", for: .normal)
exchangeBtn?.setTitleColor(.black, for: .normal)
exchangeBtn?.frame = CGRect(x: 300, y: 510, width: 70, height: 50)
exchangeBtn?.addTarget(self, action: #selector(self.exchange(_:)), for: .touchUpInside)
view.addSubview(exchangeBtn!)
}
func makeDrinkList(with count: Int){
for index in 0..<count
{
let col: CGFloat = CGFloat(index%2)
let row: CGFloat = CGFloat(index/2)
let margin: CGFloat = 30
let drinkView = ItemView(frame: CGRect(x: (margin*(col+1))+(150*col), y: (margin*(row+1))+(150*row), width: 150, height: 150))
drinkView.priceText = priceList[index]
drinkView.index = index
drinkView.img = UIImage(named: imgName[index])
drinkView.addTarget(self, action: #selector(self.drinkPriceBtn(_:)), for: .touchUpInside)
view.addSubview(drinkView)
}
}
@objc func inputPriceBtn(_ sender: UIButton){
if sender == price1000Btn{
statusLb?.text = "1000원 입금됨"
inputTemp += 1000
}else if sender == price500Btn{
statusLb?.text = "500원 입금됨"
inputTemp += 500
}
resultLb?.text = "잔액 : \(inputTemp)"
}
@objc func drinkPriceBtn(_ sender: UIButton){
exchangeTemp = inputTemp
if sender.tag == 0
{
exchangeTemp = inputTemp - 1000
inputTemp = exchangeTemp
statusLb?.text = "콜라가 나왔습니다"
}else if sender.tag == 1
{
exchangeTemp = inputTemp - 800
inputTemp = exchangeTemp
statusLb?.text = "사이다가 나왔습니다"
}else if sender.tag == 2
{
exchangeTemp = inputTemp - 1500
inputTemp = exchangeTemp
statusLb?.text = "칸타타가 나왔습니다"
}else if sender.tag == 3
{
exchangeTemp = inputTemp - 500
inputTemp = exchangeTemp
statusLb?.text = "삼다수가 나왔습니다"
}
if exchangeTemp > 0{
resultLb?.text = "잔액 : \(exchangeTemp)"
}else if exchangeTemp < 0
{
resultLb?.text = "잔액 반환되었습니다 다시 돈을 넣어주세요"
statusLb?.text = "\(exchangeTemp*(-1))만큼 부족합니다"
exchangeTemp = 0
inputTemp = 0
}
}
@objc func exchange(_ sender: UIButton){
// resultLb?.text?.removeAll()
statusLb?.text = "\(inputTemp)원이 반환됨"
exchangeTemp = 0
inputTemp = 0
}
}
| true
|
a301a583788f06b8908191db2f6f09013a9fac08
|
Swift
|
StIch0/Ayaga
|
/MVPProject/ResultPresenter.swift
|
UTF-8
| 1,628
| 2.578125
| 3
|
[] |
no_license
|
//
// ResultPresentr.swift
// MVPProject
//
// Created by Pavel Burdukovskii on 24/01/18.
// Copyright © 2018 Pavel Burdukovskii. All rights reserved.
//
import Foundation
import UIKit
struct ResulViewData: ViewData{
let id : AnyObject
let result : String
}
class ResultPresenter {
private let service : ResultServise
weak private var resultView: ViewBuild?
init(service : ResultServise) {
self.service = service
}
func atachView (resultView : ViewBuild){
self.resultView = resultView
}
func detachView() -> Void {
resultView = nil
}
func getData (_ url :String,
parameters: [String: AnyObject],
withName: String,
imagesArr : [UIImage],
videoArr : [String],
audioArr : [String],
docsArr : [String]){
self.resultView?.startLoading()
service.postAnyData(url, parameters: parameters, withName: withName, imagesArr: imagesArr, videoArr: videoArr, audioArr: audioArr, docsArr: docsArr, onSucces: {result in
self.resultView?.finishLoading()
if result.count == 0 {
self.resultView?.setEmptyData()
}
else {
let resMap = result.map {
rmap in
return ResulViewData(id : rmap.id ?? -1 as AnyObject, result : "\(rmap.status)")
}
self.resultView?.setData(data: resMap)
}
}, onFailure: {
(errorMessage) in
self.resultView?.finishLoading()
})
}
}
| true
|
e892c770e2c5a83c5fcd63aac8267f82897fd057
|
Swift
|
cocoataster/NearStores
|
/nearStores/Tienda.swift
|
UTF-8
| 2,750
| 2.90625
| 3
|
[] |
no_license
|
//
// Tienda.swift
// nearStores
//
// Created by Eric Sans Alvarez on 09/04/2017.
// Copyright © 2017 Eric Sans Alvarez. All rights reserved.
//
import Foundation
class Tienda {
private var _distance: Double!
private var _latitude: Double!
private var _longitude: Double!
private var _phoneNumber: String!
private var _storeAddress: String!
private var _storeCity: String!
private var _storeName: String!
private var _storeZipCode: String!
private var _webURL: String!
var distance: Double {
if _distance == nil {
_distance = 0.0
}
return _distance
}
var latitude: Double {
if _latitude == nil {
_latitude = 0.0
}
return _latitude
}
var longitude: Double {
if _longitude == nil {
_longitude = 0.0
}
return _longitude
}
var phoneNumber: String {
if _phoneNumber == "" {
_phoneNumber = ""
}
return _phoneNumber
}
var storeAddress: String {
if _storeAddress == "" {
_storeAddress = ""
}
return _storeAddress
}
var storeCity: String {
if _storeCity == "" {
_storeCity = ""
}
return _storeCity
}
var storeName: String {
if _storeName == "" {
_storeName = ""
}
return _storeName
}
var storeZipCode: String {
if _storeZipCode == "" {
_storeZipCode = ""
}
return _storeZipCode
}
var webURL: String {
if _webURL == "" {
_webURL = ""
}
return _webURL
}
init() {
}
init(nearStore: Dictionary<String,AnyObject>) {
_distance = stringToDouble(string: nearStore["distance"] as! String)
_latitude = stringToDouble(string: nearStore["latitude"] as! String)
_longitude = stringToDouble(string: nearStore["longitude"] as! String)
_phoneNumber = nearStore["phone_number"] as! String
_storeAddress = nearStore["store_address"] as! String
_storeCity = nearStore["store_city"] as! String
_storeName = nearStore["store_name"] as! String
_storeZipCode = nearStore["store_zip_code"] as! String
_webURL = nearStore["web_url"] as! String
}
func stringToDouble(string: String) -> Double {
var result = ""
for character in string.characters {
let char = "\(character)"
if char == "," {
result = result + "."
} else {
result = result + char
}
}
return Double(result)!
}
}
| true
|
484fd7546af3ef03423615bb55e7c3a3a58f8d9a
|
Swift
|
tebbbs/cs50fp
|
/DJ2/Transition.swift
|
UTF-8
| 5,485
| 3.171875
| 3
|
[] |
no_license
|
//
// Transition.swift
// DJ2
//
// Created by Joseph Tebbett on 8/4/20.
// Copyright © 2020 CS50. All rights reserved.
//
import Foundation
import SQLite3
struct Transition {
let id: Int
let from: Song
let to: Song
}
class TransitionManager {
var database: OpaquePointer?
static let shared = TransitionManager()
private init() {
}
// Creates 'transitions' table if it doesn't already exist
func connect() {
if database != nil {
return
}
let databaseURL = try! FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
).appendingPathComponent("music.sqlite")
if sqlite3_open(databaseURL.path, &database) != SQLITE_OK {
print("Error opening database")
return
}
if sqlite3_exec(
database,
"""
CREATE TABLE IF NOT EXISTS transitions (
id INTEGER,
from_id INTEGER,
to_id INTEGER,
PRIMARY KEY(id),
FOREIGN KEY(from_id) REFERENCES songs(id) ON DELETE CASCADE,
FOREIGN KEY(to_id) REFERENCES songs(id) ON DELETE CASCADE
)
""",
nil,
nil,
nil
) != SQLITE_OK {
print("Error creating table: \(String(cString: sqlite3_errmsg(database)!))")
}
}
// Insets a transition from song 'from' to song 'to' into the databse
func insertTransition(from: Song, to: Song) -> Int {
connect()
var statement: OpaquePointer? = nil
if sqlite3_prepare_v2(
database,
"INSERT INTO transitions (from_id, to_id) VALUES(?, ?)",
-1,
&statement,
nil
) == SQLITE_OK {
sqlite3_bind_int(statement, 1, Int32(from.id))
sqlite3_bind_int(statement, 2, Int32(to.id))
if sqlite3_step(statement) != SQLITE_DONE {
print("Error inserting transition")
}
}
else {
print("Error creating transition insert statement")
}
sqlite3_finalize(statement)
return Int(sqlite3_last_insert_rowid(database))
}
// Deletes a transition from song 'from' to song 'to' from the databse
func deleteTransition(from: Song, to: Song) {
connect()
var statement: OpaquePointer? = nil
if sqlite3_prepare_v2(
database,
"DELETE FROM transitions WHERE from_id = ? AND to_id = ?",
-1,
&statement,
nil
) == SQLITE_OK {
sqlite3_bind_int(statement, 1, Int32(from.id))
sqlite3_bind_int(statement, 2, Int32(to.id))
if sqlite3_step(statement) != SQLITE_DONE {
print("Error deleting transition")
}
}
else {
print("Error creating transition delete statement")
}
sqlite3_finalize(statement)
}
// Returns a list of songs that the song 'from' transitions to, according to the databse, ordered by the song's title
func getNextSongs(from: Song) -> [Song] {
connect()
var result: [Song] = []
var statement: OpaquePointer? = nil
if sqlite3_prepare_v2(
database,
"""
SELECT songs.id, songs.title, artists.id, artists.name, albums.id, albums.title, songs.year FROM
songs JOIN artists ON songs.artist_id = artists.id JOIN
albums ON songs.album_id = albums.id JOIN
transitions ON songs.id = transitions.to_id
WHERE transitions.from_id = ?
ORDER BY songs.title ASC
""",
-1,
&statement,
nil
) == SQLITE_OK {
sqlite3_bind_int(statement, 1, Int32(from.id))
while sqlite3_step(statement) == SQLITE_ROW {
let song = SongManager.shared.parseSong(statement: statement!)
result.append(song)
}
}
sqlite3_finalize(statement)
return result
}
// 'Opposite' of getNextSongs, returns a list of all songs that song 'from' has not yet been recorded as transitioning to
func getPossisbleTransitions(from: Song) -> [Song] {
connect()
var result: [Song] = []
var statement: OpaquePointer? = nil
if sqlite3_prepare_v2(
database,
"""
SELECT songs.id, songs.title, artists.id, artists.name, albums.id, albums.title, songs.year FROM
songs JOIN artists ON songs.artist_id = artists.id JOIN
albums ON songs.album_id = albums.id
WHERE songs.id NOT IN (SELECT to_id FROM transitions WHERE from_id = ?)
ORDER BY songs.title ASC
"""
,
-1,
&statement,
nil
) == SQLITE_OK {
sqlite3_bind_int(statement, 1, Int32(from.id))
while sqlite3_step(statement) == SQLITE_ROW {
let song = SongManager.shared.parseSong(statement: statement!)
result.append(song)
}
}
sqlite3_finalize(statement)
return result
}
}
| true
|
1afc56b9dac505035c453ade483e6bb5174978ca
|
Swift
|
ivoryeah/DoUYZB
|
/DYZB/Classes/Tools/uiButton_extension.swift
|
UTF-8
| 1,010
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// uiButton_extension.swift
// DYZB
//
// Created by 冯强 on 2019/2/13.
// Copyright © 2019 IVOR. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
/* 类方式
class func createItem(imageName:String,highImageName:String,size:CGSize)->UIBarButtonItem{
let btn=UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
btn.setImage(UIImage(named: highImageName), for: .highlighted)
btn.frame=CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
//便利构造函数1、convenience开头 2、在构造函数中必须明确调用一个设计的构造函数(self)
@objc convenience init(imageName:String,highImageName:String,size:CGSize){
let btn=UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
btn.setImage(UIImage(named: highImageName), for: .highlighted)
btn.frame=CGRect(origin: CGPoint.zero, size: size)
self.init(customView:btn)
}
}
| true
|
f6601f3ea8bec96db65c1a7518f18689eb29769d
|
Swift
|
quannguyen90/NQLibrary
|
/Pod/Classes/NQHTTPRequest.swift
|
UTF-8
| 4,573
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// NQHTTPRequest.swift
// Pods
//
// Created by MAC MINI on 11/26/15.
//
//
import UIKit
import Foundation
import AFNetworking
public class NQHTTPRequest: NSObject {
var httpRequest:AFHTTPRequestOperationManager!
var BASE_URL:String = ""
public static let sharedInstance = NQHTTPRequest()
override init() {
super.init()
self.httpRequest = AFHTTPRequestOperationManager()
}
// MARK:
// MARK: Create url
public func URLRequestWithPath(pathRequest:String) ->String{
var baseURL = BASE_URL
if (baseURL.characters.last == "/" ) {
baseURL = BASE_URL.substringToIndex(BASE_URL.endIndex)
}
var path = pathRequest
if pathRequest.characters.first == "/" {
path = pathRequest.substringFromIndex(pathRequest.startIndex)
}
return baseURL + "/" + path
}
public func URLRequestWithPath(pathRequest:String, baseURL:String) ->String{
var baseURLRequest = baseURL
if (baseURLRequest.characters.last == "/" ) {
baseURLRequest = baseURL.substringToIndex(baseURL.endIndex)
}
var path = pathRequest
if pathRequest.characters.first == "/" {
path = pathRequest.substringFromIndex(pathRequest.startIndex)
}
return baseURLRequest + "/" + path
}
// MARK:
// MARK: Add header and Response Accept ContentType
public func addHeader(header:[String:String]?){
if header == nil{
return
}
for key:String in header!.keys{
httpRequest.requestSerializer.setValue(header![key], forHTTPHeaderField: key)
}
}
public func addAcceptContentType(contentTypeValue:String){
let contentType:Set<NSObject> = httpRequest.responseSerializer.acceptableContentTypes!
let contenTypeSet = NSMutableSet(set: contentType)
contenTypeSet.addObject(contentTypeValue)
httpRequest.responseSerializer.acceptableContentTypes = contenTypeSet as Set<NSObject>
}
//MARK:
//MARK: http request
// GET Request
public func GETRequest(urlRequest: String, headerRequest: [String:String]?, urlParam: [String:String], success: (responseObject:AnyObject)->(), fail: (error:NSError)->()){
addHeader(headerRequest)
httpRequest.GET(urlRequest, parameters: urlParam, success: { (operation:AFHTTPRequestOperation, responseObject:AnyObject) ->
Void in
success (responseObject: responseObject)
}) { (operation:AFHTTPRequestOperation?, error:NSError) -> Void in
fail(error: error)
}
}
// POST Request
public func POSTRequest(urlRequest: String, headerRequest: [String:String]?, urlParam: [String:String], success: (responseObject:AnyObject)->(), fail: (error:NSError)->()){
addHeader(headerRequest)
httpRequest.POST(urlRequest, parameters: urlParam, success: { (operations:AFHTTPRequestOperation, responseObject:AnyObject) -> Void in
success (responseObject: responseObject)
}) { (operation:AFHTTPRequestOperation?, error:NSError) -> Void in
fail(error: error)
}
}
// PUT Request
public func PUTRequest(urlRequest: String, headerRequest: [String:String]?, urlParam: [String:String], success: (responseObject:AnyObject)->(), fail: (error:NSError)->()){
addHeader(headerRequest)
httpRequest.PUT(urlRequest, parameters: urlParam, success: { (operation:AFHTTPRequestOperation, responseObject:AnyObject) -> Void in
success(responseObject: responseObject)
}) { (operation:AFHTTPRequestOperation?, error:NSError) -> Void in
fail(error: error)
}
}
// DELETE Request
public func DELETERequest(urlRequest: String, headerRequest: [String:String]?, urlParam: [String:String], success: (responseObject:AnyObject)->(), fail: (error:NSError)->()){
addHeader(headerRequest)
httpRequest.DELETE(urlRequest, parameters: urlParam, success: { (operation:AFHTTPRequestOperation, responseObject:AnyObject) -> Void in
success(responseObject: responseObject)
}) { (operation:AFHTTPRequestOperation?, error:NSError) -> Void in
fail(error: error)
}
}
}
| true
|
35494ce3e81b4002bebc0bc755521bebbc0f186c
|
Swift
|
hpbl/projetoPG2
|
/rugosidadePG2/rugosidadePG2/Point.swift
|
UTF-8
| 3,684
| 3.734375
| 4
|
[] |
no_license
|
//
// Point.swift
// rugosidadePG2
//
// Created by Hilton Pintor Bezerra Leite on 08/12/16.
// Copyright © 2016 Chien&Pintor&Melo. All rights reserved.
//
import Foundation
// Manter como struct, para perder referência quando valor mudar
struct Point {
var x: Double
var y: Double
var z: Double?
var color: (Double, Double, Double)?
//MARK: - inits
init() {
self.x = Double.infinity
self.y = Double.infinity
}
init(x: Double, y: Double) {
self.x = x
self.y = y
}
init(x: Double, y: Double, z: Double) {
self.x = x
self.y = y
self.z = z
}
init(x: Double, y: Double, z: Double, color: (Double, Double, Double)) {
self.x = x
self.y = y
self.z = z
self.color = color
}
//MARK: - Vector Basic Operations
static func * (vector: Point, scalar: Double) -> Point {
guard let z = vector.z else {
return Point(x: scalar*(vector.x), y: scalar*(vector.y))
}
return Point(x: scalar * (vector.x), y: scalar * (vector.y), z: scalar * z)
}
static func - (u: Point, v: Point) -> Point {
if u.z != nil && v.z != nil {
return Point(x: u.x - v.x , y: u.y - v.y , z: u.z! - v.z!)
} else {
return Point(x: u.x - v.x, y: u.y - v.y)
}
}
static func + (u: Point, v: Point) -> Point {
if u.z != nil && v.z != nil {
return Point(x: u.x + v.x , y: u.y + v.y , z: u.z! + v.z!)
} else {
return Point(x: u.x + v.x , y: u.y + v.y)
}
}
func normalized() -> Point {
guard let z = self.z else {
let norm = sqrt((self.x * self.x) + (self.y * self.y))
return Point(x: self.x/norm, y: self.y/norm)
}
let norm = sqrt((self.x * self.x) + (self.y * self.y) + (z * z))
return Point(x: self.x/norm, y: self.y/norm, z: self.z!/norm)
}
//MARK: - Geometry
func getBarycentricCoords(triangle: Triangle) -> Point {
let v0 = triangle.secondVertex - triangle.firstVertex
let v1 = triangle.thirdVertex - triangle.firstVertex
let v2 = self - triangle.firstVertex
let d00 = innerProduct(u: v0, v: v0)
let d01 = innerProduct(u: v0, v: v1)
let d11 = innerProduct(u: v1, v: v1)
let d20 = innerProduct(u: v2, v: v0)
let d21 = innerProduct(u: v2, v: v1)
let denom = (d00 * d11) - (d01 * d01)
var point = Point()
point.y = ((d11 * d20) - (d01 * d21)) / denom
point.z = ((d00 * d21) - (d01 * d20)) / denom
point.x = 1 - point.y - point.z!
return point
}
//usar as coordenadas baricentricas para achar o 3D
func approx3DCoordinates(alfaBetaGama: Point, triangle3D: Triangle) -> Point{
let alfa = alfaBetaGama.x
let beta = alfaBetaGama.y
let gama = alfaBetaGama.z
return triangle3D.firstVertex*alfa + triangle3D.secondVertex*beta + triangle3D.thirdVertex*gama!
}
}
//MARK: - Protocols
//MARK: Equatable
extension Point: Equatable {
static func ==(lhs: Point, rhs: Point) -> Bool {
return (lhs.x == rhs.x) && (lhs.y == rhs.y) && (lhs.z == rhs.z)
}
}
// MARK: Hashable
extension Point: Hashable {
var hashValue: Int {
get {
return "\(self.x)\(self.y)\(self.z)".hashValue
}
}
var hashValueString: String {
get {
return "\(self.x)\(self.y)\(self.z)"
}
}
}
| true
|
8b89c1907ee54109fcb8d216d23d73a9effd922e
|
Swift
|
arjunpa/USNews
|
/USNews/Repositories/ArticleDetailRepository.swift
|
UTF-8
| 4,681
| 2.859375
| 3
|
[] |
no_license
|
//
// ArticleDetailRepository.swift
// USNews
//
// Created by Arjun P A on 20/05/21.
// Copyright © 2021 Arjun P A. All rights reserved.
//
import Foundation
protocol ArticleDetailRepositoryInterface {
func retrieveComments(articleID: String,
queue: OperationQueue,
completion: @escaping (Result<ArticleComments, Error>) -> Void)
func retrieveLikes(articleID: String,
queue: OperationQueue,
completion: @escaping (Result<ArticleLikes, Error>) -> Void)
func retrieveLikesAndComments(articleID: String,
queue: OperationQueue,
completion: @escaping (Result<ArticleLikes, Error>, Result<ArticleComments, Error>) -> Void)
}
final class ArticleDetailRepository: ArticleDetailRepositoryInterface {
let apiService: APIServiceInterface
private let groupQueue = DispatchQueue(label: "com.detail.repository")
init(apiService: APIServiceInterface) {
self.apiService = apiService
}
func retrieveComments(articleID: String,
queue: OperationQueue,
completion: @escaping (Result<ArticleComments, Error>) -> Void) {
let commentsURL: URLFormable
do {
commentsURL = try APIEndPoint.articleComments.appendingPathComponent(component: articleID)
} catch {
completion(.failure(error))
return
}
let request = Request(url: commentsURL,
method: .get,
parameters: nil,
headers: nil,
encoding: RequestURLEncoding())
self.apiService.request(for: request) { (result: Result<APIHTTPDecodableResponse<ArticleComments>, Error>) in
switch result {
case .success(let response):
queue.addOperation {
completion(.success(response.decoded))
}
case .failure(let error):
queue.addOperation {
completion(.failure(error))
}
}
}
}
func retrieveLikes(articleID: String,
queue: OperationQueue,
completion: @escaping (Result<ArticleLikes, Error>) -> Void) {
let likesURL: URLFormable
do {
likesURL = try APIEndPoint.articleLikes.appendingPathComponent(component: articleID)
} catch {
completion(.failure(error))
return
}
let request = Request(url: likesURL,
method: .get,
parameters: nil,
headers: nil,
encoding: RequestURLEncoding())
self.apiService.request(for: request) { (result: Result<APIHTTPDecodableResponse<ArticleLikes>, Error>) in
switch result {
case .success(let response):
queue.addOperation {
completion(.success(response.decoded))
}
case .failure(let error):
queue.addOperation {
completion(.failure(error))
}
}
}
}
func retrieveLikesAndComments(articleID: String, queue: OperationQueue, completion: @escaping (Result<ArticleLikes, Error>, Result<ArticleComments, Error>) -> Void) {
var likesResult: Result<ArticleLikes, Error>?
var commentsResult: Result<ArticleComments, Error>?
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
dispatchGroup.enter()
dispatchGroup.notify(queue: groupQueue) {
queue.addOperation {
guard let likesResult = likesResult, let commentsResult = commentsResult else {
return
}
completion(likesResult, commentsResult)
}
}
self.retrieveComments(articleID: articleID,
queue: .main)
{ result in
commentsResult = result
dispatchGroup.leave()
}
self.retrieveLikes(articleID: articleID,
queue: .main)
{ result in
likesResult = result
dispatchGroup.leave()
}
}
}
| true
|
33099295938389eada9c96a685dab053b1bc6724
|
Swift
|
291Airi/MemoryFace2-master
|
/MemoryFace2/ChoiceViewController.swift
|
UTF-8
| 3,064
| 2.9375
| 3
|
[] |
no_license
|
//
// ChoiceViewController.swift
// MemoryFace2
//
// Created by 福井 愛梨 on 2020/07/16.
// Copyright © 2020 福井 愛梨. All rights reserved.
//
import UIKit
import RealmSwift
class ChoiceViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
private var realm: Realm!
@IBOutlet weak var table: UITableView!
//名前を入れるための配列
var NameArray = [String]()
//写真を入れるための配列
var imageNameArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self
table.delegate = self
// (1)Realmのインスタンスを生成する
let realm2 = try! Realm()
// (2)全データの取得
let results = realm2.objects(personArray.self)
// (3)取得データの確認
print(results)
//NameArray,imageNameArrayに名前を入れる
NameArray = [results[0].textFieldString]
imageNameArray = [results[0].pictureurl]
}
//セルの数を設定
func tableView(_ tableView: UITableView, numberOfRowsInSection: Int) -> Int{
return NameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
//セルに画像を表示する
cell?.imageView?.image = UIImage(named: imageNameArray[indexPath.row])
//セルにNameArrayを表示する
cell?.textLabel?.text = NameArray[indexPath.row]
return cell!
}
//セルが押された時に呼ばれるメソッド
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
print("\(NameArray[indexPath.row])が選ばれました!")
// (1)Realmのインスタンスを生成する
let realm2 = try! Realm()
// (2)全データの取得
let results = realm2.objects(personArray.self)
// (3)取得データの確認
print(results)
try! realm.write {
realm.delete(results)
// (1)Realmのインスタンスを生成する
let realm2 = try! Realm()
// (2)全データの取得
let results = realm2.objects(personArray.self)
// (3)取得データの確認
print(results)
}
//スワイプしたセルを削除
if editingStyle == UITableViewCell.EditingStyle.delete {
NameArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
}
}
//セルの編集許可
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool{
return true
}
}
| true
|
6d7e149bec3bf1d0946e949afd357f32b361507c
|
Swift
|
matoelorriaga/pokemon-ios
|
/pokemon-ios/Model/PokemonSprites.swift
|
UTF-8
| 955
| 2.5625
| 3
|
[] |
no_license
|
//
// PokemonSprites.swift
// pokemon-ios
//
// Created by Matías Elorriaga on 5/4/17.
// Copyright © 2017 melorriaga. All rights reserved.
//
import Foundation
import ObjectMapper
class PokemonSprites: Mappable {
var frontDefault: String?
var frontShiny: String?
var frontFemale: String?
var frontShinyFemale: String?
var backDefault: String?
var backShiny: String?
var backFemale: String?
var backShinyFemale: String?
required init?(map: Map) {}
func mapping(map: Map) {
frontDefault <- map["front_default"]
frontShiny <- map["front_shiny"]
frontFemale <- map["front_female"]
frontShinyFemale <- map["front_shiny_female"]
backDefault <- map["back_default"]
backFemale <- map["back_female"]
backFemale <- map["back_female"]
backShinyFemale <- map["back_shiny_female"]
}
}
| true
|
0db7f98c7e8acdb0453651a9a780ac8feecd400d
|
Swift
|
kaden-kykim/CICCC-iOS
|
/Lecture/EmojiDictionary/EmojiDictionary/EmojiTableViewController.swift
|
UTF-8
| 6,535
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// EmojiTableViewController.swift
// EmojiDictionary
//
// Created by Kaden Kim on 2020-05-02.
// Copyright © 2020 CICCC. All rights reserved.
//
import UIKit
class EmojiTableViewController: UITableViewController {
struct SegueIdentifier {
static let addEmoji = "AddEmoji"
static let editEmoji = "EditEmoji"
}
private let cellId = "EmojiCell"
var emojis: [Emoji] = [
Emoji(symbol: "😀", name: "Grinning Face", description: "A typical smiley face.", usage: "happiness"),
Emoji(symbol: "😕", name: "Confused Face", description: "A confused, puzzled face.", usage: "unsure what to think; displeasure"),
Emoji(symbol: "😍", name: "Heart Eyes", description: "A smiley face with hearts for eyes. It typically conveys that you love something", usage: "love of something; attractive"),
Emoji(symbol: "👮", name: "Police Officer", description: "A police officer wearing a blue cap with a gold badge.", usage: "person of authority"),
Emoji(symbol: "🐢", name: "Turtle", description: "A cute turtle.", usage: "Something slow"),
Emoji(symbol: "🐘", name: "Elephant", description: "A gray elephant.", usage: "good memory"),
Emoji(symbol: "🍝", name: "Spaghetti", description: "A plate of spaghetti.", usage: "spaghetti"),
Emoji(symbol: "🎲", name: "Die", description: "A single die.", usage: "taking a risk, chance; game"),
Emoji(symbol: "⛺️", name: "Tent", description: "A small tent.", usage: "camping"),
Emoji(symbol: "📚", name: "Stack of Books", description: "Three colored books stacked on each other.", usage: "homework, studying"),
Emoji(symbol: "💔", name: "Broken Heart", description: "A red, broken heart.", usage: "extreme sadness"),
Emoji(symbol: "💤", name: "Snore", description: "Three blue \'z\'s.", usage: "tired, sleepiness"),
Emoji(symbol: "🏁", name: "Checkered Flag", description: "A black-and-white checkered flag.", usage: "completion")]
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44.0
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? emojis.count : 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Step 1: Dequeue cell
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! EmojiTableViewCell
// Step 2: Fetch model object to display
let emoji = emojis[indexPath.row]
// Step 3: Configure cell
cell.update(with: emoji)
cell.showsReorderControl = true
// Step 4: Return cell
return cell
}
// MARK: - table view delegate
// override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let emoji = emojis[indexPath.row]
// print("\(emoji.symbol) \(indexPath)")
// }
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let movedEmoji = emojis.remove(at: fromIndexPath.row)
emojis.insert(movedEmoji, at: to.row)
tableView.reloadData()
}
// Defines left buttons when in editting mode
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
// Remove the delete indicator
// return .none
}
// Override to support editing the table view and swiping to delete
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
emojis.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
/// Custom row editting buttons
// override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// return UISwipeActionsConfiguration(actions: [
// UIContextualAction(style: .destructive, title: "Remove", handler: { [weak self] (action, view, handler) in
// // update the model
// self?.emojis.remove(at: indexPath.row)
// // update the tableview
// tableView.deleteRows(at: [indexPath], with: .automatic)
// }),
// UIContextualAction(style: .normal, title: "Edit", handler: { (action, view, handler) in
// print("Edit")
// })
// ])
// }
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueIdentifier.editEmoji {
let indexPath = tableView.indexPathForSelectedRow!
let emoji = emojis[indexPath.row]
let navController = segue.destination as! UINavigationController
let addEditEmojiTableViewController = navController.topViewController as! AddEditEmojiTableViewController
addEditEmojiTableViewController.emoji = emoji
}
}
@IBAction func unwindToEmojiTableView(segue: UIStoryboardSegue) {
guard segue.identifier == AddEditEmojiTableViewController.unwindSegueSaveId,
let sourceViewController = segue.source as? AddEditEmojiTableViewController,
let emoji = sourceViewController.emoji
else { return }
if let selectedIndexPath = tableView.indexPathForSelectedRow {
emojis[selectedIndexPath.row] = emoji
tableView.reloadRows(at: [selectedIndexPath], with: .none)
} else {
let newIndexPath = IndexPath(row: emojis.count, section: 0)
emojis.append(emoji)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.