I want to choose and display the correct dataset from Firebase, based on the pickerView selection.
The main problem - the values of the UILabels are not changing.
The second thing I would like to note, that the pickerView does not disappear after I click on one of the values in it.
import UIKit
import Firebase
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var priceView: UILabel!
#IBOutlet weak var dayView: UILabel!
#IBOutlet weak var monthView: UILabel!
#IBOutlet weak var personPicker: UITextField!
var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData = [String]()
var person : String = "jack"
let people = ["jack", "jenny", "don"]
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = UIPickerView()
personPicker.delegate = self
personPicker.inputView = pickerView
ref = Database.database().reference()
ref?.child("xf").child(person).child("price").observe(.value, with: { (snapshot) in
if let i = snapshot.value as? Double
self.priceView.text = "\(i)"
self.priceView.reloadInputViews()
}
})
ref?.child("xf").child(person).child("day").observe(.value, with: { (snapshot) in
if let i = snapshot.value as? String {
self.dayView.text = "\(i)"
self.dayView.reloadInputViews()
}
})
ref?.child("xf").child(person).child("month").observe(.value, with: { (snapshot) in
if let i = snapshot.value as? String {
self.monthView.text = "\(i)"
self.monthView.reloadInputViews()
}
})
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return people.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return people[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
personPicker.text = people[row]
person = people[row]
}
}
For the first issue, I tried adding the 'person = people[row]' but the values in the UILabes do not change
For the issue with the pickerView removal, I tried adding 'pickerView.isHidden = true', but it only removes the values, not the card
Xcode Version 12.3
Related
I have 2 pickerviews, 1 pickerview is to select a crypto-currency from an Array and the other pickerview is used to select a currency from an array. The problem I am having is when I run the app on simulator and select the cryptocurreny in cryptoPicker the app it also selects the same array value from currencyPicker and vice a versa. I don't want the array value of 0 to be pulled from both arrays unless it is selected by the user.
#IBOutlet weak var cryptoCurrentRate: UILabel!
#IBOutlet weak var currencyLabel: UILabel!
#IBOutlet weak var currencyPicker: UIPickerView!
#IBOutlet weak var cryptoPicker: UIPickerView!
#IBOutlet weak var cryptoLabel: UILabel!
var coinManager = CoinManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
coinManager.delegate = self
currencyPicker.dataSource = self
currencyPicker.delegate = self
cryptoPicker.dataSource = self
cryptoPicker.delegate = self
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == currencyPicker {
return coinManager.currencyArray.count
}
if pickerView == cryptoPicker {
return coinManager.cryptoArray.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == currencyPicker {
return coinManager.currencyArray[row]
}
if pickerView == cryptoPicker {
return coinManager.cryptoArray[row]
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let selectedCurrency = coinManager.currencyArray[row]
let selectedCrypto = coinManager.cryptoArray[row]
coinManager.fetchCryptoCoin(assetIdBase: selectedCrypto, assetIdQuote: selectedCurrency)
}
}
Do the same check for picker and in 'didSelectRow', you can do it like this:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var selectedCurrency: CurrencyModel? = nil
var selectedCrypt: CryptModel? = nil
if pickerView == currencyPicker {
selectedCurrency = coinManager.currencyArray[row]
}
if pickerView == cryptoPicker {
selectedCrypto = coinManager.cryptoArray[row]
}
coinManager.fetchCryptoCoin(assetIdBase: selectedCrypt == nil ? coinManager.cryptoArray[.zero] : selectedCrypt!, assetIdQuote: selectedCurrency == nil ? coinManager.currencyArray[.zero] : selectedCurrency!)
}
By default it will get the first value from 'coinManager.currencyArray' or 'coinManager.cryptoArray'
I want to use realm to append all data in one VC.
parentVC is showing Category List, in ParentVC can only append new Category
childVC is showing toDoItem List, and can only append to selectedCategory.toDoList
I created a new VC "addToDoListVC", to achieve result of "Adding new toDoItems to selected todoListCategory".
below is my code and image shown is the new addToDoListVC layout.
addToDoItemVC layout
class Category : Object {
#objc dynamic var categoryName : String = ""
let ofToDoItem = List<ToDoItem>()
}
class ToDoList : Object {
#objc dynamic var toDoItem : String = ""
var parentCategory = LinkingObjects(fromType: Category.self, property: "ofToDoItem")
}
addItemVC
let realm = try! Realm()
var categorySelection : Results<Category>?
#IBOutlet weak var categoryName: UILabel!
#IBOutlet weak var categoryNamePicker: UIPickerView!
#IBAction func addItemBtnPressed(_ sender: UIButton) {
if let currentCategory = self.categorySelection {
do {
try! realm.write
let newToDoItem = ToDoList()
**// HOW DO I ADD THE ITEM TO SELECTED CATEGORY?**
newToDoItem.toDoItem = textField.text
selectedCategory[**???**].ofToDoItem.append(newToDoItem)
**[// I can append data into selected category by "selectedCategory\[0\].ofToDoItem.append(newToDoItem)" but it is hardcoded.][1]**
}
}
}
//MARK:- PICKERVIEW METHODS
extension ParentVC : UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return categorySelection?.count ?? 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return categorySelection?[row].categoryName
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
categoryName.text = categorySelection?[row].categoryName
}
CODE HAS BEEN UPDATED AND IS WORKING AS EXPECTED
I have a View Controller with a text field and a PickerView. I want to display the data i have stored in Firebase inside the PickerView. I'm able to retrieve and print the data from Firebase but I can't find a way to display it inside the PickerView. Here is my code:
import UIKit
import Firebase
class pickerVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet weak var labelTxt: UITextField!
#IBOutlet weak var infoPickerViewer: UIPickerView!
var dbRef: CollectionReference!
var pickerView: UIPickerView?
var itemsClass = [ItemInfo]()
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = UIPickerView()
infoPickerViewer.delegate = self
infoPickerViewer.dataSource = self
dbRef = Firestore.firestore().collection(ITEMS_REF)
labelTxt.inputView = pickerView
labelTxt.delegate = self
self.infoPickerViewer = pickerView
self.infoPickerViewer?.delegate = self
self.infoPickerViewer?.dataSource = self
self.infoPickerViewer.reloadAllComponents()
getItems()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func textFieldDidBeginEditing(_ textField: UITextField) {
labelTxt = textField
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.pickerView?.reloadAllComponents()
return true
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if labelTxt.isFirstResponder {
return self.itemsClass.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if labelTxt.isFirstResponder {
return itemsClass[row].itemName
}
return nil
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if labelTxt.isFirstResponder {
let item = itemsClass[row].itemName
labelTxt.text = item
}
}
func getItems() {
dbRef.getDocuments { (snapshot, error) in
if let err = error {
debugPrint("error fetching docs: \(err)")
} else {
self.infoPickerViewer.reloadAllComponents()
let snap = snapshot
for document in snap!.documents {
let data = document.data()
let itemCode = data[ITEMS_CODE] as? String ?? ""
let itemName = data[ITEMS_NAME] as? String ?? ""
let t = ItemInfo(itemCode: itemCode, itemName: itemName)
self.itemsClass.append(t)
print("ITEMS_CODE", itemCode as Any)
print("ITEMS_NAME", itemName as Any)
}
}
}
}
}
The Firebase DB is structured as follow:
collection/AutoID/itemCode: "item1"
itemName: "item2"
collection/AutoID/itemCode: "item3"
itemName: "item4"
I only need to display the itemName inside the PickerView, the itemCode I'm going to use it to run a query depending on the selection in the PickerView.
Any help with this is greatly appreciated.
From "var myValue:[Double]..." and "var activeCurrency:Double = 0;" to the third pickerview code, I am not sure what to do in order to fix the "self.myValues.append((Url as? Double)!)" so that my app displays the currency amount. I have searched everywhere, and have no luck in finding anything. You are my last hope, please help. I'm still fairly new to coding, so I may not know the certain jargon.
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var myCurrency:[String] = []
var myValues:[Double] = []
var activeCurrency:Double = 0;
//OBJECTS
#IBOutlet weak var textbox: UITextField!
#IBOutlet weak var pickerView: UIPickerView!
#IBOutlet weak var output: UILabel!
//CREATING PICKER VIEW
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return myCurrency.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return myCurrency[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
activeCurrency = myValues[row]
}
//BUTTON
#IBAction func action(_ sender: AnyObject) {
if (textbox.text != "") {
output.text = String(Double(textbox.text!)! * activeCurrency)
}
}
override func viewDidLoad() {
super.viewDidLoad()
//DATA GRABBING
let url = URL(string: "https://min-api.cryptocompare.com/data/all/coinlist")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print ("ERROR")
}
else {
if let content = data {
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let rates = myJson["Data"] as? NSDictionary {
for (Name, Url) in rates {
self.myCurrency.append((Name as? String)!)
self.myValues.append((Url as? Double)!)
}
}
}
catch {
}
}
}
if data != nil {
DispatchQueue.main.async { // Correct
self.pickerView.reloadAllComponents()
}
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I tried to program a sign up view controller and use a UIPickerView for country choice. The issue is that when I tried to pass the picker country to Parse to save the input, Xcode give me an error. Why Xcode can't allow me to use the selected data to Parse? The error is in the last line.
Any help guys?
#IBOutlet var usernameTextField: UITextField!
#IBOutlet var fullnameTextField: UITextField!
#IBOutlet var emailTextField: UITextField!
#IBOutlet var passwordTextField: UITextField!
#IBOutlet var phonenumberTextField: UITextField!
#IBOutlet var countryPicker: UIPickerView!
let countryData: [String] = ["Saudi Arabia", "Turkey"]
#available(iOS 2.0, *)
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return countryData.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let countrySelect = countryData[row]
print(countrySelect)
}
override func viewDidLoad() {
super.viewDidLoad()
countryPicker.dataSource = self
countryPicker.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signUpAction(sender: AnyObject) {
// Declare user object
let newUser = PFUser()
let fullName = fullnameTextField.text!
let username = usernameTextField.text!
let email:String = emailTextField.text!
let password:String = passwordTextField.text!
let phoneNumber:Int? = Int(phonenumberTextField.text!)
// Passing arguments
newUser.username = username
newUser["fullName"] = fullName
newUser.email = email
newUser.password = password
newUser["phoneNumber"] = phoneNumber! as Int
newUser["country"] = countryData [row]
Based on your comment that the error is "unresolved identifier row":
You are never declaring a variable named row, yet you're using it. You can either replace the use of this undefined variable with the correct array index that will give you the country from the countryData variable OR you make sure that row is actually declared and accessible in your function.