BSK-Team
BSK-Team

Reputation: 1810

Different height in custom UITableViewCell

I want to create a custom UITableViewCell programmatically and cells have different height. But the height is fixed.

SingeTableViewCell.swift

class SingleTableViewCell: UITableViewCell {

var title = UILabel()
var content = UILabel()

override func awakeFromNib() {
    super.awakeFromNib()

    self.setSeparator()
    self.setTitle()
    self.setContent()

}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

func setSeparator() {
    let separator = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 10))
    separator.backgroundColor = UIColor(hex: "#E7EBF2")
    contentView.addSubview(separator)
}

func setTitle() {
    let viewTitle = UIView(frame: CGRectMake(0, 10, UIScreen.mainScreen().bounds.width, 40))
    viewTitle.backgroundColor = UIColor(hex: "#EEE")
    viewTitle.layer.borderColor = UIColor.lightGrayColor().CGColor
    viewTitle.layer.borderWidth = 1.0
    self.title = UILabel(frame: CGRectMake(5, 0, UIScreen.mainScreen().bounds.width-5, 40))
    self.title.textAlignment = NSTextAlignment.Center
    self.title.font = self.title.font.fontWithSize(13)
    viewTitle.addSubview(self.title)
    contentView.addSubview(viewTitle)
}

func setContent() {
    self.content = UILabel(frame: CGRectMake(0, 50, UIScreen.mainScreen().bounds.width, 400))
    self.backgroundColor = UIColor.whiteColor()
    contentView.addSubview(self.content)
}

}

I want cell's height is equals to frame's height. Thank you and sorry for my bad english.

Upvotes: 0

Views: 71

Answers (1)

nRewik
nRewik

Reputation: 9148

You can use Auto Layout to set self-sizing cell. Working with Self-Sizing Table View Cells


Alternatively, you can set the height with - tableView:heightForRowAtIndexPath: in UITableViewDelegate

class ViewController: UIViewController, UITableViewDelegate{

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // assume that you want to set height equal to 300 in 1st secion, and 200 in 2nd section.
        let heights: [CGFloat] = [ 300,200 ]
        return heights[indexPath.section]
    }
}

Upvotes: 1

Related Questions