简体   繁体   English

自定义UITableViewCell中的不同高度

[英]Different height in custom UITableViewCell

I want to create a custom UITableViewCell programmatically and cells have different height. 我想以编程方式创建自定义UITableViewCell,并且单元格具有不同的高度。 But the height is fixed. 但是高度是固定的。

SingeTableViewCell.swift 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. 谢谢,抱歉我的英语不好。

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 或者,您可以使用UITableViewDelegate - tableView:heightForRowAtIndexPath:来设置高度

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]
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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