简体   繁体   中英

Set height of a specific cell in my UITableView

I have two cells (one dynamic and other static) and I want to set different height for each cell like:

 override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       /*tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath)
       tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
      if cell1 return 100
      if cell2 return 20  */
    }

It's possible to specific height for each cell not row.
How can I resolve this issue?

For static cell (created either as Xib or in storyboard), you can set the height like this, if you are displaying static cell in first row of your Table View.

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
    return 120
}

return UITableViewAutomaticDimension

}

To populate the static cell along with dynamic cell, You should do,

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return datasource.count + 1

}

UITableViewAutomaticDimension

https://www.raywenderlich.com/129059/self-sizing-table-view-cells -

If you set correctly the autolayout for the cell you can use UITableViewAutomaticDimension to have the size without have to specify.

*In, Swift 3.0

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

   if indexPath.row == 0 {

         return 100
   } else {

         return 200
   }

}

or you can set Constraint of your Cell proper and then write this code of your ViewDidLoad Method

yourTblView.estimatedRowHeight = 100

yourTblView.rowHeight = UITableViewAutomaticDimension*
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
      if indexPath.row == 0 {
          return 100
      } else {
          return 20
      }
}

You only need to return a height for each indexPath. There is no need to dequeue a cell here. If you want different prototype cells you will do this in cellForRowAtIndexPath .

You can specify as many sections and rows as you want:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
      switch indexPath.section {
      case 0:
          switch indexPath.row {
          case 0:
              return 100.0
          case 1:
              return 20.0
          // Add rows here if needed
          default:
              return UITableViewAutomaticDimension
      // Add sections here if needed
      default:
          default:
              return UITableViewAutomaticDimension
      }
}

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