Dynamic UITableView row height using UIStackView? Dynamic UITableView row height using UIStackView? xcode xcode

Dynamic UITableView row height using UIStackView?


It seems that for this to work the constraints need to be added in the init of the UITableViewCell and added to the contentView instead of cell's view.

enter image description here

The working code looks like this:

import UIKitclass StackCell : UITableViewCell {    enum VisualFormat: String {        case HorizontalStackViewFormat = "H:|[stackView]|"        case VerticalStackViewFormat = "V:|[stackView(>=44)]|"    }    var hasSetupConstraints = false    lazy var stackView : UIStackView! = {        let stack = UIStackView()        stack.axis = UILayoutConstraintAxis.Vertical        stack.distribution = .FillProportionally        stack.alignment = .Fill        stack.spacing = 3.0        stack.translatesAutoresizingMaskIntoConstraints = false        stack.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Vertical)        return stack    }()    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {        super.init(style: style, reuseIdentifier: reuseIdentifier)        contentView.addSubview(stackView)        addStackConstraints()    }    required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }    private func addStackConstraints() {        let viewsDictionary: [String:AnyObject] = ["stackView" : stackView]        var newConstraints = [NSLayoutConstraint]()        newConstraints += self.newConstraints(VisualFormat.HorizontalStackViewFormat.rawValue, viewsDictionary: viewsDictionary)        newConstraints += self.newConstraints(VisualFormat.VerticalStackViewFormat.rawValue, viewsDictionary: viewsDictionary)        contentView.addConstraints(newConstraints)        super.updateConstraints()    }    private func newConstraints(visualFormat: String, viewsDictionary: [String:AnyObject]) -> [NSLayoutConstraint] {        return NSLayoutConstraint.constraintsWithVisualFormat(visualFormat, options: [], metrics: nil, views: viewsDictionary)    }}