I am trying to get the value of a tapered row in a UIPickerView but every time I scroll through it, it gives me every value I go through. How can I get the value of when the user taps the row?
I am trying to append the value that the user clicks on to an array called squaresTaken.
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
pickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
intToString()
return pickerData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
squaresTaken.append(Int(pickerData[row])!)
yourSquare.text = pickerData[row]
}
Post
Replies
Boosts
Views
Activity
How do I save the state of the switch. I have a switch in a custom cell. I have a class for the custom cell. I am trying to save it from a view controller.
class Settings_Custom_Cell: UITableViewCell {
@IBOutlet weak var settingLabel: UILabel!
@IBOutlet weak var quickAddSwitch: UISwitch!
}
class SettingsCell {
var settingLabel: String
var settingValue: UISwitch
init(settingLabel: String, settingValue: UISwitch) {
self.settingLabel = settingLabel
self.settingValue = settingValue
}
}
import UIKit
class Settings: UIViewController, UITableViewDelegate, UITableViewDataSource {
var array: [String] = ["Quick Add"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
cell.textLabel?.text = ""
cell.textLabel?.text = array[indexPath.row]
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.textLabel?.font = UIFont.systemFont(ofSize: 20)
return cell
}
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
}
How do I read in a csv file and input the data into a class?
Here is my class object code
class PlayerData: Codable {
var num: Int = 0
var numPosPick: Int = 0
var numRookie: Int = 0
var name: String = ""
var team: String = ""
var position: String = ""
var byeWeek: Int = 0
var rosterPosition: Int = -1
var draftPosition: Int = -1
var isTopPlayer: Bool
var isRookie: Bool
var isRostered: Bool { return rosterPosition >= 0 }
var isDrafted: Bool { return draftPosition >= 0 }
init(num: Int, numPosPick: Int, numRookie: Int, name: String, team: String, position: String, byeWeek: Int, isTopPlayer: Bool, isRookie: Bool) {
self.num = num
self.numPosPick = numPosPick
self.numRookie = numRookie
self.name = name
self.team = team
self.position = position
self.byeWeek = byeWeek
self.isTopPlayer = isTopPlayer
self.isRookie = isRookie
}
}
Here is what I want it to look like but I want it to be inserted from the csv file.
allPlayers = [
PlayerData(num: 1, numPosPick: 1, numRookie: 0, name: "Christian McCaffrey", team: "CAR", position: "RB", byeWeek: 13, isTopPlayer: true, isRookie: false),
PlayerData(num: 2, numPosPick: 2, numRookie: 0, name: "Dalvin Cook", team: "MIN", position: "RB", byeWeek: 7, isTopPlayer: true, isRookie: false),
PlayerData(num: 3, numPosPick: 3, numRookie: 0, name: "Saquon Barkley", team: "NYG", position: "RB", byeWeek: 10, isTopPlayer: true, isRookie: false),
PlayerData(num: 4, numPosPick: 4, numRookie: 0, name: "Derrick Henry", team: "TEN", position: "RB", byeWeek: 13, isTopPlayer: true, isRookie: false),
PlayerData(num: 5, numPosPick: 1, numRookie: 0, name: "Tyreek Hill", team: "KC", position: "WR", byeWeek: 12, isTopPlayer: true, isRookie: false)
]
Here is the csv file
fantasy_2021.csv
Is there a way to save data to the iPhone when the app has been deleted so that when the app is reinstalled the app is in the same state it was in before it got deleted? I created an app but when I delete it, it doesn't save and reload the data.
I am running the following code and it keeps getting an error saying that found nil while unwrapping an optional. What am I doing wrong? I am using a good API.
class Database_2020 {
static let shared = Database_2020()
var leagueNames: [String]
var leagues: [[String]]
let url = " https://www.someURL.com/service/"
private func getData(from url: String) {
let task = URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
guard let data = data, error == nil else
print("something went wrong")
return
}
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
}
catch {
print("failed to convert \(error.localizedDescription)")
}
guard let json = result else {
return
}
print(json.status)
print(json.results.draftPosition)
print(json.results.name)
}
task.resume()
func printData() {
getData(from: url)
}
}
How do I create an array of a class?I am managing my data in a singleton database.The structure is the following:Main view - Has a table view to select top quarterbacks, top running backs, etc. When the row is clicked, it segues to another view controller displaying the top quarterbacks, running backs, etc.Top quarterbacks view, runningbacks view, etc.: When the row is swiped, two buttons display - Add, taken -- Add will add that player to my team.- Taken will mark the player as taken and add that player to draft order.After the draft is complete, I have a button called 'add to league'.- Add to league button will segue to another view controller.Add league view: This view has a text field to name the league and then a button to add the league.- Add button adds the league name and segues to another view controller to view the added leagues.My leagues view: This is a table view that has the added league names. If there are more than one added league, then there will be more than one row in the table view. What I want is when a row is tapped to segue to another view controller with a table view and display that added leagues players and at the same time to reset the draft.This is how I get the players on my team:class PlayerData: Codable {
var num: Int = 0
var numPosPick: Int = 0
var numRookie: Int = 0
var name: String = ""
var team: String = ""
var position: String = ""
var rosterPosition: Int = -1
var draftPosition: Int = -1
var isTopPlayer: Bool
var isRookie: Bool
var isRostered: Bool { return rosterPosition >= 0 }
var isDrafted: Bool { return draftPosition >= 0 }
init(num: Int, numPosPick: Int, numRookie: Int, name: String, team: String, position: String, isTopPlayer: Bool, isRookie: Bool) {
self.num = num
self.numPosPick = numPosPick
self.numRookie = numRookie
self.name = name
self.team = team
self.position = position
self.isTopPlayer = isTopPlayer
self.isRookie = isRookie
}
}class Database_2019 {
static let shared = Database_2019()
var myLeagues: [String] = []
var myleaguePlayers: [PlayerData]
var myLeaguePlayersData: [[PlayerData]]
func addPlayersToLeague(league: String) {
myleaguePlayers = rosterList()
if myLeagues == [] {
myLeagues.insert(league, at: 0)
myLeaguePlayersData.insert(myleaguePlayers, at: 0)
} else {
myLeagues.append(league)
myLeaguePlayersData.append(myleaguePlayers)
}
resetDraft()
}
// All players and leagues 2019
fileprivate var allPlayers: [PlayerData]
fileprivate var allPlayersReset: [PlayerData] // To hold the reset properties.
fileprivate func playerDataURL() -> URL {
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).last!
return documentDirectoryURL.appendingPathComponent("playerData_2019.json")
}
fileprivate func leaguesDataURL() -> URL {
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).last!
return documentDirectoryURL.appendingPathComponent("leaguesData_2019.json")
}
fileprivate func leaguePlayersDataURL() -> URL {
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).last!
return documentDirectoryURL.appendingPathComponent("leaguePlayersData_2019.json")
}
// Save players and leagues to disk
fileprivate func playersWriteToDisk() {
do {
let data = try JSONEncoder().encode(allPlayers)
try data.write(to: playerDataURL())
} catch let error as NSError {
NSLog("Error reading file: \(error.localizedDescription)")
}
}
fileprivate func leaguesWriteToDisk() {
do {
let data = try JSONEncoder().encode(myLeagues)
try data.write(to: leaguesDataURL())
} catch let error as NSError {
NSLog("Error reading file: \(error.localizedDescription)")
}
}
fileprivate func leaguesPlayersWriteToDisk() {
do {
let data = try JSONEncoder().encode(myLeaguePlayersData)
try data.write(to: leaguePlayersDataURL())
} catch let error as NSError {
NSLog("Error reading file: \(error.localizedDescription)")
}
}
// Load players and leagues from disk
fileprivate func playersReadFromDisk() -> [PlayerData]? {
let filePlayerURL = playerDataURL()
guard FileManager.default.fileExists(atPath: filePlayerURL.path) else {
return nil
}
do {
let fileContents = try Data(contentsOf: filePlayerURL)
let list = try JSONDecoder().decode([PlayerData].self, from: fileContents)
return list
} catch let error as NSError {
NSLog("Error reading file: \(error.localizedDescription)")
}
return nil
}
fileprivate func leaguesReadFromDisk() -> [String]? {
let fileLeaguesURL = leaguesDataURL()
guard FileManager.default.fileExists(atPath: fileLeaguesURL.path) else {
return nil
}
do {
let fileContents = try Data(contentsOf: fileLeaguesURL)
let list = try JSONDecoder().decode([String].self, from: fileContents)
return list
} catch let error as NSError {
NSLog("Error reading file: \(error.localizedDescription)")
}
return nil
}
fileprivate func leaguePlayersReadFromDisk() -> [[PlayerData]]? {
let fileLeaguePlayersURL = leaguePlayersDataURL()
guard FileManager.default.fileExists(atPath: fileLeaguePlayersURL.path) else {
return nil
}
do {
let fileContents = try Data(contentsOf: fileLeaguePlayersURL)
let list = try JSONDecoder().decode([[PlayerData]].self, from: fileContents)
return list
} catch let error as NSError {
NSLog("Error reading file: \(error.localizedDescription)")
}
return nil
}
// Player lists
func playerList(position: String) -> [PlayerData] {
return allPlayers.filter({ $0.position == position })
}
func playerList(topPlayer: Bool) -> [PlayerData] {
return allPlayers.filter({ $0.isTopPlayer == topPlayer })
}
func playerList(rookie: Bool) -> [PlayerData] {
return allPlayers.filter({ $0.isRookie == rookie })
}
// Roster lists/My team lists
func rosterList() -> [PlayerData] {
let rosteredPlayers = allPlayers.filter { ($0.rosterPosition >= 0)}
return rosteredPlayers.sorted(by: { $0.rosterPosition < $1.rosterPosition })
}
func rosterArray() -> [PlayerData] {
let roster = rosterList()
return roster
}
func addToRosterList(player: PlayerData) {
let maxRosteredIndex = allPlayers.map({ $0.rosterPosition }).max()!
player.rosterPosition = maxRosteredIndex + 1
}
fileprivate func removeFromRosterList(player: PlayerData) {
let currentRosterPosition = player.rosterPosition
player.rosterPosition = -1 // No longer on the rosterList. Gets all players on roster at a higher index.
let higherNumberedRosterPlayers = allPlayers.filter({ $0.rosterPosition > currentRosterPosition}) // Their rosterPositions have now gone down by one.
for otherPlayer in higherNumberedRosterPlayers {
otherPlayer.rosterPosition -= 1 // Decrease position by 1.
}
}
// draft List
func draftList() -> [PlayerData] {
let draftedPlayers = allPlayers.filter({ $0.draftPosition >= 0 })
return draftedPlayers.sorted(by: { $0.draftPosition < $1.draftPosition })
}
func addToDraftList(player: PlayerData) {
let maxDraftedIndex = allPlayers.map({ $0.draftPosition }).max()!
player.draftPosition = maxDraftedIndex + 1
}
fileprivate func removeFromDraftList(player: PlayerData) {
let currentDraftPosition = player.draftPosition
player.draftPosition = -1 // No longer on the rosterList. Gets all players on roster at a higher index.
let higherNumberedRosterPlayers = allPlayers.filter({ $0.draftPosition > currentDraftPosition}) // Their rosterPositions have now gone down by one.
for otherPlayer in higherNumberedRosterPlayers {
otherPlayer.draftPosition-=1 // Decrease position by 1.
}
}
func removeFromLists(player: PlayerData) {
removeFromRosterList(player: player)
removeFromDraftList(player: player)
}
fileprivate func removeFromRosterListToBeAdded_2019(player: PlayerData) {
let currentRosterPosition = player.rosterPosition
player.rosterPosition = -1 // No longer on the rosterList. Gets all players on roster at a higher index.
let higherNumberedRosterPlayers = allPlayers.filter({ $0.rosterPosition > currentRosterPosition}) // Their rosterPositions have now gone down by one.
for otherPlayer in higherNumberedRosterPlayers {
otherPlayer.rosterPosition -= 1 // Decrease position by 1.
}
}
// Leagues list to be added to My Leagues
func leaguesList() -> [String] {
return myLeagues
}
func leaguesArray() -> [String] {
let leagues = leaguesList()
return leagues
}
fileprivate func removeFromLeaguesList(player: String) {
let index = IndexPath.Element()
myLeagues.remove(at: index)
}
func removeLeague(league: String) {
removeFromLeaguesList(player: league)
}
// Reset the draft
func resetDraft() {
allPlayers = allPlayersReset
changeMade()
}
// Executed when a change is made
func changeMade() {
playersWriteToDisk()
leaguesWriteToDisk()
}In line 9 of class Database_2019, I created an array of the class PlayerData but it isn't working.This is what class myLeague_2019 looks like:class MyLeague_2019: UIViewController, UITableViewDelegate, UITableViewDataSource {
var players: [[PlayerData]] = [[]]
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
players = Database_2019.shared.myLeaguePlayersData
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return players[section].count
}
func numberOfSections(in tableView: UITableView) -> Int {
return players.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let players = Database_2019.shared.myLeaguePlayersData[indexPath.section][indexPath.row]
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row+1). \(players.name), \(players.team) - \(players.position)"
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.font = UIFont.systemFont(ofSize: 22)
return cell
}
@IBOutlet weak var table: UITableView!
}
I want to be able to reset the properties of a class and then reload the table. I make changes in my app and then it saves the changes of the properties and when I return to the view, it loads the saved changes. I have a row in a table view that will reset the properties in the class back to the default properties. How do I implement this?
I am trying to hide a bar button item. There is no isHidden method for a button. How do I accomplish this?
I have a function that generates the random color. Every time I call the function, it generates the same color. I put the function in viewDidLoad() but it still generates the same color.
Xcode, Swift 4How do I pass data to another view controller in Swift 4?Below is my code and I am getting an error message.I am getting an error on line 181. It saysCannot assign value of type 'DataToPass' to type 'ViewController'struct DataToPass {
var principal: Double = 0
var balance: Double = 0
var monthlyInterest: Double = 0
var paymentNumber: Int = 0
}
class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
var valueToPass: DataToPass = DataToPass(principal: 0.00, balance: 0.00, monthlyInterest: 0.00, paymentNumber: 0)
// Class-level constant to hold the months per year.
let dblMONTHS_YEAR: Double = 12
// To not allow more than 1 decimal point.
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
let countdots = (textField.text?.components(separatedBy: ".").count)! - 1
if countdots > 0 && string == "."
{
return false
}
return true
}
@IBAction func textFieldCost(_ sender: TextField) {
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
@IBAction func textFieldDownPayment(_ sender: TextField) {
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
@IBAction func textFieldMonths(_ sender: TextField) {
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
@IBAction func textFieldAPR(_ sender: TextField) {
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
@IBOutlet weak var txtViewLabels: UITextView!
@IBOutlet weak var txtViewResults: UITextView!
// Text Field Outlets.
@IBOutlet weak var txtCost: UITextField!
@IBOutlet weak var txtDownPayment: UITextField!
@IBOutlet weak var txtMonths: UITextField!
@IBOutlet weak var txtAPR: UITextField!
// Error Message.
@IBOutlet weak var lblMessage: UILabel!
// Buttons
@IBAction func btnCalculate(_ sender: UIButton) {
var dblAPR: Double = 0 // To hold the Annual Rate.
var dblTotalAmount: Double = 0 // To hold the vehicle total cost.
var dblCost: Double = 0 // To hold vehicle cost.
var dblDownPayment: Double = 0 // To hold down payment.
var intMonths: Int = 0 // To hold number of months for the loan.
var dblLoan: Double = 0 // To hold the amount of the loan.
var dblMonthlyPayment: Double = 0 // To hold the monthly payment.
var dblTotalInterest: Double = 0 // To hold the total interest.
var dblMonthlyRate: Double = 0 // To hold the monthly Rate.
var monthlyInterest: Double = 0
var balance: Double = 0
var principal: Double = 0
var paymentNumber: Int = 0
var data: [String] = []
func passedValue() {
func paymentStructure() {
data = []
balance = dblLoan
for _ in 1...intMonths {
paymentNumber+=1
dblCost = Double(txtCost.text!)!
dblDownPayment = Double(txtDownPayment.text!)!
intMonths = Int(txtMonths.text!)!
dblAPR = Double(txtAPR.text!)!
monthlyInterest = balance * ((dblAPR/100)/12)
principal = dblMonthlyPayment - monthlyInterest
balance = balance - principal
let fPrincipal = NSNumber(value: principal)
let fResultPrincipal = NumberFormatter.localizedString(from: fPrincipal, number: .currency)
let fBalance = NSNumber(value: balance)
let fResultBalance = NumberFormatter.localizedString(from: fBalance, number: .currency)
let fMonthlyInterest = NSNumber(value: monthlyInterest)
let fResultMonthlyInterest = NumberFormatter.localizedString(from: fMonthlyInterest, number: .currency)
data += ["\(paymentNumber). P: \(fResultPrincipal), I: \(fResultMonthlyInterest), B: \(fResultBalance)"]
}
valueToPass.paymentNumber = intMonths
valueToPass.monthlyInterest = monthlyInterest
valueToPass.principal = principal
valueToPass.balance = balance
}
}
else if txtCost.text != nil && txtDownPayment.text != nil && txtMonths.text != nil && txtAPR.text != nil {
// Clear the message.
lblMessage.text = ""
dblCost = Double(txtCost.text!)!
dblDownPayment = Double(txtDownPayment.text!)!
intMonths = Int(txtMonths.text!)!
dblAPR = Double(txtAPR.text!)!
// Get the APR rate.
dblAPR = dblAPR / 100
// Get the monthly rate.
dblMonthlyRate = dblAPR / dblMONTHS_YEAR
// Get the monthly payment.
dblMonthlyPayment = (dblCost - dblDownPayment) * (dblMonthlyRate / (1 - pow(1 + dblMonthlyRate, Double(-intMonths))))
// Get the amount of the loan.
dblLoan = dblCost - dblDownPayment
// Get the total interest.
dblTotalInterest = dblMonthlyPayment * Double(intMonths) - dblLoan
// Get the Total Amount.
dblTotalAmount = dblCost + dblTotalInterest
// Get the Vehicle Cost.
dblCost = dblTotalAmount - dblTotalInterest
// Format the results.
let fCost = NSNumber(value: dblCost)
let fResultCost = NumberFormatter.localizedString(from: fCost, number: .currency)
let fDownPayment = NSNumber(value: dblDownPayment)
let fResultDownPayment = NumberFormatter.localizedString(from: fDownPayment, number: .currency)
let fLoan = NSNumber(value: dblLoan)
let fResultLoan = NumberFormatter.localizedString(from: fLoan, number: .currency)
let fMonthlyPayment = NSNumber(value: dblMonthlyPayment)
let fResultMonthkyPayment = NumberFormatter.localizedString(from: fMonthlyPayment, number: .currency)
let fAPR = NSNumber(value: dblAPR)
let fResultAPR = NumberFormatter.localizedString(from: fAPR, number: .percent)
let fTotalInterest = NSNumber(value: dblTotalInterest)
let fResultTotalInterest = NumberFormatter.localizedString(from: fTotalInterest, number: .currency)
let fTotalAmount = NSNumber(value: dblTotalAmount)
let fResultTotalAmount = NumberFormatter.localizedString(from: fTotalAmount, number: .currency)
txtViewLabels.text = " APR:\n Months: \n Cost:\n Down Payment:\n Loan Amount:\n Monthly Payment:\n Total Interest:\n Total Amo
txtViewResults.text = " \(fResultAPR)\n \(intMonths)\n \(fResultCost)\n \(fResultDownPayment)\n \(fResultLoan)\n \(fResultMonthkyPayment)\n \(fResultTotalInterest)\n \(fResultTotalAmount)"
passedValue()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "payout structure" {
if let destVC = segue.destination as? PayoutStructure {
destVC.passedData = valueToPass
}
}
}
}