简体   繁体   中英

How to hide empty cell tableview, which are not at the end? Swift 3

I'm just starting swift and I'm making a calendar app. Right now I'm showing a list on events if you click on a date. All questions here are about hiding cells that are at the end of a tablieview, but mine are not so eventsTableView.tableFooterView = UIView() doesn't work.

override func viewDidLoad() {
    super.viewDidLoad()
    eventsTableView.register(UITableViewCell.self, forCellReuseIdentifier: "theCell")
    self.eventsTableView.rowHeight = 80
}

func tableView(_ eventsTableView: UITableView,
               cellForRowAt indexPath: IndexPath)->UITableViewCell{


    let event = model.events[indexPath.row]

    let theItem = eventsTableView.dequeueReusableCell(
        withIdentifier: "theCell",for: indexPath)

    let what = event.value(forKeyPath:"what") as? String
    let location = event.value(forKeyPath:"location") as? String
    let when = event.value(forKeyPath:"when") as? Date

    if model.checkDay(date: when!) == model.givendate && model.checkMonth(date: when!) == model.displayedMonth {
        theItem.textLabel?.numberOfLines = 3
        let labelText = what! + "\n" + "time: " + model.getTime(date: when!) + "\n" + "location: " + location!
        theItem.textLabel?.text = labelText
    } else {
        theItem.textLabel?.numberOfLines = 0
    }
    print(theItem)
    return theItem
}

This is what my output looks like

Try this code : You can put a check for empty data in a model and hide that cell completely like this:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  //Check if model is empty
  if shouldHideCell {
            return 0
        } else {
            return UITableViewAutomaticDimension
        }
  }

Please refer to this SO Post . Happy coding.

What you can do here is just customise your dataSource, like if the Data corresponding to that row is empty then it's better to not to add that row in your datasource array.

Example while customising your dataSource

if hasEvent{
dataSource.append(day)
}else{
// No need to show in UI
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM