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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d11255d34f3bbd75781ec3fe7d7837cfad021f5d
|
Swift
|
BhaskerGarudadri/kavsoft-swiftui-animations
|
/SignalImagePicker/SignalImagePicker/ViewModel/ImageViewModel.swift
|
UTF-8
| 5,823
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ImageViewModel.swift
// SignalImagePicker
//
// Created by recherst on 2021/8/26.
//
import SwiftUI
import Photos
import AVKit
class ImagePickerViewModel: NSObject, ObservableObject, PHPhotoLibraryChangeObserver {
@Published var showImagePicker = false
@Published var libraryStatus = LibraryStatus.denied
// List of fetched photos
@Published var fetchedPhotos: [Asset] = []
// To get updates
@Published var allPhotos: PHFetchResult<PHAsset>!
// Preview
@Published var showPreview = false
@Published var selectedImagePreview: UIImage!
@Published var selectedVideoPreview: AVAsset!
func openImagePicker() {
// Close keyboard if opened
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
// fetch image when it needed
if fetchedPhotos.isEmpty {
fetchPhotos()
}
withAnimation { showImagePicker.toggle() }
}
func Setup() {
// Repuest permission
PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
DispatchQueue.main.async {
switch status {
case .denied:
self.libraryStatus = .denied
case .authorized:
self.libraryStatus = .approved
case .limited:
self.libraryStatus = .limited
default:
self.libraryStatus = .denied
}
}
}
// Register observer
PHPhotoLibrary.shared().register(self)
}
// Listen to changes
func photoLibraryDidChange(_ changeInstance: PHChange) {
guard let _ = allPhotos else { return }
if let updates = changeInstance.changeDetails(for: allPhotos) {
// Get updated list
let updatedPhotos = updates.fetchResultAfterChanges
// There is bug in it
// It is not updating the inserted or removed items
// print(updates.insertedObjects.count)
// print(updates.removedObjects.count)
// So we're going to verify all and append only No in the list
// to avoid of reloading all and ram usage
updatedPhotos.enumerateObjects { asset, index, _ in
if !self.allPhotos.contains(asset) {
// If its not there
// get image and append it to array
self.getImage(from: asset, size: CGSize(width: 150, height: 150)) { image in
DispatchQueue.main.async {
self.fetchedPhotos.append(Asset(asset: asset, image: image))
}
}
}
}
// To remove if image is removed
allPhotos.enumerateObjects { asset, index, _ in
if !updatedPhotos.contains(asset) {
// Remove it
DispatchQueue.main.async {
self.fetchedPhotos.removeAll { $0.asset == asset }
}
}
}
DispatchQueue.main.async {
self.allPhotos = updatedPhotos
}
}
}
func fetchPhotos() {
// Fetching all photos
let options = PHFetchOptions()
options.sortDescriptors = [
// Latest to old
NSSortDescriptor(key: "creationDate", ascending: false)
]
options.includeHiddenAssets = false
let fetchedResults = PHAsset.fetchAssets(with: options)
allPhotos = fetchedResults
fetchedResults.enumerateObjects { asset, index, _ in
// Get image from asset
self.getImage(from: asset, size: CGSize(width: 150, height: 150)) { image in
// Append it to array
// Why we store asset?
// To get full image for sending
self.fetchedPhotos.append(Asset(asset: asset, image: image))
}
}
}
// Use completion handlers to recive objects
func getImage(from asset: PHAsset, size: CGSize, completion: @escaping (UIImage) -> ()) {
// To cache image in memory
let imageManager = PHCachingImageManager()
imageManager.allowsCachingHighQualityImages = true
// Your own properties for images
let imageOptions = PHImageRequestOptions()
imageOptions.deliveryMode = .highQualityFormat
imageOptions.isSynchronous = false
// To reduce Ram uage just getting thumbnail size of image
let size = CGSize(width: 150, height: 150)
imageManager.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: imageOptions) { image, _ in
guard let resizedImage = image else { return }
completion(resizedImage)
}
}
// Open image or video
func extractPreviewData(asset: PHAsset) {
let manager = PHCachingImageManager()
if asset.mediaType == .image {
// Extract image
getImage(from: asset, size: PHImageManagerMaximumSize) { image in
DispatchQueue.main.async {
self.selectedImagePreview = image
}
}
}
if asset.mediaType == .video {
// Extract video
let videoManager = PHVideoRequestOptions()
videoManager.deliveryMode = .highQualityFormat
manager.requestAVAsset(forVideo: asset, options: videoManager) { videoAsset, _, _ in
guard let videoURL = videoAsset else { return }
DispatchQueue.main.async {
self.selectedVideoPreview = videoURL
}
}
}
}
}
| true
|
4ab90226dce865a4295de91a952b8d0bcb53df13
|
Swift
|
edias/Blity
|
/Blity/Views/Summary/Category/SummaryCategoryViewModel.swift
|
UTF-8
| 1,156
| 2.984375
| 3
|
[] |
no_license
|
//
// SummaryCategoryViewModel.swift
// Blity
//
// Created by Eduardo Dias on 26/07/21.
//
import Foundation
struct SummaryCategoryViewModel {
private let expenses: CategoryExpenses
var categoryName: String { expenses.name }
var categoryIcon: String { expenses.iconName }
var budget: Int { expenses.budget }
var totalSpent: Int { expenses.totalSpent }
init(expenses: CategoryExpenses) {
self.expenses = expenses
}
var tracking: (message: String, icon: String) {
let percentageSpent = 100 * expenses.totalSpent / expenses.budget
switch percentageSpent {
case (0...77):
return (message: "Your \(categoryName.lowercased()) spending is still on track", icon: "CheckIcon")
case (78...82):
return (message:"You are almost exceeding your budget", icon: "WarningIcon")
case (83...99):
return (message: "You are very close to reach your budget", icon: "WarningIcon")
default:
return (message: "You excedded your budget", icon: "ErrorIcon")
}
}
}
| true
|
87e995196733a9428e9cdad1b19a4c4095335fbe
|
Swift
|
albertopeam/clean-architecture
|
/CleanArchitectureUITests/tools/network/MockUrlSession.swift
|
UTF-8
| 1,254
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//
// MockUrlSession.swift
// CleanArchitectureUITests
//
// Created by Alberto on 24/12/2018.
// Copyright © 2018 Alberto. All rights reserved.
//
import Foundation
//Sundell https://medium.com/@johnsundell/mocking-in-swift-56a913ee7484
class MockURLSession: URLSession {
typealias CompletionHandler = (Data?, URLResponse?, Error?) -> Void
var data: Data?
var error: Error?
var response: URLResponse = DummyURLResponse()
init(data: Data) {
self.data = data
}
init(error: Error) {
self.error = error
}
override func dataTask(with url: URL,
completionHandler: @escaping CompletionHandler) -> URLSessionDataTask {
let data = self.data
let error = self.error
let response = self.response
return MockURLSessionDataTask {
completionHandler(data, response, error)
}
}
}
private final class DummyURLResponse: URLResponse {
init() {
super.init(url: URL(string: "https://www.google.es")!, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
6de5b063e59afa1d90845b7da9eafec321363d8a
|
Swift
|
ctrador/PeopleMonChad
|
/Models/People.swift
|
UTF-8
| 3,285
| 2.734375
| 3
|
[] |
no_license
|
//
// People.swift
// PeopleMon2
//
// Created by Chad Trador on 11/10/16.
// Copyright © 2016 Chad Trador. All rights reserved.
//
//
// OtherUsers.swift
// Peoplemon
//
// Created by Andrew Noble on 11/6/16.
// Copyright © 2016 Andrew Noble. All rights reserved.
//
import Foundation
import MapKit
import Freddy
import Alamofire
class People : NetworkModel {
var userId : String?
var userName : String?
var avatarBase : String?
var longitute : Double?
var latitude : Double?
var created : String?
var radiusInMeters : Double?
var radius : Double?
var requestType: RequestType = .nearby
enum RequestType {
case userCaught
case userCheckin
case nearby
case userCatch
}
required init() {
requestType = .userCaught
}
required init(json: JSON) throws {
userId = try? json.getString(at: Constants.Person.userId)
userName = try? json.getString(at: Constants.Person.userName)
avatarBase = try? json.getString(at: Constants.Person.avatarBase64)
longitute = try? json.getDouble(at: Constants.Person.longitude)
latitude = try? json.getDouble(at: Constants.Person.latitude)
created = try? json.getString(at: Constants.Person.created)
radiusInMeters = try? json.getDouble(at: Constants.Person.radius)
}
init(radius: Double) {
self.radiusInMeters = radius
self.requestType = .nearby
}
init (coordinate : CLLocationCoordinate2D) {
self.longitute = coordinate.longitude
self.latitude = coordinate.latitude
self.requestType = .userCheckin
}
init(longitude: Double, latitude: Double) {
self.longitute = longitude
self.latitude = latitude
self.requestType = .userCheckin
}
init(userId: String, radiusInMeters: Double) {
self.requestType = .userCaught
self.userId = userId
self.radiusInMeters = radiusInMeters
}
func method() -> Alamofire.HTTPMethod {
switch requestType {
case .nearby, .userCaught:
return .get
default:
return .post
}
}
func path() -> String {
switch requestType {
case .nearby:
return "/v1/User/Nearby"
case .userCheckin:
return "/v1/User/CheckIn"
case .userCatch:
return "/v1/User/Catch"
case .userCaught:
return "/v1/User/Caught"
}
}
func toDictionary() -> [String: AnyObject]? {
var params: [String: AnyObject] = [:]
switch requestType {
case .nearby:
params[Constants.Person.radius] = radiusInMeters as AnyObject?
case .userCheckin:
params[Constants.Person.longitude] = longitute as AnyObject?
params[Constants.Person.latitude] = latitude as AnyObject?
case .userCatch:
params[Constants.Person.caughtUserId] = userId as AnyObject?
params[Constants.Person.radius] = radiusInMeters as AnyObject?
case .userCaught:
break
}
return params
}
}
| true
|
bb0a1f28bb29f4b681d14a6068bde73cac3cce2b
|
Swift
|
sauledossymbekova/IOS
|
/6task.swift
|
UTF-8
| 687
| 2.78125
| 3
|
[] |
no_license
|
class Solution {
func moveZeroes(_ nums: inout [Int]) {
if !nums.isEmpty {
var locIndex = nums.startIndex
var numIndex = nums.startIndex
while numIndex != nums.endIndex {
if nums[numIndex] != 0 {
nums[locIndex] = nums[numIndex]
if locIndex != numIndex {
nums[numIndex] = 0
}
locIndex += 1
}
numIndex += 1
}
}
}
func getSolution() -> Void {
var array: [Int] = [1, 2, 3, 4]
Solution().moveZeroes(&array)
print(array)
}
}
| true
|
cac4534f6560a8366a71609c01a070ae9b1f4907
|
Swift
|
nagyist/CanvasKit
|
/CanvasKitTests/Model Tests/CKISubmissionCommentTests.swift
|
UTF-8
| 1,611
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// CKISubmissionCommentTests.swift
// CanvasKit
//
// Created by Nathan Lambson on 7/14/14.
// Copyright (c) 2014 Instructure. All rights reserved.
//
import XCTest
class CKISubmissionCommentTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testJSONModelConversion() {
let submissionCommentDictionary = Helpers.loadJSONFixture("submission_comment") as NSDictionary
let submissionComment = CKISubmissionComment(fromJSONDictionary: submissionCommentDictionary)
XCTAssertEqual(submissionComment.id!, "37", "Submission Comment ID was not parsed correctly")
XCTAssertEqual(submissionComment.comment!, "Well here's the thing...", "Submission Comment comment was not parsed correctly")
let formatter = ISO8601DateFormatter()
formatter.includeTime = true
let createdAtDate = formatter.dateFromString("2012-01-01T01:00:00Z")
XCTAssertEqual(submissionComment.createdAt!, createdAtDate, "Submission Comment createdAt date was not parsed correctly")
XCTAssertEqual(submissionComment.authorID!, "134", "Submission Comment authorID was not parsed correctly")
XCTAssertEqual(submissionComment.authorName!, "Toph Beifong", "Submission Comment authorName was not parsed correctly")
}
}
| true
|
00038c27538594e1130222c47a248d18a4883925
|
Swift
|
shndrs/SwitchTheShitOutOfTheColor
|
/SwitchTheShitOutOfTheColor/Scenes/MenuScene.swift
|
UTF-8
| 2,755
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// MenuScene.swift
// SwitchTheShitOutOfTheColor
//
// Created by NP2 on 5/4/19.
// Copyright © 2019 shndrs. All rights reserved.
//
import SpriteKit
final class MenuScene: SKScene {
override func didMove(to view: SKView) {
addLogoAndBackground()
addLabels()
}
private func addLogoAndBackground() {
backgroundColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
let backgroundImage = SKSpriteNode()
backgroundImage.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
backgroundImage.zPosition = 0
backgroundImage.texture = SKTexture(imageNamed: SKShits.bg4.rawValue)
backgroundImage.aspectFillToSize(fillSize: view!.frame.size)
addChild(backgroundImage)
}
private func addLabels() {
let playLabel = SKLabelNode(text: SKShits.tapToPlay.rawValue)
playLabel.fontName = FontName.copperplate.rawValue
playLabel.fontSize = 34.0
playLabel.fontColor = .white
playLabel.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(playLabel)
animate(label: playLabel)
let highscoreLabel = SKLabelNode(text: SKShits.highscore.rawValue + "\(UserDefaultsManager.shared.value.integer(forKey: UserDefaultsKeys.highscore.rawValue))")
highscoreLabel.fontName = FontName.copperplate.rawValue
highscoreLabel.fontSize = 27.0
highscoreLabel.fontColor = .white
highscoreLabel.position = CGPoint(x: frame.midX, y: frame.midY - highscoreLabel.frame.size.height*4)
addChild(highscoreLabel)
let recentScoreLabel = SKLabelNode(text: SKShits.recentScore.rawValue + "\(UserDefaultsManager.shared.value.integer(forKey: UserDefaultsKeys.recentScroe.rawValue))")
recentScoreLabel.fontName = FontName.copperplate.rawValue
recentScoreLabel.fontSize = 20.0
recentScoreLabel.fontColor = .white
recentScoreLabel.position = CGPoint(x: frame.midX,
y: highscoreLabel.position.y - recentScoreLabel.frame.size.height*2)
addChild(recentScoreLabel)
}
func animate(label:SKLabelNode) {
let scaleUp = SKAction.scale(to: 1.02, duration: 0.5)
let scaleDown = SKAction.scale(to: 1.0, duration: 0.5)
let sequence = SKAction.sequence([scaleDown, scaleUp])
label.run(SKAction.repeatForever(sequence))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let gameScene = GameScene(size: view!.bounds.size)
view?.presentScene(gameScene, transition: .reveal(with: .up, duration: 0.6))
}
}
| true
|
f7ccb4ffba9833e7e501833a3336817548a97526
|
Swift
|
uxap/EPContactsPicker
|
/Contacts Picker/ViewController4.swift
|
UTF-8
| 4,687
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController2.swift
// Contacts Picker
//
// Created by Eddie Hiu-Fung Lau on 28/3/2017.
// Copyright © 2017 Prabaharan Elangovan. All rights reserved.
//
import Foundation
import UIKit
import UXContactsPicker
class ViewController4 : UIViewController {
@IBOutlet var searchButtonItem: UIBarButtonItem!
/*
lazy var cancelButtonItem: UIBarButtonItem = {
let button = UIButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 60, height: 32)
button .setTitle("Cancel", for: .normal)
button.addTarget(self, action: #selector(didTapCancelSearchButton),
for: .touchUpInside)
return UIBarButtonItem(customView: button)
}()
*/
lazy var contactsPicker: EPContactsPicker = {
let picker = EPContactsPicker(delegate: self, multiSelection: false)
var style = EPContactsPickerStyle()
style.showSearchBar = false
picker.style = style
var searchBarStyle = EPContactsPickerSearchBarStyle()
//searchBarStyle.hasCancelButton = false
picker.searchBarStyle = searchBarStyle
return picker
}()
var isSearching = false
override func viewDidLoad() {
addChild(contactsPicker)
contactsPicker.view.frame = view.bounds
contactsPicker.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(contactsPicker.view)
}
override func viewDidLayoutSubviews() {
let top = topLayoutGuide.length
let bottom = bottomLayoutGuide.length
contactsPicker.tableView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0)
contactsPicker.tableView.scrollIndicatorInsets = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if (isSearching) {
contactsPicker.searchBar.becomeFirstResponder()
}
}
}
// MARK: - Action
extension ViewController4 {
@IBAction func didTapSearchButton() {
beginSearch(animated: true)
}
func didTapCancelSearchButton() {
contactsPicker.cancelSearch()
}
}
// MARK: - Search
extension ViewController4 {
func beginSearch(animated:Bool) {
let searchBar = contactsPicker.searchBar
self.navigationItem.setRightBarButton(nil, animated: animated)
self.navigationItem.titleView = searchBar
self.navigationItem.setHidesBackButton(true, animated: animated)
searchBar.becomeFirstResponder()
isSearching = true
if animated {
searchBar.alpha = 0
UIView.animate(withDuration: 0.3, animations: {
searchBar.alpha = 1.0
})
}
}
func endSearch(animated:Bool) {
let searchBar = contactsPicker.searchBar
let completion: (Bool)->Void = { Bool -> Void in
self.navigationItem.setRightBarButton(self.searchButtonItem, animated: animated)
self.navigationItem.titleView = nil
self.navigationItem.setHidesBackButton(false, animated: animated)
self.isSearching = false
}
if animated {
UIView.animate(withDuration: 0.3, animations: {
searchBar.alpha = 0.0
}, completion: completion )
} else {
completion(true)
}
}
}
extension ViewController4: EPPickerDelegate {
func epContactPicker(_: EPContactsPicker, didContactFetchFailed error: NSError) {
}
func epContactPicker(_: EPContactsPicker, didCancel error: NSError) {
}
func epContactPicker(_: EPContactsPicker, didSelectContact contact: EPContact) {
print(contact.phoneNumbers)
if (isSearching) {
endSearch(animated: true)
}
if contact.phoneNumbers.count > 0 {
let alert = UIAlertController(title: "Selected Contact", message: contact.phoneNumbers[0].phoneNumber, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
func epContactPicker(_: EPContactsPicker, didSelectMultipleContacts contacts: [EPContact]) {
}
func epContactPickerSearchDidEnd(_: EPContactsPicker) {
endSearch(animated: true)
}
}
| true
|
1221ace2b4016529989d39ab4d3912a6af333393
|
Swift
|
JulianDMartinez/Social-Media-Templates
|
/Social Media Templates/Views/RoundCornerCollectionViewCell.swift
|
UTF-8
| 1,121
| 2.6875
| 3
|
[] |
no_license
|
//
// RoundCornerCollectionViewCell.swift
// Social Media Templates
//
// Created by Julian Martinez on 5/21/21.
//
import UIKit
class RoundCornerCollectionViewCell: UICollectionViewCell {
let imageView = UIImageView()
override func didMoveToSuperview() {
configureImageView()
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.3
layer.shadowRadius = 2
layer.shadowOffset = CGSize(width: 1, height: 1)
}
func configureImageView() {
addSubview(imageView)
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 20
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: topAnchor),
imageView.bottomAnchor.constraint(equalTo: bottomAnchor),
imageView.trailingAnchor.constraint(equalTo: trailingAnchor),
imageView.leadingAnchor.constraint(equalTo: leadingAnchor)
])
}
}
| true
|
ec8c353b3e74990616718dffe6146c81f14e19d8
|
Swift
|
asianxjay/facebook-exercise
|
/Facebook_Exercise/LoginViewController.swift
|
UTF-8
| 4,243
| 2.515625
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// Facebook_Exercise
//
// Created by Jason Demetillo on 9/11/14.
// Copyright (c) 2014 codepath. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet var inputsView: UIView!
@IBOutlet var emailTextView: UITextField!
@IBOutlet var passwordTextView: UITextField!
@IBOutlet var loadingView: UIActivityIndicatorView!
var loggingAlertView: UIAlertView?
func doCheck()->(){
println("doCheck")
//
self.loadingView.stopAnimating()
//
var email = self.emailTextView.text
var password = self.passwordTextView.text
self.loggingAlertView!.dismissWithClickedButtonIndex(0, animated: true)
if email == "jay@yahoo.com" && password == "password" {
// OK
performSegueWithIdentifier("Connect", sender: self)
} else {
// ERROR
UIAlertView(title: "Ew", message: "You are not Jay", delegate: self, cancelButtonTitle:"Ok").show()
}
}
@IBAction func onLoad(sender: UIButton) {
self.loadingView.startAnimating()
delay(2,doCheck)
self.loggingAlertView = UIAlertView (title: "Logging In", message: nil, delegate: self, cancelButtonTitle: nil)
self.loggingAlertView!.show()
}
@IBAction func onEmailValueChange(sender: UITextField) {
println("onEmailValueChange")
if emailTextView.text=="" || passwordTextView.text==""{
self.loginButton2.enabled=false
println("disabled")
}
else{
self.loginButton2.enabled=true
println("enabled")
}
}
@IBAction func onPasswordValueChange(sender: UITextField) {
if emailTextView.text=="" || passwordTextView.text==""{
self.loginButton2.enabled=false
println("disabled")
}
else{
self.loginButton2.enabled=true
println("enabled")
}
}
@IBOutlet var loginButton: UIView!
@IBOutlet var loginButton2: UIButton!
@IBAction func onTap(sender: UITapGestureRecognizer) {
view.endEditing(true)
}
func keyboardWillShow(notification: NSNotification!) {
println("LoginViewController - willShowKeyboard")
var userInfo: NSDictionary = notification.userInfo!
var kbSize: CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size
println("height:\(kbSize.height), width: \(kbSize.width)")
inputsView.frame.origin.y=160
loginButton.frame.origin.y=kbSize.height-10
}
func keyboardWillHide(notification: NSNotification!) {
inputsView.frame.origin.y=189
loginButton.frame.origin.y=265
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
loginButton2.enabled=false
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
3455e7024900e2fd63c37e1587b55715425168d7
|
Swift
|
mrk21/study_mobile
|
/swift_function/swift_function.playground/Contents.swift
|
UTF-8
| 1,731
| 4.3125
| 4
|
[
"MIT"
] |
permissive
|
//: Playground - noun: a place where people can play
import UIKit
func func1() {
print("a")
}
func1()
func func2(v: String) {
print(v)
}
func2("a")
func func3(v: String) -> String {
return "v: \(v)"
}
print(func3("a"))
/// Outer function's arguments
func func4(count c: Int) {
print(c)
}
func4(count: 4)
/// Default parameters
func func5(value: Int = 4) {
print(value)
}
func5(2)
func5()
/// variable parameters
func func6(values: Int...) {
print(values)
}
func6(1)
func6(1,2)
func6(1,2,3)
//// variable parameters with label parameters
func func7(values: Int..., value1: Int, value2: Int) {
print("\(values), value1: \(value1), value2: \(value2)")
}
func7(1, value1: 10, value2: 11)
func7(1,2, value1: 10, value2: 11)
func7(1,2,3, value1: 10, value2: 11)
/// Constant parameters and variable parameters
func func8(value: Int) {
// value += 3 // Error
print(value)
}
func8(1)
func func9(var value: Int) {
value += 3 // OK
print(value)
}
func9(1)
/// Lambda
func func10(a: Int, b: Int, f: (Int, Int) -> Int) -> Int {
return f(a, b)
}
print(func10(2, b: 3, f: {(v1: Int, v2: Int) in return v1 * v2}))
print(func10(2, b: 3, f: {(v1, v2) in return v1 * v2}))
print(func10(2, b: 3, f: {(v1, v2) in v1 * v2}))
print(func10(2, b: 3, f: { $0 * $1 }))
print(func10(2, b: 3, f: *))
print(func10(2, b: 3){ $0 * $1 })
/// Nested Function
func func11() {
func display() {
print("a")
}
display()
}
func11()
// display() // Error
/// Clojure
func func12(v1: Int) -> (Int) -> Int {
func f(v2: Int) -> Int {
return v1 * v2
}
return f
}
print(func12(3)(4))
func func13(v1: Int) -> (Int) -> Int {
return { v1 * $0 }
}
print(func13(3)(4))
| true
|
4c7bf8cc0916048f503de9e82d5d329f111f9ab3
|
Swift
|
Gray-Wind/ChessClockSwift
|
/ChessClock/Clocks/ViewController.swift
|
UTF-8
| 2,096
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ChessClock
//
// Created by joan barroso on 13/07/2019.
// Copyright © 2019 joan barroso. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var topChrono: UILabel!
@IBOutlet weak var bottomChrono: UILabel!
@IBOutlet weak var bottomClockButton: UIButton!
@IBOutlet weak var topClockButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var resumeButton: UIButton!
var presenter: ClocksPresenter!
override func viewDidLoad() {
super.viewDidLoad()
customize()
self.presenter = ClocksPresenter(view: self)
}
@IBAction func topClockPressed(_ sender: Any) {
presenter.clocksStateBehaviourSubject.onNext(ClocksEvents.bottomRunning)
}
@IBAction func bottomClockPressed(_ sender: Any) {
presenter.clocksStateBehaviourSubject.onNext(ClocksEvents.topRunning)
}
@IBAction func pauseButtonPressed(_ sender: Any) {
presenter.clocksStateBehaviourSubject.onNext(ClocksEvents.pause)
pauseState(turnOn: true)
}
@IBAction func resetButtonPressed(_ sender: Any) {
presenter.clocksStateBehaviourSubject.onNext(ClocksEvents.restart)
pauseState(turnOn: false)
}
@IBAction func resumeButtonPressed(_ sender: Any) {
presenter.clocksStateBehaviourSubject.onNext(ClocksEvents.resume)
pauseState(turnOn: false)
}
}
extension ViewController: ClockView {
func render(viewModel: ClocksViewModel) {
topChrono.text = viewModel.topTime
bottomChrono.text = viewModel.bottomTime
}
}
private extension ViewController {
private func customize() {
topChrono.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
}
}
// MARK: - Paused state UI setup extension
private extension ViewController {
private func pauseState(turnOn trigger: Bool) {
resetButton.isEnabled = trigger
resumeButton.isEnabled = trigger
bottomClockButton.isEnabled = !trigger
topClockButton.isEnabled = !trigger
}
}
| true
|
c2808372596d9e59b5fbabe0f28c33dd6b496a40
|
Swift
|
KonstantinKiski/Pulse
|
/PulseApp/UI/OneRateView.swift
|
UTF-8
| 3,115
| 2.53125
| 3
|
[] |
no_license
|
//
// OneRateView.swift
// PulseApp
//
// Created by Константин Киски on 16.02.2021.
//
import Foundation
class OneRateView: UIView {
// MARK: - UI Elements
@IBOutlet private var dateLabel: UILabel!
@IBOutlet private var bpmLabel: UILabel!
@IBOutlet private var pulseView: UIView!
@IBOutlet private var infoImageView: UIImageView!
@IBOutlet private var pulseLabel: UILabel!
@IBOutlet private var iconImage: UIImageView!
@IBOutlet private var iconView: UIView!
private var view: UIView!
// MARK: - Set data
public func setData(date: Date, pulse: Int, icon: UIImage) {
if pulse < 65 {
setLowPulse()
} else if pulse > 86 {
setBadPulse()
} else {
setNormalPulse()
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM YYYY, HH:mm"
dateLabel.text = "\(dateFormatter.string(from: Date()))"
bpmLabel.text = "\(pulse) bpm"
iconView.layer.borderColor = UIColor(red: 0.76, green: 0.76, blue: 0.76, alpha: 1.00).cgColor
}
private func setNormalPulse() {
pulseView.backgroundColor = UIColor(red: 0.68, green: 0.92, blue: 0.86, alpha: 1.00)
pulseLabel.textColor = UIColor(red: 0.00, green: 0.74, blue: 0.08, alpha: 1.00)
infoImageView.tintColor = UIColor(red: 0.00, green: 0.74, blue: 0.08, alpha: 1.00)
//UIColor(red: 0.00, green: 0.74, blue: 0.55, alpha: 1.00)
pulseLabel.text = "Normal pulse"
}
private func setLowPulse() {
pulseView.backgroundColor = UIColor(red: 0.98, green: 0.84, blue: 0.72, alpha: 1.00)
pulseLabel.textColor = UIColor(red: 0.96, green: 0.49, blue: 0.15, alpha: 1.00)
infoImageView.tintColor = UIColor(red: 0.96, green: 0.49, blue: 0.15, alpha: 1.00)
pulseLabel.text = "Low pulse"
}
private func setBadPulse() {
pulseView.backgroundColor = UIColor(red: 0.98, green: 0.70, blue: 0.71, alpha: 1.00)
pulseLabel.textColor = UIColor(red: 0.92, green: 0.10, blue: 0.19, alpha: 1.00)
infoImageView.tintColor = UIColor(red: 0.92, green: 0.10, blue: 0.19, alpha: 1.00)
pulseLabel.text = "Bad pulse"
}
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
private func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "OneRateView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
xibSetup()
view?.prepareForInterfaceBuilder()
}
}
| true
|
a611d314c15f55588dbe86566eec7606fdf23fb9
|
Swift
|
Evelyn09/MDB-iOS-Projects
|
/MDB Social/Project/MDB Social/OnBoarding/SignUpVC.swift
|
UTF-8
| 8,296
| 2.65625
| 3
|
[] |
no_license
|
//
// SignUpVC.swift
// MDB Social
//
// Created by Evelyn Hu on 11/4/21.
//
import UIKit
import NotificationBannerSwift
class SignUpVC: UIViewController {
private let signUpStack: UIStackView = {
let stack = UIStackView()
stack.axis = .vertical
stack.distribution = .equalSpacing
stack.spacing = 25
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
private let fullNameTextField: AuthTextField = {
let tf = AuthTextField(title: "Full Name:")
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
private let newEmailTextField: AuthTextField = {
let tf = AuthTextField(title: "Email:")
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
private let usernameTextField: AuthTextField = {
let tf = AuthTextField(title: "Username:")
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
private let newPasswordTextField: AuthTextField = {
let tf = AuthTextField(title: "Password:")
tf.textField.isSecureTextEntry = true
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
private let confirmPasswordTextField: AuthTextField = {
let tf = AuthTextField(title: "Confirm Password:")
tf.textField.isSecureTextEntry = true
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
private let signUpButton: LoadingButton = {
let btn = LoadingButton()
btn.layer.backgroundColor = UIColor.primary.cgColor
btn.setTitle("Sign Up", for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .bold)
btn.isUserInteractionEnabled = true
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
private let errorLabel: UILabel = {
let lbl = UILabel()
lbl.text = "Error"
lbl.textColor = .red
lbl.font = .systemFont(ofSize: 16, weight: .semibold)
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
private var bannerQueue = NotificationBannerQueue(maxBannersOnScreenSimultaneously: 1)
private let contentEdgeInset = UIEdgeInsets(top: 120, left: 40, bottom: 30, right: 40)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(signUpStack)
signUpStack.addArrangedSubview(fullNameTextField)
signUpStack.addArrangedSubview(newEmailTextField)
signUpStack.addArrangedSubview(usernameTextField)
signUpStack.addArrangedSubview(newPasswordTextField)
signUpStack.addArrangedSubview(confirmPasswordTextField)
signUpStack.addArrangedSubview(signUpButton)
signUpStack.addArrangedSubview(errorLabel)
signUpButton.layer.cornerRadius = 10
signUpButton.addTarget(self, action: #selector(didTapSignUp(_:)), for: .touchUpInside)
errorLabel.alpha = 0
NSLayoutConstraint.activate([
signUpStack.leadingAnchor.constraint(equalTo: view.leadingAnchor,
constant: contentEdgeInset.left),
signUpStack.trailingAnchor.constraint(equalTo: view.trailingAnchor,
constant: -contentEdgeInset.right),
signUpStack.topAnchor.constraint(equalTo: view.topAnchor,
constant: contentEdgeInset.top),
signUpButton.heightAnchor.constraint(equalToConstant: 40)
])
// Do any additional setup after loading the view.
}
func showError(_ message:String){
errorLabel.text = message
errorLabel.alpha = 1
}
//change this code, but replicate design of the signInButton
@objc private func didTapSignUp(_ sender: UIButton) {
let error = checkFields()
if error != nil{
showError(error!)
}
else{
errorLabel.alpha = 0
let fullName = fullNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let email = newEmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = newPasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let userName = usernameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
//this will check if the password is weak,
SOCAuthManager.shared.signUp(withEmail: email, userName: userName, password: password, fullName: fullName) { [weak self] result in
guard let self = self else { return }
switch result {
case .failure(let error):
switch error {
case .emailAlreadyInUse:
self.showErrorBanner(withTitle: "Email already in use", subtitle: "Please check your email address")
case .weakPassword:
self.showErrorBanner(withTitle: "Weak password", subtitle: "Please make it stronger")
case .internalError:
self.showErrorBanner(withTitle: "Internal error", subtitle: "")
default:
self.showErrorBanner(withTitle: "Unspecified error", subtitle: "")
}
case .success:
guard let window = self.view.window else { return }
window.rootViewController = FeedVC()
let options: UIView.AnimationOptions = .transitionCrossDissolve
let duration: TimeInterval = 0.3
UIView.transition(with: window, duration: duration, options: options, animations: {}, completion: nil)
}
}
}
}
private func showErrorBanner(withTitle title: String, subtitle: String? = nil) {
showBanner(withStyle: .warning, title: title, subtitle: subtitle)
}
private func showBanner(withStyle style: BannerStyle, title: String, subtitle: String?) {
guard bannerQueue.numberOfBanners == 0 else { return }
let banner = FloatingNotificationBanner(title: title, subtitle: subtitle,
titleFont: .systemFont(ofSize: 17, weight: .medium),
subtitleFont: .systemFont(ofSize: 14, weight: .regular),
style: style)
banner.show(bannerPosition: .top,
queue: bannerQueue,
edgeInsets: UIEdgeInsets(top: 15, left: 15, bottom: 0, right: 15),
cornerRadius: 10,
shadowColor: .primaryText,
shadowOpacity: 0.3,
shadowBlurRadius: 10)
}
//add in the check to make sure both passwords match
func checkFields() -> String? {
if fullNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
newEmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
newPasswordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
confirmPasswordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all fields."
}
if newPasswordTextField.text != confirmPasswordTextField.text{
return "Your passwords do not match"
}
return nil
}
}
| true
|
c172d979a2a74d96b386c1eb80f50b65979c33eb
|
Swift
|
mohamadilk/CRBot
|
/Crypto Bot/Models/CellModel/CellModel.swift
|
UTF-8
| 718
| 2.859375
| 3
|
[] |
no_license
|
//
// CellModel.swift
// Crypto Bot
//
// Created by mohamad ilk on 8/13/1398 AP.
// Copyright © 1398 AP Mohammad Ilkhani. All rights reserved.
//
import Foundation
class CellModel {
var priceType: PriceCellTypes?
var value: String?
var cellType: CellType
var title: String?
var index: Int
var isValid = false
var targetsArray: [String]?
init(priceType: PriceCellTypes? = nil, value: String? = nil, cellType: CellType, title: String? = nil, index: Int, targetsArray: [String]? = nil) {
self.priceType = priceType
self.value = value
self.cellType = cellType
self.title = title
self.index = index
self.targetsArray = targetsArray
}
}
| true
|
1754459a4edea21c216e44ef474a7117ec86205a
|
Swift
|
sharplet/Swiftopt
|
/Tests/Helpers.swift
|
UTF-8
| 176
| 2.515625
| 3
|
[] |
no_license
|
// Created by Adam Sharp on 23/02/2015.
func catOptionals<T>(optionals: [T?]) -> [T] {
return optionals.reduce([]) { result, each in
each.map { result + [$0] } ?? result
}
}
| true
|
e33399a7806406dce09397589dbea7fba61327cb
|
Swift
|
nguyenhao12345/GraduateThesis
|
/PianoKaraoke/Piano_App/Models/ModelCategory.swift
|
UTF-8
| 639
| 2.65625
| 3
|
[] |
no_license
|
//
// ModelCategory.swift
// Piano_App
//
// Created by Nguyen Hieu on 5/26/19.
// Copyright © 2019 com.nguyenhieu.demo. All rights reserved.
//
import Foundation
struct CategoryModel: ModelHome {
var heighthSize: Float?
var widthSize: Float?
let name: String
let arrCategory: [CategoryDetail]
init(name: String, arrCategory: [CategoryDetail]) {
self.name = name
self.arrCategory = arrCategory
}
}
struct CategoryDetail {
var title: String
var content: String
init(title: String, content: String) {
self.title = title
self.content = content
}
}
| true
|
867106555cbf9a76ca63388234b9edff4842fde3
|
Swift
|
kljsoftware/lalala
|
/Music/Music/View/Main/Discover/DiscoverCollectionSectionView.swift
|
UTF-8
| 1,181
| 2.546875
| 3
|
[] |
no_license
|
//
// DiscoverCollectionSectionView.swift
// Music
//
// Created by hzg on 2017/12/5.
// Copyright © 2017年 demo. All rights reserved.
//
/// 分区视图
class DiscoverCollectionSectionView: UICollectionReusableView {
/// 名称
@IBOutlet weak var nameLabel: UILabel!
/// 箭头
@IBOutlet weak var arrowImageView: UIImageView!
/// type: 0表示排行榜 1表示热门歌单
private var type:Int?
/// 按钮点击
@IBAction func onButtonClicked(_ sender: UIButton) {
if type != nil && type == 0 {
let view = Bundle.main.loadNibNamed("DiscoverRankDetailView", owner: nil, options: nil)?.first as! DiscoverRankDetailView
AppUI.push(from: self, to: view, with: APP_SIZE)
}
}
// MARK: - public methods
/// 更新 type: 0表示排行榜 1表示热门歌单
func update(type:Int) {
self.type = type
nameLabel.text = type == 0 ? LanguageKey.Discover_Rank.value : LanguageKey.Discover_PopularPlaylist.value
arrowImageView.isHidden = type != 0
}
}
/// 空的分区视图
class DiscoverCollectionEmptyView : UICollectionReusableView {}
| true
|
4d8da455bd2e5079ea388963b0a4671a57af1fce
|
Swift
|
emotiog/MSLD
|
/MSLD/ResultViewController.swift
|
UTF-8
| 3,295
| 2.984375
| 3
|
[] |
no_license
|
//
// ResultViewContoller.swift
// MSLD
//
// Created by USER on 2021/05/15.
//
import Foundation
class ResultViewController : ViewController {
var originImage : UIImage!
var resultImage : UIImage!
var imageView: UIImageView!
let pngFileManager: PNGFileManager = PNGFileManager()
override func viewDidLoad() {
super.viewDidLoad()
self.imageView = buildImageView()
self.view.addSubview(self.imageView)
var position = CGPoint(x: self.view.frame.width * 0.8971, y: 10)
self.view.addSubview(buildSaveButton(position: position))
position.x += 10
self.view.addSubview(buildBackButton(position: position))
self.imageView.image = originImage
}
//MARK: private function
private func buildImageView() -> UIImageView {
let view: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 480, height: 640))
view.layer.position = CGPoint(x: self.view.frame.width * 0.5, y: self.view.frame.height * 0.5)
return view
}
private func buildBackButton(position: CGPoint) -> UIButton {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 40), primaryAction: UIAction(title: "back", handler: { _ in self.dismiss(animated: true, completion: nil)}))
button.backgroundColor = UIColor.gray
button.layer.masksToBounds = true
button.layer.cornerRadius = 20.0
button.layer.position = position
return button
}
private func buildSaveButton(position: CGPoint) -> UIButton {
let action = UIAction(title: "Save", handler: { _ in
let uuid = UUID().uuidString
self.pngFileManager.save(image: self.originImage, forKey: uuid)
OpenCVWrapper.appendDesc(self.originImage, savePath: uuid)
self.messageBox(title: "Success", message: "Save new image successfully", messageBoxStyle: .alert, alertActionStyle: .cancel) {
self.dismiss(animated: true, completion: nil)
}
})
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 40), primaryAction: action)
button.backgroundColor = UIColor.red
button.layer.masksToBounds = true
button.layer.cornerRadius = 20.0
button.layer.position = position
return button
}
// @escaping 클로저는 함수의 인자로 전달되었을 때, 함수의 실행이 종료된 후 실행되는 클로저 -> 함수 밖(escaping)에서 실행되는 클로저
// 반대 -> Non-Escaping 클로저
// https://jusung.github.io/Escaping-Closure/
private func messageBox(title: String, message: String, messageBoxStyle: UIAlertController.Style, alertActionStyle: UIAlertAction.Style, completionHandler: @escaping () -> Void) {
let okAction = UIAlertAction(title: "Ok", style: alertActionStyle, handler: { _ in completionHandler() // 이건 okay 누른 이후에 비동기 식으로 작동
})
let alert = UIAlertController(title: title, message: message, preferredStyle: messageBoxStyle)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
| true
|
88d3d4aa9dad0f2a4fb477550e2a738008b5205b
|
Swift
|
AlexLittlejohn/ALTextInputBar
|
/Example/ViewController.swift
|
UTF-8
| 3,767
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// ALTextInputBar
//
// Created by Alex Littlejohn on 2015/04/24.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let textInputBar = ALTextInputBar()
let keyboardObserver = ALKeyboardObservingView()
let scrollView = UIScrollView()
// This is how we observe the keyboard position
override var inputAccessoryView: UIView? {
get {
return keyboardObserver
}
}
// This is also required
override var canBecomeFirstResponder: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
configureScrollView()
configureInputBar()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChanged(notification:)), name: NSNotification.Name(rawValue: ALKeyboardFrameDidChangeNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.frame = view.bounds
textInputBar.frame.size.width = view.bounds.size.width
}
func configureScrollView() {
view.addSubview(scrollView)
let contentView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height * 2))
contentView.backgroundColor = UIColor(white: 0.8, alpha: 1)
scrollView.addSubview(contentView)
scrollView.contentSize = contentView.bounds.size
scrollView.keyboardDismissMode = .interactive
scrollView.backgroundColor = UIColor(white: 0.6, alpha: 1)
}
func configureInputBar() {
let leftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
leftButton.setImage(#imageLiteral(resourceName: "leftIcon"), for: .normal)
rightButton.setImage(#imageLiteral(resourceName: "rightIcon"), for: .normal)
keyboardObserver.isUserInteractionEnabled = false
textInputBar.showTextViewBorder = true
textInputBar.leftView = leftButton
textInputBar.rightView = rightButton
textInputBar.frame = CGRect(x: 0, y: view.frame.size.height - textInputBar.defaultHeight, width: view.frame.size.width, height: textInputBar.defaultHeight)
textInputBar.backgroundColor = UIColor(white: 0.95, alpha: 1)
textInputBar.keyboardObserver = keyboardObserver
view.addSubview(textInputBar)
}
@objc func keyboardFrameChanged(notification: NSNotification) {
if let userInfo = notification.userInfo {
let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
textInputBar.frame.origin.y = frame.origin.y
}
}
@objc func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
textInputBar.frame.origin.y = frame.origin.y
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let userInfo = notification.userInfo {
let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
textInputBar.frame.origin.y = frame.origin.y
}
}
}
| true
|
2e791790ec56a029eb038016d6215e2b09a66d34
|
Swift
|
AhmedRajib/The-News
|
/The News/HomeVC/ViewController.swift
|
UTF-8
| 7,959
| 2.609375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// The News
//
// Created by MacBook Pro on 27/8/20.
// Copyright © 2020 MacBook Pro. All rights reserved.
//
import UIKit
import RealmSwift
class ViewController: UIViewController {
@IBOutlet weak var loading: UIActivityIndicatorView!
var getdata = [DbForLates]()
@IBOutlet weak var tblView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Latest News"
// Start indicator
loading.startAnimating()
//Hide the seoaretor line
tblView.separatorColor = .clear
// this is the base url of
let url = URL(string: "https://newsapi.org/v2/everything?q=latest&apiKey=0472a1c18ebf4b01b17ae65d9cb5481f")
// instance create in realm
let realmm = try! Realm()
getdata = Array(realmm.objects(DbForLates.self)) // retrive the data from Database
// Check data empty or nil for api calling
if getdata.count == 0 || getdata.count == nil{
apiCalling(url: url!)
}else {
resetDefaults() // set the data empty on database
apiCalling(url: url!) // api calling
}
// loading indicator hide when data successfully set in tableview
loading.hidesWhenStopped = true
loading.stopAnimating()
}
@IBAction func unwind(_ sender: UIStoryboardSegue) {
}
func apiCalling(url: URL) {
let task = URLSession.shared.dataTask(with: url) { (rawData, response, err) in
if err == nil{
var imgArray = [String]()
do {
let data = try JSONDecoder().decode(TheNews.self, from: rawData!)
let r = try! Realm()
for i in 0..<data.articles.count{
let db = DbForLates()
db.title = data.articles[i].title
db.desc = "\(data.articles[i].description)"
db.url = "\(data.articles[i].url)"
if data.articles[i].urlToImage != nil{
imgArray.append(data.articles[i].urlToImage!)
do{
try! r.write{
r.add(db)
}
}
}
}
// store imgUrl
UserDefaults.standard.set(imgArray, forKey: "imgArray")
DispatchQueue.main.async {
self.tblView.reloadData()
}
} catch {
print(error.localizedDescription)
}
}
}.resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
}
override func viewWillAppear(_ animated: Bool) {
// Segmented Control
customSegment()
}
func customSegment(){
let codeSegmented = CustomSegmentedControl(frame: CGRect(x: 0, y: (navigationController?.navigationBar.frame.size.height)! + 20, width: self.view.frame.width, height: 50), buttonTitle: ["Latest","Bangladesh","Sports"])
codeSegmented.delegate = self
codeSegmented.accessibilityScroll(.right)
codeSegmented.backgroundColor = .clear
view.addSubview(codeSegmented)
}
}
func resetDefaults() {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
let defaults = UserDefaults.standard
let dictionary = defaults.dictionaryRepresentation()
dictionary.keys.forEach { key in
defaults.removeObject(forKey: key)
}
}
extension ViewController: CustomSegmentedControlDelegate{
func change(to index: Int) {
if index == 0{
navigationItem.title = "Latest News"
loading.startAnimating()
resetDefaults()
let latestUrl = "https://newsapi.org/v2/everything?q=latest&apiKey=0472a1c18ebf4b01b17ae65d9cb5481f"
let url1 = URL(string: latestUrl)
apiCalling(url: url1!)
DispatchQueue.main.async {
self.tblView.reloadData()
}
loading.hidesWhenStopped = true
loading.stopAnimating()
}
if index == 1{
navigationItem.title = "Bangladesh News"
loading.startAnimating()
resetDefaults()
let bangladeshUrl = "https://newsapi.org/v2/everything?q=bangladesh&apiKey=0472a1c18ebf4b01b17ae65d9cb5481f"
let url1 = URL(string: bangladeshUrl)
apiCalling(url: url1!)
DispatchQueue.main.async {
self.tblView.reloadData()
}
loading.hidesWhenStopped = true
loading.stopAnimating()
}
if index == 2{
navigationItem.title = "Sports News"
loading.startAnimating()
resetDefaults()
let sportsUrl = "https://newsapi.org/v2/everything?q=sport&apiKey=0472a1c18ebf4b01b17ae65d9cb5481f"
let url1 = URL(string: sportsUrl)
apiCalling(url: url1!)
DispatchQueue.main.async {
self.tblView.reloadData()
}
loading.hidesWhenStopped = true
loading.stopAnimating()
}
}
}
extension ViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let realmm = try! Realm()
getdata = Array(realmm.objects(DbForLates.self))
return getdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tblView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customTableViewCell
cell.lvl.text = getdata[indexPath.row].title
let defaults = UserDefaults.standard
let imgarray = defaults.stringArray(forKey: "imgArray") ?? [String]()
let url = URL(string: imgarray[indexPath.row])
// data task
URLSession.shared.dataTask(with: url!) { [weak self] data, response, error in
guard let data = data else {
return
}
DispatchQueue.main.async {
cell.img.image = UIImage(data: data)
}
}.resume()
return cell
}
}
extension ViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
260
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "detailsVC") as! DetailsVC
nextViewController.detailsLink = indexPath.row
self.present(nextViewController, animated:true, completion:nil)
}
}
| true
|
a4f09e755e8bf96d7ec7daebd38dd89fa914f987
|
Swift
|
randyzhao/TipCalculator
|
/tips/ViewController.swift
|
UTF-8
| 2,787
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ViewController.swift
// tips
//
// Created by randy_zhao on 4/24/16.
// Copyright © 2016 randy_zhao. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private let currencyFormatter = NSNumberFormatter()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
currencyFormatter.numberStyle = .CurrencyStyle
currencyFormatter.maximumFractionDigits = 2
}
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var billField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
setPercentageSegs()
if let billAmount = StorageHelper.loadBillAmountIfNotExpired() {
billField.text = String(billAmount)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setPercentageSegs()
updateLabels()
billField.becomeFirstResponder();
}
func setPercentageSegs() {
for index in 0...2 {
let percentage = StorageHelper.loadOrUseDefaultPercentage(index)
PercentageSeg.setTitle("\(percentage)%", forSegmentAtIndex: index)
}
PercentageSeg.selectedSegmentIndex = StorageHelper.loadDefaultPercentageIndex()
}
@IBOutlet weak var tipControl: UISegmentedControl!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func formatedPrice(price: Double) -> String{
return self.formatAmount(price)
}
@IBAction func onEditingChanged(sender: AnyObject) {
updateLabels()
if let billAmount = Double(billField.text ?? "") {
StorageHelper.saveBillAmountWithTimestamp(billAmount)
}
}
func formatAmount(total: Double) -> String {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
return formatter.stringFromNumber(total) ?? ""
}
func updateLabels() {
let tipPercentage = Double(StorageHelper.loadOrUseDefaultPercentage(tipControl.selectedSegmentIndex)) * 0.01
let billAmount = Double(billField.text ?? "0") ?? 0
let tip = billAmount * tipPercentage
let total = billAmount + tip
tipLabel.text = self.formatedPrice(tip)
totalLabel.text = self.formatedPrice(total)
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
@IBOutlet weak var PercentageSeg: UISegmentedControl!
}
| true
|
4f19e622766f82f61bb3b4f7421088d835be62db
|
Swift
|
workoutplz/Vridge
|
/Vridge/Vridge/View/Ranking/RankingHeader.swift
|
UTF-8
| 3,360
| 2.640625
| 3
|
[] |
no_license
|
//
// RankingHeader.swift
// Vridge_Pages
//
// Created by Kang Mingu on 2020/10/09.
//
import UIKit
class RankingHeader: UIView {
// MARK: - Properties
var viewModel = RankingViewModel()
lazy var profileImage2 = viewModel.profileImage2
lazy var profileImage1 = viewModel.profileImage1View
lazy var profileImage3 = viewModel.profileImage3
lazy var username2 = viewModel.username2
lazy var username1 = viewModel.username1
lazy var username3 = viewModel.username3
lazy var type2 = viewModel.type2
lazy var type1 = viewModel.type1
lazy var type3 = viewModel.type3
lazy var point2 = viewModel.point2
lazy var point1 = viewModel.point1
lazy var point3 = viewModel.point3
lazy var saladImage2 = viewModel.pointImage2
lazy var saladImage1 = viewModel.pointImage1
lazy var saladImage3 = viewModel.pointImage3
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
configureUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Selectors
// MARK: - Helpers
func configureUI() {
let imageWithPoint2 = UIStackView(arrangedSubviews: [saladImage2, point2])
imageWithPoint2.spacing = 0
imageWithPoint2.alignment = .center
let imageWithPoint1 = UIStackView(arrangedSubviews: [saladImage1, point1])
imageWithPoint1.spacing = 0
imageWithPoint1.alignment = .center
let imageWithPoint3 = UIStackView(arrangedSubviews: [saladImage3, point3])
imageWithPoint3.spacing = 0
imageWithPoint3.alignment = .center
let userStack2 = UIStackView(arrangedSubviews: [profileImage2, username2,
type2, imageWithPoint2])
userStack2.axis = .vertical
userStack2.setCustomSpacing(14, after: profileImage2)
userStack2.setCustomSpacing(3, after: username2)
userStack2.setCustomSpacing(0, after: type2)
userStack2.alignment = .center
let userStack1 = UIStackView(arrangedSubviews: [profileImage1, username1,
type1, imageWithPoint1])
userStack1.axis = .vertical
userStack1.setCustomSpacing(14, after: profileImage1)
userStack1.setCustomSpacing(3, after: username1)
userStack1.setCustomSpacing(0, after: type1)
userStack1.alignment = .center
let userStack3 = UIStackView(arrangedSubviews: [profileImage3, username3,
type3, imageWithPoint3])
userStack3.axis = .vertical
userStack3.setCustomSpacing(14, after: profileImage3)
userStack3.setCustomSpacing(3, after: username3)
userStack3.setCustomSpacing(0, after: type3)
userStack3.alignment = .center
let stack = UIStackView(arrangedSubviews: [userStack2, userStack1, userStack3])
stack.axis = .horizontal
stack.spacing = 30
stack.alignment = .bottom
addSubview(stack)
stack.centerX(inView: self, topAnchor: topAnchor, paddingTop: 30)
}
}
| true
|
20f7dc9587b3424b0c7ec192353517f2f0137b87
|
Swift
|
ahmedmohamedeid98/DN-Wallet
|
/DN-Wallet/Custom View/DNTextView/DNTextView.swift
|
UTF-8
| 865
| 2.671875
| 3
|
[] |
no_license
|
//
// DNTextView.swift
// DN-Wallet
//
// Created by Mac OS on 6/23/20.
// Copyright © 2020 DN. All rights reserved.
//
import UIKit
class DNTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
init(text: String, alignment: NSTextAlignment, fontSize: CGFloat, editable: Bool = false) {
super.init(frame: .zero, textContainer: nil)
self.text = text
self.textAlignment = alignment
self.font = UIFont.systemFont(ofSize: fontSize)
configure()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configure() {
textColor = .secondaryLabel
backgroundColor = .clear
}
}
| true
|
7ad1f1e3e0ba8a789c36db387433e6f9465046c7
|
Swift
|
Purchasely/Purchasely-iOS
|
/Example/Purchasely/ViewController.swift
|
UTF-8
| 1,668
| 2.53125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Purchasely
//
// Created by jfgrang on 12/27/2019.
// Copyright (c) 2019 jfgrang. All rights reserved.
//
import UIKit
import Purchasely
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NotificationCenter.default.addObserver(self, selector: #selector(reloadContent(_:)), name: .ply_purchasedSubscription, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// The SDK can now pop screens over
Purchasely.isReadyToPurchase(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
@IBAction func mySubscriptions(_ sender: Any) {
if let ctrl = Purchasely.subscriptionsController() {
present(ctrl, animated: true, completion: nil)
}
}
@IBAction func purchase(_ sender: Any) {
if let ctrl = Purchasely.presentationController(with: "CAROUSEL") {
present(ctrl, animated: true, completion: nil)
}
}
@IBAction func purchaseAsync(_ sender: Any) {
Purchasely.fetchPresentation(with:"CAROUSEL", fetchCompletion: { [weak self] presentation, error in
guard let `self` = self else { return }
if let ctrl = presentation?.controller {
self.present(ctrl, animated: true, completion: nil)
}
}, completion: nil)
}
@objc func reloadContent(_ notification: Notification) {
// Reload content when purchased
}
}
| true
|
b1d3cee26f104f92ad413150f84042d63a7a0486
|
Swift
|
katsumoto1019/Swift_ImagePost_Comment_PAO
|
/Pao/Controls/DeselectableSegmentedControl.swift
|
UTF-8
| 835
| 2.75
| 3
|
[] |
no_license
|
//
// DeselectableSegmentedControl.swift
// Pao
//
// Created by Exelia Technologies on 06/07/2018.
// Copyright © 2018 Exelia. All rights reserved.
//
import Foundation
import UIKit
// REF: https://stackoverflow.com/questions/17652773/how-to-deselect-a-segment-in-segmented-control-button-permanently-till-its-click
class DeselectableSegmentedControl: UISegmentedControl {
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let previousIndex = selectedSegmentIndex
super.touchesEnded(touches, with: event)
if previousIndex == selectedSegmentIndex {
let touchLocation = touches.first!.location(in: self)
if bounds.contains(touchLocation) {
sendActions(for: .touchUpInside)
}
}
}
}
| true
|
cd492edf3177c948926064fd3d88c61bbe26fc36
|
Swift
|
markk628/SeatGeekAPI
|
/SeatGeekAPI/View/HomeEventsTableCell.swift
|
UTF-8
| 6,618
| 2.640625
| 3
|
[] |
no_license
|
//
// HomeEventsTableCell.swift
// SeatGeekAPI
//
// Created by Mark Kim on 2/11/21.
//
import UIKit
import Kingfisher
class HomeEventsTableCell: UITableViewCell {
//MARK: Properties
static var identifier: String = "HomeEventsCell"
var favoriteEvents: [String] = UserDefaults.standard.stringArray(forKey: "Favorites") ?? [String]()
var details: Event? {
didSet {
guard let details = self.details else { return }
let imageUrl = URL(string: details.performers.first!.image)
eventImageView.kf.setImage(with: imageUrl)
titleLabel.text = details.short_title
locationLabel.text = "\(details.venue.city), \(details.venue.state)"
let splitDateAndTime = details.datetime_utc.components(separatedBy: "T")
dateLabel.text = AppService.formatDate(date: splitDateAndTime.first!)
timeLabel.text = AppService.formatTime(time: splitDateAndTime.last!)
}
}
//MARK: Views
private let eventImageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 10
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
private let titleAndDescriptionStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 20, weight: .heavy)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let locationDateTimeStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private let locationLabel: UILabel = {
let label = UILabel()
label.textColor = .lightGray
label.font = UIFont.systemFont(ofSize: 15, weight: .light)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let dateAndTimeStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private let dateLabel: UILabel = {
let label = UILabel()
label.textColor = .lightGray
label.font = UIFont.systemFont(ofSize: 15, weight: .light)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let timeLabel: UILabel = {
let label = UILabel()
label.textColor = .lightGray
label.font = UIFont.systemFont(ofSize: 15, weight: .light)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var favoriteButtonImageView: UIImageView = {
var imageView = UIImageView()
imageView.image = UIImage(systemName: "heart.fill")!
imageView.isHidden = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.clipsToBounds = true
setupViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Methods
private func setupViews() {
selectionStyle = .gray
self.addSubview(eventImageView)
self.addSubview(favoriteButtonImageView)
self.addSubview(titleAndDescriptionStackView)
[titleLabel, locationDateTimeStackView].forEach {
titleAndDescriptionStackView.addArrangedSubview($0)
}
[locationLabel, dateAndTimeStackView].forEach {
locationDateTimeStackView.addArrangedSubview($0)
}
[dateLabel, timeLabel].forEach {
dateAndTimeStackView.addArrangedSubview($0)
}
NSLayoutConstraint.activate([
eventImageView.heightAnchor.constraint(equalToConstant: 80),
eventImageView.widthAnchor.constraint(equalTo: eventImageView.heightAnchor),
eventImageView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 20),
eventImageView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 20),
favoriteButtonImageView.heightAnchor.constraint(equalToConstant: 50),
favoriteButtonImageView.widthAnchor.constraint(equalTo: favoriteButtonImageView.heightAnchor),
favoriteButtonImageView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 10),
favoriteButtonImageView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 10),
titleAndDescriptionStackView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 20),
titleAndDescriptionStackView.leadingAnchor.constraint(equalTo: self.eventImageView.trailingAnchor, constant: 20),
titleAndDescriptionStackView.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: -20),
titleAndDescriptionStackView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: -20),
titleLabel.heightAnchor.constraint(equalTo: titleAndDescriptionStackView.heightAnchor, multiplier: 0.5),
locationDateTimeStackView.heightAnchor.constraint(equalTo: titleAndDescriptionStackView.heightAnchor, multiplier: 0.5),
locationLabel.heightAnchor.constraint(equalTo: locationDateTimeStackView.heightAnchor, multiplier: 0.5),
dateAndTimeStackView.heightAnchor.constraint(equalTo: locationDateTimeStackView.heightAnchor, multiplier: 0.5),
dateLabel.heightAnchor.constraint(equalTo: dateAndTimeStackView.heightAnchor, multiplier: 0.5),
timeLabel.heightAnchor.constraint(equalTo: dateAndTimeStackView.heightAnchor, multiplier: 0.5)
])
}
}
| true
|
222d2eea30b5db9253a8bd24815030af43ade6cb
|
Swift
|
luanhenriq10/TesteiOS
|
/SantanderExample/Models/Contact/ContactForm.swift
|
UTF-8
| 1,598
| 3.078125
| 3
|
[] |
no_license
|
//
// ContactForm.swift
// SantanderExample
//
// Created by Luan Henrique Damasceno Costa on 13/05/2018.
// Copyright © 2018 Luan Henrique Damasceno Costa. All rights reserved.
//
import UIKit
struct ContactForm: Codable {
enum FormType: Int, Codable {
case field = 1
case text = 2
case image = 3
case checkbox = 4
case send = 5
}
enum TypeField: Int, Codable {
case text = 1
case telNumber = 2
case email = 3
}
var id: Int?
var type: FormType?
var message: String?
var typefield: TypeField?
var hidden: Bool?
var topSpacing: Float?
var show: Int?
var required: Bool?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(Int.self, forKey: .id)
type = try values.decode(FormType.self, forKey: .type)
message = try values.decode(String.self, forKey: .message)
hidden = try values.decode(Bool.self, forKey: .hidden)
topSpacing = try values.decode(Float.self, forKey: .topSpacing)
required = try values.decode(Bool.self, forKey: .required)
// For some reason, the type text field are returning a string instead of a int.
do {
let field = try values.decode(Int.self, forKey: .typefield)
typefield = TypeField(rawValue: field)
} catch {
do {
let string = try values.decode(String.self, forKey: .typefield)
if string == "telnumber" {
typefield = TypeField.telNumber
} else {
typefield = TypeField.text
}
} catch {
typefield = nil
}
}
}
}
| true
|
7026e1e0ebc500a7c2a59c6327a82ad68a5a42b9
|
Swift
|
Ahmed-Masoud/maze-game
|
/Bullet.swift
|
UTF-8
| 920
| 2.734375
| 3
|
[] |
no_license
|
//
// Bullet.swift
// maze
//
// Created by Ahmed masoud on 12/1/15.
// Copyright © 2015 Ahmed masoud. All rights reserved.
//
import Foundation
import SpriteKit
class Bullet:SKSpriteNode{
var bullet : SKSpriteNode
init(){
bullet = SKSpriteNode(imageNamed: "bullet")
let size1 = CGSize(width: 32, height: 44)
super.init(texture: nil, color: UIColor.blackColor(), size: size1)
//var bullet : SKSpriteNode
bullet.position = CGPoint(x: 96, y: 672)
bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.size.width / 2)
bullet.physicsBody!.allowsRotation = false
bullet.physicsBody!.categoryBitMask = CollisionTypes.bullet.rawValue
bullet.physicsBody!.contactTestBitMask = CollisionTypes.Player.rawValue
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
7e753abebdc957b9a65ccf31125d1fb27607c008
|
Swift
|
UmarA88/Y3-iOS-Food-Hygiene-App
|
/FoodHygieneApp/BusinessDetailsViewController.swift
|
UTF-8
| 3,383
| 2.734375
| 3
|
[] |
no_license
|
//
// BusinessDetailsViewController.swift
// FoodHygieneApp
//
// Created by Nathan Kiernan on 22/03/2018.
// Copyright © 2018 Nathan Kiernan. All rights reserved.
//
import UIKit
import MapKit
class BusinessDetailsViewController: UIViewController, MKMapViewDelegate {
// information passed from ViewController via segue
var latitude: Double!
var longitude: Double!
var business: Business!
// outlets corresponding to selected business's details
@IBOutlet weak var businessNameLabel: UILabel!
@IBOutlet weak var addressLine1Label: UILabel!
@IBOutlet weak var addressLine2Label: UILabel!
@IBOutlet weak var addressLineLabel3: UILabel!
@IBOutlet weak var postcodeLabel: UILabel!
@IBOutlet weak var ratingDateLabel: UILabel!
@IBOutlet weak var ratingValueImage: UIImageView!
@IBOutlet weak var businessLocationMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// display business details using respective outlets
businessNameLabel.text = business!.BusinessName
addressLine1Label.text = business!.AddressLine1
addressLine2Label.text = business!.AddressLine2
addressLineLabel3.text = business!.AddressLine3
postcodeLabel.text = business!.PostCode
ratingDateLabel.text = "Rating from \(business!.RatingDate):"
ratingValueImage.image = UIImage.init(named: "fhrs_\(business!.RatingValue)_en-gb.jpg")
businessLocationMap.delegate = self
businessLocationMap.showsUserLocation = true
// setup map zoom and focus
let span :MKCoordinateSpan = MKCoordinateSpanMake(0.003, 0.003)
let location :CLLocationCoordinate2D = CLLocationCoordinate2DMake(Double(business!.Latitude)!, Double(business!.Longitude)!)
let region :MKCoordinateRegion = MKCoordinateRegionMake(location, span)
// use region to set map
businessLocationMap.setRegion(region, animated: true)
businessLocationMap.mapType = .standard
// set up annotation to add to map
let userAnnotation = CustomPin()
userAnnotation.coordinate = location
businessLocationMap.addAnnotation(userAnnotation)
let annotation = CustomPin()
annotation.image = UIImage(named: "pin\(business.RatingValue)")
annotation.coordinate = CLLocationCoordinate2DMake(Double(business!.Latitude)!, Double(business!.Longitude)!)
annotation.title = business!.BusinessName
businessLocationMap.addAnnotation(annotation)
}
// add annotation to map view
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !annotation.isKind(of: MKUserLocation.self) else { return nil }
let annotationIdentifier = "AnnotationIdentifier"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView!.canShowCallout = true
}
else {
annotationView!.annotation = annotation
}
let customPointAnnotation = annotation as! CustomPin
annotationView!.image = customPointAnnotation.image
return annotationView
}
}
| true
|
791bc4f7bf3d63c161106121f6e162869e2f36aa
|
Swift
|
podkriznik/KINO
|
/KinoiPad/KinoiPad/Termin.swift
|
UTF-8
| 423
| 2.578125
| 3
|
[] |
no_license
|
//
// Termin.swift
// KinoiPad
//
// Created by Nace Selišnik on 04/05/2019.
// Copyright © 2019 Nace Selisnik. All rights reserved.
//
import Foundation
class Termin {
var id_termin:Int
var cas:Date
var idfilm:Int
init(id_termin:Int, cas:Date, idfilm:Int) {
self.id_termin = id_termin
self.cas = cas
self.idfilm = idfilm
}
func toJSON() -> String {
return ""
}
}
| true
|
3571f5d2bfb671e17b32dae4cd357b79dc30a77b
|
Swift
|
xReee/WWDC2020
|
/AI4Games by Renata.playgroundbook/Contents/UserModules/System.playgroundmodule/Sources/HUDEndGame.swift
|
UTF-8
| 1,595
| 2.65625
| 3
|
[] |
no_license
|
import UIKit
import PlaygroundSupport
public class HUDEndGame: HUDView {
override func buildView() {
addSubview(titleLabel)
addSubview(nextButton)
}
override func setupConstraints() {
configureAutomask()
NSLayoutConstraint.activate([
titleLabel.fix(in: self,to: .top, with: 20),
titleLabel.fix(in: self, to: .centerX, with: 0),
nextButton.fix(in: titleLabel, to: .top, with: 45),
nextButton.fix(in: self, to: .right, with: -25),
nextButton.fix(in: self, to: .left, with: 25),
nextButton.fix(in: self, to: .bottom, with: -25),
])
nextButton.addTarget(self, action: #selector(nextPage), for: .touchUpInside)
}
@objc func nextPage() {
PlaygroundPage.current.navigateTo(page: .next)
}
public func setText(_ text: String) {
titleLabel.text = text
}
var nextButton: UIButton = {
let view = UIButton(frame: .zero)
let imageConfig = UIImage.SymbolConfiguration(pointSize: 50, weight: .black, scale: .large)
let img = UIImage.init(systemName: "chevron.right.2", withConfiguration: imageConfig)
view.setImage(img, for: .normal)
view.tintColor = .label
return view
}()
var titleLabel: UILabel = {
let label = UILabel(frame: .zero)
label.font = .systemFont(ofSize: 20)
label.textColor = .label
label.numberOfLines = 0
label.textAlignment = .center
label.text = "Time's up!\n Let's go to next page."
return label
}()
}
| true
|
750f86ece1e3928c4c346aa4d24ff36b32954fb0
|
Swift
|
gracenamucuo/Study
|
/T_Animations/T_Animations/ViewController.swift
|
UTF-8
| 2,281
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// T_Animations
//
// Created by dyp on 2019/7/3.
// Copyright © 2019 dyp. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var items:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
items = ["AutoLayoutAnimationsController","KeyboardAnimationController"]
}
}
extension ViewController:UITableViewDataSource,UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var vc = UIViewController.init()
switch indexPath.row {
case 0:
vc = AutoLayoutAnimationsController()
break
case 1:
vc = KeyboardAnimationController()
break
default: break
}
navigationController?.pushViewController(vc, animated: true)
}
}
//extension NSObject {
// // create a static method to get a swift class for a string name
// class func swiftClassFromString(className: String) -> AnyClass! {
// // get the project name
// if var appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String? {
// // generate the full name of your class (take a look into your "YourProject-swift.h" file)
//
// let classStringName = "_TtC\(appName.)\(String(describing: appName))\(countElements(className))\(className)"
// // return the class!
// return NSClassFromString(classStringName)
// }
// return nil;
// }
//}
//let clsStr = items[indexPath.row]
//
//let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String
//let vcName = items[indexPath.row]
//
//let cls = NSClassFromString(clsName! + "." + vcName) as? UIViewController.Type
//
//print(cls)
| true
|
401b1078352c887de96d27a488e55f8468949b04
|
Swift
|
SadNews/TestApp
|
/TestApp/MapView/Extensions+GoogleMaps.swift
|
UTF-8
| 3,080
| 2.703125
| 3
|
[] |
no_license
|
//
// Extensions+GoogleMaps.swift
// TestApp
//
// Created by Андрей Ушаков on 04.08.2020.
// Copyright © 2020 Андрей Ушаков. All rights reserved.
//
import Foundation
import GoogleMaps
import GooglePlaces
// MARK: - CLLocationManagerDelegate
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else {return}
locationManager.startUpdatingLocation()
mapView.isMyLocationEnabled = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {return}
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
// MARK: - GMSMapViewDelegate
extension MapViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
reverseGeocodeCoordinate(position.target)
}
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
zoom = mapView.camera.zoom
}
}
extension MapViewController: GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(String(describing: place.name))")
dismiss(animated: true, completion: nil)
self.mapView.clear()
self.searchAdress.text = place.name
let cord2D = CLLocationCoordinate2D(latitude: (place.coordinate.latitude), longitude: (place.coordinate.longitude))
marker.position = cord2D
marker.title = "Location"
marker.snippet = place.name
marker.map = self.mapView
self.mapView.camera = GMSCameraPosition.camera(withTarget: cord2D, zoom: 15)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print(error)
}
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
}
extension MapViewController {
private func reverseGeocodeCoordinate(_ coordinate: CLLocationCoordinate2D) {
let geocoder = GMSGeocoder()
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
guard let address = response?.firstResult(), let lines = address.lines else {
return
}
self.addressLabel.text = lines.joined(separator: "\n")
let labelHeight = self.addressLabel.intrinsicContentSize.height
self.mapView.padding = UIEdgeInsets(top: self.view.safeAreaInsets.top, left: 0,
bottom: labelHeight, right: 0)
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
}
}
}
| true
|
c02941ab649505e43d1d8320197dc92fe7de6ae1
|
Swift
|
andreipopa1002/clean-code---multiple-dependencies
|
/Headlines/DataStore/ArticlesDataStore.swift
|
UTF-8
| 1,798
| 2.984375
| 3
|
[] |
no_license
|
//
// ArticleDataStore.swift
// Headlines
//
// Created by Andrei Popa on 15/07/2017.
// Copyright © 2017 Example. All rights reserved.
//
import Foundation
class ArticlesDataStore: ArticlesDataStoreInterface {
var articles: [Article] {
didSet {
let favoriteArticles = persistenceStore.articles()
articles = articles.map({
var article = $0
article.isFavorite = false
if let _ = favoriteArticles.first(where: { $0.id == article.id }) {
article.isFavorite = true
}
return article
})
}
}
private let service: ArticleServiceInterface
private let persistenceStore: PersistenceManagerInterface
init(service: ArticleServiceInterface = ArticleService(),
persistenceStore: PersistenceManagerInterface = PersistenceManager()) {
self.service = service
self.persistenceStore = persistenceStore
self.articles = [Article]()
}
func fetchArticles(completion: @escaping ((ArticlesDataStoreResponse) -> Void)) {
service.fetchArticles(completion: completion)
}
func addToFavourites(article: Article) -> Bool {
persistenceStore.save(article: article)
refreshArticles()
return true
}
func removeFromFavorites(article: Article) -> Bool {
persistenceStore.delete(article: article)
refreshArticles()
return true
}
func article(with id: String) -> Article? {
return articles.first(where: {$0.id == id})
}
}
extension ArticlesDataStore {
//MARK: private methods
fileprivate func refreshArticles() {
let currentArticles = articles
articles = currentArticles
}
}
| true
|
2f63c0722208f47edb91d9e85ee432ef0d6fcc66
|
Swift
|
Blissfulman/Course2Week5Task2
|
/Course2Week5Task2/Code/ViewController2.swift
|
UTF-8
| 718
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController2.swift
// Course2Week5Task2
//
// Created by User on 18.07.2020.
// Copyright © 2020 Evgeny. All rights reserved.
//
import UIKit
class ViewController2: UIViewController {
@IBAction func unwindToViewController2(segue: UIStoryboardSegue) { }
@IBAction func pressToViewController4Button(_ sender: UIButton) {
present(ViewController4(), animated: true, completion: nil)
// show(ViewController4(), sender: nil)
}
@IBAction func pressAddChildViewControllerButton(_ sender: UIButton) {
let viewController5 = ViewController5()
addChild(viewController5)
view.addSubview(viewController5.view)
didMove(toParent: self)
}
}
| true
|
819c760401dbc75b04346a8af9efd804c3a54845
|
Swift
|
p1atdev/memo
|
/SuperMemo/ViewController.swift
|
UTF-8
| 4,336
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// SuperMemo
//
// Created by 周廷叡 on 2020/08/19.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class ViewController: UIViewController, UITextFieldDelegate {
//MARK: outlet
//メール
@IBOutlet weak var emailTextView: UITextField!
//パスワード
@IBOutlet weak var passwordTextView: UITextField!
//タイトル
@IBOutlet weak var titleLabel: UILabel!
var ref: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
emailTextView.delegate = self
passwordTextView.delegate = self
//FirebaseApp.configure()
if FirebaseAuth.Auth.auth().currentUser != nil {
//ログイン済みの時
//遷移
self.performSegue(withIdentifier: "toMemos", sender: nil) //画面遷移
} else {
//ログインしていない時
}
ref = Database.database().reference().child("users")
}
override func viewWillAppear(_ animated: Bool) {
//リスナーの削除
ref.removeAllObservers()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
//遷移の時に値を渡す
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMemos" {
let nextVC = segue.destination as! MemosViewController
print("USER ID")
print((FirebaseAuth.Auth.auth().currentUser?.uid)!)
nextVC.uid = (FirebaseAuth.Auth.auth().currentUser?.uid)! //ここで値渡し
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
//アカウント作成
func createAccount(email: String, password: String){
//これでアカウントのログイン
FirebaseAuth.Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
//guard let strongSelf = self else { return }
print("USER ID")
print((authResult?.user.uid)!)
self.performSegue(withIdentifier: "toMemos", sender: nil) //画面遷移
}
}
//ログイン
func loginAuth(email: String, password: String){
FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in
guard let strongSelf = self else { return }
print(authResult?.user.uid)
self!.performSegue(withIdentifier: "toMemos", sender: nil) //画面遷移
}
}
//TODO: 匿名ログイン
func anonymousLogin(){
FirebaseAuth.Auth.auth().signInAnonymously() { (authResult, error) in
self.performSegue(withIdentifier: "toMemos", sender: nil) //画面遷移
}
}
//キーボードを閉じれる様に
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// キーボードを閉じる
textField.resignFirstResponder()
return true
}
@IBAction func makeAccount(_ sender: Any) {
let email = emailTextView.text
let password = passwordTextView.text
if email != nil && password != nil{
createAccount(email: email!, password: password!)
}
}
@IBAction func login(_ sender: Any) {
let email = emailTextView.text
let password = passwordTextView.text
if email != "" && password != ""{
loginAuth(email: email!, password: password!)
}else{
print("ERROR")
}
print("login button")
}
//匿名認証
@IBAction func skipCreate(_ sender: Any) {
anonymousLogin()
}
}
| true
|
04cfcc414ca79cd675d47fec62d62b7368ac8b6b
|
Swift
|
angel08012000/TFBOYS_app
|
/TFBOYS/songList.swift
|
UTF-8
| 10,505
| 2.96875
| 3
|
[] |
no_license
|
//
// songList.swift
// TFBOYS
//
// Created by 慈慈 on 2020/10/19.
//
import SwiftUI
import AVFoundation
struct song{
var name: String
var singer: String
var pic: String
}
struct songRow: View{
@State private var show = false
let player = AVPlayer()
let mySong: song
var body: some View{
HStack(){
Image("\(mySong.pic)")
.resizable()
.scaledToFit()
.frame(width: 80, height: 80)
VStack(alignment: .leading, spacing: 10){
Text("\(mySong.name)")
.font(.system(.headline, design: .rounded))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.foregroundColor(.gray)
Text("\(mySong.singer)")
.font(.system(.caption, design: .rounded))
.foregroundColor(.gray)
}
Spacer()
if mySong.name=="Heart" || mySong.name=="愛出發" || mySong.name=="夢想啟航" || mySong.name=="青春修煉手冊" || mySong.name=="大夢想家" || mySong.name=="我們的時光" || mySong.name=="和你在一起"{
Button(action:{
let fileUrl = Bundle.main.url(forResource: "\(mySong.name)", withExtension: "mp3")!
let playerItem = AVPlayerItem(url: fileUrl)
if player.currentItem==nil{
player.replaceCurrentItem(with: playerItem)
}
player.volume = 0.1
if show == false{
show = true
player.play()
}
else{
show = false
player.pause()
}
}){
if show == false{
Image(systemName: "play")
}
else{
Image(systemName: "pause")
}
}
}
}
}
}
struct songPhoto: View{
let photo = ["Heart", "青春修煉手冊", "大夢想家", "我們的時光", "和你在一起"]
// let target=[Heart(), HandBook(), Dreamer(), Time(), Together()]
var body: some View{
NavigationView{
VStack{
ScrollView(.horizontal) {
let rows = [GridItem()]
LazyHGrid(rows: rows) {
ForEach(photo.indices) { (index) in
VStack{
if index==0{
NavigationLink(destination: Heart()){
Image(photo[index])
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.clipped()
}
}
else if index==1{
NavigationLink(destination: HandBook()){
Image(photo[index])
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.clipped()
}
}
else if index==2{
NavigationLink(destination: Dreamer()){
Image(photo[index])
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.clipped()
}
}
else if index==3{
NavigationLink(destination: Time()){
Image(photo[index])
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.clipped()
}
}
else{
Image(photo[index])
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.clipped()
}
if photo[index]=="和你在一起"{
Text("其他")
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.foregroundColor(.gray)
}
else{
Text(photo[index])
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.foregroundColor(.gray)
}
}
}
}
}
.navigationTitle("專輯主打歌")
.fixedSize(horizontal: false, vertical: true)
}
}
}
}
struct mySongList: View{
let mini_one = [
song(name: "Heart", singer: "TFBOYS", pic: "Heart"),
song(name: "愛出發", singer: "TFBOYS", pic: "愛出發"),
song(name: "夢想啟航", singer: "TFBOYS", pic: "夢想啟航")
]
let mini_two = [
song(name: "青春修煉手冊", singer: "TFBOYS", pic: "青春修煉手冊"),
song(name: "幸運符號", singer: "TFBOYS", pic: "幸運符號"),
song(name: "快樂環島", singer: "TFBOYS", pic: "快樂環島"),
song(name: "信仰之名", singer: "TFBOYS", pic: "信仰之名")
]
let mini_three = [
song(name: "大夢想家", singer: "TFBOYS", pic: "大夢想家"),
song(name: "寵愛", singer: "TFBOYS", pic: "寵愛"),
song(name: "樣Young", singer: "TFBOYS", pic: "樣Young"),
song(name: "剩下的盛夏", singer: "TFBOYS", pic: "剩下的盛夏"),
song(name: "少年說", singer: "TFBOYS", pic: "少年說"),
song(name: "Love With You", singer: "TFBOYS", pic: "Love With You")
]
let ep1 = [
song(name: "我們的時光", singer: "TFBOYS", pic: "我們的時光"),
song(name: "躲貓貓", singer: "TFBOYS", pic: "躲貓貓"),
song(name: "不完美小孩", singer: "TFBOYS", pic: "不完美小孩"),
song(name: "是你", singer: "TFBOYS", pic: "是你"),
song(name: "小精靈", singer: "TFBOYS", pic: "小精靈"),
song(name: "真心話太冒險", singer: "TFBOYS", pic: "真心話太冒險"),
song(name: "螢火", singer: "TFBOYS", pic: "螢火")
]
let others = [
song(name: "魔法城堡", singer: "TFBOYS", pic: "魔法城堡"),
song(name: "未來的進擊", singer: "TFBOYS", pic: "未來的進擊"),
song(name: "不息之河", singer: "TFBOYS", pic: "不息之河"),
song(name: "加油!Amigo!", singer: "TFBOYS", pic: "加油!Amigo!"),
song(name: "同一秒快樂", singer: "TFBOYS", pic: "同一秒快樂"),
song(name: "喜歡你", singer: "TFBOYS", pic: "喜歡你"),
song(name: "最好的那年", singer: "TFBOYS", pic: "最好的那年"),
song(name: "第一次告白", singer: "TFBOYS", pic: "第一次告白"),
song(name: "我的朋友", singer: "TFBOYS", pic: "我的朋友"),
song(name: "和你在一起", singer: "TFBOYS", pic: "和你在一起"),
song(name: "燈火", singer: "TFBOYS", pic: "燈火")
]
var body: some View{
NavigationView{
VStack{
songPhoto()
List{
Section(header: Text("迷你專輯1 - Heart 夢·出發") ){
ForEach(mini_one.indices){(item) in
songRow(mySong: mini_one[item])
}
}
Section(header: Text("迷你專輯2 - 青春修煉手冊") ){
ForEach(mini_two.indices){(item) in
songRow(mySong: mini_two[item])
}
}
Section(header: Text("迷你專輯3 - 大夢想家") ){
ForEach(mini_three.indices){(item) in
songRow(mySong: mini_three[item])
}
}
Section(header: Text("正規專輯1 - 我們的時光") ){
ForEach(ep1.indices){(item) in
songRow(mySong: ep1[item])
}
}
Section(header: Text("其他") ){
ForEach(others.indices){(item) in
songRow(mySong: others[item])
}
}
}
.toolbar(content: {
ToolbarItem(placement: .principal) {
Text("TFBOYS歌單")
.font(.system(.largeTitle, design: .rounded))
.fontWeight(.bold)
.foregroundColor(.gray)
}
})
.edgesIgnoringSafeArea(.all)
.navigationBarTitleDisplayMode(.inline)
}
}
}
}
struct songList: View {
var body: some View {
mySongList()
}
}
struct songList_Previews: PreviewProvider {
static var previews: some View {
Group {
songList()
songList()
.preferredColorScheme(.dark)
}
}
}
| true
|
76dadc01f276d89aea2da4d4cf05c33e5bfa98c6
|
Swift
|
giftapp/gift-ios
|
/gift/Controllers/VenueSearch/VenueSearchResultsViewController.swift
|
UTF-8
| 4,419
| 2.625
| 3
|
[] |
no_license
|
//
// Created by Matan Lachmish on 21/12/2016.
// Copyright (c) 2016 GiftApp. All rights reserved.
//
import Foundation
import UIKit
class VenueSearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//Injections
private var appRoute: AppRoute
private var createCoupleViewController: CreateCoupleViewController
//Views
private var venueSearchResultsView: VenueSearchResultsView!
//Public Properties
public var searchResultVenues: Array<Venue> = [] {
didSet {
venueSearchResultsView.update()
}
}
public var currentLocation: (lat: Double, lng: Double)! {
didSet {
venueSearchResultsView.update()
}
}
//-------------------------------------------------------------------------------------------
// MARK: - Initialization & Destruction
//-------------------------------------------------------------------------------------------
internal dynamic init(appRoute: AppRoute,
createCoupleViewController: CreateCoupleViewController) {
self.appRoute = appRoute
self.createCoupleViewController = createCoupleViewController
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//-------------------------------------------------------------------------------------------
// MARK: - Lifecycle
//-------------------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
self.addCustomViews()
}
private func addCustomViews() {
if venueSearchResultsView == nil {
venueSearchResultsView = VenueSearchResultsView()
venueSearchResultsView.tableViewDataSource = self
venueSearchResultsView.tableViewDelegate = self
self.view = venueSearchResultsView
}
}
//-------------------------------------------------------------------------------------------
// MARK: - Public
//-------------------------------------------------------------------------------------------
func clearSearchResults() {
searchResultVenues.removeAll()
shouldPresentEmptyPlaceholder(shouldPresent: false)
}
func activityAnimation(shouldAnimate: Bool) {
venueSearchResultsView.activityAnimation(shouldAnimate: shouldAnimate)
}
func shouldPresentEmptyPlaceholder(shouldPresent: Bool) {
venueSearchResultsView.shouldPresentEmptyPlaceholder(shouldPresent: shouldPresent)
}
//-------------------------------------------------------------------------------------------
// MARK: - UITableViewDataSource
//-------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResultVenues.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:VenueCell = tableView.dequeueReusableCell(withIdentifier: VenueCellConstants.reuseIdentifier, for: indexPath) as! VenueCell
let venue = searchResultVenues[indexPath.item]
cell.venueName = venue.name
cell.venueAddress = venue.address
cell.venueImageUrl = venue.imageUrl
cell.distanceAmount = LocationUtils.distanceBetween(lat1: currentLocation.lat, lng1: currentLocation.lng, lat2: (venue.latitude)!, lng2: (venue.longitude)!)
cell.distanceUnit = DistanceUnit.kiloMeter
return cell
}
//-------------------------------------------------------------------------------------------
// MARK: - UITableViewDelegate
//-------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return VenueCellConstants.height
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
Logger.debug("User tapped on venue")
let venue = searchResultVenues[indexPath.item];
createCoupleViewController.selectedVenue = venue
appRoute.pushViewController(controller: createCoupleViewController, animated: true)
}
}
| true
|
8c22ca69449e323b34f82613883225df875f2d30
|
Swift
|
villajohn/RappiTest
|
/SplashViewController.swift
|
UTF-8
| 1,409
| 2.65625
| 3
|
[] |
no_license
|
//
// SplashViewController.swift
// RappiTest
//
// Created by Jhon Villalobos on 9/24/16.
// Copyright © 2016 Jhon Villalobos. All rights reserved.
//
import UIKit
class SplashViewController: UIViewController {
var puslsing: Bool = false
var backgroundGridView : BackgroundGridView!
public init(fileName: String) {
super.init(nibName: nil, bundle: nil)
backgroundGridView = BackgroundGridView(FileName: fileName)
view.addSubview(backgroundGridView)
backgroundGridView.frame = view.bounds
backgroundGridView.startAnimating()
/*
let imageContainer = UIImageView()
imageContainer.image = UIImage(named: "logo1")
imageContainer.frame = CGRect(x: 0, y:0, width: 200, height: 50)
imageContainer.layer.position = view.center
imageContainer.alpha = 0.0
//imageContainer.center.x -= view.bounds.width //Si quieres colocar el logo outside the view
view.addSubview(imageContainer)
UIView.animate(withDuration: 1.5, delay: 0.4, options: .curveEaseOut, animations: {
//imageContainer.center.x += self.view.bounds.width //si quieres mostrarlo con entrada
imageContainer.alpha = 1.0
})
*/
}
required public init(coder aDecoder: NSCoder) {
fatalError(NSLocalizedString("error_initcoder", comment: ""))
}
}
| true
|
9ad6e423d32197531b5c0a4e0af9a392b329e30f
|
Swift
|
emrdgrmnci/HipoAssignment
|
/HipoAssignment/Utility/Extensions/StaticString.swift
|
UTF-8
| 1,515
| 2.875
| 3
|
[] |
no_license
|
//
// StaticString.swift
// HipoAssignment
//
// Created by Ali Emre Değirmenci on 24.04.2020.
// Copyright © 2020 Ali Emre Degirmenci. All rights reserved.
//
import Foundation
enum LocalizedStrings: String {
case addNewMember = "Add New Member"
case name = "Name:"
case position = "Position:"
case age = "Age:"
case location = "Location:"
case numberOfYearsInHipo = "Number of years in Comp:"
case github = "Github:"
case pleaseEnterYourName = "Please enter your name"
case pleaseEnterYourPosition = "Please enter your position"
case pleaseEnterYourAge = "Please enter your age"
case pleaseEnterYourLocation = "Please enter your location"
case pleaseEnterYourHipoYear = "Please enter how many years you worked in Comp"
case pleaseEnterYourGithubUserName = "Please enter your Github username"
case members = "Members"
case sortMembers = "SORT MEMBERS"
case capitalizedAddNewMember = "ADD NEW MEMBER"
case capitalizedSaved = "SAVED"
case newMemberSavedSuccessfully = "New member saved successfully!"
case newMemberDoesNotSavedSuccessfully = "New member does not saved successfully!"
case capitalizedOk = "OK"
case error = "Error"
case allowedCharacters = "ABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZabcçdefgğhıijklmnoöpqrstuüvwxyz "
case allowedCharactersWithSpecialized = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_!'^+%&/()=?,;:."
}
enum URLString: String {
case urlForGithub = "https://api.github.com/users/"
}
| true
|
e4bbd70ebd6ba7a07c7e3c0d47413d84b6ad2e49
|
Swift
|
Dmitrykarp/iOS---Anekdots-App
|
/Anekdots/ViewController.swift
|
UTF-8
| 3,241
| 2.765625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Anekdots
//
// Created by dmka on 18.04.2020.
// Copyright © 2020 dmka. All rights reserved.
//
import UIKit
var typeJokeId = "1"
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var textView: UITextView!
var typeJoke = ["Анекдот","Рассказ","Стишок","Афоризм","Цитата","Тост","Статус","Анекдот (18+)","Рассказ (18+)","Стишок (18+)","Афоризм (18+)","Цитата (18+)","Тост (18+)","Статус (18+)"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return typeJoke.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var finalRow = 1
if row == 6{
finalRow = 8
}else if row == 7 {
finalRow = 11
}else if row == 8 {
finalRow = 12
}else if row == 9 {
finalRow = 13
}else if row == 10 {
finalRow = 14
}else if row == 11 {
finalRow = 15
}else if row == 12 {
finalRow = 16
}else if row == 13 {
finalRow = 18
}else {
finalRow = row+1
}
typeJokeId = String(finalRow)
//print(typeJokeId)
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return typeJoke[row]
}
@IBOutlet weak var picker: UIPickerView!
@IBAction func pushShareButtonAction(_ sender: Any) {
let activityController = UIActivityViewController(activityItems: [textView.text!], applicationActivities: nil)
present(activityController, animated: true, completion: nil)
}
@IBAction func pushRefreshButtonAction(_ sender: Any) {
getRandomAnekdot2{ (jokeText) in
//test git changes
self.textView.text = jokeText
}
}
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
// Do any additional setup after loading the view.
}
}
func getRandomAnekdot2(block: (_ testAnekdot: String)->Void){
//http://rzhunemogu.ru/RandJSON.aspx?CType=1
if let urlRandomJoke = URL(string: "http:rzhunemogu.ru/RandJSON.aspx?CType=\(typeJokeId)") {
do{
let dataJSON = try String(contentsOf: urlRandomJoke, encoding: String.Encoding.windowsCP1251)
let start = dataJSON.index(dataJSON.startIndex, offsetBy: 12)
let end = dataJSON.index(dataJSON.endIndex, offsetBy: -2)
let range = start..<end
let mySubstring = dataJSON[range] // play
if !mySubstring.isEmpty{
block(mySubstring.replacingOccurrences(of: """, with: "\""))
return
}
}catch{
print(error)
}
}
block("")
}
| true
|
977f2049ad06559068978450aaead399a7c8fd4e
|
Swift
|
hiroaki-hirabayashi/swift6-ToDoApp
|
/Swift5 Todo/Controller/EditViewController.swift
|
UTF-8
| 3,040
| 2.71875
| 3
|
[] |
no_license
|
//
// EditViewController.swift
// Swift5 Todo
//
// Created by 平林宏淳 on 2020/11/18.
// Copyright © 2020 Hiroaki_Hirabayashi. All rights reserved.
//
import UIKit
import RealmSwift
import Combine
protocol EditViewControllerDelegate: class { //一覧画面から委任
func tapEditButton(indexPath: IndexPath)
}
final class EditViewController: UIViewController {
// MARK: - Propertie
var editTodo = Todo()
//一覧画面から来たセル番号
var returnIndexPath = IndexPath()
weak var delegate: EditViewControllerDelegate?
@IBOutlet weak var todoTextField: UITextField!
@IBOutlet weak var todoUpdateButton: UIButton!
private var didChangeCancellable: AnyCancellable? //Combineを使ってNotificationを受け取る
private var didChangeButtonColorCancellable: AnyCancellable?
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
todoTextField.text = editTodo.text
// didChangeCancellable = NotificationCenter.default
// .publisher(for: UITextField.textDidChangeNotification, object: todoTextField)
// .sink(receiveValue: { (notification) in
// if let editText = notification.object as? UITextField {
// if let editTodo = editText.text {
// if editTodo.isEmpty ?? true {
// self.todoUpdateButton.isEnabled = false
// self.todoUpdateButton.backgroundColor = .gray
// } else {
// self.todoUpdateButton.isEnabled = true
// self.todoUpdateButton.backgroundColor = .orange
// }
// }
// }
// })
didChangeCancellable = NotificationCenter.default
.publisher(for: UITextField.textDidChangeNotification, object: todoTextField)
.compactMap { $0.object as? UITextField } //notification.objectがUITextFieldにキャストできるものだけ次に進む
.compactMap { $0.text?.count ?? 1 >= 1 } //上から渡されたTextField.textの文字数が1文字以上か
.assign(to: \.isEnabled, on: todoUpdateButton)
didChangeButtonColorCancellable = NotificationCenter.default
.publisher(for: UITextField.textDidChangeNotification, object: todoTextField)
.compactMap { $0.object as? UITextField }
.compactMap { $0.text?.isEmpty ?? true ? .gray : .systemPurple }
.assign(to: \.backgroundColor, on: todoUpdateButton)
}
// MARK: - function
@IBAction func tapEditButton(_ sender: Any) {
let realm = try! Realm()
try! realm.write {
editTodo.text = todoTextField.text!
}
navigationController?.popViewController(animated: true)
delegate?.tapEditButton(indexPath: returnIndexPath) //一覧画面から渡されたindexPathをそのまま返す
}
}
| true
|
e345df60689a86ed8c27ea0a1d01278e7c95f0a1
|
Swift
|
TomFrank/WeatherApp2
|
/WeatherApp2/Models/UserData.swift
|
UTF-8
| 669
| 2.578125
| 3
|
[] |
no_license
|
//
// Main.swift
// WeatherApp2
//
// Created by ZZJ on 2019/10/13.
// Copyright © 2019 Peking University. All rights reserved.
//
import Foundation
import Combine
final class UserData: ObservableObject {
@Published var weatherManager = WeatherManager()
@Published var currentCityID: String! = "CN101010100" {
willSet {
weatherManager.update(of: newValue)
}
}
var currentCityName: String? {
weatherManager.city.availableCityList.first(where: {$0.cityID == currentCityID})?.location
}
init() {
weatherManager.enableLocationServices()
// weatherManager.timer.fire()
}
}
| true
|
fc080bc83c62316b392238fbd9253754affe9eec
|
Swift
|
heldrida/swiftUIApplicationEntryPoint
|
/EntryPoint/SomethingView.swift
|
UTF-8
| 1,027
| 3.609375
| 4
|
[] |
no_license
|
// exposed needed protocol "view"
// the "view" is a protocol required to display a view in our "app"
// these "view" is a `component`
import SwiftUI
struct SomethingView: View {
// "some" is new in 5.1
// whatever it returns inside the closure or fn is comformed to view
// such as returning "Text", "TextField", or other Views
var body: some View {
// in 5.1 there is no need for return
Text("Hello world!")
}
}
// this is how we trigger a canvas to see how a view looks like
// a view can be a whole view of an app, or a small component, such
// as Text
// We could either use struct or class, but struct is a convention or
// best practice in swift
// Can be named anything, but follows the convention X_Previews
// Xcode statically discovers types that conform to the PreviewProvider protocol
// in your app, and generates previews for each provider it discovers.
struct SomethingView_Previews: PreviewProvider {
static var previews: some View {
SomethingView()
}
}
| true
|
8abfb08650cc1ad1d2dae82f117b50f948f94832
|
Swift
|
jsj2008/manhattan_forum
|
/client/ManhattanForum/MFLocation.swift
|
UTF-8
| 4,256
| 3.09375
| 3
|
[] |
no_license
|
//
// MFLocation.swift
// ManhattanForum
//
// Created by Dimitri Roche on 9/15/14.
// Copyright (c) 2014 dimroc. All rights reserved.
//
import Foundation
import CoreLocation
class MFLocation: Printable, DebugPrintable, Equatable {
let neighborhood, sublocality, locality: String?
let coordinate: CLLocationCoordinate2D?
init(neighborhood: String?, sublocality: String?, locality: String?, coordinate: CLLocationCoordinate2D?) {
self.neighborhood = neighborhood
self.sublocality = sublocality
self.locality = locality
self.coordinate = coordinate
}
var description: String {
switch (neighborhood, sublocality) {
case (.Some, _):
return neighborhood!
case (.None, .Some):
return sublocality!
default:
return "Unknown"
}
}
var debugDescription: String {
return "\(neighborhood), \(sublocality), \(locality) at \(coordinate?.latitude), \(coordinate?.longitude)"
}
var valid: Bool {
switch (neighborhood, sublocality, locality) {
case (.Some,.Some,.Some):
return true
default:
return false
}
}
class func empty() -> MFLocation {
return MFLocation(neighborhood: nil, sublocality: nil, locality: nil, coordinate: nil)
}
// JSON Parsing in Swift: http://robots.thoughtbot.com/efficient-json-in-swift-with-functional-concepts-and-generics
class func fromGoogleJson(json: Dictionary<String, AnyObject>) -> MFLocation {
var lastLocation: MFLocation = MFLocation.empty()
if let results: [AnyObject] = json["results"] as [AnyObject]? {
// Couldn't use standard iterator on results because of some esoteric swift issue.
for index in 0...results.endIndex-1 {
let result: AnyObject = results[index]
lastLocation = fetchLocationFromResult(result)
if (lastLocation.valid) {
return lastLocation
}
}
}
return lastLocation
}
private class func fetchLocationFromResult(result: AnyObject?) -> MFLocation {
// println("## DEBUG: Parsing through:\n\(result)")
if let addressComponents: AnyObject? = result?["address_components"] {
return MFLocation(
neighborhood: fromAddressComponents(addressComponents!, type: "neighborhood"),
sublocality: fromAddressComponents(addressComponents!, type: "sublocality"),
locality: fromAddressComponents(addressComponents!, type: "locality"),
coordinate: coordinateFromResult(result!)
)
}
return MFLocation.empty()
}
private class func coordinateFromResult(result: AnyObject) -> CLLocationCoordinate2D? {
if let geometry: AnyObject? = result["geometry"] {
if let location: AnyObject? = geometry?["location"] {
if let lat: AnyObject? = location?["lat"] {
if let lng: AnyObject? = location?["lng"] {
return CLLocationCoordinate2D(latitude: lat! as CLLocationDegrees, longitude: lng! as CLLocationDegrees)
}
}
}
}
return nil
}
private class func fromAddressComponents(addressComponents: AnyObject, type: String) -> String? {
let array = addressComponents as Array<Dictionary<String, AnyObject>>
for addressComponent in array {
let types: AnyObject? = addressComponent["types"]
let typeArray = types as Array<String>
if let presence = find(typeArray, type) {
let long_name: AnyObject? = addressComponent["long_name"]
return long_name as? String
}
}
return nil
}
}
func == (lhs: MFLocation, rhs: MFLocation) -> Bool {
if lhs.neighborhood == rhs.neighborhood && lhs.sublocality == rhs.sublocality && lhs.locality == rhs.locality {
return lhs.coordinate?.latitude == rhs.coordinate?.latitude && lhs.coordinate?.longitude == rhs.coordinate?.longitude
}
return false
}
| true
|
afe2dac9e79d7d144ed0b20ab198240904d5af4e
|
Swift
|
XhrCkYsSgZokJL/markoff
|
/Markoff/Sources/Wrappers/BlurView.swift
|
UTF-8
| 861
| 2.734375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"ISC"
] |
permissive
|
import SwiftUI
import AppKit
struct BlurView: NSViewRepresentable {
var material: NSVisualEffectView.Material
var blendingMode: NSVisualEffectView.BlendingMode
func makeNSView(context: Context) -> NSVisualEffectView {
let visualEffectView = NSVisualEffectView()
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
visualEffectView.state = NSVisualEffectView.State.active
return visualEffectView
}
func updateNSView(
_ visualEffectView: NSVisualEffectView,
context: Context
) {
visualEffectView.material = material
visualEffectView.blendingMode = blendingMode
}
init(
material: NSVisualEffectView.Material = .windowBackground,
blendingMode: NSVisualEffectView.BlendingMode = .withinWindow
) {
self.material = material
self.blendingMode = blendingMode
}
}
| true
|
7033e024c86b3fa36c40a9490972d975ff797898
|
Swift
|
oppsx7/Swift
|
/MemeGenerator/MemeGenerator/ViewController.swift
|
UTF-8
| 2,639
| 2.84375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// MemeGenerator
//
// Created by Todor Dimitrov on 17.08.20.
// Copyright © 2020 Todor Dimitrov. All rights reserved.
//
import UIKit
enum Position: UInt32 {
case top = 1
case bottom = 2
}
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var textLabel: UILabel!
@IBOutlet var picture: UIImageView!
@IBOutlet var bottomTextLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(onCameraClick))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Add text", style: .plain, target: self, action: #selector(addtext))
}
@objc func addtext() {
let ac = UIAlertController(title: "Add text", message: nil, preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Submit", style: .default) {
[weak self, weak ac] action in
guard let text = ac?.textFields?[0].text else { return }
self?.submit(text,Position.top)
self?.addBottomtext()
})
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
func submit(_ text: String,_ position: Position) {
if position.rawValue == 1 {
textLabel.text = text
} else if position.rawValue == 2 {
bottomTextLabel.text = text
}
}
@objc func onCameraClick() {
let vc = UIImagePickerController()
vc.sourceType = .camera
vc.allowsEditing = true
vc.delegate = self
present(vc, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true)
guard let image = info[.editedImage] as? UIImage else {
print("No image found")
return
}
picture.image = image
}
func addBottomtext() {
let ac = UIAlertController(title: "Add bottom text", message: nil, preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Submit", style: .default) {
[weak self, weak ac] action in
guard let text = ac?.textFields?[0].text else { return }
self?.submit(text,Position.bottom)
})
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
}
| true
|
f292aa57a9a5f0aaa9d5c6fbb63ebbe45e7764d0
|
Swift
|
stutid/UserLocationApp
|
/UserLocationApp/UserLocationApp/ViewModel/MapViewModel.swift
|
UTF-8
| 2,000
| 2.890625
| 3
|
[] |
no_license
|
//
// MapViewModel.swift
// locationApp
//
// Created by admin on 02/08/18.
// Copyright © 2018 iOS. All rights reserved.
//
import Foundation
import CoreLocation
import Alamofire
import SwiftyJSON
class MapViewModel {
let WEATHER_URL = "https://samples.openweathermap.org/data/2.5/weather?"
let APP_ID = "20eb6c47522cfde9c342b1aece2ea94c"
private var modelObj = CallOutViewModel()
func getWeatherData(for location: CLLocation) {
let myStrLatitude = String(location.coordinate.latitude)
let myStrLongitude = String(location.coordinate.longitude)
let params = ["lat": myStrLatitude, "lon": myStrLongitude, "appid": APP_ID]
Alamofire.request(WEATHER_URL, method: .get, parameters: params).responseJSON { (response) in
if response.result.isSuccess {
let weatherJSON: JSON = JSON(response.result.value!)
print(weatherJSON)
self.getWeatherInformation(from: weatherJSON)
}
else {
print(response.result.error!)
print("No Internet connection")
}
}
}
func getAddressFromCoordinates(location: CLLocation) {
CLGeocoder().reverseGeocodeLocation(location) { (placemarks, err) -> Void in
if let p = placemarks {
let address = p[0].name
self.modelObj.address = address
}
}
}
func getCallOutValues() -> CallOutViewModel {
return modelObj
}
private func getWeatherInformation(from json: JSON) {
if let weatherInfo = json["weather"][0]["main"].string {
modelObj.weather = weatherInfo
}
else {
print("No data found")
}
}
}
struct CallOutViewModel {
var name: String = "John"
var address: String?
var date: String = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .short)
var weather: String?
}
| true
|
4b7d7362c864492759e98dc72a4e8743400b42c0
|
Swift
|
InventoryBox/inventorybox_iOS
|
/inventorybox_iOS/inventorybox_iOS/Sources/VCs/SignProgress/PersonalInfoChangeVC.swift
|
UTF-8
| 4,655
| 2.546875
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
//
// PersonalInfoChangeVC.swift
// inventorybox_iOS
//
// Created by 황지은 on 2020/08/11.
// Copyright © 2020 jaeyong Lee. All rights reserved.
//
import UIKit
class PersonalInfoChangeVC: UIViewController,UITextFieldDelegate {
@IBOutlet var repNameTextField: UITextField!
@IBOutlet var coNameTextField: UITextField!
@IBOutlet var phoneNumberTextField: UITextField!
@IBOutlet var goToProfileBtn: UIButton!
var appdelegate = UIApplication.shared.delegate as? AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
setOutlets()
repNameTextField.layer.borderWidth = 1
repNameTextField.layer.borderColor = UIColor.veryLightPinkTwo.cgColor
repNameTextField.layer.cornerRadius = 10
coNameTextField.layer.borderWidth = 1
coNameTextField.layer.borderColor = UIColor.veryLightPinkTwo.cgColor
coNameTextField.layer.cornerRadius = 10
phoneNumberTextField.layer.borderWidth = 1
phoneNumberTextField.layer.borderColor = UIColor.veryLightPinkTwo.cgColor
phoneNumberTextField.layer.cornerRadius = 10
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
self.view.endEditing(true)
}
@IBAction func backButtonDidTap(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func saveData() {
appdelegate?.repName = repNameTextField.text!
appdelegate?.coName = coNameTextField.text!
appdelegate?.phoneNumber = phoneNumberTextField.text!
}
func setOutlets(){
repNameTextField.delegate = self
coNameTextField.delegate = self
phoneNumberTextField.delegate = self
goToProfileBtn.isEnabled = false
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.repNameTextField {
textField.resignFirstResponder()
self.coNameTextField.becomeFirstResponder()
}
else if textField == self.coNameTextField {
textField.resignFirstResponder()
self.phoneNumberTextField.becomeFirstResponder()
}
textField.resignFirstResponder()
return true
}
func format(with mask: String, phone: String) -> String {
let numbers = phone.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
var result = ""
var index = numbers.startIndex // numbers iterator
// iterate over the mask characters until the iterator of numbers ends
for ch in mask where index < numbers.endIndex {
if ch == "X" {
// mask requires a number in this place, so take the next one
result.append(numbers[index])
// move numbers iterator to the next index
index = numbers.index(after: index)
} else {
result.append(ch) // just append a mask character
}
}
return result
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == phoneNumberTextField {
var strText: String? = textField.text
if strText == nil {
strText = ""
}
let newString = (strText! as NSString).replacingCharacters(in: range, with: string)
textField.text = format(with: "XXX-XXXX-XXXX", phone: newString)
return false
}
if (repNameTextField.text != "") && (coNameTextField.text != "") && (phoneNumberTextField.text != "") {
goToProfileBtn.isEnabled = true
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if (repNameTextField.text != "") && (coNameTextField.text != "") && (phoneNumberTextField.text != "") {
goToProfileBtn.isEnabled = true
} else {
goToProfileBtn.isEnabled = false
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension PersonalInfoChangeVC {
}
| true
|
2d7782ce724712f848001785967aaa66ef0e53e1
|
Swift
|
vninfo/Stanford-CS193p-Winter-2017
|
/Calculator/Calculator/CalculatorViewController.swift
|
UTF-8
| 6,437
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// Calculator
//
// Created by Witek on 15/03/2017.
// Copyright © 2017 Witek Bobrowski. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController {
@IBOutlet weak var display: UILabel!
@IBOutlet weak var variableDisplay: UILabel!
@IBOutlet weak var descriptionDisplay: UILabel!
var userIsInTheMiddleOfTyping = false
@IBAction func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTyping{
let textCurrentlyInDisplay = display.text!
if digit == "." && textCurrentlyInDisplay.characters.contains("."){
display.text = textCurrentlyInDisplay
} else {
display.text = textCurrentlyInDisplay + digit
}
} else {
if digit == "." {
display.text = "0."
} else {
display.text = digit
}
userIsInTheMiddleOfTyping = true
}
}
var displayValue: Double {
get {
return Double(display.text!)!
}
set {
if newValue.truncatingRemainder(dividingBy: 1) == 0 {
let formattedValue = String(newValue).characters.dropLast(2)
display.text = String(formattedValue)
} else {
display.text = brain.formatter.string(from: NSNumber(value: newValue))
}
}
}
var displayVariable: Double{
get {
if variableDictionary.count != 0 {
return (variableDictionary["M"])!
} else {
return 0
}
}
set{
if variableDictionary.count != 0 {
variableDisplay.text = "M = \(newValue)"
} else {
variableDisplay.text = " "
}
}
}
var evaluatedResult: (result: Double?, isPending: Bool, description: String)? = nil{
didSet {
if let result = evaluatedResult!.result{
displayValue = result
}
descriptionDisplay.text = (evaluatedResult!.isPending ? "\(evaluatedResult!.description) ..." : "\(evaluatedResult!.description) = ")
}
}
private var brain = CalculatorBrain()
private var variableDictionary = [String: Double]()
@IBAction func clear(_ sender: UIButton) {
display.text = "0"
descriptionDisplay.text = " "
variableDisplay.text = " "
userIsInTheMiddleOfTyping = false
variableDictionary = [:]
brain = CalculatorBrain()
}
@IBAction func setVariable(_ sender: UIButton) {
// Programming Assingment 2 : Task 7
let symbol = String(sender.currentTitle!.characters.dropFirst())
variableDictionary[symbol] = displayValue
displayVariable = displayValue
evaluatedResult = brain.evaluate(using: variableDictionary)
userIsInTheMiddleOfTyping = false
}
@IBAction func enterVariable(_ sender: UIButton) {
// Programming Assingment 2 : Task 7
brain.setOperand(variable: sender.currentTitle!)
evaluatedResult = brain.evaluate()
}
@IBAction func undo(_ sender: UIButton) {
// Programming Assingment 2 : Task 10
brain.undo()
evaluatedResult = brain.evaluate(using: variableDictionary)
}
@IBAction func performOperation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping {
brain.setOperand(displayValue)
userIsInTheMiddleOfTyping = false
}
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
if let result = brain.evaluate(using: variableDictionary).result {
displayValue = result
}
descriptionDisplay.text = brain.evaluate(using: variableDictionary).description + (brain.evaluate(using: variableDictionary).isPending ? "..." : " = ")
}
//MARK: - Lecture 12 demo code
// private func showSizeClasses() {
// if !userIsInTheMiddleOfTyping {
// display.textAlignment = .center
// display.text = "width " + traitCollection.horizontalSizeClass.description + " height " + traitCollection.verticalSizeClass.description
//
// }
// }
override func viewDidAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: animated)
// showSizeClasses()
}
// override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// super.viewWillTransition(to: size, with: coordinator)
// coordinator.animate(alongsideTransition: { coordinator in
// self.showSizeClasses()
// }, completion: nil)
// }
// Programming Assingment 3 : Task7
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var destinationViewController = segue.destination
if let navigationController = destinationViewController as? UINavigationController {
destinationViewController = navigationController.visibleViewController ?? destinationViewController
}
if let graphingViewController = destinationViewController as? GraphingViewController {
// Programming Assingment 3 : Task 9
graphingViewController.navigationItem.title = self.brain.evaluate(using: self.variableDictionary).description
graphingViewController.function = {(x: CGFloat) -> Double? in
self.variableDictionary["M"] = Double(x)
return self.brain.evaluate(using: self.variableDictionary).result
}
}
}
//MARK: - Lecture 6 demo code
//
// override func viewDidLoad() {
// super.viewDidLoad()
// brain.addUnaryOperation(named: "✅") { [unowned self] in
// self.display.textColor = UIColor.green
// return sqrt($0)
// }
// }
//
}
//extension UIUserInterfaceSizeClass: CustomStringConvertible {
// public var description: String {
// switch self {
// case .compact:
// return "Compact"
// case .unspecified:
// return "???"
// case .regular:
// return "Regular"
// }
// }
//}
| true
|
6960e083cc35551a324ee9f14e31855e8b9f6ec1
|
Swift
|
KenkenIchimura/ShareBooks
|
/BooksApp/TimeLine/TimeLineTableViewCell.swift
|
UTF-8
| 1,880
| 2.59375
| 3
|
[] |
no_license
|
//
// TimeLineTableViewCell.swift
// BooksApp
//
// Created by 市村健太 on 2018/06/01.
// Copyright © 2018年 GeekSalon. All rights reserved.
//
import UIKit
//プロトコルで共通化しておく。
protocol TimeLineTableViewCellDelegate{
func didTapLikeButton(tableViewCell:UITableViewCell,button:UIButton)
func didTapMenuButton(tableViewCell:UITableViewCell,button:UIButton)
func didTapCommentsButton(tableViewCell:UITableViewCell,button:UIButton)
}
class TimeLineTableViewCell: UITableViewCell {
var delegate:TimeLineTableViewCellDelegate?
@IBOutlet var userImageView:UIImageView!
@IBOutlet var userNameLabel:UILabel!
@IBOutlet var bookImageView:UIImageView!
@IBOutlet var bookTitleLabel:UILabel!
@IBOutlet var authorLabel:UILabel!
@IBOutlet var likeButton:UIButton!
@IBOutlet var likeCountLabel:UILabel!
@IBOutlet var commentTextView:UITextView!
//@IBOutlet var timestampLabel:UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
userImageView.layer.cornerRadius = userImageView.bounds.width / 2.0
userImageView.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func like(button:UIButton){
self.delegate?.didTapLikeButton(tableViewCell:self,button:button)
}
@IBAction func openMenu(button:UIButton){
self.delegate?.didTapMenuButton(tableViewCell:self,button:button)
}
@IBAction func showComments(button:UIButton){
self.delegate?.didTapCommentsButton(tableViewCell:self,button:button)
}
}
| true
|
94608498c63d1a261331768697526fd860b3bca8
|
Swift
|
inoity/nariko
|
/Nariko/Classes/BubbleControl.swift
|
UTF-8
| 13,194
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// BubbleControl.swift
// BubbleControl-Swift
//
// Created by Cem Olcay on 11/12/14.
// Copyright (c) 2014 Cem Olcay. All rights reserved.
//
import UIKit
// MARK: - Animation Constants
private let BubbleControlMoveAnimationDuration: TimeInterval = 0.5
private let BubbleControlSpringDamping: CGFloat = 0.6
private let BubbleControlSpringVelocity: CGFloat = 0.6
let closeButton = UIButton(frame: CGRect(x: 0, y: 20, width: 40, height: 40))
// MARK: - UIView Extension
extension UIView {
// MARK: Frame Extensions
var x: CGFloat {
get {
return self.frame.origin.x
} set (value) {
self.frame = CGRect (x: value, y: self.y, width: self.w, height: self.h)
}
}
var y: CGFloat {
get {
return self.frame.origin.y
} set (value) {
self.frame = CGRect (x: self.x, y: value, width: self.w, height: self.h)
}
}
var w: CGFloat {
get {
return self.frame.size.width
} set (value) {
self.frame = CGRect (x: self.x, y: self.y, width: value, height: self.h)
}
}
var h: CGFloat {
get {
return self.frame.size.height
} set (value) {
self.frame = CGRect (x: self.x, y: self.y, width: self.w, height: value)
}
}
var position: CGPoint {
get {
return self.frame.origin
} set (value) {
self.frame = CGRect (origin: value, size: self.frame.size)
}
}
var size: CGSize {
get {
return self.frame.size
} set (value) {
self.frame = CGRect (origin: self.frame.origin, size: size)
}
}
var left: CGFloat {
get {
return self.x
} set (value) {
self.x = value
}
}
var right: CGFloat {
get {
return self.x + self.w
} set (value) {
self.x = value - self.w
}
}
var top: CGFloat {
get {
return self.y
} set (value) {
self.y = value
}
}
var bottom: CGFloat {
get {
return self.y + self.h
} set (value) {
self.y = value - self.h
}
}
func leftWithOffset (_ offset: CGFloat) -> CGFloat {
return self.left - offset
}
func rightWithOffset (_ offset: CGFloat) -> CGFloat {
return self.right + offset
}
func topWithOffset (_ offset: CGFloat) -> CGFloat {
return self.top - offset
}
func botttomWithOffset (_ offset: CGFloat) -> CGFloat {
return self.bottom + offset
}
func spring (_ animations: @escaping ()->Void, completion:((Bool)->Void)?) {
UIView.animate(withDuration: BubbleControlMoveAnimationDuration,
delay: 0,
usingSpringWithDamping: BubbleControlSpringDamping,
initialSpringVelocity: BubbleControlSpringVelocity,
options: UIViewAnimationOptions(),
animations: animations,
completion: completion)
}
func moveY (_ y: CGFloat) {
var moveRect = self.frame
moveRect.origin.y = y
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func moveX (_ x: CGFloat) {
var moveRect = self.frame
moveRect.origin.x = x
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func movePoint (_ x: CGFloat, y: CGFloat) {
var moveRect = self.frame
moveRect.origin.x = x
moveRect.origin.y = y
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func movePoint (_ point: CGPoint) {
var moveRect = self.frame
moveRect.origin = point
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func setScale(_ s: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DScale(transform, s, s, s)
self.layer.transform = transform
}
func alphaTo(_ to: CGFloat) {
UIView.animate(withDuration: BubbleControlMoveAnimationDuration,
animations: {
self.alpha = to
})
}
func bubble() {
self.setScale(1.2)
spring({ () -> Void in
self.setScale(1)
}, completion: nil)
}
}
// MARK: - BubbleControl
class BubbleControl: UIControl {
var WINDOW: UIWindow?
var screenShot: UIImage?
// MARK: Constants
let snapOffsetMin: CGFloat = 0
let snapOffsetMax: CGFloat = 0
// MARK: Optionals
var contentView: UIView?
var snapsInside: Bool = false
var movesBottom: Bool = false
// MARK: Actions
var didToggle: ((Bool) -> ())?
var didNavigationBarButtonPressed: (() -> ())?
var setOpenAnimation: ((_ contentView: UIView, _ backgroundView: UIView?)->())?
var setCloseAnimation: ((_ contentView: UIView, _ backgroundView: UIView?) -> ())?
// MARK: Bubble State
enum BubbleControlState {
case snap // snapped to edge
case drag // dragging around
}
var bubbleState: BubbleControlState = .snap {
didSet {
if bubbleState == .snap {
setupSnapInsideTimer()
} else {
snapOffset = snapOffsetMin
}
}
}
// MARK: Snap
fileprivate var snapOffset: CGFloat!
fileprivate var snapInTimer: Timer?
fileprivate var snapInInterval: TimeInterval = 2
// MARK: Toggle
fileprivate var positionBeforeToggle: CGPoint?
var toggle: Bool = false {
didSet {
didToggle? (toggle)
if toggle {
openContentView()
} else {
closeContentView()
}
}
}
// MARK: Image
var imageView: UIImageView?
var image: UIImage? {
didSet {
imageView?.image = image
}
}
// MARK: Init
init (win: UIWindow, size: CGSize) {
super.init(frame: CGRect (origin: CGPoint.zero, size: size))
defaultInit(win)
}
init (win: UIWindow, image: UIImage) {
let size = image.size
super.init(frame: CGRect (origin: CGPoint.zero, size: size))
self.image = image
defaultInit(win)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
func defaultInit (_ win: UIWindow) {
self.WINDOW = win
// self
snapOffset = snapOffsetMin
layer.cornerRadius = w/2
// image view
imageView = UIImageView(frame:CGRect(x: 50, y: 0, width: size.width - 50, height: size.height))
imageView?.isUserInteractionEnabled = false
imageView?.clipsToBounds = true
addSubview(imageView!)
closeButton.setTitle("✕", for: .normal)
closeButton.titleLabel!.font = UIFont.systemFont(ofSize: 16)
closeButton.setTitleColor(UIColor.white, for: .normal)
closeButton.backgroundColor = UIColor.black
closeButton.layer.cornerRadius = 20
closeButton.addTarget(NarikoTool.sharedInstance, action: #selector(NarikoTool.removeBubbleForce), for: .touchUpInside)
closeButton.isHidden = true
addSubview(closeButton)
// events
addTarget(self, action: #selector(BubbleControl.touchDown), for: UIControlEvents.touchDown)
addTarget(self, action: #selector(BubbleControl.touchUp), for: UIControlEvents.touchUpInside)
addTarget(self, action: #selector(BubbleControl.touchDrag(_:event:)), for: UIControlEvents.touchDragInside)
// place
center.x = WINDOW!.w - w/2 + snapOffset
center.y = 84 + h/2
snap()
}
// MARK: Snap To Edge
func snap() {
var targetX = WINDOW!.leftWithOffset(snapOffset + 50)
if center.x > WINDOW!.w/2 {
targetX = WINDOW!.rightWithOffset(snapOffset) - w
}
// move to snap position
moveX(targetX)
}
func snapInside() {
print("snap inside !")
if !toggle && bubbleState == .snap {
snapOffset = snapOffsetMax
snap()
}
}
func setupSnapInsideTimer() {
if !snapsInside {
return
}
if let timer = snapInTimer {
if timer.isValid {
timer.invalidate()
}
}
snapInTimer = Timer.scheduledTimer(timeInterval: snapInInterval,
target: self,
selector: #selector(BubbleControl.snapInside),
userInfo: nil,
repeats: false)
}
func lockInWindowBounds() {
if top < 64 {
var rect = frame
rect.origin.y = 64
frame = rect
}
if left < -50 {
var rect = frame
rect.origin.x = -50
frame = rect
}
if bottom > WINDOW!.h {
var rect = frame
rect.origin.y = WINDOW!.botttomWithOffset(-h)
frame = rect
}
if right > WINDOW!.w {
var rect = frame
rect.origin.x = WINDOW!.rightWithOffset(-w)
frame = rect
}
}
// MARK: Events
func touchDown() {
bubble()
}
func touchUp() {
if bubbleState == .snap {
toggle = !toggle
} else {
bubbleState = .snap
snap()
}
}
func touchDrag (_ sender: BubbleControl, event: UIEvent) {
if closeButton.isHidden {
bubbleState = .drag
if toggle {
toggle = false
}
let touch = event.allTouches!.first!
if touch.location(in: nil).x == touch.previousLocation(in: nil).x && touch.location(in: nil).y == touch.previousLocation(in: nil).y{
bubbleState = .snap
} else {
let location = touch.location(in: WINDOW!)
center = location
lockInWindowBounds()
}
}
}
func navButtonPressed (_ sender: AnyObject) {
didNavigationBarButtonPressed? ()
}
func degreesToRadians (_ angle: CGFloat) -> CGFloat {
return (CGFloat (M_PI) * angle) / 180.0
}
// MARK: Toggle
func openContentView() {
if let v = contentView {
screenShotMethod()
let win = WINDOW!
win.addSubview(v)
win.bringSubview(toFront: self)
snapOffset = snapOffsetMin
snap()
positionBeforeToggle = frame.origin
if let anim = setOpenAnimation {
anim(v, win.subviews[0])
} else {
v.bottom = win.bottom
}
if movesBottom {
movePoint(CGPoint (x: win.center.x - w/2, y: win.bottom - h - snapOffset))
} else {
moveY(v.top - h - snapOffset)
}
closeButton.isHidden = false
NarikoTool.sharedInstance.textView.becomeFirstResponder()
}
}
func screenShotMethod() {
//Create the UIImage
print("shot")
self.isHidden = true
UIGraphicsBeginImageContext(WINDOW!.frame.size)
WINDOW!.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print(image)
screenShot = image
//Save it to the camera roll
// UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
self.isHidden = false
}
func closeContentView() {
if let v = contentView {
if let anim = setCloseAnimation {
anim (v, (WINDOW?.subviews[0])! as UIView)
} else {
v.removeFromSuperview()
}
if (bubbleState == .snap) {
setupSnapInsideTimer()
if positionBeforeToggle != nil {
movePoint(positionBeforeToggle!)
}
}
}
closeButton.isHidden = true
}
}
| true
|
5398ec25339768d29452b1d8dfdeec46525f7a5a
|
Swift
|
vikingosegundo/HearThisMiniplayer
|
/HearThis/ArtistsListViewController.swift
|
UTF-8
| 2,403
| 2.5625
| 3
|
[] |
no_license
|
//
// ArtistsListViewController.swift
// HearThis
//
// Created by Manuel Meyer on 17.11.16.
// Copyright © 2016 Manuel Meyer. All rights reserved.
//
import UIKit
import HearThisAPI
class ArtistsListViewController: BaseTableViewController, ArtistSelectionObserver, HearThisPlayerHolder {
@IBOutlet weak var bottomContraint: NSLayoutConstraint!
override var tableView: UITableView! {
didSet{
configure()
}
}
var hearThisAPI: HearThisAPIType {
set{
privateApi = newValue
}
get {
if privateApi == nil {
privateApi = HearThisAPI(networkConnector: NetworkConnector())
}
return privateApi!
}
}
private var privateApi: HearThisAPIType?
private var datasource: ArtistsListDatasource?
var hearThisPlayer: HearThisPlayerType? {
didSet{
hearThisPlayer?.registerObserver(observer: self)
}
}
private var selectedArtist: Artist?
func selected(_ artist: Artist, on: IndexPath) {
selectedArtist = artist
performSegue(withIdentifier: "ArtistDetailViewController", sender: self)
selectedArtist = nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destiantion = segue.destination as? HearThisPlayerHolder {
destiantion.hearThisPlayer = hearThisPlayer
}
if let destination = segue.destination as? ArtistDetailViewController {
destination.artist = selectedArtist
}
}
private func configure(){
guard let tableView = self.tableView else { return }
do {
let ds = try ArtistsListDatasource(tableView:tableView,
artistsResource: ArtistsResource(hearThisAPI: hearThisAPI)
)
ds.registerSelectionObserver(observer: self)
self.datasource = ds
} catch(let e) {
fatalError(e.localizedDescription)
}
}
}
extension ArtistsListViewController: HearThisPlayerObserver {
func player(_ player: HearThisPlayerType, willStartPlaying track: Track) {
bottomContraint.constant = 64
}
func player(_ player: HearThisPlayerType, didStopPlaying track: Track) {
bottomContraint.constant = 0
}
}
| true
|
29b3cc1bfb3068a574f57740527e356432b83c43
|
Swift
|
CodeEagle/CombineEx
|
/Sources/CombineEx/CombineEx+Either.swift
|
UTF-8
| 388
| 2.71875
| 3
|
[] |
no_license
|
import Foundation
public enum EitherBio<A: Error, B: Error>: Error {
case a(A)
case b(B)
}
public enum EitherTri<A: Error, B: Error, C: Error>: Error {
case a(A)
case b(B)
case c(C)
}
public enum EitherFor<A: Error, B: Error, C: Error, D: Error>: Error {
case a(A)
case b(B)
case c(C)
case d(D)
}
public enum AwaitError: Error {
case unknown
}
| true
|
f05606510eca5b16b677ed1fb1cb7a19921c162a
|
Swift
|
gifton/homeworkHelperSwift
|
/homeworkHelper/homeworkHelper/AssignmentTableViewCell.swift
|
UTF-8
| 1,288
| 2.546875
| 3
|
[] |
no_license
|
//
// AssignmentTableViewCell.swift
// homeworkHelper
//
// Created by Gifton Okoronkwo on 9/20/17.
// Copyright © 2017 Gifton Okoronkwo. All rights reserved.
//
import UIKit
class AssignmentTableViewCell: UITableViewCell {
@IBOutlet var classNameLabel: UILabel!
@IBOutlet var workTypeLabel: UILabel!
@IBOutlet var dueDateLabel: UILabel!
@IBOutlet var estTimeLabel: UILabel!
@IBOutlet var urgencyLabel: UILabel!
@IBOutlet var dateAssignedLabel: UILabel!
@IBOutlet var aboutLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// let mScreenSize = UIScreen.main.bounds
// let mSeparatorHeight = CGFloat(10.0) // Change height of speatator as you want
// let mAddSeparator = UIView.init(frame: CGRect(x: 0, y: self.frame.size.height - mSeparatorHeight, width: mScreenSize.width, height: mSeparatorHeight))
// mAddSeparator.backgroundColor = UIColor(red:0.27, green:0.44, blue:0.51, alpha:1.0) // Change backgroundColor of separator
// self.addSubview(mAddSeparator)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
1d5b8afda00aa94da374e9f00622f136a33293f0
|
Swift
|
nikhiljainlive/Drawing_IOS
|
/FundooDraw/Controllers/SettingsViewController.swift
|
UTF-8
| 8,069
| 2.75
| 3
|
[] |
no_license
|
//
// SettingsViewController.swift
// FundooDraw
//
// Created by Admin on 09/08/20.
// Copyright © 2020 nikhiljain. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
var color : CGColor = UIColor.black.cgColor
var lineWidth : CGFloat = 1 {
didSet {
lineWidthValueLabel.text = String(format: "%\(0.1)f", lineWidth)
onLineWidthChange?(lineWidth)
}
}
var onColorChange : ((CGColor) -> Void)?
var onLineWidthChange : ((CGFloat) -> Void)?
private var redColorValue : Int = 0 {
didSet {
redColorValueLabel.text = redColorValue.description
}
}
private var greenColorValue : Int = 0 {
didSet {
greenColorValueLabel.text = greenColorValue.description
}
}
private var blueColorValue : Int = 0 {
didSet {
blueColorValueLabel.text = blueColorValue.description
}
}
private var alphaValue : CGFloat = 0 {
didSet {
opacityValueLabel.text = String(format: "%\(0.1)f", alphaValue)
}
}
private let closeButton : UIButton = {
let button = UIButton(type: .close)
button.addTarget(self, action: #selector(dismissViewController), for: .touchUpInside)
return button
}()
private let redColorSlider : UISlider = {
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 255
slider.addTarget(self, action: #selector(colorValueDidChange), for: .valueChanged)
return slider
}()
private let greenColorSlider : UISlider = {
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 255
slider.addTarget(self, action: #selector(colorValueDidChange), for: .valueChanged)
return slider
}()
private let blueColorSlider : UISlider = {
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 255
slider.addTarget(self, action: #selector(colorValueDidChange), for: .valueChanged)
return slider
}()
private let opacitySlider : UISlider = {
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 1
slider.addTarget(self, action: #selector(colorValueDidChange), for: .valueChanged)
return slider
}()
private let lineWidthSlider : UISlider = {
let slider = UISlider()
slider.minimumValue = 1
slider.maximumValue = 20
slider.addTarget(self, action: #selector(lineWidthDidChange), for: .valueChanged)
return slider
}()
private lazy var redColorValueLabel : UILabel = {
let label = UILabel()
label.textColor = .red
return label
}()
private lazy var greenColorValueLabel : UILabel = {
let label = UILabel()
label.textColor = .green
return label
}()
private lazy var blueColorValueLabel : UILabel = {
let label = UILabel()
label.textColor = .blue
return label
}()
private lazy var opacityValueLabel : UILabel = {
let label = UILabel()
label.textColor = .black
return label
}()
private lazy var lineWidthValueLabel : UILabel = {
let label = UILabel()
label.textColor = .black
return label
}()
private lazy var colorStackView = UIStackView(arrangedSubviews: [
stackView(for: redColorSlider, with: "Red", valueLabel: redColorValueLabel),
stackView(for: greenColorSlider, with: "Green", valueLabel: greenColorValueLabel),
stackView(for: blueColorSlider, with: "Blue", valueLabel: blueColorValueLabel),
stackView(for: opacitySlider, with: "Opacity", valueLabel: opacityValueLabel),
stackView(for: lineWidthSlider, with: "Line Width", valueLabel: lineWidthValueLabel)
])
private let previewView : UIView = {
let view = UIView()
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setUpLayout()
setUpVariablesFromColor()
setUpSliderValues()
previewView.backgroundColor = UIColor(cgColor: color)
}
private func setUpLayout() {
view.backgroundColor = UIColor.white
setUpColorStackView()
setUpColorPreview()
setUpCloseButton()
}
private func setUpVariablesFromColor() {
redColorValue = Int(CIColor(cgColor: color).red * 255)
greenColorValue = Int(CIColor(cgColor: color).green * 255)
blueColorValue = Int(CIColor(cgColor: color).blue * 255)
alphaValue = CIColor(cgColor: color).alpha
}
private func setUpSliderValues(){
redColorSlider.value = Float(redColorValue)
greenColorSlider.value = Float(greenColorValue)
blueColorSlider.value = Float(blueColorValue)
opacitySlider.value = Float(alphaValue)
lineWidthSlider.value = Float(lineWidth)
}
private func setUpCloseButton() {
self.view.addSubview(closeButton)
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
}
private func stackView(for slider : UISlider, with text : String, valueLabel : UILabel) -> UIStackView {
let label = UILabel()
label.text = text
let sliderStackView = UIStackView(arrangedSubviews: [label, slider, valueLabel])
sliderStackView.spacing = 10
return sliderStackView
}
private func setUpColorStackView() {
colorStackView.distribution = .equalCentering
colorStackView.axis = .vertical
self.view.addSubview(colorStackView)
colorStackView.translatesAutoresizingMaskIntoConstraints = false
colorStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
colorStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
colorStackView.centerYAnchor.constraint(equalToSystemSpacingBelow: view.centerYAnchor, multiplier: 1).isActive = true
}
private func setUpColorPreview() {
let previewLabel = UILabel()
previewLabel.text = "Color Preview"
previewView.layer.cornerRadius = 25
previewView.translatesAutoresizingMaskIntoConstraints = false
previewView.heightAnchor.constraint(equalToConstant: 50).isActive = true
previewView.widthAnchor.constraint(equalToConstant: 50).isActive = true
let stackView = UIStackView(arrangedSubviews: [
previewLabel, previewView
])
stackView.spacing = 20
self.view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: colorStackView.bottomAnchor, constant: 20).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
@objc private func dismissViewController() {
dismiss(animated: true)
}
@objc private func colorValueDidChange() {
redColorValue = Int(redColorSlider.value)
greenColorValue = Int(greenColorSlider.value)
blueColorValue = Int(blueColorSlider.value)
alphaValue = CGFloat(opacitySlider.value)
let changedColor = UIColor(red: CGFloat(redColorSlider.value) / 255.0, green: CGFloat(greenColorSlider.value) / 255.0, blue: CGFloat(blueColorSlider.value) / 255.0, alpha: alphaValue)
onColorChange?(changedColor.cgColor)
previewView.backgroundColor = changedColor
}
@objc private func lineWidthDidChange() {
lineWidth = CGFloat(lineWidthSlider.value)
}
}
| true
|
cd2834129b6b3135cf309ae1db1af332bd99c1c1
|
Swift
|
rdv0011/dog-breed-catalog
|
/DogCat/DogCat/FavoritesStore/FavoritesStore.swift
|
UTF-8
| 3,419
| 3.03125
| 3
|
[] |
no_license
|
//
// Copyright © 2021 Dmitry Rybakov. All rights reserved.
import Foundation
import Combine
/// Is used to save and fetch from a persistent storage ```Breed``` objects
protocol FavoritesStoring {
func toggle(for breed: Breed)
func publisher(for breed: Breed) -> AnyPublisher<Bool, Never>
func all() -> [Breed]
}
/// Sample implementation of ```Favorites``` persistent storage mechanizm
///
/// This implementation is based on the ```UserDefaults```
/// ```Breed``` type supports serialization to JSON string which is saved in the store
/// - Warning: To simplify implementation when changes is made to the store all objects are populated back to the publisher subscribers
/// Which may lead to extra work done in the UI
final class FavoriteStore: FavoritesStoring {
private let defaults = UserDefaults.standard
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
init() {
if defaults.favorites == nil {
log.debug(.favoritesStore, "Init empty storage for \(FavoriteStore.self)")
defaults.setValue([:], forKey: UserDefaults.favoritesKey)
}
}
/// - Returns: True if a provided objects exists in the store and False otherwise
private func isFavorite(for breed: Breed) -> Bool {
defaults.favorites?[breed.id] != nil
}
/// Adds the provided objects to the store if it does not exists and removes it otherwise
func toggle(for breed: Breed) {
var favorites = defaults.favorites
let encodedBreedData: Data?
if !isFavorite(for: breed) {
encodedBreedData = try? encoder.encode(breed)
log.verbose(.favoritesStore, "Add favorite to store: \(breed.id)")
} else {
encodedBreedData = nil
log.verbose(.favoritesStore, "Remove favorite from store: \(breed.id)")
}
favorites?[breed.id] = encodedBreedData
defaults.favorites = favorites
}
/// Notifies the subscribers when of the objects is added or removed from the store
func publisher(for breed: Breed) -> AnyPublisher<Bool, Never> {
defaults
.publisher(for: \.favorites)
.map { favorites in
favorites?[breed.id] != nil
}
.handleEvents(receiveOutput: { isOn in
log.verbose(.favoritesStore, "\(breed.id) favorite: \(isOn)")
})
.eraseToAnyPublisher()
}
/// - Returns: All objects from the store
func all() -> [Breed] {
let favorites = defaults.favorites?
.compactMap { (key, encodedBreedData) -> Breed? in
guard let breed =
try? decoder.decode(Breed.self, from: encodedBreedData) else {
log.error(.favoritesStore, "Failed to decode: key \(key) data \(encodedBreedData)")
return nil
}
return breed
} ?? []
return favorites
}
func removeAll() {
defaults.setValue([:], forKey: UserDefaults.favoritesKey)
}
}
extension UserDefaults {
static let favoritesKey = "favoritesKey"
@objc fileprivate dynamic var favorites: [String: Data]? {
get {
self.dictionary(forKey: UserDefaults.favoritesKey) as? [String: Data]
}
set {
self.setValue(newValue, forKey: UserDefaults.favoritesKey)
}
}
}
| true
|
866fa4a7e6d32902951dc8d1b5ddf9251276b66c
|
Swift
|
eduguru/AzeniaBlogTest
|
/AzeniaBlogTest/models/Comment.swift
|
UTF-8
| 324
| 2.65625
| 3
|
[] |
no_license
|
//
// Comment.swift
// AzeniaBlogTest
//
// Created by edwin weru on 11/06/2021.
//
import Foundation
// MARK: - Comment
struct Comment: Codable {
let postID, id: Int?
let name, email, body: String?
enum CodingKeys: String, CodingKey {
case postID = "postId"
case id, name, email, body
}
}
| true
|
e9a07f3de5f84f5287f94c141e540026b8634fee
|
Swift
|
erikfloresq/SimpleApp
|
/SimpleApp/View/ResultViewController.swift
|
UTF-8
| 1,049
| 2.5625
| 3
|
[] |
no_license
|
//
// ResultViewController.swift
// SimpleApp
//
// Created by Erik Flores on 2/18/18.
// Copyright © 2018 Erik Flores. All rights reserved.
//
import UIKit
class ResultViewController: UIViewController {
@IBOutlet weak var resultTableView: UITableView!
var results = [ClassRoom]() {
didSet {
resultTableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
resultTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension ResultViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath)
cell.textLabel?.text = results[indexPath.row].name
return cell
}
}
| true
|
7ec87a17aa2cc63e4c62dcddaddee4bd5152a75f
|
Swift
|
samuelsys/msl
|
/mosyle/MosyleFamily/MosyleFamily/Source/Manager/Group/GroupManager.swift
|
UTF-8
| 761
| 2.515625
| 3
|
[] |
no_license
|
//
// GroupManager.swift
// MosyleFamily
//
// Created by Samuel Furtado on 16/03/2018.
// Copyright © 2018 Samuel Furtado. All rights reserved.
//
import Foundation
class GroupManager : BaseManager {
/// Group Business
private lazy var business: GroupBusiness = {
return GroupBusiness()
}()
/// GroupOperaion manager
///
/// - Parameters:
/// - completion: completion callback
func fetchGroup(refresh: Bool = false,
_ completion: @escaping GroupObjectCallback) {
addOperation {
self.business.fetchGroup(completion: { (group) in
OperationQueue.main.addOperation {
completion(group)
}
})
}
}
}
| true
|
041547e0f0da48ded8fe7ee0bbf07a338a863d97
|
Swift
|
gotnull/unstoppable-wallet-ios
|
/UnstoppableWallet/UnstoppableWallet/Modules/Favorites/CoinPriceAlerts/CoinPriceAlertService.swift
|
UTF-8
| 1,646
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import RxSwift
import RxCocoa
import CoinKit
class CoinPriceAlertService {
private let priceAlertManager: IPriceAlertManager
private let localStorage: ILocalStorage
private let disposeBag = DisposeBag()
let coinType: CoinType
let coinTitle: String
private let priceAlertRelay = PublishRelay<PriceAlert?>()
var priceAlert: PriceAlert? {
didSet {
priceAlertRelay.accept(priceAlert)
}
}
init(priceAlertManager: IPriceAlertManager, localStorage: ILocalStorage, coinType: CoinType, coinTitle: String) {
self.priceAlertManager = priceAlertManager
self.localStorage = localStorage
self.coinType = coinType
self.coinTitle = coinTitle
priceAlertManager.updateObservable
.observeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated))
.subscribe(onNext: { [weak self] in self?.sync(priceAlerts: $0) })
.disposed(by: disposeBag)
priceAlert = priceAlertManager.priceAlert(coinType: coinType, title: coinTitle)
}
private func sync(priceAlerts: [PriceAlert]) {
priceAlert = priceAlerts.first {
$0.coinType == coinType
}
}
}
extension CoinPriceAlertService {
var alertsOn: Bool {
localStorage.pushNotificationsOn
}
func priceAlert(coin: Coin?) -> PriceAlert? {
guard let coin = coin else {
return nil
}
return priceAlertManager.priceAlert(coinType: coin.type, title: coin.title)
}
var priceAlertObservable: Observable<PriceAlert?> {
priceAlertRelay.asObservable()
}
}
| true
|
798428dda729270b2996aa6d6c0b9c254a403aec
|
Swift
|
neonichu/swift-funtime
|
/code/Swizzle.swift
|
UTF-8
| 483
| 2.6875
| 3
|
[] |
no_license
|
#!/usr/bin/xcrun swift
import Foundation
import ObjectiveC.runtime
extension NSString {
func swizzle_description() -> NSString {
return "💥"
}
}
var myString = "foobar" as NSString
print(myString.description)
var originalMethod = class_getInstanceMethod(NSString.self, "description")
var swizzledMethod = class_getInstanceMethod(NSString.self, "swizzle_description")
method_exchangeImplementations(originalMethod, swizzledMethod)
print(myString.description)
| true
|
1fda96ca1a385d108d8fcf0519a4677889daf6d8
|
Swift
|
Hudihka/all_support_class
|
/кривая Безье/Mask/Mask/MaskView.swift
|
UTF-8
| 1,133
| 2.65625
| 3
|
[] |
no_license
|
//
// MaskView.swift
// Mask
//
// Created by Username on 26.01.2020.
// Copyright © 2020 itMegastar. All rights reserved.
//
import Foundation
import UIKit
class MaskView: UIView {
private let rootLayer = CALayer()
private let maskLayer = CALayer()
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
commonInit()
}
private func commonInit() {
if let maskingImage = UIImage(named: "PolygonPDF"){
let maskingLayer = CALayer()
maskingLayer.frame = self.bounds
maskingLayer.contents = maskingImage.cgImage
self.layer.contents = UIImage(named: "oboi-priroda")?.cgImage
self.layer.mask = maskingLayer
}
self.layer.masksToBounds = false
}
private func addShadow(){
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 1
self.layer.shadowOffset = .zero
self.layer.shadowRadius = 10
}
}
| true
|
95967ea0a6f4b12dd5422003c3462fa3e6e1138f
|
Swift
|
cengizhan-ozcan/flights
|
/Flights/Core/Service/Http.swift
|
UTF-8
| 366
| 2.796875
| 3
|
[] |
no_license
|
//
// Http.swift
// Flights
//
// Created by Cengizhan Özcan on 9/16/20.
// Copyright © 2020 Cengizhan Özcan. All rights reserved.
//
import Foundation
struct Http {
var path: String
var method: HttpMethod
var body: Data?
}
enum HttpMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
| true
|
3599adb3a29a1ec670b877c1fb66b2ebabdbd749
|
Swift
|
xtremeactor/InstaChat
|
/InstaChat/ICSignupViewController.swift
|
UTF-8
| 3,748
| 2.71875
| 3
|
[] |
no_license
|
//
// ICSignupViewController.swift
// InstaChat
//
// Created by Benjamin Tan on 11/20/16.
// Copyright © 2016 TheAustinSpace. All rights reserved.
//
import UIKit
import FirebaseAuth
import AlertHelperKit
import SwiftyUserDefaults
import ObjectMapper
class ICSignupViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextfield: UITextField!
@IBOutlet weak var passwordTextfield: UITextField!
@IBOutlet weak var emailTextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.usernameTextfield.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (ICHelper.checkingUsername(string: string)){
return true
} else{
return false
}
}
@IBAction func signupPressed(_ sender: Any) {
let email = emailTextfield.text!
let password = passwordTextfield.text!
let username = usernameTextfield.text!
if (ICHelper.verifyEmail(email: email) && ICHelper.verifyPassword(password: password)){
// Task 4: Submit to firebase
ICUserService.sharedInstance.registerUser(email: email, password: password, username: username, completion: { (error, completed) in
if ((error) != nil){
AlertHelperKit().showAlert(self, title: "Error", message: "\(error)", button: "Ok")
}
if (completed == true){
print("User was created successfully")
// Add them as a user in Firebase Database
ICUserService.sharedInstance.addUserToFirebase(email: email, username: username, completion: { (error, completed) in
if error != nil {
AlertHelperKit().showAlert(self, title: "Error adding to Firebase", message: "\(error)", button: "Ok")
} else {
// Authentication Service to third party APIs - Yelp, etc
ICAuthenticationService.sharedInstance.authenticateYelp(completion: { (error, isCompleted) in
if ((error) != nil){
AlertHelperKit().showAlert(self, title: "Error", message: "\(error)", button: "Ok")
}
else if (isCompleted == true){
print("its done")
if (Defaults[.access_token]?.isEmpty)!{
AlertHelperKit().showAlert(self, title: "Error", message: "error", button: "Ok")
}
else{
// Task 6: Create a new VC that allows for us to push once the user has successfully created an account
self.performSegue(withIdentifier: "welcomeSegue", sender: nil)
}
}
else{
AlertHelperKit().showAlert(self, title: "Error", message: "\(error)", button: "Ok")
}
})
}
})
}
})
}
else {
print ("this fails")
}
}
}
| true
|
2db5684563a43501f9ea2cc8ef7f09e277e482bc
|
Swift
|
Hyeongyu-IM/WeatherApp-Clone
|
/BasicWeatherApp iOS/Protocol/LocationListDelegate.swift
|
UTF-8
| 312
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// LocationListDelegate.swift
// BasicWeatherApp iOS
//
// Created by 임현규 on 2020/12/31.
//
import UIKit
protocol LocationListViewDelegate: AnyObject {
func userDidSelectLocation(at index: Int,image: UIColor)
func userAdd(newLocation: Location)
func userDeleteLocation(at index: Int)
}
| true
|
1468ee419cc4555d9e17cfa9117bfb81312395fd
|
Swift
|
rbkmoney/payments-ios-sdk
|
/RBKmoneyPaymentsSDK/Sources/UI/Scenarios/Payment/Modules/PaymentProgress/URLRequestFactory/3DS/ThreeDSURLRequestFactory.swift
|
UTF-8
| 3,984
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2019 RBKmoney
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
final class ThreeDSURLRequestFactory {
// MARK: - Dependencies
lazy var terminationURL: URL = deferred()
// MARK: - Internal
func urlRequest(for browserRequest: BrowserRequestDTO) -> URLRequest? {
let terminationURI = terminationURLString
let escapedTerminationURI = terminationURI.escaped
switch browserRequest {
case let .get(data):
let urlString = Self.processedString(from: data.uriTemplate, terminationURI: escapedTerminationURI)
guard let url = URL(string: urlString) else {
return nil
}
var urlRequest = URLRequest(url: url, timeoutInterval: 15)
urlRequest.httpMethod = "GET"
return urlRequest
case let .post(data):
let urlString = Self.processedString(from: data.uriTemplate, terminationURI: escapedTerminationURI)
guard let url = URL(string: urlString) else {
return nil
}
let queryString = Self.queryString(
for: data.form.map { ($0.key, Self.processedString(from: $0.template, terminationURI: terminationURI)) }
)
var urlRequest = URLRequest(url: url, timeoutInterval: 15)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = queryString.data(using: .utf8)
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
return urlRequest
}
}
var terminationURLString: String {
return terminationURL.absoluteString
}
// MARK: - Private
private static let templateProcessingItems: [(prefix: String, includePrefix: Bool, includeName: Bool)] = [
// {name} -> value
("", false, false),
// {+name} -> value
("+", false, false),
// {#name} -> #value
("#", true, false),
// {.name} -> .value
(".", true, false),
// {/name} -> /value
("/", true, false),
// {?name} -> ?name=value
("?", true, true),
// {&name} -> &name=value
("&", true, true),
// {;name} -> ;name=value
(";", true, true)
]
private static func processedString(from template: String, terminationURI: String) -> String {
return templateProcessingItems.reduce(template) {
$0.replacingOccurrences(
of: "{\($1.prefix)termination_uri}",
with: "\($1.includePrefix ? $1.prefix : "")\($1.includeName ? "termination_uri=" : "")\(terminationURI)"
)
}
}
private static func queryString(for parameters: [(String, String)]) -> String {
return parameters.map({ "\($0.0.escaped)=\($0.1.escaped)" }).joined(separator: "&")
}
}
private extension String {
var escaped: String {
return addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? self
}
}
private extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
| true
|
16a2e013235aaf52dd5d4e5de1831fdd565e9b83
|
Swift
|
luoshiqing/LuckyDraw
|
/LuckyDraw/LuckyView.swift
|
UTF-8
| 3,821
| 2.765625
| 3
|
[] |
no_license
|
//
// LuckyView.swift
// LuckyDraw
//
// Created by sqluo on 2016/11/21.
// Copyright © 2016年 sqluo. All rights reserved.
//
import UIKit
class LuckyView: UIView {
//奖区
fileprivate var itemArray = [String]()
//frame
fileprivate var myFrame: CGRect!
//外圆半径
fileprivate var radiu: CGFloat!
//线条的宽度
fileprivate let lineWidth: CGFloat = 1
//外圆中心点
fileprivate var arcCenter: CGPoint!
//每个item的弧度
fileprivate var oneRadian: CGFloat!
init(frame: CGRect,items: [String]) {
super.init(frame: frame)
self.backgroundColor = UIColor.yellow
self.itemArray = items
self.myFrame = frame
self.radiu = (frame.width - lineWidth * 2) / 2
self.arcCenter = CGPoint(x: frame.width / 2, y: frame.height / 2)
//每个的弧度
self.oneRadian = CGFloat(M_PI) * 2 / CGFloat(itemArray.count)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let color = UIColor.red
color.set()
let path = UIBezierPath(arcCenter: arcCenter, radius: radiu, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
path.lineWidth = lineWidth
path.stroke()
for i in 0..<self.itemArray.count {
let linePath = UIBezierPath()
linePath.lineWidth = lineWidth
linePath.lineCapStyle = .round
linePath.lineJoinStyle = .round
linePath.move(to: self.arcCenter)
//第一个从y轴上画,x = 0
/*
if i == 0{ //区分下颜色,看看那个是第一个
let color = UIColor.red
color.set()
}else{
let color = UIColor.blue
color.set()
}
*/
let x = radiu + (sin(CGFloat(i) * oneRadian) * radiu) + lineWidth
let y = radiu - (cos(CGFloat(i) * oneRadian) * radiu) + lineWidth
let toPoint = CGPoint(x: x, y: y)
linePath.addLine(to: toPoint)
linePath.stroke()
//label
//label的中心,应该是 oneRadian 的 一半跟 radiu 的位置
let labelRadiu = radiu / 2
let labelOneRadian = oneRadian / 2
let hudu = CGFloat(i) * oneRadian + labelOneRadian
let labelX: CGFloat = radiu + (sin(hudu) * labelRadiu) + lineWidth
let labelY = radiu - (cos(hudu) * labelRadiu) + lineWidth
let labelCent = CGPoint(x: labelX, y: labelY)
// let labelW = radiu / 5 * 3
let labelW: CGFloat = radiu
let labelH: CGFloat = 18
let label = UILabel(frame: CGRect(x: 0, y: 0, width: labelW, height: labelH))
label.center = labelCent
label.backgroundColor = UIColor.clear
label.font = UIFont.systemFont(ofSize: 11)
label.text = self.itemArray[i]
label.textAlignment = .center
label.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2) + hudu + CGFloat(M_PI))
// label.transform = CGAffineTransform(rotationAngle: hudu)
self.addSubview(label)
}
}
}
| true
|
fd9f21dac3d8e3517ac0fd2638dfd0f4327b83c3
|
Swift
|
LeiChenML/YunToDo
|
/YunToDo/ServerHelper.swift
|
UTF-8
| 5,650
| 2.703125
| 3
|
[] |
no_license
|
//
// MySQLOps.swift
// MinorDianping
//
// Created by Apple on 2017/6/6.
// Copyright © 2017年 NJU.EE. All rights reserved.
//
import Foundation
public class ServerHelper{
let URL_REGISTER_USERS:String = "http://104.199.144.39/YunToDo/registerUser.php"
let URL_FETCH_USERS:String = "http://104.199.144.39/YunToDo/selectUser.php"
let URL_UPDATE_USERS:String = "http://104.199.144.39/YunToDo/updateUser.php"
func registerNewUser(username: String, password: String, handler: @escaping (_ success: Bool)-> ()){
var request = URLRequest(url: URL(string: URL_REGISTER_USERS)!)
request.httpMethod = "POST"
let postString = "username=\(username)&password=\(password)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request){
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
return
}
//print("response = \(String(describing: response))")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
do{
let responseJSON = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
handler(responseJSON["status"]! as! String != "400")
}
catch{
print(error)
}
print("REGISTER responseString = \(String(describing: responseString))")
}
task.resume();
}
func fetchUserInfoFromMySQL(username:String, attributeName:String, handler: @escaping (_ attributeValue: String?)-> ()){
var request = URLRequest(url: URL(string: URL_FETCH_USERS)!)
request.httpMethod = "POST"
let getString = "username=\(username)&attributeName=\(attributeName)"
request.httpBody = getString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request){
data, response, error in
//exiting if there is some error
if error != nil{
print("error is \(String(describing: error))")
return;
}
// parse the response
do{
// convert response to NSDictionary
let userJSON = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
handler(userJSON[attributeName] as? String)
}catch{
print(error)
}
}
task.resume()
}
func updateUserInfoToMySQL(username: String, attributeName: String, attributeValue: String, handler: @escaping (_ success: Bool)-> ()){
var request = URLRequest(url: URL(string: URL_UPDATE_USERS)!)
request.httpMethod = "POST"
let getString = "username=\(username)&attributeName=\(attributeName)&attributeValue=\(attributeValue)"
request.httpBody = getString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request){
data, response, error in
if error != nil{
print("error is \(String(describing: error))")
return;
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
do{
let responseJSON = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
handler(responseJSON["status"]! as! String != "400")
}
catch{
print(error)
}
print("UPDATE responseString = \(String(describing: responseString))")
}
task.resume()
}
// public func validatePassword(username: String, password: String, handler: @escaping (_ success: Bool)-> ()){
// let serverHelper = ServerHelper()
// serverHelper.fetchUserInfoFromMySQL(username: username, attributeName: "password"){
// pass in
// let passToString = pass! as NSString
// let subPass = passToString.substring(to: 40)
// let inputPassToSha1 = password.sha1() as NSString
// let subInputPassToSha1 = inputPassToSha1.substring(to: 40)
//
// handler(subPass == subInputPassToSha1)
// }
// }
public func validatePassword(username: String, password: String, handler: @escaping (_ success: Bool)-> ()){
let mySQLOps = ServerHelper()
mySQLOps.fetchUserInfoFromMySQL(username: username, attributeName: "password"){
pass in
if let passUnWarpped = pass{
let passToString = passUnWarpped as NSString
let subPass = passToString.substring(to: 40)
let inputPassToSha1 = password.sha1() as NSString
let subInputPassToSha1 = inputPassToSha1.substring(to: 40)
handler(subPass == subInputPassToSha1)
}
else{
print("user \(username) Yeah!")
handler(false)
}
}
}
}
extension String {
func sha1() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA1($0, CC_LONG(data.count), &digest)
}
//return Data(bytes: digest).base64EncodedString()
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joined()
}
}
| true
|
da4116273bd07c4611bd1d1c481e14c5911731cc
|
Swift
|
ffedukk/withoutStoryboard
|
/withoutStoryboard/SectionModelList.swift
|
UTF-8
| 1,196
| 3.015625
| 3
|
[] |
no_license
|
//
// SectionModelList.swift
// withoutStoryboard
//
// Created by 18592232 on 22.07.2020.
// Copyright © 2020 18592232. All rights reserved.
//
import Foundation
struct SectionsList {
var listOfSections : [TextModelList] = []
init(){
listOfSections = []
}
init(numberOfSections: Int, with rows: Int){
for _ in 0..<numberOfSections {
let section = TextModelList(numberOfModels: rows)
listOfSections.append(section)
}
}
mutating func append(_ section: TextModelList) {
listOfSections.append(section)
}
func retrieveSection(with index: Int) -> TextModelList {
return listOfSections[index]
}
func numberOfSections() -> Int {
return listOfSections.count
}
mutating func showingEnabled(){
listOfSections = listOfSections.map { section -> TextModelList in
var switchSection = section
switchSection.showingEnabled()
return switchSection
}
}
mutating func updateList(with model: TextModel, section: Int, row: Int) {
listOfSections[section].listOfModels[row] = model
}
}
| true
|
9a994f19b907036daaffe52fc9521ec83fc773c0
|
Swift
|
RCaroff/list
|
/List/Services/Storage.swift
|
UTF-8
| 1,079
| 3.21875
| 3
|
[] |
no_license
|
//
// Storage.swift
// List
//
// Created by Rémi Caroff on 21/01/2019.
// Copyright © 2019 Rémi Caroff. All rights reserved.
//
import Foundation
protocol Storage: class {
func get<T: Decodable>(key: String) throws -> T
func delete(key: String) throws
func set<T: Encodable>(object: T, forKey key: String) throws
}
enum StorageError: Error {
case noDataForKey(key: String)
case unknown
}
class UserDefaultsStorage: Storage {
private let userDefaults = UserDefaults(suiteName: "group.rcaroff.list") ?? UserDefaults.standard
func get<T: Decodable>(key: String) throws -> T {
guard let object = userDefaults.data(forKey: key) else {
throw StorageError.noDataForKey(key: key)
}
return try JSONDecoder().decode(T.self, from: object)
}
func delete(key: String) throws {
userDefaults.set(nil, forKey: key)
userDefaults.synchronize()
}
func set<T: Encodable>(object: T, forKey key: String) throws {
let data = try JSONEncoder().encode(object)
userDefaults.set(data, forKey: key)
userDefaults.synchronize()
}
}
| true
|
84214c7d0f6075f81a8f145200918b4bb05f7445
|
Swift
|
raaziqmasud/Mobile-Lab-SP20
|
/VisualizerHW/VisualizerHW/RaazsVisualizer.swift
|
UTF-8
| 1,639
| 2.828125
| 3
|
[] |
no_license
|
//
// RaazsVisualizer.swift
// VisualizerHW
//
// Created by Raaziq Brown on 3/3/20.
// Copyright © 2020 Raaziq Brown. All rights reserved.
//
import SwiftUI
struct RaazsVisualizer: View {
@Binding var signal: Signal
@Binding var viz: Viz
var body: some View {
ZStack{
HStack{
VStack{
RoundedRectangle(cornerRadius: CGFloat(10))
.fill(Color.black)
.frame(width: CGFloat(50), height:CGFloat(50))
.rotationEffect(self.viz.boxOneOpac ? .degrees(360) : .degrees(0))
.opacity(self.viz.boxOneOpac ? 2 : 0.1)
}
VStack{
RoundedRectangle(cornerRadius: 10)
.fill(Color.yellow)
.frame(width: 50, height:50)
.opacity(self.signal.toggleValue2 ? 2 : 1.0)
}
}
if self.signal.toggleValue == true{
ForEach(0..<self.signal.intValue, id: \.self) { _ in
Circle()
.fill(Color.blue)
.frame(width: 100, height: 100)
}
}
}
}
}
//struct RaazsVisualizer_Previews: PreviewProvider {
// static var previews: some View {
// RaazsVisualizer()
// }
//}
| true
|
625ff78ac2b4500625764dbec68893f7149558d7
|
Swift
|
danackerman/fjs
|
/fjs/fjsTests/Mocks/MockCLLocationManager.swift
|
UTF-8
| 684
| 2.671875
| 3
|
[] |
no_license
|
//
// MockCLLocationManager.swift
// fjsTests
//
// Created by Dan Ackerman on 9/6/21.
//
import Foundation
import CoreLocation
class MockCLLocationManager: CLLocationManager {
var mockLocation: CLLocation = CLLocation(latitude: 0, longitude: 0)
override var location: CLLocation? {
return mockLocation
}
override init() {
super.init()
}
override func requestLocation() {
self.delegate?.locationManager?(self, didUpdateLocations: [mockLocation])
}
func getAuthorizationStatus() -> CLAuthorizationStatus {
return .authorizedWhenInUse
}
func isLocationServicesEnabled() -> Bool {
return true
}
}
| true
|
1c5bf35b3d56059d367b3ad5295d2b1d8fb122fc
|
Swift
|
arr00/InteractiveVCBuilder
|
/InteractiveVCBuilder.playground/Contents.swift
|
UTF-8
| 25,372
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
typealias UIButtonTargetClosure = (UIButton) -> ()
public class InteractiveVCBlocks {
public var actionsText:String? // url will be rootUrl + /actionsText
public var viewsText:String? // url will be rootUrl + /viewsText
private var rootUrl:String?
public init(rootUrl:String) {
self.rootUrl = rootUrl
}
public func buildVC() throws -> InteractiveVC {
if actionsText == nil || viewsText == nil {
throw VCBuildingError.ConstuctionFileEmpty
}
do {
let vc = try VCBuilder.buildVC(text: self.viewsText!)
let actionRunner = ActionRunner()
try actionRunner.runActionsOn(vc: vc, text: actionsText!)
return vc
}
}
public func fetchData(closure:@escaping (Bool) -> ()) {
if rootUrl != nil {
let urlViews = rootUrl! + "/viewsText.txt"
let urlActions = rootUrl! + "/actionsText.txt"
guard let url1 = URL(string: urlViews) else {return}
guard let url2 = URL(string: urlActions) else {return}
do {
let text = try String(contentsOf: url1)
let text2 = try String(contentsOf: url2)
viewsText = text
actionsText = text2
closure(true)
}
catch {
print("Error fetching text. Internet connection probably broken or invalid url")
closure(false)
}
}
else {
closure(false)
}
// Fetch data here
}
}
class ClosureWrapper: NSObject {
let closure: UIButtonTargetClosure
init(_ closure: @escaping UIButtonTargetClosure) {
self.closure = closure
}
}
extension UIButton {
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
}
private var targetClosure: UIButtonTargetClosure? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper else { return nil }
return closureWrapper.closure
}
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func addTargetClosure(closure: @escaping UIButtonTargetClosure) {
targetClosure = closure
addTarget(self, action: #selector(UIButton.closureAction), for: .touchUpInside)
}
@objc func closureAction() {
guard let targetClosure = targetClosure else { return }
targetClosure(self)
}
}
// This is esentially a web browser built in native swift and UIKIt
//Input in the following format:
// * Each line is an indevidual element
// * Each line contains first a class name (choose from the valid classes), and a dictionary containing item specifications
// * All coordinates are given in percentages relative to the rendered page and anchored at the element's center
// * Manditory specifactions are specified for each element in the documentation. Adherance to these is manditory—if not done correctly, an error will be thrown, and rendering will not complete.
//Actions
// * actions are based on tags of items
// * actions are defined in a seperate file, and are based on tags
// * actions may be saved as variables and passed into other actions only AFTER they are defined.
// * each action occupies one line of the file
public class InteractiveVC:UIViewController {
public var path:String?
}
public class VCBuilder {
public static let validClasses = ["button","imageview","textlabel","slider","experation"]
public static func buildVC(text:String) throws -> InteractiveVC {
let viewController = InteractiveVC()
viewController.view.backgroundColor = UIColor.white
var items = text.components(separatedBy: "\n")
// CHECK FOR EXPERATION
if items.contains(where: { (str) -> Bool in
return str.lowercased().hasPrefix("experation")
}) {
let indexOfExperation = items.index { (str) -> Bool in
return str.lowercased().hasPrefix("experation")
}
let experationInfo = items[indexOfExperation!]
let values = experationInfo.components(separatedBy: "=")
let epochExp = TimeInterval(values[1])!
if(Date().timeIntervalSince1970 > epochExp) {
// EXPIRED
let expiredVC = UIViewController()
expiredVC.title = "EXPIRED"
let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
label.text = "EXPIRED"
label.font = UIFont.systemFont(ofSize: 20)
expiredVC.view.addSubview(label)
expiredVC.view.backgroundColor = UIColor.white
return expiredVC as! InteractiveVC
}
else {
// NOT EXPIRED
items.remove(at: indexOfExperation!)
}
}
for item in items {
let values = item.components(separatedBy: "=")
var standardized = [String]()
for value in values {
standardized.append(value.trimmingCharacters(in: .whitespaces).lowercased())
}
// Check first value for class
if VCBuilder.validClasses.contains(standardized[0]) {
let input = values[1]
// extract dictionary from standardized[1]
guard let dictionary = try? input.buildDictionary() else {
throw VCBuildingError.InvalidDictionaryFormat(message: "Issue building dictionary from input")
}
// Extract next four values for rect data. Always the same
if dictionary.count < 5 {
throw VCBuildingError.MissingEntries
}
var x:CGFloat = 0.0
if dictionary["x"]!.contains("%") {
x = percentToPixelsHorizontal(percent: dictionary["x"]!)
}
else {
x = dictionary["x"]!.CGFloatValue() ?? 0
}
var y:CGFloat = 0.0
if dictionary["y"]!.contains("%") {
y = percentToPixelsVertical(percent: dictionary["y"]!)
}
else {
y = dictionary["y"]!.CGFloatValue() ?? 0
}
var width:CGFloat = 0.0
if dictionary["width"]!.contains("%") {
width = percentToPixelsHorizontal(percent: dictionary["width"]!)
}
else {
width = dictionary["width"]!.CGFloatValue() ?? 0
}
var height:CGFloat = 0.0
if dictionary["height"]!.contains("%") {
height = percentToPixelsVertical(percent: dictionary["height"]!)
}
else {
height = dictionary["height"]!.CGFloatValue() ?? 0
}
let rect = CGRect(x: x, y: y, width: width, height: height)
switch (standardized[0]) {
case "button":
do {
let button = try buildButtonWithData(rect: rect, data: dictionary)
viewController.view.addSubview(button)
print("Added button succesfully")
}
catch {
print("error building button")
}
case "imageview":
let imageView = buildImageViewWithData(rect: rect, data:dictionary)
viewController.view.addSubview(imageView)
case "textlabel":
let label = UILabel(frame: rect)
viewController.view.addSubview(label)
case "slider":
let slider = UISlider(frame: rect)
viewController.view.addSubview(slider)
default:
print("Add nothing")
}
}
else {
print("Invalid class")
if (standardized[0] != "") {
throw VCBuildingError.InvalidClass
}
}
}
return viewController
}
public static func percentToPixelsVertical(percent:String) -> CGFloat {
let changed = percent.replacingOccurrences(of: "%", with: "")
let percentValue = CGFloat(Double(changed)!)/100
let temp = UIViewController()
//TODO: Get actual height
return 660 * percentValue
}
public static func percentToPixelsHorizontal(percent:String) -> CGFloat {
let changed = percent.replacingOccurrences(of: "%", with: "")
let percentValue = CGFloat(Double(changed)!)/100
let temp = UIViewController()
//TODO: Get actual width
return 375 * percentValue
}
// MARK - Element Creation
private static func buildTextLabelWithData(rect: CGRect, data: [String:String]) throws -> UILabel {
// Data
// required:
// * text
// optional
// * textcolor
// * backgroundcolor
// * textcentering
// * font
return UILabel()
}
// Required:
// * imageUrl
private static func buildImageViewWithData(rect:CGRect, data:[String:String]) -> UIImageView {
let imageView = UIImageView(frame: rect)
let urlString = data["imageUrl"]!
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
print("Data is nill")
return
}
let image = UIImage(data: data)!
DispatchQueue.main.async {
imageView.image = image
}
}
task.resume()
return imageView
}
private static func buildButtonWithData(rect:CGRect, data:[String:String]) throws -> UIButton {
// Data
// required:
// * color
// * tag
// optional:
// * titleTextColor
// * title
/*var standardized = [String]()
for dataPoint in data {
standardized.append(dataPoint.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: .newlines))
}*/
if(data.count < 7) {
throw ButtonBuildingError.MissingEntries
}
let button = UIButton(frame: rect)
print(data["title"]!)
button.backgroundColor = data["color"]!.colorValue() ?? .clear
button.tag = Int(data["tag"]!) ?? -1
// Set optional values
if data.keys.contains("titleTextColor") {
button.setTitleColor(data["titleTextColor"]!.colorValue() ?? .black, for: .normal)
}
if data.keys.contains("title") {
button.setTitle(data["title"]!, for: .normal)
}
return button
}
}
public class ActionRunner {
private var processedActions = [Int:() -> ()]()
public static let validActions = ["moveAnimation","opacityAnimation","jointAction","removeAction","buttonTriggerAction","rotateAnimation","showViewController","dismissViewController"]
public func prepareToRunActionsOn(vc:InteractiveVC,text:String) throws {
}
public func runActionsOn(vc:InteractiveVC,text:String) throws {
let actions = text.components(separatedBy: "\n")
// Type of actions
// * animation
// ** specify tag, destination, duration, curve
// All actions MUST specify an animationTag
// All actions have an optional onCompletion tag
// In general, animations are run asyncrously
for action in actions {
let value = action.components(separatedBy: "=")
if ActionRunner.validActions.contains(value[0]) {
let input = value[1]
guard let dictionary = try? input.buildDictionary() else {
throw VCBuildingError.InvalidDictionaryFormat(message: "Issue building dictionary from input")
}
print(value[0])
switch(value[0]) {
case "moveAnimation":
let action = buildMoveAnimationWithData(data:dictionary,vc:vc)
processedActions[Int(dictionary["actionTag"]!)!] = action
case "rotateAnimation":
print("Building rotation animation")
let action = buildRotateAnimationWithData(data: dictionary, vc: vc)
processedActions[Int(dictionary["actionTag"]!)!] = action
case "opacityAnimation":
let action = buildOpacityAnimationWithData(data:dictionary,vc:vc)
processedActions[Int(dictionary["actionTag"]!)!] = action
case "jointAction":
do {
let action = try buildJointAction(data: dictionary)
processedActions[Int(dictionary["actionTag"]!)!] = action
}
catch {
print("error building joint action")
}
case "removeAction":
do {
let action = try buildRemoveAction(data:dictionary,vc:vc)
processedActions[Int(dictionary["actionTag"]!)!] = action
}
catch {
print("Error building remove action")
}
case "buttonTriggerAction":
buildButtonTriggerAction(data:dictionary,vc:vc)
//Returns nil since it is just tethering an existing action to a button
case "showViewController":
do {
let action = try buildShowViewControllerAction(data: dictionary, vc: vc)
processedActions[Int(dictionary["actionTag"]!)!] = action
}
catch {
print("error building joint action")
}
case "dismissViewController":
let action = {vc.dismiss(animated: true, completion: nil)}
processedActions[Int(dictionary["actionTag"]!)!] = action
default:
print("Invalid action")
}
}
}
print("running action")
processedActions[1]!()
}
// MARK - ACTION CREATION
// * actionTag
// * elementTag
// * duration
// * toX
// * toY
// * optional onCompletion
private func buildMoveAnimationWithData(data:[String:String],vc:UIViewController) -> (() -> ()) {
let animation = {
let itemOfInterest = vc.view.viewWithTag(Int(data["elementTag"]!)!)!
UIView.animate(withDuration: Double(data["duration"]!)!, delay: 0, options: [UIView.AnimationOptions.curveLinear], animations: {
var x:CGFloat = 0.0
if data["toX"]!.contains("%") {
x = VCBuilder.percentToPixelsHorizontal(percent: data["toX"]!)
} else {
x = CGFloat(Double(data["toX"]!)!)
}
var y:CGFloat = 0.0
if data["toY"]!.contains("%") {
y = VCBuilder.percentToPixelsVertical(percent: data["toY"]!)
}
else {
y = CGFloat(Double(data["toY"]!)!)
}
itemOfInterest.center = CGPoint(x:x, y: y)
}, completion: { (success) in
if(data["onCompletion"] != nil) {
self.processedActions[Int(data["onCompletion"]!)!]!()
}
})
/*
UIView.animate(withDuration: Double(data["duration"]!)!, animations: {
itemOfInterest.center = CGPoint(x: Double(data["toX"]!)!, y: Double(data["toY"]!)!)
}, completion: { (success) in
if(data["onCompletion"] != nil) {
self.processedActions[Int(data["onCompletion"]!)!]!()
}
})*/
}
return animation
}
// Require:
// * actionTag
// * elementTag
// * duration
// * angle in radians
private func buildRotateAnimationWithData(data:[String:String],vc:UIViewController) -> (() -> ()) {
let animation = {
let itemOfInterest = vc.view.viewWithTag(Int(data["elementTag"]!)!)!
UIView.animate(withDuration: Double(data["duration"]!)!, animations: {
itemOfInterest.transform = CGAffineTransform(rotationAngle: CGFloat(Double(data["angle"]!)!))
}, completion: { (success) in
if(data["onCompletion"] != nil) {
self.processedActions[Int(data["onCompletion"]!)!]!()
}
})
}
return animation
}
// Require:
// * actionTag
// * elementTag (must be a button)
// * targetActionTag
private func buildButtonTriggerAction(data:[String:String],vc:UIViewController) {
let button = vc.view.viewWithTag(Int(data["elementTag"]!)!) as! UIButton
button.addTargetClosure(closure: { (button) in
print("Running action")
self.processedActions[Int(data["targetActionTag"]!)!]!()
})
}
// Require:
// * actionTag
// * elementTag
// * targetOpacity
// * duration
// Optional:
// * onCompletion
private func buildOpacityAnimationWithData(data:[String:String],vc:UIViewController) -> () -> () {
let animation = {
let element = vc.view.viewWithTag(Int(data["elementTag"]!)!)!
UIView.animate(withDuration: Double(data["duration"]!)!, animations: {
element.alpha = NumberFormatter().number(from: data["targetOpacity"]!) as! CGFloat
}, completion: { (success) in
if(data.keys.contains("onCompletion")) {
self.processedActions[Int(data["onCompletion"]!)!]!()
}
})
}
return animation
}
// Require:
// * tags (array of tags to run asyncronously) in the format [12,1,5,1,51]
// * actionTag
// * NO individual on completion. Must use on completion of child actions
private func buildJointAction(data:[String:String]) throws -> () -> () {
do {
let arrayOfTags = try data["tags"]!.buildArray()
let animation = {
for tag in arrayOfTags {
let action = self.processedActions[Int(tag)!]!
action()
}
}
return animation
}
catch {
throw ActionBuildingError.ErrorBuildingAction
}
}
// Require:
// * actionTag
// * url (root url of dvc to show)
private func buildShowViewControllerAction(data:[String:String], vc: InteractiveVC) throws -> () -> () {
print("Building show view controller")
print(data)
let url = data["url"]!
var thisVc:InteractiveVC?
let vcBlock = InteractiveVCBlocks(rootUrl: url)
vcBlock.fetchData { (success) in
if success {
do {
thisVc = try vcBlock.buildVC()
}
catch {
print("Error building vc")
}
}
else {
print("Error fetching")
}
}
if thisVc == nil {
print("Error building")
// Incorrect error message
throw VCBuildingError.MissingEntries
}
else {
print("All good proceed")
}
let action = {
vc.present(thisVc!, animated: true)
}
return action
}
private func buildRemoveAction(data:[String:String],vc:UIViewController) throws -> () -> () {
guard let itemOfInterest = vc.view.viewWithTag(Int(data["elementTag"]!)!) else {
throw ActionBuildingError.ErrorBuildingAction
}
let action = {
itemOfInterest.removeFromSuperview()
}
return action
}
}
public enum VCBuildingError:Error {
case InvalidClass
case MissingEntries
case InvalidDictionaryFormat(message:String?)
case ConstuctionFileEmpty
}
public enum ButtonBuildingError:Error {
case MissingEntries
}
public enum DictionaryBuildingError:Error {
case InvalidFormat
case EmptyString
}
public enum ArrayBuildingError:Error {
case InvalidFormat
case EmptyString
}
public enum ActionBuildingError:Error {
case ErrorBuildingAction
}
// MARK - Extensions
extension String {
func CGFloatValue() -> CGFloat? {
guard let doubleValue = Double(self) else {
return nil
}
return CGFloat(doubleValue)
}
func colorValue() -> UIColor? {
switch self.lowercased() {
case "red":
return UIColor.red
case "blue":
return UIColor.blue
case "green":
return UIColor.green
case "orange":
return UIColor.orange
case "purple":
return UIColor.purple
case "clear":
return UIColor.clear
default:
return nil
}
}
public func buildDictionary() throws -> [String:String] {
if self.isEmpty {
throw DictionaryBuildingError.EmptyString
}
if self.first! != "[" || self.last! != "]" {
throw DictionaryBuildingError.InvalidFormat
}
var contentString = self
contentString.removeLast()
contentString.removeFirst()
var result = [String:String]()
let dataEntries = contentString.components(separatedBy: ",")
for dataEntry in dataEntries {
let keyAndValue = dataEntry.components(separatedBy: ":")
//Value is the rest
var value = keyAndValue[1]
if keyAndValue.count > 2 {
for i in 2..<keyAndValue.count {
value += ":"
value += keyAndValue[i]
}
}
result[keyAndValue[0]] = value
}
return result
}
public func buildArray() throws -> [String] {
if self.isEmpty {
throw ArrayBuildingError.EmptyString
}
if self.first! != "[" || self.last! != "]" {
throw DictionaryBuildingError.InvalidFormat
}
var contentString = self
contentString.removeLast()
contentString.removeFirst()
let result = contentString.components(separatedBy: "-")
return result
}
}
let testBlock = InteractiveVCBlocks.init(rootUrl: "http://agapps.xyz/dvc/test1")
testBlock.fetchData { (success) in
print(success)
if success {
do {
let vc = try testBlock.buildVC()
PlaygroundPage.current.liveView = vc
}
catch {
print("Error building vc")
}
}
else {
print("Error fetching")
}
}
/*
let url = Bundle.main.url(forResource: "testTxt", withExtension: "txt")!
let actionsUrl = Bundle.main.url(forResource: "actions", withExtension: "txt")!
do {
let text = try String(contentsOf: url)
let actionText = try String(contentsOf: actionsUrl)
let vc = try VCBuilder.buildVC(text: text)
if vc.title != "EXPIRED" {
let actionRunner = ActionRunner()
try actionRunner.runActionsOn(vc: vc, text: actionText)
}
PlaygroundPage.current.liveView = vc
}
catch (let error) {
print("Error, \(error.localizedDescription)")
}*/
| true
|
d7afb8c74569b618c40bb3c741685d14ede151e8
|
Swift
|
jasdehart/SnapCat
|
/SnapCat/Home/PostView.swift
|
UTF-8
| 3,338
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// PostView.swift
// SnapCat
//
// Created by Corey Baker on 7/11/21.
// Copyright © 2021 Network Reconnaissance Lab. All rights reserved.
//
import SwiftUI
import ParseSwift
struct PostView: View {
@ObservedObject var timeLineViewModel: QueryImageViewModel<Post>
@ObservedObject var viewModel = PostViewModel()
@State private var isShowingImagePicker = false
@Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
Form {
Section {
HStack {
Spacer()
Button(action: {
self.isShowingImagePicker = true
}, label: {
if let image = viewModel.image {
Image(uiImage: image)
.resizable()
.frame(width: 200, height: 200, alignment: .center)
.clipShape(Rectangle())
.padding()
} else {
Image(systemName: "camera")
.resizable()
.frame(width: 200, height: 200, alignment: .center)
.clipShape(Rectangle())
.padding()
}
})
.buttonStyle(PlainButtonStyle())
Spacer()
}
TextField("Caption", text: $viewModel.caption)
if let placeMark = viewModel.currentPlacemark,
let name = placeMark.name {
Text(name)
} else {
Text("Location: N/A")
}
}
Section {
Button(action: {
viewModel.requestPermission()
}, label: {
if viewModel.currentPlacemark == nil {
Text("Use Location")
} else {
Text("Remove Location")
}
})
}
}
.navigationBarBackButtonHidden(true)
.navigationTitle(Text("Post"))
.navigationBarItems(leading: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("Cancel")
}), trailing: Button(action: {
viewModel.save { result in
if case .success(let post) = result {
timeLineViewModel.results.insert(post, at: 0)
}
}
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("Done")
}))
.sheet(isPresented: $isShowingImagePicker, onDismiss: {}, content: {
ImagePickerView(image: $viewModel.image)
})
}
}
}
struct PostView_Previews: PreviewProvider {
static var previews: some View {
PostView(timeLineViewModel: .init(query: Post.query()))
}
}
| true
|
025dc3e41768ad239231673a4ba6ca1d34ed5cff
|
Swift
|
yanglei3kyou/Leetcode_trips
|
/LeetCode/LeetCode/L-283.swift
|
UTF-8
| 1,327
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
//
// L-283.swift
// LeetCode
//
// Created by yanglei on 2019/9/28.
// Copyright © 2019 Lyren. All rights reserved.
//
import Foundation
/*
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
*/
// 移动非零数字(后续填零)
/*
func moveZeroes(_ nums: inout [Int]) {
var index: Int = 0
for num in nums {
if num != 0 {
nums[index] = num
index += 1
}
}
for i in index..<nums.count { nums[i] = 0 }
}
*/
// 数组筛选(后续补零)
/*
func moveZeroes(_ nums: inout [Int]) {
let totalCount: Int = nums.count
nums = nums.filter{ $0 != 0 }
let notZeroCount: Int = nums.count
for _ in 0..<(totalCount - notZeroCount) {
nums.append(0)
}
}
*/
// 遍历交换
/*
func moveZeroes(_ nums: inout [Int]) {
var lastNotZeroFoundAt: Int = 0
for (index, item) in nums.enumerated() {
if item != 0 {
let tmp = nums[lastNotZeroFoundAt]
nums[lastNotZeroFoundAt] = item
nums[index] = tmp
lastNotZeroFoundAt += 1
}
}
}
*/
| true
|
dcfe26ea2e57a20ff6958e49739d3dc910017190
|
Swift
|
coalalib/coalaswift
|
/Source/SRTxState.swift
|
UTF-8
| 1,843
| 2.890625
| 3
|
[] |
no_license
|
//
// SRTxState.swift
// Coala
//
// Created by Roman on 03/08/2017.
// Copyright © 2017 NDM Systems. All rights reserved.
//
import Foundation
struct SRTxBlock {
let number: Int
let data: Data
let isMoreComing: Bool
}
final class SRTxState {
let data: Data
let blockSize: Int
private var window: SlidingWindow<Bool>
init(data: Data, windowSize: Int, blockSize: Int) {
self.data = data
self.blockSize = blockSize
let totalBlocks = data.count / blockSize + (data.count % blockSize != 0 ? 1 : 0)
let windowSize = min(windowSize, totalBlocks)
window = SlidingWindow(size: windowSize, offset: -windowSize)
guard windowSize > 0 else { return }
for index in -windowSize ... -1 {
try? window.set(value: true, atIndex: index)
}
}
var isCompleted: Bool {
var lastDeliveredBlock = window.getOffset()
var index = 0
while index < window.size && window.getValue(atWindowIndex: index) == true {
lastDeliveredBlock += 1
index += 1
}
return lastDeliveredBlock * blockSize >= data.count
}
var windowSize: Int {
return window.size
}
func didTransmit(blockNumber: Int) throws {
try window.set(value: true, atIndex: blockNumber)
}
func popBlock() -> SRTxBlock? {
guard window.advance() != nil else {
return nil
}
let blockNumber = window.tail
let rangeStart = blockNumber * blockSize
let rangeEnd = min(rangeStart + blockSize, data.count)
guard rangeStart < rangeEnd else {
return nil
}
let block = data.subdata(in: rangeStart..<rangeEnd)
return SRTxBlock(number: blockNumber, data: block, isMoreComing: rangeEnd != data.count)
}
}
| true
|
aa1f2abe98864805756a94e2f5bd91fa66040997
|
Swift
|
hamza233/ios-assessment
|
/eventy/Controllers/DetailView.swift
|
UTF-8
| 4,008
| 3.078125
| 3
|
[] |
no_license
|
//
// DetailView.swift
// eventy
//
// Created by Hamza Mahmood on 2/4/21.
//
import UIKit
import WebKit
@available(iOS 13.0, *)
class DetailView: UIViewController {
// the variable ev will be sent from the EventListViewController, it will hold the event the user clicked on
var ev: Event!
// list of favorite events to add/remove this event in the list when user taps on tha heart
var favList = [Int]()
let defaults = UserDefaults.standard
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// set the label to show the name of event, it will be displayed as title of the navigation item
let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: 44.0))
label.backgroundColor = .clear
label.numberOfLines = 3
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = .black
label.text = ev.performers?[0].name ?? "No name"
self.navigationItem.titleView = label
// this variable will store the name of heart, it could be filled or empty
var imageName: String = "suit.heart"
// load the favorite events if the "favs" key exists
if let list = defaults.object(forKey: "favs") as? [Int]{
favList = list
if (favList.contains(ev.id)){
// set the image name to filled, if this event is in the fav list
imageName = "suit.heart.fill"
}
// set the key "favs" if it doesn't exist... handles the case when the app is used for the first time and there is no fav event
}else {
defaults.set(favList, forKey: "favs")
}
// put the heart icon as the rightBarButton of navigatiomItem. favTapped function is triggered when this icon is tapped
let favImage = UIImage(systemName: imageName)?.withTintColor(.red, renderingMode: .alwaysOriginal)
let favButton = UIBarButtonItem(image: favImage, landscapeImagePhone: favImage, style: .plain, target: self, action: #selector(favTapped))
self.navigationItem.rightBarButtonItem = favButton
// update the date, time, location labels and the webview to load the image
let date = String(ev.datetime_utc.prefix(10))
let time = String(ev.datetime_utc.suffix(8).prefix(5))
timeLabel.text = Utils.convertDate(stringDate: date) + " " + Utils.convertTime(stringTime: time)
locationLabel.text = ev.venue.display_location
if let safeUrl = ev.performers?[0].image{
if let url = URL(string: safeUrl){
let request = URLRequest(url: url)
webView.load(request)
}
}
}
//MARK:- FavTapped() controls the interaction with heart icon
@objc func favTapped(){
// when the event is already fav, remove it from the list and change the icon from filled to empty
if(favList.contains(ev.id)){ //get the index of event id and remove from favlist
guard let index = favList.firstIndex(of: ev.id) else {
return
}
favList.remove(at: index)
print("\(ev.id) removed")
// update the list in defaults
defaults.set(favList, forKey: "favs")
self.navigationItem.rightBarButtonItem?.image = UIImage(systemName: "suit.heart")?.withTintColor(.red, renderingMode: .alwaysOriginal)
// add the event in fav list when heart icon is tapped
}else{
favList.append(ev.id)
defaults.set(favList, forKey: "favs")
self.navigationItem.rightBarButtonItem?.image = UIImage(systemName: "suit.heart.fill")?.withTintColor(.red, renderingMode: .alwaysOriginal)
}
}
}
| true
|
7f82430c3fadbe1caee396816527b6ff8957c5e9
|
Swift
|
yagi2/iOS-GitHubClient
|
/GitHubClient/Views/RepoListView.swift
|
UTF-8
| 2,903
| 2.859375
| 3
|
[] |
no_license
|
import SwiftUI
struct RepoListView: View {
@StateObject private var viewModel: RepoListViewModel
init(viewModel: RepoListViewModel = RepoListViewModel()) {
_viewModel = StateObject(wrappedValue: viewModel)
}
var body: some View {
NavigationView {
Group {
switch viewModel.repos {
case .idle, .loading:
ProgressView("loading...")
case .failed:
VStack {
Group {
Image("GitHubMark")
Text("Failed to load repositories")
.padding(.top, 4)
}
.foregroundColor(.black)
.opacity(0.4)
Button(
action: {
viewModel.onRetryButtonTapped()
},
label: {
Text("Retry")
.fontWeight(.bold)
}
)
.padding(.top, 8)
}
case let .loaded(repos):
if repos.isEmpty {
Text("No repositories")
.fontWeight(.bold)
} else {
List(repos) { repo in
NavigationLink(
destination: RepoDetailView(repo: repo)) {
RepoRowView(repo: repo)
}
}
}
}
}
.navigationTitle("Repositories")
}
.onAppear {
viewModel.onAppear()
}
}
}
struct RepoListView_Previews: PreviewProvider {
static var previews: some View {
Group {
RepoListView(
viewModel: RepoListViewModel(
repoRepository: MockRepoRepository(
repos: [ .mock1, .mock2, .mock3, .mock4, .mock5 ]
)
)
)
.previewDisplayName("Default")
RepoListView(
viewModel: RepoListViewModel(
repoRepository: MockRepoRepository(
repos: []
)
)
)
.previewDisplayName("Empty")
RepoListView(
viewModel: RepoListViewModel(
repoRepository: MockRepoRepository(
repos: [],
error: DummyError()
)
)
)
.previewDisplayName("Error")
}
}
}
| true
|
8b9f8445d8e487c98734bbcba35aa4c1efbce3b9
|
Swift
|
Pixelmatters/ios-viper-todolist-app
|
/Todolist/Modules/Home/HomePresenter.swift
|
UTF-8
| 2,588
| 2.953125
| 3
|
[] |
no_license
|
//
// HomePresenter.swift
// Todolist
//
// Created by Filipe Santos on 14/07/2020.
// Copyright © 2020 Pixelmatters. All rights reserved.
//
import Foundation
protocol HomePresenterType {
func onHomePresenter(on homeView: HomeViewControllerType)
func onTodoTapped(on homeView: HomeViewControllerType, todo: Todo)
func onTodoDeleted(on homeView: HomeViewControllerType, todo: Todo)
func onAddTodoTapped(on homeView: HomeViewControllerType)
func onAddTodoTapped(on addTodoView: AddTodoViewControllerType, title: String)
func onCloseTapped(on addTodoView: AddTodoViewControllerType)
}
protocol HomePresenterRouterDelegate: class {
func routeToAddTodo(from homeView: HomeViewControllerType)
func dismissAddTodo()
}
final class HomePresenter {
private let interactor: HomeInteractorType
private weak var routerDelegate: HomePresenterRouterDelegate?
weak var homeView: HomeViewControllerType?
weak var addTodoView: AddTodoViewControllerType?
init(interactor: HomeInteractorType, routerDelegate: HomePresenterRouterDelegate) {
self.interactor = interactor
self.routerDelegate = routerDelegate
}
}
extension HomePresenter: HomePresenterType {
func onHomePresenter(on homeView: HomeViewControllerType) {
self.homeView = homeView
self.interactor.fetchTodos()
}
func onTodoTapped(on homeView: HomeViewControllerType, todo: Todo) {
self.homeView = homeView
self.interactor.updateTodo(todo: todo)
}
func onTodoDeleted(on homeView: HomeViewControllerType, todo: Todo) {
self.homeView = homeView
self.interactor.deleteTodo(todo: todo)
}
func onAddTodoTapped(on homeView: HomeViewControllerType) {
self.homeView = homeView
self.routerDelegate?.routeToAddTodo(from: homeView)
}
func onAddTodoTapped(on addTodoView: AddTodoViewControllerType, title: String) {
self.addTodoView = addTodoView
self.interactor.addTodo(title: title)
}
func onCloseTapped(on addTodoView: AddTodoViewControllerType) {
self.addTodoView = addTodoView
self.routerDelegate?.dismissAddTodo()
}
}
extension HomePresenter: HomeInteractorDelegate {
func onTodosFetched(todos: [Todo]) {
guard let homeView = self.homeView else {
assertionFailure("homeView should be present on HomePresenter")
return
}
homeView.onTodosFetched(todos: todos)
}
func onTodoAdded() {
self.routerDelegate?.dismissAddTodo()
}
}
| true
|
b13d2e8e6f6e879fd4f6c87110d6b7d966c95e76
|
Swift
|
WilliamHester/Breadit-iOS
|
/Breadit/ViewControllers/NavigationViewController.swift
|
UTF-8
| 4,364
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// NavigationViewController.swift
// Breadit
//
// Created by William Hester on 5/1/16.
// Copyright © 2016 William Hester. All rights reserved.
//
import UIKit
class NavigationViewController: UITableViewController, UISearchBarDelegate {
private static let places = ["Home", "Inbox", "Account", "Friends", "Submit", "Settings"]
var delegate: NavigationDelegate?
var subredditStore: SubredditStore!
var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Colors.backgroundColor
let height = UIApplication.sharedApplication().statusBarFrame.height
tableView.contentInset = UIEdgeInsetsMake(height, 0, 0, 0)
tableView.separatorColor = Colors.secondaryColor
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "default")
setUpSearchView()
subredditStore.loadSubreddits {
self.tableView.reloadData()
}
}
private func setUpSearchView() {
searchBar = UISearchBar()
searchBar.autoresizingMask = .FlexibleWidth
searchBar.searchBarStyle = .Minimal
searchBar.tintColor = Colors.secondaryTextColor
searchBar.sizeToFit()
searchBar.delegate = self
tableView.tableHeaderView = searchBar
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
var text = searchBar.text!
if let range = text.rangeOfString("/r/") where range.startIndex == text.startIndex {
text.replaceRange(range, with: "")
delegate?.didNavigateTo(.Subreddit(text))
} else if let range = text.rangeOfString("r/") where range.startIndex == text.startIndex {
text.replaceRange(range, with: "")
delegate?.didNavigateTo(.Subreddit(text))
} else {
delegate?.didNavigateTo(.Search(text))
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return NavigationViewController.places.count
} else {
return subredditStore.subreddits.count
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let place: NavigationPlace
if indexPath.section == 0 {
switch indexPath.row {
case 0:
place = .Subreddit("")
case 1:
place = .Inbox
case 2:
place = .Account
case 3:
place = .Friends
case 4:
place = .Submit
case 5:
place = .Settings
default:
place = .Subreddit("")
}
} else {
place = .Subreddit(subredditStore.subreddits[indexPath.row].displayName)
}
delegate?.didNavigateTo(place)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("default")
cell?.backgroundColor = UIColor.clearColor()
cell?.selectedBackgroundView = UIView()
cell?.selectedBackgroundView?.backgroundColor = UIColor.darkGrayColor()
if let textLabel = cell?.textLabel {
if indexPath.section == 0 {
textLabel.text = NavigationViewController.places[indexPath.row]
} else {
textLabel.text = subredditStore.subreddits[indexPath.row].displayName.lowercaseString
}
textLabel.textColor = Colors.textColor
}
return cell!
}
func stopSearching() {
if searchBar.isFirstResponder() {
searchBar.resignFirstResponder()
}
}
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
stopSearching()
}
}
enum NavigationPlace {
case Subreddit(String)
case Search(String)
case Inbox
case Account
case Friends
case Submit
case Settings
}
protocol NavigationDelegate {
func didNavigateTo(place: NavigationPlace)
}
| true
|
5e76ac8ac41c03d253ff45fc9935e0cbb9de71f1
|
Swift
|
souleywague/AppDevelopment-Swift4-Student
|
/5 - Working With the Web/5 - WWW JSON Serialization/iTunes Search.playground/Contents.swift
|
UTF-8
| 2,080
| 3.484375
| 3
|
[] |
no_license
|
import UIKit
extension URL {
func withQueries(_ queries: [String: String]) -> URL? {
var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
components?.queryItems = queries.compactMap { URLQueryItem(name: $0.0, value: $0.1) }
return components?.url
}
}
struct StoreItems: Codable {
let results: [StoreItem]
}
struct StoreItem: Codable {
var artistName: String
var title: String
var url: URL
enum CodingKeys: String, CodingKey {
case artistName
case title = "trackName"
case url = "trackViewUrl"
}
init(from decoder: Decoder) throws {
let valueContainer = try decoder.container(keyedBy: CodingKeys.self)
self.artistName = try valueContainer.decode(String.self, forKey: CodingKeys.artistName)
self.title = try valueContainer.decode(String.self, forKey: CodingKeys.title)
self.url = try valueContainer.decode(URL.self, forKey: CodingKeys.url)
}
static func fetchItems(_ query: [String: String], completion: @escaping ([StoreItem]?) -> Void) {
let baseURL = URL(string: "https://itunes.apple.com/search?")!
guard let url = baseURL.withQueries(query) else {
completion(nil)
print("Unable to build URL with supplied queries.")
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
let jsonDecoder = JSONDecoder()
if let data = data, let storeItems = try? jsonDecoder.decode(StoreItems.self, from: data) {
completion(storeItems.results)
} else {
print("Either no data was returned, or data was not serialized.")
completion(nil)
return
}
}
task.resume()
}
}
var query: [String: String] = ["term": "michael+jackson", "country": "US", "media": "music"]
StoreItem.fetchItems(query) { (storeItems) in
guard let storeItems = storeItems else { return }
print(storeItems)
}
| true
|
92cb72cc2b405cc628c0ed1181ae3768327ccb76
|
Swift
|
maybemichael/New-Music
|
/New-Music/New-Music/Views/NowPlayingBarView/NowPlayingBarAnimationView.swift
|
UTF-8
| 2,772
| 2.84375
| 3
|
[] |
no_license
|
//
// NowPlayingBarAnimationView.swift
// New-Music
//
// Created by Michael McGrath on 12/11/20.
//
import SwiftUI
struct NowPlayingBarAnimationView: View {
@EnvironmentObject var nowPlayingViewModel: NowPlayingViewModel
let musicController: MusicController
var height: CGFloat
var body: some View {
GeometryReader { geometry in
HStack {
Rectangle()
.foregroundColor(.clear)
.frame(width: height - 5, height: height - 5, alignment: .center)
GeometryReader { geo in
HStack(alignment: .center) {
VStack(alignment: .leading) {
// Text(nowPlayingViewModel.artist)
Text("Fall Out Boy")
.font(Font.system(.subheadline).weight(.light))
.foregroundColor(.lightTextColor)
.lineLimit(1)
// Text(nowPlayingViewModel.songTitle)
Text("Nobody Puts Baby in the Corner" )
.font(Font.system(.headline).weight(.light))
.foregroundColor(.white)
.lineLimit(1)
}
.frame(maxWidth: height * 3.5)
HStack(spacing: 12) {
BarPlayPauseButton(isPlaying: nowPlayingViewModel.isPlaying, musicController: musicController, size: height - 5)
.foregroundColor(.white)
.frame(width: height - 5, height: height - 5, alignment: .center)
BarTrackButton(size: height - 16, buttonType: .trackForward, musicController: musicController)
.frame(width: height - 16, height: height - 16, alignment: .center)
}
}
.frame(height: geometry.size.height + 2.5, alignment: .center)
.padding(.trailing, 15)
}
.frame(width: UIScreen.main.bounds.width - 20 - (height - 5) - 8, height: geometry.size.height, alignment: .center)
}
.padding(.leading, 20)
.background(Color.nowPlayingBG.opacity(1))
}
.frame(width: UIScreen.main.bounds.width, height: height, alignment: .center)
}
}
struct NowPlayingBarAnimationView_Previews: PreviewProvider {
static var previews: some View {
let musicController = MusicController()
NowPlayingBarAnimationView(musicController: musicController, height: 65).environmentObject(musicController.nowPlayingViewModel)
}
}
| true
|
3be5d1d199d37b3b2243fb80d09033fcc34779a0
|
Swift
|
mamunabcoder/TextFieldExtension
|
/TextFieldDemo/TextFieldDemo/TextField.swift
|
UTF-8
| 1,129
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// TextField.swift
// TextFieldDemo
//
// Created by Mason Ingram on 1/13/18.
// Copyright © 2018 Mason Ingram. All rights reserved.
//
import UIKit
@IBDesignable
class TextField: UITextField {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable var cornerRadius:CGFloat {
set {
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
get {
return layer.cornerRadius
}
}
@IBInspectable var insetX:CGFloat = 0
@IBInspectable var insetY:CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: insetX, dy: insetY)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: insetX, dy: insetY)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: insetX, dy: insetY)
}
}
| true
|
ad331cabbcefa6a33dbadf099700a24f6dfc9c88
|
Swift
|
dannyw7/CarBuy
|
/CarBuy/ListingDataViewController.swift
|
UTF-8
| 14,594
| 2.578125
| 3
|
[] |
no_license
|
//
// ListingDataViewController.swift
// CarBuy
//
// Created by Robert Tyler Young, Daniel Wold, and Nahom Teshome on 4/28/18.
// Copyright © 2018 Robert Tyler Young, Daniel Wold, and Nahom Teshome. All rights reserved.
//
import UIKit
class ListingDataViewController: UIViewController {
// Instance variables from storyboard
@IBOutlet var carListingImageView: UIImageView!
@IBOutlet var carTitleLabel: UILabel!
@IBOutlet var carHeadingLabel: UILabel!
@IBOutlet var dealerTitleLabel: UILabel!
@IBOutlet var dealerNameLabel: UILabel!
@IBOutlet var locationTitleLabel: UILabel!
@IBOutlet var locationNameLabel: UILabel!
@IBOutlet var transmissionTitleLabel: UILabel!
@IBOutlet var transmissionNameLabel: UILabel!
@IBOutlet var engineTitleLabel: UILabel!
@IBOutlet var engineNameLabel: UILabel!
@IBOutlet var fuelEconomyTitleLabel: UILabel!
@IBOutlet var fuelEconomyNameLabel: UILabel!
// Add to My Favorites button is pressed
@IBAction func addToMyFavoritesPressed(_ sender: UIButton) {
// obtain dictionary
let data = applicationDelegate.dict_CarName_CarData
// Create item to add
let heading = carListingDataPassed["heading"]
var newHeading = String()
if heading is NSNull {
newHeading = "N/A"
} else {
if let heading = carListingDataPassed["heading"] as! String? {
newHeading = heading
} else {
newHeading = "N/A"
}
}
let dealerData = carListingDataPassed["dealer"] as! [String : AnyObject]
let dealerName = dealerData["name"]
var newDealerName = String()
if dealerName is NSNull {
newDealerName = "N/A"
} else {
if let dealerName = dealerData["name"] as! String? {
newDealerName = dealerName
} else {
newDealerName = "N/A"
}
}
let street = dealerData["street"]
var newStreet = String()
if street is NSNull {
newStreet = "N/A"
} else {
if let street = dealerData["street"] as! String? {
newStreet = street
} else {
newStreet = "N/A"
}
}
let city = dealerData["street"]
var newCity = String()
if city is NSNull {
newCity = "N/A"
} else {
if let city = dealerData["city"] as! String? {
newCity = city
} else {
newCity = "N/A"
}
}
let state = dealerData["state"]
var newState = String()
if state is NSNull {
newState = "N/A"
} else {
if let state = dealerData["state"] as! String? {
newState = state
} else {
newState = "N/A"
}
}//vdp_url
let listingURL = carListingDataPassed["vdp_url"]
var newListingURL = String()
if listingURL is NSNull {
newListingURL = "N/A"
} else {
if let listingURL = carListingDataPassed["vdp_url"] as! String? {
newListingURL = listingURL
} else {
newListingURL = "N/A"
}
}
let x = carListingDataPassed["media"] as! [String: [String]]
var imageString = String()
if x["photo_links"]!.count > 0 {
let y = x["photo_links"]![0]
let url = URL(string: y)
let logoImageData = try? Data(contentsOf: url!)
if let imageData = logoImageData {
imageString = y
print(imageData)
}
else {
imageString = "vehiclePhotoNotAvailable.jpg"
}
}
else {
imageString = "vehiclePhotoNotAvailable.jpg"
}
let location = "\(newStreet), \(newCity), \(newState)"
let value = [newDealerName, location, newListingURL, imageString]
// Add or modify object to dictionary
data.setObject(value, forKey: newHeading as NSCopying)
}
// Obtain the object reference to the App Delegate object
let applicationDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
var carListingDataPassed = [String: AnyObject]()
// Number of images in the slide show
var numberOfImages = 0
var listPhotos = [String]()
var previousImageNumber: Int = 0
// A timer that invokes a method after a certain time interval has elapsed
var timer = Timer()
override func viewDidLoad() {
// Do any additional setup after loading the view.
let media = carListingDataPassed["media"] as! [String: [String]]
if media["photo_links"]!.count > 0 {
let photoUrl = media["photo_links"]![0]
let url = URL(string: photoUrl)
let logoImageData = try? Data(contentsOf: url!)
if let imageData = logoImageData {
carListingImageView.image = UIImage(data: imageData)
}
else {
carListingImageView.image = UIImage(named: "vehiclePhotoNotAvailable.jpg")
}
}
else {
carListingImageView.image = UIImage(named: "vehiclePhotoNotAvailable.jpg")
}
carListingImageView.contentMode = UIViewContentMode.scaleAspectFit
carListingImageView.backgroundColor = UIColor.black
carTitleLabel.backgroundColor = UIColor.red
dealerTitleLabel.backgroundColor = UIColor.red
locationTitleLabel.backgroundColor = UIColor.red
transmissionTitleLabel.backgroundColor = UIColor.red
engineTitleLabel.backgroundColor = UIColor.red
fuelEconomyTitleLabel.backgroundColor = UIColor.red
let heading = carListingDataPassed["heading"]
var newHeading = String()
if heading is NSNull {
newHeading = "N/A"
} else {
if let heading = carListingDataPassed["heading"] as! String? {
newHeading = heading
} else {
newHeading = "N/A"
}
}
carHeadingLabel.text = "\t\(newHeading)"
let dealerData = carListingDataPassed["dealer"] as! [String : AnyObject]
let dealerName = dealerData["name"]
var newDealerName = String()
if dealerName is NSNull {
newDealerName = "N/A"
} else {
if let dealerName = dealerData["name"] as! String? {
newDealerName = dealerName
} else {
newDealerName = "N/A"
}
}
let street = dealerData["street"]
var newStreet = String()
if street is NSNull {
newStreet = "N/A"
} else {
if let street = dealerData["street"] as! String? {
newStreet = street
} else {
newStreet = "N/A"
}
}
let city = dealerData["street"]
var newCity = String()
if city is NSNull {
newCity = "N/A"
} else {
if let city = dealerData["city"] as! String? {
newCity = city
} else {
newCity = "N/A"
}
}
let state = dealerData["state"]
var newState = String()
if state is NSNull {
newState = "N/A"
} else {
if let state = dealerData["state"] as! String? {
newState = state
} else {
newState = "N/A"
}
}
let location = "\(newStreet), \(newCity), \(newState)"
dealerNameLabel.text = "\t\((newDealerName))"
locationNameLabel.text = "\t\(location)"
let carData = carListingDataPassed["build"] as! [String: AnyObject]
let transmission = carData["transmission"]
var newTransmission = String()
if transmission is NSNull {
newTransmission = "N/A"
print("yeah")
} else {
if let transmission = carData["transmission"] as! String? {
newTransmission = transmission
} else {
newTransmission = "N/A"
}
}
transmissionNameLabel.text = "\t\(newTransmission)"
let engine = carData["engine"]
var newEngine = String()
if engine is NSNull {
newEngine = "N/A"
} else {
if let engine = carData["engine"] as! String? {
newEngine = engine
} else {
newEngine = "N/A"
}
}
engineNameLabel.text = "\t\(newEngine)"
let city_mpg = carData["city_miles"]
var newCityMpg = String()
if city_mpg is NSNull {
newCityMpg = "N/A"
} else {
if let city_mpg = carData["city_miles"] as! String? {
newCityMpg = city_mpg
} else {
newCityMpg = "N/A"
}
}
let hwy_mpg = carData["highway_miles"]
var newHwyMPG = String()
if hwy_mpg is NSNull {
newHwyMPG = "N/A"
} else {
if let hwy_mpg = carData["highway_miles"] as! String? {
newHwyMPG = hwy_mpg
} else {
newHwyMPG = "N/A"
}
}
let fuelEconomy = "\t\(newCityMpg), \(newHwyMPG)"
fuelEconomyNameLabel.text = fuelEconomy
// Set up image gallery
// Obtain list of images from car listing
listPhotos = media["photo_links"]!
numberOfImages = listPhotos.count
if listPhotos.count == 0 {
listPhotos = ["vehiclePhotoNotAvailable.jpg"]
}
previousImageNumber = 1
startTimer()
// Gesture stuff
let singleTap = UITapGestureRecognizer(target: self, action: #selector(ListingDataViewController.handleSingleTap(_:)))
singleTap.numberOfTapsRequired = 1
carListingImageView.addGestureRecognizer(singleTap)
}
/*
-------------------------------
MARK: - Creation of a New Timer
-------------------------------
*/
func startTimer() {
/*
Schedule a timer to invoke the changeImage() method given below
after 3 seconds in a loop that repeats itself until it is stopped.
*/
timer = Timer.scheduledTimer(timeInterval: 3,
target: self,
selector: (#selector(ListingDataViewController.changeImage)),
userInfo: nil,
repeats: true)
}
/*
----------------------------------
MARK: - Change Image in the Slider
----------------------------------
*/
@objc func changeImage() {
if listPhotos[0] != "vehiclePhotoNotAvailable.jpg" {
if previousImageNumber == numberOfImages {
// End of list is reached
// Make initializations to start the slide show again with image 1
previousImageNumber = 1
let y = listPhotos[previousImageNumber - 1]
let url = URL(string: y)
let logoImageData = try? Data(contentsOf: url!)
if let imageData = logoImageData {
carListingImageView.image = UIImage(data: imageData)
}
} else {
// Set the previousImageNumber to be the next image number by incrementing by 1
previousImageNumber += 1
let y = listPhotos[previousImageNumber - 1]
let url = URL(string: y)
let logoImageData = try? Data(contentsOf: url!)
if let imageData = logoImageData {
carListingImageView.image = UIImage(data: imageData)
}
}
}
}
/*
----------------------------
MARK: - Tap Handling Methods
----------------------------
*/
// This method is invoked when single tap gesture is applied
@objc func handleSingleTap(_ gestureRecognizer: UIGestureRecognizer) {
if listPhotos[0] != "vehiclePhotoNotAvailable.jpg" {
print(listPhotos)
performSegue(withIdentifier: "Images", sender: self)
}
else {
showAlertMessage(messageHeader: "No Images Available!", messageBody: "The listing does not have any images available.")
}
}
/*
-----------------------------
MARK: - Display Alert Message
-----------------------------
*/
func showAlertMessage(messageHeader header: String, messageBody body: String) {
/*
Create a UIAlertController object; dress it up with title, message, and preferred style;
and store its object reference into local constant alertController
*/
let alertController = UIAlertController(title: header, message: body, preferredStyle: UIAlertControllerStyle.alert)
// Create a UIAlertAction object and add it to the alert controller
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
// Present the alert controller
present(alertController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "Images" {
// Obtain the object reference of the destination view controller
let photoGalleryViewController: PhotoGalleryViewController = segue.destination as! PhotoGalleryViewController
// Pass the data object to the downstream view controller object
photoGalleryViewController.photosPassed = listPhotos
}
}
}
| true
|
94ac00bbc56fcb47215d5c5036655c79057cdbbe
|
Swift
|
suryaharahap/iOS-beginners-labs
|
/LayoutUIProgramatically/LayoutUIProgramatically/ViewController.swift
|
UTF-8
| 6,363
| 2.671875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// LayoutUIProgramatically
//
// Created by Surya on 08/08/21.
//
import UIKit
class ViewController: UIViewController {
lazy var signUpLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor(red: 130/255, green: 131/255, blue: 134/255, alpha: 1)
label.font = .systemFont(ofSize: 52, weight: .regular)
label.text = "Sign Up"
return label
}()
lazy var emailLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor(red: 130/255, green: 131/255, blue: 134/255, alpha: 1)
label.font = .systemFont(ofSize: 17, weight: .medium)
label.text = "Email"
return label
}()
lazy var emailTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.borderStyle = .roundedRect
textField.textContentType = .emailAddress
textField.keyboardType = .emailAddress
textField.autocapitalizationType = .none
return textField
}()
lazy var passwordLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor(red: 130/255, green: 131/255, blue: 134/255, alpha: 1)
label.font = .systemFont(ofSize: 17, weight: .medium)
label.text = "Password"
return label
}()
lazy var passwordTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.borderStyle = .roundedRect
textField.textContentType = .newPassword
textField.autocapitalizationType = .none
textField.isSecureTextEntry = true
return textField
}()
lazy var createAccountButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Create Account", for: .normal)
button.setTitleColor(UIColor(red: 130/255, green: 131/255, blue: 134/255, alpha: 1), for: .normal)
button.backgroundColor = UIColor(red: 224/255, green: 226/255, blue: 226/255, alpha: 1)
button.layer.cornerRadius = 5
return button
}()
lazy var appleButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "appleButton"), for: .normal)
return button
}()
lazy var facebookButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "facebookButton"), for: .normal)
return button
}()
lazy var googleButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "googleButton"), for: .normal)
return button
}()
override func loadView() {
super.loadView()
view.backgroundColor = .white
view.addSubview(signUpLabel)
view.addSubview(emailLabel)
view.addSubview(emailTextField)
view.addSubview(passwordLabel)
view.addSubview(passwordTextField)
view.addSubview(createAccountButton)
view.addSubview(appleButton)
view.addSubview(facebookButton)
view.addSubview(googleButton)
signUpLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 130).isActive = true
signUpLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
emailLabel.topAnchor.constraint(equalTo: signUpLabel.bottomAnchor, constant: 46).isActive = true
emailLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
emailTextField.topAnchor.constraint(equalTo: emailLabel.bottomAnchor, constant: 5).isActive = true
emailTextField.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
emailTextField.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
emailTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
passwordLabel.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 30).isActive = true
passwordLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
passwordTextField.topAnchor.constraint(equalTo: passwordLabel.bottomAnchor, constant: 5).isActive = true
passwordTextField.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
passwordTextField.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
passwordTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
createAccountButton.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor, constant: 50).isActive = true
createAccountButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
createAccountButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
createAccountButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
appleButton.topAnchor.constraint(equalTo: createAccountButton.bottomAnchor, constant: 103).isActive = true
appleButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
appleButton.widthAnchor.constraint(equalToConstant: 57).isActive = true
appleButton.heightAnchor.constraint(equalToConstant: 57).isActive = true
facebookButton.centerYAnchor.constraint(equalTo: appleButton.centerYAnchor).isActive = true
facebookButton.rightAnchor.constraint(equalTo: appleButton.leftAnchor, constant: -20).isActive = true
facebookButton.widthAnchor.constraint(equalToConstant: 57).isActive = true
facebookButton.heightAnchor.constraint(equalToConstant: 57).isActive = true
googleButton.centerYAnchor.constraint(equalTo: appleButton.centerYAnchor).isActive = true
googleButton.leftAnchor.constraint(equalTo: appleButton.rightAnchor, constant: 20).isActive = true
googleButton.widthAnchor.constraint(equalToConstant: 57).isActive = true
googleButton.heightAnchor.constraint(equalToConstant: 57).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| true
|
91211adc3ba073d3f3fe90407961e6aba6c7a6e8
|
Swift
|
gucchi43/PicCalendar
|
/selectDayPic/PIcCollectionViewController.swift
|
UTF-8
| 2,695
| 2.609375
| 3
|
[] |
no_license
|
//
// PIcCollectionViewController.swift
// selectDayPic
//
// Created by HIroki Taniguti on 2016/10/19.
// Copyright © 2016年 HIroki Taniguti. All rights reserved.
//
import UIKit
import Photos
class PIcCollectionViewController: UIView, UICollectionViewDataSource, UICollectionViewDelegate , UICollectionViewDelegateFlowLayout {
var collectionView:UICollectionView!
override init(frame: CGRect) {
super.init(frame: frame)
// レイアウト作成
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .Horizontal
flowLayout.minimumInteritemSpacing = 2.0
flowLayout.minimumLineSpacing = 2.0
flowLayout.itemSize = CGSizeMake(frame.height, frame.width / 2)
// コレクションビュー作成
collectionView = UICollectionView(frame: frame, collectionViewLayout: flowLayout)
collectionView.backgroundColor = UIColor.greenColor()
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.delegate = self
collectionView.dataSource = self
addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let count = PicDataArray.sharedSingleton.PicOneDayAssetArray.count
return count
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//選択した時の処理
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as UICollectionViewCell
let imageView = UIImageView()
imageView.sizeThatFits(cell.bounds.size)
let asset = PicDataArray.sharedSingleton.PicOneDayAssetArray[indexPath.row]
assetToImage(asset, imageView: imageView)
return cell
}
func assetToImage(asset: PHAsset, imageView: UIImageView)
{
let manager: PHImageManager = PHImageManager()
manager.requestImageForAsset(asset,
targetSize: imageView.bounds.size,
contentMode: .AspectFill,
options: nil) { (image, info) -> Void in
// 取得したimageをUIImageViewなどで表示する
imageView.image = image
}
}
}
| true
|
096d51726747cabb5800f202683fa9c1a27312e6
|
Swift
|
xTIVx/Photo-Reporter
|
/Photo Reporter/Controller/WorkWithPhotos/PhotoPhoneStorage.swift
|
UTF-8
| 3,224
| 3.015625
| 3
|
[] |
no_license
|
//
// PhotoPhoneStorage.swift
// Photo Reporter
//
// Created by Igor Chernobai on 6/29/19.
// Copyright © 2019 Igor Chernobai. All rights reserved.
//
import Foundation
import UIKit
class PhotoPhoneStorage {
// Getting document directory for save images to temporary folder in documents
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func getFilesFromDocuments () -> [URL] {
var imagesURL = [URL]()
do {
let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let docs = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: [], options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants])
imagesURL = docs.filter{ $0.pathExtension == "jpg" }
imagesURL.append(contentsOf: docs.filter{ $0.pathExtension == "png" })
print(documentsURL)
// GETTING FILE NAMES! images.map{ $0.deletingPathExtension().lastPathComponent }
} catch {
print(error)
}
return imagesURL
}
// DELETE FILE FROM DOCUMENTS!
func deleteFromTempFolder (fileName: String) {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
print(documentsUrl)
do {
let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsUrl,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants])
for fileURL in fileURLs {
if fileURL.lastPathComponent == fileName {
try FileManager.default.removeItem(at: fileURL)
}
}
} catch { print(error) }
}
func checkFileExists (name: String) -> String? {
let fileNameToDelete = name
var filePath = ""
// Find documents directory on device
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs.count > 0 {
let dir = dirs[0] //documents directory
filePath = dir.appendingFormat("/" + fileNameToDelete)
} else {
print("Could not find local directory to store file")
}
let fileManager = FileManager.default
// Check if file exists
if fileManager.fileExists(atPath: filePath) {
return filePath
} else {
return nil
}
}
func saveToDocuments(image: UIImage, photoName: String) {
print(photoName, "00000000000000000000")
if let data = image.jpegData(compressionQuality: 0.7) {
let filename = self.getDocumentsDirectory().appendingPathComponent(photoName)
try? data.write(to: filename)
}
}
}
| true
|
4135c4345d001c67d16e9093ced3bebf45d15de5
|
Swift
|
havilog/UIStudy
|
/ChaiOnboarding/ChaiOnboarding/ChaiTimerProgressView.swift
|
UTF-8
| 2,606
| 2.8125
| 3
|
[] |
no_license
|
//
// ChaiTimerProgressView.swift
// ChaiOnboarding
//
// Created by 한상진 on 2021/07/19.
//
import UIKit
final class ChaiTimerProgressView: UIView {
private var circleLayer: CAShapeLayer = .init()
private var progressLayer: CAShapeLayer = .init()
private var startPoint: CGFloat = CGFloat(-Double.pi / 2)
private var endPoint: CGFloat = CGFloat(3 * Double.pi / 2)
override init(frame: CGRect) {
super.init(frame: frame)
createCircularPath()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func createCircularPath() {
let circularPath = UIBezierPath(
arcCenter: .init(
x: frame.size.width,
y: frame.size.height
),
radius: 40,
startAngle: startPoint,
endAngle: endPoint,
clockwise: true
)
circleLayer.do {
$0.path = circularPath.cgPath
$0.fillColor = UIColor.clear.cgColor
$0.lineCap = .round
$0.lineWidth = 20.0
$0.strokeColor = UIColor.white.cgColor
$0.strokeEnd = 1.0
}
layer.addSublayer(circleLayer)
progressLayer.do {
$0.path = circularPath.cgPath
$0.fillColor = UIColor.clear.cgColor
$0.lineCap = .round
$0.lineWidth = 10.0
$0.strokeColor = UIColor.green.cgColor
$0.strokeEnd = 0
}
layer.addSublayer(progressLayer)
}
func progressAnimation(duration: TimeInterval) {
let circularAnimation: CABasicAnimation = .init(keyPath: "strokeEnd")
circularAnimation.do {
$0.duration = duration
$0.toValue = 1
$0.fillMode = .forwards
$0.isRemovedOnCompletion = false
}
progressLayer.add(circularAnimation, forKey: "circularAnimation")
}
}
// MARK: Preview
#if canImport(SwiftUI) && DEBUG
import SwiftUI
@available(iOS 13.0, *)
struct ChaiTimerProgressViewRepresentable: UIViewRepresentable {
typealias UIViewType = UIView
func makeUIView(context: Context) -> UIView {
ChaiTimerProgressView()
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
@available(iOS 13.0, *)
struct ChaiTimerProgressViewPreview: PreviewProvider {
typealias Previews = ChaiTimerProgressViewRepresentable
static var previews: Previews {
return ChaiTimerProgressViewRepresentable()
}
}
#endif
| true
|
f4288d2d054b29263d2e89084b7d32546fa17a1d
|
Swift
|
shoppy-junction/ios
|
/Shoppy/Models/ProximityPromotion.swift
|
UTF-8
| 1,044
| 2.859375
| 3
|
[] |
no_license
|
//
// ProximityPromotion.swift
// Shoppy
//
// Created by Jack Cook on 11/24/18.
// Copyright © 2018 Jack Cook. All rights reserved.
//
import SwiftyJSON
struct ProximityPromotion {
let beacon: Int
let name: String
let product: Product
static var bread: ProximityPromotion {
let product = Product(identifier: "6410402003488", imageURL: "https://public.keskofiles.com/f/k-ruoka/product/6410402003488?w=800&h=500&fm=jpg&q=90&fit=clip&bg=fff", name: "Bread", price: "€1.50", pricePerWeight: "Buy two for the price of one", weight: "On sale!", recommendation: "Gluten-Free Bread")
return ProximityPromotion(beacon: 13, name: "Bread", product: product)
}
static var promotions: [ProximityPromotion] {
return [.bread]
}
func matches(distances: [Int: Int]) -> Bool {
guard let closestBeacon = distances.filter({ $0.key != -1 }).min(by: { $0.value > $1.value })?.key else {
return false
}
return closestBeacon == beacon
}
}
| true
|
f7c07fdb899a5388c9ae189fcbbb68bbcb2b4722
|
Swift
|
takahia1988/ApplicationCoordinatorSample
|
/ApplicationCoordinatorSample/Classes/Coordinator/Coordinator.swift
|
UTF-8
| 1,073
| 3.296875
| 3
|
[] |
no_license
|
//
// Coordinator.swift
// ApplicationCoordinatorSample
//
// Created by Hiasa, Takahiro on 2017/03/19.
// Copyright © 2017年 takahia. All rights reserved.
//
import Foundation
protocol Coordinator: class {
var childCoordinators:[Coordinator] { get set }
func start()
func addChildDependency(coordinator: Coordinator)
func removeChildDependency(coordinator: Coordinator?)
}
extension Coordinator {
func addChildDependency(coordinator: Coordinator) {
for element in self.childCoordinators {
if element === coordinator { return }
}
self.childCoordinators.append(coordinator)
}
func removeChildDependency(coordinator: Coordinator?) {
guard self.childCoordinators.isEmpty == false, let coordinator = coordinator else {
return
}
for (index, element) in self.childCoordinators.enumerated() {
if element === coordinator {
self.childCoordinators.remove(at: index)
break
}
}
}
}
| true
|
56bae6332af96d2973a33cb59c8d1f8ec9f72ed4
|
Swift
|
pacscs/Crush
|
/Crush/View/CombineCardView.swift
|
UTF-8
| 2,319
| 2.796875
| 3
|
[] |
no_license
|
//
// CombineCardView.swift
// Crush
//
// Created by Paulo Alfredo Coraini de Souza on 22/07/21.
//
import UIKit
class CombineCardView: UIView {
var user: User? {
didSet {
if let user = user {
picImageView.image = UIImage(named: user.photo)
nameLabel.text = user.name
ageLabel.text = String(user.Age)
phraseLabel.text = user.phrase
}
}
}
let picImageView: UIImageView = .picImageView()
let nameLabel: UILabel = .txtBoldLabel(32, textColor: .white)
let ageLabel: UILabel = .txtLabel(28, textColor: .white)
let phraseLabel: UILabel = .txtLabel(18, textColor: .white, numberOfLine: 2)
let deslikeImageView: UIImageView = .iconCard(named: "card-deslike")
let likeImageView: UIImageView = .iconCard(named: "card-like")
override init (frame: CGRect) {
super.init(frame: frame)
layer.borderWidth = 0.3
layer.borderColor = UIColor.lightGray.cgColor
layer.cornerRadius = 8
clipsToBounds = true
nameLabel.addShadow()
ageLabel.addShadow()
phraseLabel.addShadow()
addSubview(picImageView)
addSubview(deslikeImageView)
deslikeImageView.fill(top: topAnchor, leading: nil, trailing: trailingAnchor, bottom: nil, padding: .init(top: 20, left: 0, bottom: 0, right: 20))
addSubview(likeImageView)
likeImageView.fill(top: topAnchor, leading: leadingAnchor, trailing: nil, bottom: nil, padding: .init(top: 20, left: 20, bottom: 0, right: 0))
picImageView.fillSuperview()
let nameAgeStackView = UIStackView(arrangedSubviews: [nameLabel, ageLabel, UIView()])
nameAgeStackView.spacing = 12
let stackView = UIStackView(arrangedSubviews: [nameAgeStackView, phraseLabel])
stackView.distribution = .fillEqually
stackView.axis = .vertical
addSubview(stackView)
stackView.fill(top: nil, leading: leadingAnchor, trailing: trailingAnchor, bottom: bottomAnchor, padding: .init(top: 0, left: 16, bottom: 16, right: 16))
}
required init?(coder: NSCoder) {
fatalError()
}
}
| true
|
997b045199d57f08f4fa8fa3c60ce2ebe4dabc78
|
Swift
|
avito-tech/Paparazzo
|
/Paparazzo/Core/VIPER/MediaPicker/View/MediaRibbonDataSource.swift
|
UTF-8
| 2,085
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
final class MediaRibbonDataSource {
typealias DataMutationHandler = (_ indexPaths: [IndexPath], _ mutatingFunc: () -> ()) -> ()
private var mediaPickerItems = [MediaPickerItem]()
// MARK: - MediaRibbonDataSource
var cameraCellVisible: Bool = true
var numberOfItems: Int {
return mediaPickerItems.count + (cameraCellVisible ? 1 : 0)
}
subscript(indexPath: IndexPath) -> MediaRibbonItem {
if indexPath.item < mediaPickerItems.count {
return .photo(mediaPickerItems[indexPath.item])
} else {
return .camera
}
}
func addItems(_ items: [MediaPickerItem]) -> [IndexPath] {
let insertedIndexes = mediaPickerItems.count ..< mediaPickerItems.count + items.count
let indexPaths = insertedIndexes.map { IndexPath(item: $0, section: 0) }
mediaPickerItems.append(contentsOf: items)
return indexPaths
}
func updateItem(_ item: MediaPickerItem) -> IndexPath? {
if let index = mediaPickerItems.firstIndex(of: item) {
mediaPickerItems[index] = item
return IndexPath(item: index, section: 0)
} else {
return nil
}
}
func removeItem(_ item: MediaPickerItem) -> IndexPath? {
if let index = mediaPickerItems.firstIndex(of: item) {
mediaPickerItems.remove(at: index)
return IndexPath(item: index, section: 0)
} else {
return nil
}
}
func moveItem(from index: Int, to destinationIndex: Int) {
mediaPickerItems.moveElement(from: index, to: destinationIndex)
}
func indexPathForItem(_ item: MediaPickerItem) -> IndexPath? {
return mediaPickerItems.firstIndex(of: item).flatMap { IndexPath(item: $0, section: 0) }
}
func indexPathForCameraItem() -> IndexPath {
return IndexPath(item: mediaPickerItems.count, section: 0)
}
}
enum MediaRibbonItem {
case photo(MediaPickerItem)
case camera
}
| true
|
755b9d6bc1e40ebdfee309510703e09023d05646
|
Swift
|
iSpentak/flappyswift
|
/FlappySwift/GameScene.swift
|
UTF-8
| 5,569
| 2.75
| 3
|
[] |
no_license
|
//
// GameScene.swift
// FlappySwift
//
// Created by Mark Price on 7/28/14.
// Copyright (c) 2014 Verisage. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate
{
//Scenery
let hillsYPos: CGFloat = 300
let totalGroundPieces = 5
var groundPieces = [SKSpriteNode]()
let groundSpeed: CGFloat = 3.5
var moveGroundAction: SKAction!
var moveGroundForeverAction: SKAction!
let groundResetXCoord: CGFloat = -164
//Game
var bird: SKSpriteNode!
var birdAtlas = SKTextureAtlas(named: "bird")
var birdFrames = [SKTexture]()
var startJump = false
var getTimeStamp = false
var jumpStartTime: CFTimeInterval = 0.0
var jumpCurrentTime: CFTimeInterval = 0.0
var jumpDuration = 0.7
override func didMoveToView(view: SKView)
{
initSetup()
setupScenery()
setupBird()
startGame()
}
func initSetup()
{
moveGroundAction = SKAction.moveByX(-groundSpeed, y: 0, duration: 0.02)
moveGroundForeverAction = SKAction.repeatActionForever(SKAction.sequence([moveGroundAction]))
self.physicsWorld.gravity = CGVectorMake(0.0, -5.0)
self.physicsWorld.contactDelegate = self
}
func setupScenery()
{
println("Scene Width \(self.view.frame.size.width)")
/* Setup your scene here */
//Add background sprites
var bg = SKSpriteNode(imageNamed: "sky")
bg.position = CGPointMake(bg.size.width / 2, bg.size.height / 2)
self.addChild(bg)
var hills = SKSpriteNode(imageNamed: "hills")
hills.position = CGPointMake(hills.size.width / 2, hillsYPos)
self.addChild(hills)
//Add ground sprites
for var x = 0; x < totalGroundPieces; x++
{
var sprite = SKSpriteNode(imageNamed: "ground_piece")
groundPieces.append(sprite)
var wSpacing = sprite.size.width / 2
var hSpacing = sprite.size.height / 2
if x == 0
{
sprite.position = CGPointMake(wSpacing, hSpacing)
}
else
{
sprite.position = CGPointMake((wSpacing * 2) + groundPieces[x - 1].position.x,groundPieces[x - 1].position.y)
}
self.addChild(sprite)
}
}
func setupBird()
{
//Bird animations
var totalImgs = birdAtlas.textureNames.count
for var x = 1; x < totalImgs; x++
{
var textureName = "bird-0\(x)"
var texture = birdAtlas.textureNamed(textureName)
birdFrames.append(texture)
}
bird = SKSpriteNode(texture: birdFrames[0])
self.addChild(bird)
bird.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
bird.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(birdFrames, timePerFrame: 0.2, resize: false, restore: true)))
//Bird physics
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height / 2.0)
//bird.physicsBody.dynamic = true
bird.physicsBody.allowsRotation = false
}
func startGame()
{
for sprite in groundPieces
{
sprite.runAction(moveGroundForeverAction)
}
}
func updateWithTimeSinceLastUpdate(timeSinceLast: CFTimeInterval)
{
jumpCurrentTime += timeSinceLast
if jumpCurrentTime > jumpDuration
{
jumpCurrentTime = 0.0
startJump = false
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
getTimeStamp = true
startJump = true
jumpStartTime = NSDate().timeIntervalSince1970
println(jumpStartTime)
}
func groundMovement()
{
for var x = 0; x < groundPieces.count; x++
{
if groundPieces[x].position.x <= groundResetXCoord
{
if x != 0
{
groundPieces[x].position = CGPointMake(groundPieces[x - 1].position.x + groundPieces[x].size.width,groundPieces[x].position.y)
}
else
{
groundPieces[x].position = CGPointMake(groundPieces[groundPieces.count - 1].position.x + groundPieces[x].size.width,groundPieces[x].position.y)
}
}
}
}
override func update(currentTime: CFTimeInterval)
{
//println("Current Time \(currentTime)")
/* Called before each frame is rendered */
groundMovement()
if getTimeStamp
{
getTimeStamp = false
jumpStartTime = currentTime
}
if startJump
{
var timeSinceLast = currentTime - jumpStartTime
}
}
}
/*
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = location
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
}
*/
| true
|
67376aec6abb5b06ea1d86bd62f907ae7f3f5b72
|
Swift
|
yafengxn/SwiftStudy
|
/05SwiftSyntax.playground/Contents.swift
|
UTF-8
| 3,394
| 4
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
//////////////////////////协议和扩展
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
// 类、枚举和结构体都可以实现协议
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class"
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
func hello() {
print("------- simpleClass -> hello ------ ")
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct simpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() { // mutating用来标记一个会修改结构体的方法,Class中不需要标记任何方法因为类中的方法经常会修改类
simpleDescription += " (adjusted)"
}
}
var b = simpleStructure()
b.adjust()
let bDescription = b.simpleDescription
// 枚举实现协议怎么写
//enum SimpleEnum: ExampleProtocol {
// case simpleDescription: String = "A simple enum"
// mutating func adjust() {
// simpleDescription += " had adjusted"
// }
//}
// 使用extension来为现有的类型添加功能,如新的方法和参数;
// 可以使用扩展在别处修改定义,甚至从外部库或者框架引入的一个类型,似的这个类型遵循某个协议
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
var numInt: Int = 10
numInt.adjust()
numInt.simpleDescription
// 练习: 给Double类型写一个扩展,添加absoluteValue功能。
protocol ValueProtocol {
var simpleDescription: String { get }
mutating func absoluteValue()
}
extension Double: ValueProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func absoluteValue() {
self = fabs(self)
}
}
var doubleVar: Double = -10.0
doubleVar.absoluteValue()
doubleVar.simpleDescription
let protocolValue: ExampleProtocol = a // 此处ExampleProtocol就是一个类型,变量protocolValue运行时执行simpleClass,类似于父类变量 --> 子类实例
protocolValue.simpleDescription
// protocolValue.hello() 此时protocolValue变量只能调用protocol中的方法,不能调用SimpleClass中的方法
//let value: SimpleClass = SimpleClass(protocolValue) // 貌似不能进行强转,然后调用hello方法
//value.hello()
/////////////////////////////泛型
//func repeat<ItemType>(item: ItemType, times: Int) -> [ItemType] {
// var result = [ItemType]()
// for i in 0 ..<times {
// result.append(item)
// }
// return result
//}
//repeat("knock", 4)
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
// 这里不是很懂????
//func anyCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool {
// for lhsItem in lhs {
// for rhsItem in rhs {
// if lhsItem == rhsItem {
// return true
// }
// }
// }
// return false
//}
//anyCommonElements([1, 2, 3], [3])
| true
|
258ab0fa6192f807e3df67c5eb0514c676ab6525
|
Swift
|
dillanj/Agelpse
|
/AgeLapse/GenerationViewController.swift
|
UTF-8
| 1,065
| 2.59375
| 3
|
[] |
no_license
|
//
// GenerationViewController.swift
// AgeLapse
//
// Created by Dillan Johnson on 3/23/20.
// Copyright © 2020 Dillan Johnson. All rights reserved.
//
import UIKit
//import SwiftVideoGenerator
class GenerationViewController: UIViewController {
var imageStore: ImageStore!
var photoStore: PhotoStore!
var image_urls = [String]()
override func viewDidLoad() {
image_urls = getAllURLs()
}
// override func viewDidAppear(_ animated: Bool) {
// super.viewDidAppear(animated)
// let timelapseBuilder = TimeLapseBuilder(photoURLs: image_urls)
// timelapseBuilder.build({ progress in
// print(progress)
// }, success: { url in
// print(url)
// }, failure: { error in
// print(error)
// })
// }
//
func getAllURLs() -> [String] {
var urls = [String]()
for photo in photoStore.allPhotos {
urls.append( imageStore.imageURL(forKey: photo.photoKey).absoluteString )
}
return urls
}
}
| true
|
e39124ab25439381a31befbc71668af2d6012388
|
Swift
|
nikktro/VK_app
|
/VK_app/Network/RealmProvider.swift
|
UTF-8
| 626
| 2.59375
| 3
|
[] |
no_license
|
//
// RealmProvider.swift
// VK_app
//
// Created by Nikolay.Trofimov on 27/02/2019.
// Copyright © 2019 Nikolay.Trofimov. All rights reserved.
//
import RealmSwift
class RealmProvider {
static func save<T: Object>(items: [T], config: Realm.Configuration = Realm.Configuration.defaultConfiguration, update: Bool = true) {
guard let fileRealm = config.fileURL else { return }
print(fileRealm)
do {
let realm = try Realm(configuration: config)
try realm.write {
realm.add(items, update: update)
}
} catch {
print(error.localizedDescription)
}
}
}
| true
|
1c0aa811f9878cc60230ca5d9b804bbbb2e981d1
|
Swift
|
niksauer/ToolKit
|
/Sources/ViewController/TextViewController.swift
|
UTF-8
| 719
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// TextViewController.swift
// ToolKit
//
// Created by Niklas Sauer on 14.06.18.
// Copyright © 2018 SauerStudios. All rights reserved.
//
import Foundation
import UIKit
open class TextViewController: UIViewController {
// MARK: - Views
public let textView = UITextView()
// MARK: - Initialization
public init(text: String) {
super.init(nibName: nil, bundle: nil)
textView.text = text
view.addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.pin(to: view)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
0bc2618a6cbbf30221e5ed4010144a475dd626ce
|
Swift
|
intere/360iDevARNavigation
|
/360iDev AR Navigation/Extensions/UIViewController+Alert.swift
|
UTF-8
| 751
| 2.921875
| 3
|
[] |
no_license
|
//
// UIViewController+Alert.swift
// 360iDev AR Navigation
//
// Created by Eric Internicola on 8/14/19.
// Copyright © 2019 Eric Internicola. All rights reserved.
//
import UIKit
extension UIViewController {
typealias AlertOKCallback = (UIAlertAction) -> Void
/// Shows an alert with a title of "Error" and an "OK" button that dismisses
/// the alert.
///
/// - Parameter message: The message to show in the alert.
func showErrorAlert(message: String, completion handler: AlertOKCallback? = nil) {
let alertVC = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: handler))
present(alertVC, animated: true)
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.