Swift - Constraints issue in expandable TableViewCell

梦想与她 提交于 2019-12-25 08:14:06

问题


I'm creating an expandable cell with labels and picker view

xib

Cell Implementation

class PickerViewCell: UITableViewCell {

@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var height: NSLayoutConstraint!
@IBOutlet weak var picker: UIDatePicker!
var isExpanded:Bool = false
    {
        didSet
        {
            if isExpanded == false{
                self.height.constant = 0.0
                self.picker.hidden = true

            }
            else{
                self.height.constant = 200.0
                self.picker.hidden = false
            }
        }
}
override func awakeFromNib() {
    self.height.constant = 0.0
    super.awakeFromNib()
}

Delegate method

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    guard let cell = tableView.cellForRowAtIndexPath(indexPath) as? PickerViewCell else { return }

    cell.isExpanded = !cell.isExpanded
    print(cell.isExpanded)
    UIView.animateWithDuration(0.3) {
        cell.contentView.layoutIfNeeded()
    }

    tableView.beginUpdates()
    tableView.endUpdates()

    tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}

I keep getting runtime warining about breaking constraints.

I set up a symbolic breakpoint and what I found out is that this line

self.height.constant = 200.0

inside cell implementation is the reason of the warning.

However, I found out that it happens only during the first tap on a given cell, after the initial tap I can tap multiple times, expanding and closing it each time, and the warning does not occur. Should I even care about this runtime warning?

EDIT:

I forgot to show datePicker constraints including those on height and aspect ratio:

Also it's worth to mention that I utilize

self.tableView.estimatedRowHeight = 100.0
self.tableView.rowHeight = UITableViewAutomaticDimension

in my viewController


回答1:


You set datePicker height to 200, but then set cell height to 200 too. But cell height is datePicker's height + 10 + label's height. So those constraints conflict to each other.




回答2:


I tried before to lower the priority of height constraint to 750 and lower, that did not work.

However, thanks to this answer https://stackoverflow.com/a/30333810/4286947 I set it equal to 999 and this turns out to be the solution here



来源:https://stackoverflow.com/questions/39081865/swift-constraints-issue-in-expandable-tableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!