How to properly implement a static cell with Swift 3

纵饮孤独 提交于 2020-01-31 15:11:29

问题


I literally could not find a single tutorial that showed me how to build an app that uses static cells; with clickable cells. Based on few out dated posted and object-c answers, I've put something together. My issue is, when I click on a cell, I get staticDemoTableCell is has no member present.

I have embedded a Table Controller in my UIViewController. For that cell (only one so far), I've created a class:

class staticDemoTableCell: UITableViewCell, UITableViewDelegate {
  @IBOutlet weak var tableView: UITableView! 

  override func awakeFromNib() {
    [...]
    tableView.delegate = self
  }

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("clicked") // Works when the cell is clicked
    // self.present() do not work. I need to present another viewcontroller when this cell is clicked
  }

}

Something does not sit right, for every cell is a class?

I really need to know if I went the correct way about doing this. What I really want is more to this such. Have you seen ie: grouped transactions Monday: a list, Tuesday: a list etc. Each cell will be clickable just like the settings of your iOS device. Any pointers will be highly grateful.


回答1:


It's much easier if the table view contains only static cells:

  • In Interface Builder select the table view and set the Content to Static Cells
  • Create IBOutlets and IBActions in the controller class and connect them.
  • Implementing table view data source methods and subclassing cells is not needed.



回答2:


So you can do the following. Set your table view, then make the cells static, once you've done that, you need to make sure you know how many sections you are going to have. This depends on your design or what you want to achieve.

Then you can do something like this:

If you have more than one section, and section 1 has more than one cell. And section 2 has only one cell.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.section {
    case 1:
        switch indexPath.row {
        case 0:
            // Do something
        case 1:
            // Do something 
        default:
            break
        }
    case 2:
        // Do something
    default:
        break
    }
}

If you have only one section with two cells you can do something like:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.row {
    case 0:
        // Do something
    case 1:
        // Do something
    default:
        break
    }
}

I hope this helps to solve your problem. Good luck



来源:https://stackoverflow.com/questions/41658868/how-to-properly-implement-a-static-cell-with-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!