Peggy
Peggy

Reputation: 372

How to change height of UITableView cell in Swift?

I am trying to show a comment on an app like in the following pictures. I'm using Xcode 9.4.1.

app view

I use the following code to hide the label:

if commentManager == nil {
    cell.managerReplyLabel.isHidden = true
    cell.ratingManagerLabel.isHidden = true
}

But it looks still like it has a space on it which I hidden two labels.

I try to use cell.ratingManagerLabel.font.withSize(0) or cell.ratingManagerLabel.frame.size.height = 0 to change the label hight, but it doesn't work.

How to reduce the space?

Update:

I use storyboard to set the screen and auto-layout.

autolayout

import UIKit
import Cosmos

class RatingTableViewCell: UITableViewCell {

    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var ratingStar: CosmosView!
    @IBOutlet weak var ratingUserLabel: UILabel!
    @IBOutlet weak var ratingManagerLabel: UILabel!

    @IBOutlet weak var managerReplyLabel: UILabel!

}

Upvotes: 4

Views: 15385

Answers (3)

Alisha Chaudhary
Alisha Chaudhary

Reputation: 21

use this tableview method for increasing and decreasing height of row

var selectedIndex = -1

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == selectedIndex {
            return 354
        }else {
            return 115
        }
    }

Upvotes: 1

Sulthan
Sulthan

Reputation: 130092

There are two easy solutions:

  1. Set the text on both labels to nil (or ""). Then the labels will have zero height.

  2. Wrap the labels into a UIStackView with vertical layout direction. Then setting .isHidden = true will effectively remove the labels too.

Also note that you might need to call:

tableView.beginUpdates()
tableView.endUpdates()

to force the table to update height of its cells.

Upvotes: 7

Daniel Espina
Daniel Espina

Reputation: 674

Use the delegate method in your UITableView Class.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return 200 //or whatever you need
}

Upvotes: 8

Related Questions