Unrecognized selector sent to instance 0x7fecc7011000" In Swift - swift

I cannot figure it out why this error is happening unrecognized selector sent to instance 0x7fecc7011000" . I added the all the necessary code but cannot find which selector actually is messing .
Screenshot of the project structure with story board .
The network Manager code .
class NetworkManager {
func getCoins(from url: String, completion: #escaping (Result<VanueResponse, NetworkError>) -> Void ) {
guard let url = URL(string: url) else {
completion(.failure(.badURL))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(.other(error)))
return
}
if let data = data {
//decode
do {
let response = try JSONDecoder().decode(VanueResponse.self, from: data)
completion(.success(response))
} catch let error {
completion(.failure(.other(error)))
}
}
}
.resume()
}
}
Presenter code ..
class VenuePresenter : VanueProtocol{
// creating instance of the class
private let view : VanueViewProtocol
private let networkManager: NetworkManager
private var vanues = [Venue]()
var rows: Int{
return vanues.count
}
// initilanize the class
init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
self.view = view
self.networkManager = networkmanager
}
func getVanue(){
let url = "https://coinmap.org/api/v1/venues/"
networkManager.getCoins(from: url) { result in
switch result {
case.success(let respone):
self.vanues = respone.results
DispatchQueue.main.async {
self.view.resfreshTableView()
}
case .failure(let error):
DispatchQueue.main.async {
self.view.displayError(error.localizedDescription)
print(Thread.callStackSymbols)
}
}
}
}
func getId(by row: Int) -> Int {
return vanues[row].id
}
func getLat(by row: Int) -> Double {
return vanues[row].lat
}
func getCreated(by row: Int) -> Int {
return vanues[row].createdOn
}
func getLon(by row: Int) -> Double? {
return vanues[row].lon
}
}
Protocol code ..
import Foundation
protocol VanueProtocol {
func getVanue()
func getId(by row: Int) -> Int
func getLat(by row: Int) -> Double
func getLon(by row: Int) -> Double?
func getCreated(by row: Int) -> Int
var rows: Int { get }
}
protocol VanueViewProtocol {
func resfreshTableView()
func displayError(_ message: String)
}
Here is the code in view controller .
class ViewController: UIViewController{
private var presenter : VenuePresenter!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
presenter = VenuePresenter(view: self)
presenter.getVanue()
}
}
extension ViewController : VanueViewProtocol{
func resfreshTableView() {
tableView.reloadData()
}
func displayError(_ message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(doneButton)
present(alert, animated: true, completion: nil)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
presenter.rows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: DisplayView.identifier, for: indexPath) as? DisplayView
else { return UITableViewCell() }
let row = indexPath.row
let id = presenter.getId(by: row)
let lat = presenter.getLat(by: row)
guard let lon = presenter.getLon(by: row) else { return UITableViewCell() }
let createdon = presenter.getCreated(by: row)
cell.configureCell(id: id, lat: lat, lon: lon, createdon: createdon)
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
Here is the code in custom view controller named is display view .
import UIKit
class DisplayView: UITableViewCell{
static let identifier = "DisplayView"
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
func configureCell(id: Int ,lat : Double , lon : Double , createdon: Int){
label1.text = String(id)
label2.text = String(lat)
label3.text = String(lon)
label4.text = String(createdon)
}
}
Here is my model .
struct Coin: Codable {
let venues: [Venue]
}
// MARK: - Venue
struct Venue: Codable {
let id: Int
let lat, lon: Double
let category, name: String
let createdOn: Int
let geolocationDegrees: String
enum CodingKeys: String, CodingKey {
case id, lat, lon, category, name
case createdOn = "created_on"
case geolocationDegrees = "geolocation_degrees"
}
}
I added the break point but it retuning nil and it needs to return the data from API . Here is the API link .https://coinmap.org/api/v1/venues/
Here is the screenshot of the error .
Here is the console window .

The problem is this outlet:
IBOutlet weak var tableView: UITableView!
You have hooked it up in the storyboard to the wrong object. It is hooked to the cell, not the table view. It looks like you must have hooked it up and then changed the class of the thing it is hooked to.

Related

Swift - Save all documents of firestore collection in a list of objects

I want to retrieve all the documents of a firestore collection, and then write it in an object then append it my list of objects.
after that i display it in an UITableView.
Here is what I have, it works without errors but when I run it, nothing is displayed.
The list structure:
struct RewardsStruct {
//var rewardKey: String
var Reward: String
var noPoints: String
var QRimageURL: ImageURL = ImageURL(url: nil, didLoad: false)
var Desc: String
var isvalid: Bool
}
Here is my retrieving code:
private func getRewards() {
var rewardsList = [RewardsStruct]()
let db = Firestore.firestore()
db.collection("Rewards").getDocuments { (snapshot, error) in
if error != nil {
print(error)
} else {
for document in (snapshot?.documents)! {
let code = RewardsStruct( Reward: document.data()["Reward"] as! String , noPoints: document.data()["noPoints"] as! String , QRimageURL: document.data()["QRimageURL"] as! ImageURL, Desc:document.data()["Desc"] as! String, isvalid: (document.data()["isvalid"] != nil) )
self.rewardsList.append(code)
DispatchQueue.main.async {
self.CodeTable.reloadData()
}
}
}
}
}
The rest of code in ViewController as some requests
class RewardsVC: UIViewController {
var rewardsList = [RewardsStruct]()
var reward:RewardsStruct!
#IBOutlet weak var infoView: UIView!
#IBOutlet weak var ViewLabel: UILabel!
#IBOutlet weak var CodeTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
CodeTable.delegate = self
CodeTable.dataSource = self
ViewLabel.isHidden = true
infoView.makeCornerRounded(cornerRadius: 30, maskedCorners: [.layerMinXMinYCorner, .layerMaxXMinYCorner])
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
rewardsList.removeAll()
getRewards()
}
private func getRewards() {
....
}
extension RewardsVC: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
CodeTable.backgroundColor = UIColor(named: "#F5F5F5")
return 60
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 125
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("List number of rows")
print(rewardsList.count)
return rewardsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RewardsCell") as! RewardsCell
let object = rewardsList[indexPath.row]
cell.Reward.text = object.Reward
cell.Desc.text = object.Desc
cell.noPoints.text = "-" + object.noPoints + " Points"
return cell
}
func addShadow(backgroundColor: UIColor = .white, cornerRadius: CGFloat = 12, shadowRadius: CGFloat = 5, shadowOpacity: Float = 0.1, shadowPathInset: (dx: CGFloat, dy: CGFloat), shadowPathOffset: (dx: CGFloat, dy: CGFloat)) {
} }
Here is my FireStore:
Try this example code, to ...save all documents of firestore collection in a list of objects....
getRewards(...) is called an asynchronous function, and needs a way to "wait" for the results to be available before you can use them.
There are many ways to do this, here I present an example code that uses a completion handler to pass the results (or errors) of getRewards(...) back to the calling function. Note, the code is untested since I do not have your database (or even Firestore).
// -- here some error type for testing
enum FireError: Error {
case decodingError
case badError
// ...
}
// -- here completion handler
private func getRewards(completion: #escaping ([RewardsStruct], FireError?) -> ()) {
var rewardsList = [RewardsStruct]()
let db = Firestore.firestore()
db.collection("Rewards").getDocuments { (snapshot, error) in
if error != nil {
print(error)
completion([], FireError.badError) // <-- here
} else {
for document in (snapshot?.documents)! {
let code = RewardsStruct(Reward: document.data()["Reward"] as! String , noPoints: document.data()["noPoints"] as! String , QRimageURL: document.data()["QRimageURL"] as! ImageURL, Desc:document.data()["Desc"] as! String, isvalid: (document.data()["isvalid"] != nil) )
self.rewardsList.append(code)
}
completion(rewardsList, nil) // <-- here
}
}
}
Use the function like this:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getRewards() { results, error in // <-- here
if error == nil {
rewardsList.removeAll()
rewardsList = results
DispatchQueue.main.async {
self.CodeTable.reloadData()
}
} else {
// todo deal with errors
}
}
}
Alternatively, you can also use this code, without using a completion handler, since getRewards(...) is inside your UIViewController.
private func getRewards() {
let db = Firestore.firestore()
db.collection("Rewards").getDocuments { (snapshot, error) in
if error != nil {
print(error)
} else {
self.rewardsList.removeAll() // <-- here
for document in (snapshot?.documents)! {
let code = RewardsStruct(Reward: document.data()["Reward"] as! String , noPoints: document.data()["noPoints"] as! String , QRimageURL: document.data()["QRimageURL"] as! ImageURL, Desc:document.data()["Desc"] as! String, isvalid: (document.data()["isvalid"] != nil) )
self.rewardsList.append(code) // <-- here
}
DispatchQueue.main.async { // <-- here
self.CodeTable.reloadData()
}
}
}
}
and use it like this:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getRewards()
}

Filtering Image Data with Search Bar

I am trying to filter the data from API. The is successful loaded into view controller with table view cell . This is a movie applications . I am trying to filter the data based on the user type into the text box . I mentioned in the code filter my the title of the movie but The code is only able to filter the title and overview of the movie but the Image fields remain unfiltered such as image , overview etc. Here is the struct model .
import Foundation
struct Movie: Decodable {
let originalTitle: String
let overview: String
let posterPath: String
enum CodingKeys: String, CodingKey {
case originalTitle = "original_title"
case overview
case posterPath = "poster_path"
}
}
Here is the protocol class code .
import Foundation
class MoviePresenter: MoviePresenterProtocol {
private let view: MovieViewProtocol
private let networkManager: NetworkManager
var movies = [Movie]()
private var cache = [Int: Data]()
var rows: Int {
return movies.count
}
init(view: MovieViewProtocol, networkManager: NetworkManager = NetworkManager()) {
self.view = view
self.networkManager = networkManager
}
func getMovies() {
let url = "https://api.themoviedb.org/3/movie/popular?language=en-US&page=3&api_key=6622998c4ceac172a976a1136b204df4"
networkManager.getMovies(from: url) { [weak self] result in
switch result {
case .success(let response):
self?.movies = response.results
self?.downloadImages()
DispatchQueue.main.async {
self?.view.resfreshTableView()
}
case .failure(let error):
DispatchQueue.main.async {
self?.view.displayError(error.localizedDescription)
}
}
}
}
func getTitle(by row: Int) -> String? {
return movies[row].originalTitle
}
func getOverview(by row: Int) -> String? {
return movies[row].overview
}
func getImageData(by row: Int) -> Data? {
return cache[row]
}
private func downloadImages() {
let baseImageURL = "https://image.tmdb.org/t/p/w500"
let posterArray = movies.map { "\(baseImageURL)\($0.posterPath)" }
let group = DispatchGroup()
group.enter()
for (index, url) in posterArray.enumerated() {
networkManager.getImageData(from: url) { [weak self] data in
if let data = data {
self?.cache[index] = data
}
}
}
group.leave()
group.notify(queue: .main) { [weak self] in
self?.view.resfreshTableView()
}
}
}
Here is the controller code .
import UIKit
class MovieViewController: UIViewController, UISearchBarDelegate {
#IBOutlet weak var userName: UILabel!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
private var presenter: MoviePresenter!
var finalname = ""
override func viewDidLoad() {
super.viewDidLoad()
userName.text = "Hello: " + finalname
setUpUI()
presenter = MoviePresenter(view: self)
searchBarText()
}
private func setUpUI() {
tableView.dataSource = self
tableView.delegate = self
}
private func searchBarText() {
searchBar.delegate = self
}
#IBAction func selectSegment(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 1{
setUpUI()
presenter = MoviePresenter(view: self)
presenter.getMovies()
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == ""{
presenter.getMovies()
}
else {
presenter.movies = presenter.movies.filter({ movies in
return movies.originalTitle.lowercased().contains(searchText.lowercased())
})
}
tableView.reloadData()
}
}
extension MovieViewController: MovieViewProtocol {
func resfreshTableView() {
tableView.reloadData()
}
func displayError(_ message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(doneButton)
present(alert, animated: true, completion: nil)
}
}
extension MovieViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
presenter.rows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell
let row = indexPath.row
let title = presenter.getTitle(by: row)
let overview = presenter.getOverview(by: row)
let data = presenter.getImageData(by: row)
cell.configureCell(title: title, overview: overview, data: data)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dc = storyboard?.instantiateViewController(withIdentifier: "MovieDeatilsViewController") as! MovieDeatilsViewController
let row = indexPath.row
dc.titlemovie = presenter.getTitle(by: row) ?? ""
dc.overview = presenter.getOverview(by: row) ?? ""
dc.imagemovie = UIImage(data: presenter.getImageData(by: row)!)
self.navigationController?.pushViewController(dc, animated: true)
}
}
extension MovieViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
Here is the screenshot of the result .
Caching image in tableview is a little bit tricky, and you may get problem when the cell changes or reusing itself,
that's cause you see same image when texts are different.
there are 2 famous package you can use it for you're problem and it's easy to use with a lot of options.
1- Kingfisher
2- SDWebImage

How to add data into Firestore Swift by tapping on a cell

I have more restaurants , each have diferent food.Look here
This is how im retrieving data from the Firestore. In the previous controller I have a list of restaurants, each contains a list food.
struct Food {
var photoKeyRestaurant: String
var foodName: String
var foodDescription: String
var restaurantName: String
var priceFood: Int
}
class RestaurantViewController: UIViewController {
var restaurantName: String!
var food: [Food] = []
private let tableView: UITableView = {
let table = UITableView()
return table
}()
func getDatabaseRecords() {
let db = Firestore.firestore()
// Empty the array
food = []
db.collection("RestaurantViewController").whereField("restaurantName", isEqualTo: restaurantName).getDocuments { (snapshot, error) in
if let error = error {
print(error)
return
} else {
for document in snapshot!.documents {
let data = document.data()
let newEntry = Food(photoKeyRestaurant: data["photoKeyRestaurant"] as! String, foodName: data["foodName"] as! String, foodDescription: data["foodDescription"] as! String, restaurantName: data["restaurantName"] as! String , priceFood: data["priceLabel"] as! Int
)
self.food.append(newEntry)
}
}
DispatchQueue.main.async {
// self.datas = self.filteredData
self.tableView.reloadData()
}
}
}
How can I add the data of the selected cell by pressing on + to Firestore in this function ?
I'vrea create a protocol in my FoodTableViewCell , and I've called it in the RestaurantViewController.
func diddTapButtonCell(_ cell: FoodTableViewCell) {
let db = Firestore.firestore()
db.collection("cart").addDocument.(data: foodName) { (err) in
}
Edited: Added Table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return food.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FoodTableViewCell", for: indexPath) as! FoodTableViewCell
cell.delegate = self
let mancare = food[indexPath.row]
let storageRef = Storage.storage().reference()
let photoRef = storageRef.child(mancare.photoKeyRestaurant)
cell.foodImage.sd_setImage(with: photoRef)
cell.descriptionLabel.text = mancare.foodDescription
cell.foodNameLabel.text = mancare.foodName
cell.priceLabel.text = "\(mancare.priceFood) lei"
//Fac ca imaginea sa fie cerc - start
cell.foodImage.layer.borderWidth = 1
cell.foodImage.layer.masksToBounds = false
cell.foodImage.layer.borderColor = UIColor.black.cgColor
cell.foodImage.layer.cornerRadius = cell.foodImage.frame.height/2
cell.foodImage.clipsToBounds = true
//Fac ca imaginea sa fie cerc - finish
return cell
}
This is my tableview cell code
protocol CustomCellDelegate {
func diddTapButtonCell (_ cell: FoodTableViewCell)
}
class FoodTableViewCell: UITableViewCell {
var delegate: CustomCellDelegate?
#IBOutlet weak var foodImage: UIImageView!
#IBOutlet weak var foodNameLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBAction func addToCart(_ sender: Any) {
delegate?.diddTapButtonCell(self)
}
}
https://firebase.google.com/docs/firestore/manage-data/add-data
And here is an example from one of my projects for adding data to firestore.
func updateDocument(rootCollection : String, doc: String, newValueDict: [String : Any], completion:#escaping (Bool) -> Void = {_ in }) {
let db = Firestore.firestore()
db.collection(rootCollection).document(doc).setData(newValueDict, merge: true){ err in
if let err = err {
print("Error writing document: \(err)")
completion(false)
}else{
completion(true)
}
}
}

Not able to load data from firestore to uitableview

I am able to query the data and match it to my model but am not able to display it in my table view. I have 3 files I am working with apart from the storyboard.
Here is the main view controller:
class MealplanViewController: UIViewController {
var db: Firestore!
var mealplanArray = [Mealplan]()
#IBOutlet weak var mealplanTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
mealplanTableView?.dataSource = self
mealplanTableView?.delegate = self
db = Firestore.firestore()
loadData()
// Do any additional setup after loading the view.
}
func loadData() {
userEmail = getUserEmail()
db.collection("Meal_Plans").getDocuments() {querySnapshot , error in
if let error = error {
print("\(error.localizedDescription)")
} else {
self.mealplanArray = querySnapshot!.documents.compactMap({Mealplan(dictionary: $0.data())})
print(self.mealplanArray)
DispatchQueue.main.async {
self.mealplanTableView?.reloadData()
}
}
}
}
func getUserEmail() -> String {
let user = Auth.auth().currentUser
if let user = user {
return user.email!
} else {
return "error"
}
}
}
// MARK: - Table view delegate
extension MealplanViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mealplanArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "MealplanTableViewCell", for: indexPath)
let mealplanRow = mealplanArray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "MealplanTableViewCell") as! MealplanTableViewCell
cell.setMealplan(mealplan: mealplanRow)
return cell
}
}
And here is the cell where I am showing one of the queried values:
class MealplanTableViewCell: UITableViewCell {
#IBOutlet weak var mealplanNameLabel: UILabel!
func setMealplan(mealplan: Mealplan) {
// Link the elements with the data in here
mealplanNameLabel.text = mealplan.mpName
print(mealplan.mpName)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
And finally, here is the data model:
import Foundation
import Firebase
protocol MealplanSerializable {
init?(dictionary:[String:Any])
}
struct Mealplan {
var mealplanId:String
var mpName:String
]
}
}
extension Mealplan : MealplanSerializable {
init?(dictionary: [String : Any]) {
guard let
let mealplanId = dictionary["mealplanId"] as? String,
let mpName = dictionary["mpName"] as? String,
else { return nil }
self.init(mealplanId: mealplanId, mpName: mpName)
}
}
I am getting just an empty table view with no data in it.

How to prevent cells from mirroring button pressed action in another cell? Part #2

This would be part # 2 of my question How to prevent cells from mirroring button pressed action in another cell?
What im trying to do is have my buttons have a button pressed turn red while a previously selected button deselects to back to blue, and also preventing it from mirroring the pressed button action in another cell, I have achieved that in a previous question I posted
what Im trying to do is integrate this with classes that pass data from Firebase Firestore. since I don't know where to go to convert this prevent the cells from mirroring the same button select action in another and changes the button selected to red and automatically deselects previous button back to blue
I have been stuck trying to make this work and just not getting the right luck to make it happen, I have been getting error codes in 3 different areas in ViewController preventing my code from compiling and making it work so that it works with my cells that pass data to labels from my cloud Firestore
any help would be appreciated and thank you for your time
import Foundation
import UIKit
class Labels {
var id: String
var lbl1: String
var lbl2: String
var lbl3: String
init(id: String,
lbl1: String,
lbl2: String,
lbl3: String) {
self.id = id
self. lbl1 = lbl1
self. lbl2 = lbl2
self. lbl3 = lbl3
}
convenience init(dictionary: [String : Any]) {
let id = dictionary["id"] as? String ?? ""
let lbl1 = dictionary["lbl1"] as? String ?? ""
let lbl2 = dictionary["lbl2"] as? String ?? ""
let lbl3 = dictionary["lbl3"] as? String ?? ""
self.init(id: id,
lbl1: lbl1,
lbl2: lbl2,
lbl3: lbl3)
}
}
enum ButtonSelectionIdentity {
case first
case second
case third
}
struct CellModel {
let buttonSelectionIdentity: ButtonSelectionIdentity
let labels: Labels
}
import UIKit
import SDWebImage
import Firebase
protocol OptionSelectDelegate: class {
func onCellModelChange(cell: Cell, model: ButtonSelectionIdentity)
}
class Cell: UITableViewCell {
weak var labels: Labels!
private var elements: [ButtonSelectionIdentity] = []
weak var optionSelectDelegate: OptionSelectDelegate?
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
#IBOutlet weak var lbl3: UILabel!
#IBOutlet weak var btnOne: RoundButton!
#IBOutlet weak var btnTwo: RoundButton!
#IBOutlet weak var btnThree: RoundButton!
func configure(withLabels labels: Labels) {
lbl1.text = labels.lbl1
lbl2.text = labels.lbl2
lbl3.text = labels.lbl3
}
override func layoutSubviews() {
super.layoutSubviews()
}
func update(with model: ButtonSelectionIdentity) {
btnOne.backgroundColor = UIColor.blue
btnTwo.backgroundColor = UIColor.blue
btnThree.backgroundColor = UIColor.blue
switch model {
case .first:
btnOne.backgroundColor = UIColor.red
case .second:
btnTwo.backgroundColor = UIColor.red
case .third:
btnThree.backgroundColor = UIColor.red
}
}
#IBAction func optionSelectOne(_ sender: RoundButton!) {
optionSelectDelegate?.onCellModelChange(cell: self, model: .first)
}
#IBAction func optionSelectTwo(_ sender: RoundButton!) {
optionSelectDelegate?.onCellModelChange(cell: self, model: .second)
}
#IBAction func optionSelectThree(_ sender: RoundButton!) {
optionSelectDelegate?.onCellModelChange(cell: self, model: .third)
}
}
import UIKit
import Firebase
import FirebaseFirestore
class ViewController: UIViewController {
private var elements: [CellModel] = []
#IBOutlet weak var tableView: UITableView!
var labelSetup: [Labels] = []
override func viewDidLoad() {
super.viewDidLoad()
//▼ Cannot convert value of type 'ButtonSelectionIdentity' to expected argument type 'CellModel'
elements.append(ButtonSelectionIdentity.first) // error one
tableView.dataSource = self
tableView.delegate = self
fetchLabels { (labels) in
self.labelSetup = labels.sorted(by:
self.tableView.reloadData()
}
}
func fetchLabels(_ completion: #escaping ([Labels]) -> Void) {
let ref = Firestore.firestore().collection("labels")
ref.addSnapshotListener { (snapshot, error) in
guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
return
}
completion(snapshot.documents.compactMap( {Labels(dictionary: $0.data())} ))
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return labelSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? Cell else { return UITableViewCell() }
cell.configure(withLabels: labelSetup[indexPath.row])
cell.optionSelectDelegate = self
let model = elements[indexPath.row]
//▼ Cannot convert value of type 'CellModel' to expected argument type 'ButtonSelectionIdentity'
cell.update (with: CellModel) //error 2
return cell
}
}
extension ViewController: OptionSelectDelegate {
func onCellModelChange(cell: Cell, model: ButtonSelectionIdentity) {
guard let indexPath = productListTableView.indexPath(for: cell) else {
return
}
let index = indexPath.row
elements[index] = model
//▼ Cannot assign value of type 'ButtonSelectionIdentity' to type 'CellModel'
cell.update(with: model) //error 3
}
}