ios - 可扩展单元格,自定高度

标签 ios swift uitableview uiview uilabel

我制作了具有动态数量的 UILabels 的可扩展 View (根据查询生成的结果数以编程方式创建)。但是,我无法根据展开 View 中有多少 UILabels 来调整展开 View 的高度。

使用 for 循环 我制作的标签与查询后的结果一样多。

现在我把它们放到 View 中是这样的:

for (index, _) in timesBetween2Stations.enumerated() {
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 20))
            cell.ExpandableView.addSubview(label)
            label.translatesAutoresizingMaskIntoConstraints = false
            label.center = CGPoint(x: cell.ExpandableView.frame.width / 2, y: 0)
            label.textAlignment = NSTextAlignment.center
            var substationTime = timesBetween2Stations[index]?.time
            let substation = timesBetween2Stations[index]?.station
            substationTime = substationTime!.removeTrainTimeZeros()
            label.text = substation! + " " + substationTime!
            cell.ExpandableView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[label]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["label": label, "expandable": cell.ExpandableView]))
            if (previousLabel == nil){
                cell.ExpandableView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(10)-[label]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["label": label, "expandable": cell.ExpandableView]))
            }
            else {
                cell.ExpandableView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[previousLabel]-(10)-[label]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["label": label, "previousLabel": previousLabel as Any]))
            }
            previousLabel = label

            }

问题是 - 为什么它不根据约束调整 View 高度? :)

最佳答案

试试这个:

cell.setNeedsLayout()
cell.layoutIfNeeded()

cell.setNeedsUpdateConstraints()
cell.updateConstraintsIfNeeded()

lor 之后。

关于ios - 可扩展单元格,自定高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41226290/

相关文章:

ios - 如何从 TableView 行和核心数据实体中删除数据?

ios - SKProductsRequest 返回 0 个产品

ios - swift 3 错误 UILabel : the use of CGColor for color properties or inside attributed strings is not supported

swift - 存储对 UIImage 的引用

iOS:Tableview 多选 - AccessoryCheckmark 检查可重复使用的单元格

ios - 如何在 textview 中输入后关闭 tableView 中的键盘

ios - 如何为我的 block 方法创建包装器类,以便我可以单行使用它

ios - 在 Firebase Analytics for iOS 中设置计划计时器

swift - 如何以编程方式将 9 个偶数图像添加到 View |Swift

ios - CoreBluetooth 函数不适用于 Singleton