How to add label to UITableViewCells before inserting rows? - swift

My goal is to insert a label that says "Loading..." to each visible UITableViewCell before I insert the rows into the tableview.
So far I have the following:
I have a fully functional table view that loads the correct number of cells as well as the information to go in each cell. The code is as follows:
override func viewDidAppear(_ animated: Bool) {
let attributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: attributes)
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
MyChallengesTableView.addSubview(refreshControl) // not required when using UITableViewController
self.BetCreatorUsernameArray.removeAll()
self.BetDescriptionArray.removeAll()
self.UserMoneyInBet.removeAll()
self.BetTotalPoolArray.removeAll()
self.BetEndDateArray.removeAll()
loadData()
self.MyChallengesTableView.reloadData()
}
//refresh table view action
#objc func refresh(refreshControl:UIRefreshControl) {
// Code to refresh table view
//refreshes tableview
self.BetCreatorUsernameArray.removeAll()
self.BetDescriptionArray.removeAll()
self.UserMoneyInBet.removeAll()
self.BetTotalPoolArray.removeAll()
self.BetEndDateArray.removeAll()
loadData()
self.MyChallengesTableView.reloadData()
//stops refreshing
self.refreshControl.endRefreshing()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.BetDescriptionArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyChallengesCell", for: indexPath) as! MyChallengesTableViewCell
cell.BetDescriptionOutlet.text = BetDescriptionArray[indexPath.row]
cell.UserMoneyInBetOutlet.text = ("Money In: $" + UserMoneyInBet[indexPath.row])
cell.TotalBetPoolOutlet.text = ("Pool: $" + BetTotalPoolArray[indexPath.row])
cell.BetEndDateOutlet.text = ("End Date: " + BetEndDateArray[indexPath.row])
cell.BetCreatorUsername = BetCreatorUsernameArray[indexPath.row]
cell.betInformation = ["BetDescription" : BetDescriptionArray[indexPath.row],
"BetAmount" : UserMoneyInBet[indexPath.row],
"TotalMoneyInBet" : BetTotalPoolArray[indexPath.row],
"BetEndDate" : BetEndDateArray[indexPath.row],
"BetCreatorUsername" : BetCreatorUsernameArray[indexPath.row]]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(152)
}
#objc func loadData(){
//get username of current user
self.databaseRef.child("Users").child((Auth.auth().currentUser?.uid)!).child("Username").observeSingleEvent(of: .value, with: {(snapshot) in
self.currentUserUsername = snapshot.value as! String
//make dictionary for each bet that a user is in
self.databaseRef.child("UserBets").child(self.currentUserUsername).observeSingleEvent(of: .value, with: {(snapshot1) in
if snapshot1.exists(){
let UserBetsDictionary = snapshot1.value as! NSDictionary
for (Bet, _) in UserBetsDictionary {
//get bet information from the bets in database
self.databaseRef.child("Bets").child((Bet as? String)!).child("BetInfo").observeSingleEvent(of: .value, with: {(snapshot2) in
let BetInfoDictionary = snapshot2.value as! NSDictionary
self.BetCreatorUsernameArray.append((BetInfoDictionary["Creator Username"] as! String))
self.BetDescriptionArray.append((BetInfoDictionary["BetDescription"] as! String))
self.UserMoneyInBet.append((BetInfoDictionary["BetAmount"] as! String))
self.BetTotalPoolArray.append((BetInfoDictionary["TotalMoneyInBet"] as! String))
self.BetEndDateArray.append((BetInfoDictionary["BetEndTime"] as! String))
//insert the rows
if self.BetCreatorUsernameArray.count != 0 {
self.MyChallengesTableView.insertRows(at: [IndexPath(row:self.BetCreatorUsernameArray.count-1, section:0)], with: UITableViewRowAnimation.automatic)
}
})
}
}
})
})
}
I'm not sure if the code matters too much at this point. In short, I want to add a label before running the function "loadData" in ViewDidAppear and then hide the label once the function is ran and the rows are inserted.

I think it will suit you, just make an extension like this:
extension UITableView {
func startLoading() {
let view = UIView()
separatorStyle = .none
let activityIndicatorView = UIActivityIndicatorView(style: .gray)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -10).isActive = true
activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
let label = UILabel()
label.textColor = UIColor.lightGray
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
label.text = "Loading..."
label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 10).isActive = true
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.font = UIFont.systemFont(ofSize: 14)
self.backgroundView = view
}
func stopLoading() {
clearTableView()
}
func clearTableView() {
separatorStyle = .singleLine
self.backgroundView = nil
}
}
And after that just invoke method startLoading on your tableView instance before request, and on result from request invoke stopLoading method.

Related

Getting id by clicking on tableView

By clicking on the red area I get a comment id. But I also want to get the id if I click on the blue button. How can I do that?
Right now I use this to detect a tap on a row. But tapping on button should run some other code.
extension FirstTabSecondViewComment: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
FirstTabSecondViewComment.subComment = table[indexPath.row].commentId ?? ""
print(FirstTabSecondViewComment.subComment)
self.performSegue(withIdentifier: "CommentDetail", sender: Any?.self)
}
}
After you have register your custom cell declare it in cellForRowAt and add target in button cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! MyCell // your custom cell
// add target in buoon cell
cell.YourButtonCell.addTarget(self, action: #selector(submit(_:)), for: .touchUpInside)
return cell
}
after that add submit func:
#objc fileprivate func submit(_ sender: UIButton) {
var superview = sender.superview
while let view = superview, !(view is UITableViewCell) {
superview = view.superview
}
guard let cell = superview as? UITableViewCell else {
print("button is not contained in a table view cell")
return
}
guard let indexPath = tableView.indexPath(for: cell) else {
print("failed to get index path for cell containing button")
return
}
// We've got the index path for the cell that contains the button, now do something with it.
print("button is in index \(indexPath.row)")
}
This is a full code example, copy and paste in a new project and run:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.register(MyCell.self, forCellReuseIdentifier: cellId)
}
#objc fileprivate func submit(_ sender: UIButton) {
var superview = sender.superview
while let view = superview, !(view is UITableViewCell) {
superview = view.superview
}
guard let cell = superview as? UITableViewCell else {
print("button is not contained in a table view cell")
return
}
guard let indexPath = tableView.indexPath(for: cell) else {
print("failed to get index path for cell containing button")
return
}
// We've got the index path for the cell that contains the button, now do something with it.
print("button is in index \(indexPath.row)")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! MyCell
// add target in buoon cell
cell.cancelButton.addTarget(self, action: #selector(submit(_:)), for: .touchUpInside)
return cell
}
}
class MyCell: UITableViewCell {
let cancelButton: UIButton = {
let b = UIButton(type: .system)
b.backgroundColor = .white
b.setTitle("get Index", for: .normal)
b.layer.cornerRadius = 10
b.clipsToBounds = true
b.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
b.tintColor = .black
b.translatesAutoresizingMaskIntoConstraints = false
return b
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .darkGray
contentView.addSubview(cancelButton)
cancelButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
cancelButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
cancelButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
cancelButton.widthAnchor.constraint(equalToConstant: 300).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

Value of type 'PostModel.Type' has no subscripts swift

Im not too sure why its giving me the error "Value of type 'PostModel.Type' has no subscripts"enter image description here
.
class Universalchatcontroller: UIViewController,UITableViewDelegate,UITableViewDataSource{
let transition = slide()
var tableview : UITableView!
var postsdata = [PostModel]()
// var ref : DatabaseReference!
// var databaseHandle : DatabaseHandle?
override func viewDidLoad()
{
super.viewDidLoad()
print("mainviewdidload")
//LOOK HERE RAYMOND
//Building a News Feed w/ AutoLayout Constraints - Swift & Firebase Part 4 (youtube)
tableview = UITableView(frame:view.bounds,style: .plain)
//tableview.backgroundColor = UIColor.blue
view.addSubview(tableview)
var layoutguide : UILayoutGuide!
layoutguide = view.safeAreaLayoutGuide
let cellNib = UINib(nibName:"POSTTableViewCell" , bundle: nil)
tableview.register(cellNib, forCellReuseIdentifier: "postcell")
tableview.leadingAnchor.constraint(equalTo: layoutguide.leadingAnchor).isActive = true
tableview.topAnchor.constraint(equalTo: layoutguide.topAnchor).isActive = true
tableview.trailingAnchor.constraint(equalTo: layoutguide.trailingAnchor).isActive = true
tableview.bottomAnchor.constraint(equalTo: layoutguide.bottomAnchor).isActive = true
tableview.delegate = self
tableview.dataSource = self
observePosts()
tableview.reloadData()
}
func observePosts() {
let postref = Database.database().reference().child("moreposts?")
var tempPost = [PostModel]()
postref.observe(.value, with: {snapshot in
for child in snapshot.children {
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String: Any],
let author = dict["author"] as? [String:Any],
let uid = author[Auth.auth().currentUser!.uid],
let text = dict["text"]as? String,
let username = author[(Auth.auth().currentUser?.displayName)!] as? String {
let raymond = Auth.auth().currentUser?.displayName
let postMODEL = PostModel(id: childSnapshot.key, author: raymond!, text: text)
tempPost.append(postMODEL)
}
}
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postsdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postcell", for: indexPath) as! POSTTableViewCell
cell.set(post: PostModel[indexPath.row])
return cell
}
try and use the same data source object.
cell.set(post: PostModel[indexPath.row])
To
cell.set(post: postsdata[indexPath.row])
You have to assign array of PostModel replace
cell.set(post: PostModel[indexPath.row])
with
cell.set(post: postsdata[indexPath.row])
And from you code in observePosts() add data to postsdata or declare tempPost globally and use that array in cellForRowAt

Filter data from TableView

How can I filter a tableView by search bar? I fetch data to the tableView from a Firebase database and my search bar is inside navigationBar.
This is my code:
class TableViewCustomer: UIViewController, UITableViewDelegate, UITableViewDataSource {
var ref:DatabaseReference!
var customerList = [CustomerModel]()
lazy var searchBar: UISearchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 300, height: 20))
#IBOutlet weak var tableViewCustomer: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.placeholder = "Search"
navigationItem.titleView = searchBar
if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.gray
if let backgroundview = textfield.subviews.first {
backgroundview.backgroundColor = UIColor.white
backgroundview.layer.cornerRadius = 18
backgroundview.clipsToBounds = true
}
}
tableViewCustomer.delegate = self
tableViewCustomer.dataSource = self
ref = Database.database().reference().child("Customer");
ref.observe(DataEventType.value, with: { (snapshot) in
if snapshot.childrenCount > 0 {
self.customerList.removeAll()
for results in snapshot.children.allObjects as! [DataSnapshot] {
let results = results.value as? [String: AnyObject]
let name = results?["Name and surname"]
let phone = results?["Phone"]
let company = results?["Company name"]
let myCustomer = CustomerModel(name: name as? String, phone: phone as? String, company: company as? String)
self.customerList.append(myCustomer)
}
self.tableViewCustomer.reloadData()
}
})
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
#objc func buttonAction(sender: UIButton!) {
dismiss(animated: true, completion: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return customerList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewCustomer.dequeueReusableCell(withIdentifier: "cellCustomer") as! TableViewCellCustomer
cell.layer.backgroundColor = UIColor.init(white: 1, alpha: 0.7).cgColor
let customer: CustomerModel
customer = customerList[indexPath.row]
cell.nameLabel.text = customer.name
cell.phoneLabel.text = customer.phone
cell.companyLabel.text = customer.company
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "description", sender: self)
}
}
Add your search bar, and an empty array. As you search add the suitable items to the empty array, then remove them from the array. Use the new array to index into your UI.

searchBar filtered tableViewCells didSelectItemAt indexPath display in navigationBar Title

enter image description hereI am having trouble implementing a didSelectRowAtIndexPath from a searchBar filtered tableView cell. When I update the tableView list based on searchbar textDidChange, and perform a show segue to another ViewController, the navigationBar Title is always displaying the non-filtered tableViews indexPath 0. In other words, I would like to have the navigation title display the text from the didSelectAtIndex of search results tableView (not the original indexPath cell text from the non-filtered tableView). Hopefully that makes sense, and thanks in advance!
// viewDidLoad method
override func viewDidLoad() {
super.viewDidLoad()
searchBar.searchBarStyle = UISearchBarStyle.prominent
searchBar.placeholder = " Search Places..."
searchBar.sizeToFit()
searchBar.isTranslucent = false
searchBar.backgroundImage = UIImage()
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
navigationItem.titleView = searchBar
ref = FIRDatabase.database().reference()
fetchPlaces()
placesClient = GMSPlacesClient.shared()
locationManager.requestAlwaysAuthorization()
tableView.allowsMultipleSelectionDuringEditing = true
}
var placeList = [Place]()
var placesDictionary = [String: Place]()
// fetch places for tableView method
func fetchPlaces() {
let uid = FIRAuth.auth()?.currentUser?.uid
let ref = FIRDatabase.database().reference().child("users").child(uid!).child("Places")
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let place = Place()
place.setValuesForKeys(dictionary)
if let addedBy = place.addedBy {
self.placesDictionary[addedBy] = place
self.placeList.insert(place, at: 0)
}
//this will crash because of background thread, so lets call this on dispatch_async main thread
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}, withCancel: nil)
}
// search variables
lazy var searchBar:UISearchBar = UISearchBar()
var isSearching = false
var filteredData = [Place]()
// searchBar method
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
tableView.reloadData()
} else {
isSearching = true
filteredData = placeList.filter({$0.place?.range(of: searchBar.text!) != nil})
tableView.reloadData()
}
}
// tableView methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching {
return filteredData.count
}
return placeList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
if isSearching {
cell.textLabel?.text = filteredData[indexPath.row].place
} else {
cell.textLabel?.text = placeList[indexPath.row].place
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let placeDetailsVC = CurrentUserPlaceDetailsVC()
if isSearching == false {
placeDetailsVC.navigationTitle = placeList[(indexPath.row)].place
show(placeDetailsVC, sender: self)
} else {
placeDetailsVC.navigationTitle = filteredData[(indexPath.row)].place
show(placeDetailsVC, sender: self)
}
}
}
Create a string in your up coming ViewController.
class CurrentUserPlaceDetailsVC: UIViewController {
var navigationTitle: String?
override func viewDidLoad(){
super.viewDidLoad()
self.navigationItem.title = navigationTitle
}
}
Now instead of assigning the title directly to navigationBar you should assign it first to that string and then to navigationBar in viewDidLoad method of your viewController.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let placeDetailsVC = CurrentUserPlaceDetailsVC()
// Get Cell Label
placeDetailsVC.navigationTitle = placeList[indexPath.row].place
show(placeDetailsVC, sender: self)
}

TableView Swift with dynamic and fixed cells

I'm making an app that displays data from Firebase , I have a TV that has to show one fixed cell (to choose the type of data to display) and the other cell to display data from server this is the code:
import UIKit
import Firebase
import SwiftDate
class EventiTVC: UITableViewController {
let userID = FIRAuth.auth()?.currentUser?.uid
let ref = FIRDatabase.database().reference()
let utente = UserDefaults.standard
#IBOutlet weak var Menu_button: UIBarButtonItem!
var Eventi:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
Menu_button.target = self.revealViewController()
Menu_button.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
let imageView = UIImageView(image: #imageLiteral(resourceName: "Hangover_Background"))
imageView.contentMode = .scaleAspectFill
self.tableView.backgroundView = imageView
self.tableView.tableFooterView = UIView()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: 19)!]
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.revealViewController() != nil {
Menu_button.target = self.revealViewController()
Menu_button.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
self.navigationController?.navigationBar.barTintColor = UIColor.orange
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: 19)!,NSForegroundColorAttributeName : UIColor.white]
DeterminaInfoProprietario()
DeterminoLocali()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0{
return 1
}
else {
return Eventi.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0{
let cell = Bundle.main.loadNibNamed("Event_Type", owner: self, options: nil)?.first as! Event_Type
return cell
}
else {
let cell = Bundle.main.loadNibNamed("Evento", owner: self, options: nil)?.first as! Evento
let EventoCorrente = Eventi[indexPath.row]
// scarico info Evento corrente ref.child("Eventi").child(EventoCorrente).observeSingleEvent(of: .value, with: { (snap) in
if snap.childrenCount != 0 {
let DatiEvento = snap.value as? NSDictionary
cell.Nome.text = DatiEvento?.value(forKey: "Nome") as! String!
cell.Locale.text = DatiEvento?.value(forKey: "Locale") as! String!
let urlcopertina = DatiEvento?.value(forKey: "Immagine Copertina") as! String!
cell.Copertina.aail_load(url: NSURL(string: urlcopertina!)!)
// per scaricare il colore , devo scaricare il locale
let locale = DatiEvento?.value(forKey: "Locale") as! String!
var Colore:UIColor? = nil
var Ombra:UIColor? = nil
self.ref.child("Locali").child(locale!).observeSingleEvent(of: .value, with: { (snap2) in
if snap2.childrenCount != 0 {
let DatiLocale = snap2.value as? NSDictionary
Colore = ColoriDaStringa(Colore: (DatiLocale?.value(forKey: "Colore Pagina"))! as! String)[0]
Ombra = ColoriDaStringa(Colore: (DatiLocale?.value(forKey: "Colore Pagina"))! as! String)[1]
cell.ViewC.backgroundColor = Colore!
cell.View_ombra.backgroundColor = Ombra!
}
})
}
else {
// Evento Cancellato? // gestire situazione
}
})
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
if indexPath.row == 0{
return 44
}else {
return 190
}
}
#IBAction func ritornaHome (Segue:UIStoryboardSegue){
}
}
I got 2 static cell and 1 dynamic cell, it should be the other way around, any idea why?
In your cellForRowAtIndexPath() method you should change your if statement from:
if (indexPath.row == 0)
to
if (indexPath.section == 0)
Modify these two functions to:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Eventi.count+1
}
As we should go with latest features. You should go with Auto layout. Auto layout has in built feature for showing dynamic height of UITableView Cell. Refer below link if you want to learn.
Dynamic cell height UITableview
Otherwise here we have answer of issue in your code.
In numberOfSections() you have set wrong condition. Just replace
return 2
to
return 1
And
in numberOfRowsInSection() replace
if section == 0{
return 1
}
else {
return Eventi.count
}
to
return Eventi.count+1