Swift 3 - 从xib加载的UITableViewCell - 自动布局和高度不正确

时间:2017-05-11 15:47:14

标签: ios swift xcode uitableview swift3

我有一个关于UITableViewCell的问题,它是从xib加载并放入表中的。我用xib设计了一个自定义高度的单元格和我的东西。我有自己的桌子:

class MyTableView: UITableView, UITableViewDataSource, UITableViewDelegate{

    let sections: [String] = ["Section 1", "Section 2", "Section 3"]
    let s1Data: [String] = ["Row 1", "Row 2", "Row 3"]
    let s2Data: [String] = ["Row 1", "Row 2", "Row 3"]
    let s3Data: [String] = ["Row 1", "Row 2", "Row 3"]

    var sectionData: [Int: [String]] = [:]

    override func awakeFromNib() {
        super.awakeFromNib()

        delegate = self
        dataSource = self

        register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "MyCell")

        register(UINib(nibName: "MySection", bundle: nil), forHeaderFooterViewReuseIdentifier: "MySection")

        sectionData = [0:s1Data, 1:s2Data, 2:s3Data]

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
        -> Int {
            return (sectionData[section]?.count)!
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int)
        -> String? {
            return sections[section]
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let section = self.dequeueReusableHeaderFooterView(withIdentifier: "MySection")

        return section

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")

        return cell!

    }

}

正如你所看到的,一切都是非常基本的,我还没有清理它(只是展示)。该部分工作正常,并正确显示。但MyCell是完全错误的。行本身没有应用高度(因此内容或多或少被切割)并且我在xib中设置的自动布局不存在。这只是一团糟。

在xib中我也设置了行的高度。 RowHeight

我还尝试了以下两行:

    rowHeight = UITableViewAutomaticDimension
    estimatedRowHeight = 96.0

在xib中我设置了正确的约束以强制细胞扩展。

tableview本身只放在一个ViewController中,并配置为MyTableView-Class。

那么为什么高度和自动布局没有应用到单元格?有人可以在这里给我一个建议。

修改

这是单元格的xib文件:

xib

这是表格的结果:

table

正如您所看到的,自动布局功能现在可以正常工作。也许我身边有一个错误,但身高仍然不正确

2 个答案:

答案 0 :(得分:0)

删除您的

if not cdir.endswith("\\"): cdir += "\\"

rowHeight = UITableViewAutomaticDimension

根据您的需要,使用此方法为表格的每一行设置高度:

estimatedRowHeight = 96.0

只需func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 96 } 即可为所有单元格设置静态高度。

答案 1 :(得分:0)

我有一个解决方案。我只是在背景中设置了一个新视图,或者在标签本身中设置了一个高度约束,它等于单元格高度。所以在我的情况下96

set height