ios - 自定义 UITableViewCell 中的不同高度

标签 ios swift uitableview height

我想以编程方式创建自定义 UITableViewCell 并且单元格具有不同的高度。但高度是固定的。

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

我希望单元格的高度等于框架的高度。 谢谢你,并对我的英语不好感到抱歉。

最佳答案

您可以使用自动布局来设置自适应大小的单元格。 Working with Self-Sizing Table View Cells


或者,您可以在 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]
    }
}

关于ios - 自定义 UITableViewCell 中的不同高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33348409/

相关文章:

iphone - 清除部分 UIImage

Swift - Cocoa - 更改窗口颜色?

ios - 向左滑动时 subview 未被剪裁以删除 UITableViewCell

ios - setValue(value, forKey) 以某种方式改变了 Realm 中的整个数组

core-data - 将 NSArray 转换为 Swift Array<T>

ios - 触发 IBAction 时更新用于创建 UITableView 的数组数据

iphone - 将 indexpath 值传递给 FirstViewController

ios - 错误 ITMS-90171 : Invalid Bundle Structure - The binary file [CocoaPods file]

ios - 在 UIButton 的文本周围添加边框

iOS:隐藏 MapView 但保留覆盖图像?