ios - 使用 UIStackView 的动态 UITableView 行高?

标签 ios xcode uitableview autolayout uistackview

令人惊讶的是,这并不是开箱即用的,因为这似乎是堆栈 View 的一个重要用例。我有一个 UITableViewCell 子类,它向 contentView 添加了一个 UIStackView。我在 tableView(_cellForRowAtIndexPath:) 中向堆栈 View 添加标签,并且 tableview 设置为使用动态行高,但它似乎不起作用,至少在 Xcode 7.3 中是这样。我也觉得在堆栈 View 中隐藏排列的 subview 是可动画的,但这似乎也被破坏了。

关于如何让它正常工作的任何想法?

Broken dynamic row heights

class 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 = .Vertical
        stack.distribution = .FillProportionally
        stack.alignment = .Fill
        stack.spacing = 3.0
        stack.translatesAutoresizingMaskIntoConstraints = false
        return stack
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.addSubview(stackView)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func updateConstraints() {
        if !hasSetupConstraints {
            hasSetupConstraints = true
            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)
            addConstraints(newConstraints)
        }
        super.updateConstraints()
    }

    private func newConstraints(visualFormat: String, viewsDictionary: [String:AnyObject]) -> [NSLayoutConstraint] {
        return NSLayoutConstraint.constraintsWithVisualFormat(visualFormat, options: [], metrics: nil, views: viewsDictionary)
    }

class ViewController: UITableViewController {

    private let reuseIdentifier = "StackCell"
    private let cellClass = StackCell.self

    override func viewDidLoad() {
        super.viewDidLoad()
        configureTableView(self.tableView)
    }

    private func configureTableView(tableView: UITableView) {
        tableView.registerClass(cellClass, forCellReuseIdentifier: reuseIdentifier)
        tableView.separatorStyle = .SingleLine
        tableView.estimatedRowHeight = 88
        tableView.rowHeight = UITableViewAutomaticDimension
    }

    private func newLabel(title: String) -> UILabel {
        let label = UILabel()
        label.text = title
        return label
    }

    // MARK: - UITableView
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 4
    }

    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44.0
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StackCell
        cell.stackView.arrangedSubviews.forEach({$0.removeFromSuperview()})
        cell.stackView.addArrangedSubview(newLabel("\(indexPath.section)-\(indexPath.row)"))
        cell.stackView.addArrangedSubview(newLabel("Second Label"))
        cell.stackView.addArrangedSubview(newLabel("Third Label"))
        cell.stackView.addArrangedSubview(newLabel("Fourth Label"))
        cell.stackView.addArrangedSubview(newLabel("Fifth Label"))
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! StackCell
        for (idx, view) in cell.stackView.arrangedSubviews.enumerate() {
            if idx == 0 {
                continue
            }
            view.hidden = !view.hidden
        }
        UIView.animateWithDuration(0.3, animations: {
            cell.contentView.layoutIfNeeded()
            tableView.beginUpdates()
            tableView.endUpdates()

        })
    }
}

最佳答案

似乎要使其正常工作,需要在 UITableViewCell 的初始化中添加约束,并添加到 contentView 而不是单元格的 View 中。

enter image description here

工作代码如下所示:

import UIKit
class 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)
    }
}

关于ios - 使用 UIStackView 的动态 UITableView 行高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238662/

相关文章:

ios - 快速捕获无效用户输入的异常

ios - 用于坐标的 Obj-c 数组 - 最佳实践?

ios - 在应用程序中附加文档,打开文档文件夹或单击按钮列表

ios - 架构 i386 Facebook SDK 的 undefined symbol

ios - 我如何解决因内存错误而终止

ios - Swifty JSON UITableView 后台报错

ios - 我的应用程序正在请求 “Have offline access” 的权限,为什么?

xcode - 快捷按键功能,再按一次反转

ios - 将 UITableViewCell 设置为在代码中选中

iphone - 在 1 个单元格内绘制 6 个 ImageView