【问题标题】:Varying length cells in TableView make the view snap while scrolling SwiftTableView 中不同长度的单元格使视图在滚动 Swift 时对齐
【发布时间】:2015-12-02 22:00:40
【问题描述】:

所以我有一个带有 2 个原型单元格的 TableView。这是我的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if indexPath.row == 0 {

            let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ItemDetailsCell

            cell.centerImage.image = mainImage

            cell.heading.text = detailsHeadings[indexPath.row]
            let headingString = detailsHeadings[indexPath.row]
            cell.body.text = details[headingString]

            tableView.rowHeight = cell.labelBlack.frame.height + 40

            return cell

        } else {

            let cell = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! ItemDetailsCell

            cell.heading.text = detailsHeadings[indexPath.row]
            let headingString = detailsHeadings[indexPath.row]
            cell.body.text = details[headingString]
            let bodyString = details[headingString]

            let labelWidth = Int(cell.body.frame.width)
            println(labelWidth)
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: labelWidth, height: 10000))
            label.text = bodyString
            label.numberOfLines = 100
            label.font = UIFont(name: "OpenSans-Light", size: 12.0)
            label.sizeToFit()
            tableView.rowHeight = label.frame.height + 3

            return cell

        }

    }

所以第二个原型单元格只有两个标签,其值是从字典中分配的。单元格大小需要根据文本行数来扩大或缩小。在自动布局中,我将行数设置为 0,因此无论需要多少行,它都会选择。这很好用,除非当您在应用程序中滚动时,当用户从底部向上滚动时,它会捕捉视图。有没有办法避免这种情况?

提前感谢您的帮助。

【问题讨论】:

    标签: ios swift uitableview autolayout tableview


    【解决方案1】:

    我花了更多时间寻找后发现了这个:

    http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/

    它给了我我需要的东西。我删除了设置 rowHeight 的代码部分,然后使用 viewDidLoad 方法以及自动布局来限制我的单元格大小,经过一些试验和错误后,它可以在滚动时不对齐放置。

    【讨论】:

      【解决方案2】:

      您正在更改 tableview 的 rowHeight。这很可能是非常错误的。 tableView 的 rowHeight 是所有没有自己高度的行的默认值,因此您实际上是在更改 所有 单元格的高度。

      你应该使用委托方法 tableView:heightForRowAtIndexPath:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-28
        • 1970-01-01
        • 2017-02-18
        • 2015-05-12
        • 2019-02-20
        • 2012-12-11
        • 2016-10-27
        相关资源
        最近更新 更多