用UIImageView调整单元格高度

时间:2015-10-30 14:59:41

标签: ios uitableview uiimageview

我在UITableViewCell上有一个imageView,我想将cell / imageView的高度设置为不同的值,比较我在原型单元格中设置的值。我不想实现heightForRowAtIndexPath方法,因为我不想预先计算内容的高度。如果设置了 UITableViewAutomaticDimension ,并且至少在iOS 8上heightForRowAtIndexPath不需要实现。

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.estimatedRowHeight = 44.0
    tableView.rowHeight = UITableViewAutomaticDimension
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 3
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
    let iv = cell.viewWithTag(1) as! UIImageView
    iv.image = UIImage(named: "img1")
    let cs = iv.constraints.first! as NSLayoutConstraint
    cs.constant = 100
    cell.layoutIfNeeded()
    cell.setNeedsUpdateConstraints()

    return cell
}

原型的结构:

enter image description here enter image description here

尽管原型中单元格的高度设置为44.0 px,但在cellForRowAtIndexPath方法中我想用100.0 px覆盖此值。

1 个答案:

答案 0 :(得分:0)

它不会像你那样工作。

您应该实现UITableViewDelegate的委托方法

func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    // calculate size of image and return its height here
}