提问者:小点点

当我使用几种不同的方式显示单元格时,是否可能在UITableView单元格中具有不同的高度?


我花了几天时间想弄明白这一点,但似乎没有解决办法。我有一个非常基本的UITableView单元格,里面有两个标签。其中一个将是一行,第二个将是多行。第二个会有不同的高度。下面是我试图生成的一个示例(UIStackViews位于UITableViewCells内部):

通过阅读数以百计的SO帖子,数以百计的博客,浏览苹果开发者网站,似乎有无限的方式可以写出这篇文章。在实验了数百种不同的方法之后,我仍然无法像这样显示文本。我认为一些麻烦来自于我在一个UITableView中使用了3个不同的UITableView单元格变体。

以下是我最近一次尝试的代码:

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

    var cell : UITableViewCell!

    let (parent, isParentCell) = self.findParent(indexPath.row)

    if !isParentCell {

        let categories = ["words", "translation","commentary"]

        if categories[parent] == "words" {

            cell = tableView.dequeueReusableCellWithIdentifier(childWordsCellIdentifier, forIndexPath: indexPath) as UITableViewCell

            // Reset content
            for subview in cell.contentView.subviews {
                subview.removeFromSuperview()
            }
            cell.prepareForReuse()


            let words                   = self.page.valueForKey("words")!.allObjects as! [Word]
            let wordsInOrder            = words.sort({Int($0.order!) < Int($1.order!) })
            let word                    = wordsInOrder[indexPath.row - 1]

            let labelWidth              = (self.view.frame.width - 80) / 2


            let wordLabel               = UILabel(frame: CGRectZero)
            wordLabel.text              = word.valueForKey("sanskrit") as? String
            wordLabel.font              = UIFont(name: "EuphemiaUCAS-Bold", size: 16)
            wordLabel.numberOfLines     = 0
            wordLabel.translatesAutoresizingMaskIntoConstraints = false
            wordLabel.layer.borderColor = UIColor.greenColor().CGColor
            wordLabel.layer.borderWidth = 1.0
            let widthWordConstraint = wordLabel.widthAnchor.constraintEqualToConstant(labelWidth)
            widthWordConstraint.priority = 300
            widthWordConstraint.active = true

            let englishWordLabel           = UILabel(frame: CGRectZero)
            englishWordLabel.text          = "Foobar don't want to play my game with my anymore."
            englishWordLabel.font          = UIFont(name: "STHeitiTC-Light", size: 16)
            englishWordLabel.numberOfLines = 0
            englishWordLabel.preferredMaxLayoutWidth = labelWidth
            englishWordLabel.translatesAutoresizingMaskIntoConstraints = false
            let englishWordConstraint = englishWordLabel.widthAnchor.constraintEqualToConstant(labelWidth)
            englishWordConstraint.priority = 300
            englishWordConstraint.active = true
            englishWordLabel.layer.borderColor = UIColor.blueColor().CGColor
            englishWordLabel.layer.borderWidth = 1.0

            let stackView = UIStackView()
            stackView.axis = .Horizontal
            stackView.distribution = .FillProportionally
            stackView.alignment = .FirstBaseline
            stackView.spacing = 15
            stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
            stackView.layoutMarginsRelativeArrangement = true

            stackView.addArrangedSubview(wordLabel)
            stackView.addArrangedSubview(englishWordLabel)

            stackView.translatesAutoresizingMaskIntoConstraints = false

            englishWordLabel.topAnchor.constraintEqualToAnchor(stackView.topAnchor).active = true
            englishWordLabel.bottomAnchor.constraintEqualToAnchor(stackView.bottomAnchor).active = true


            cell.contentView.addSubview(stackView)

            cell.contentView.layoutIfNeeded()


        } else {

            cell = tableView.dequeueReusableCellWithIdentifier(childCellIdentifier, forIndexPath: indexPath) as UITableViewCell

            // Reset content
            cell.textLabel!.text = ""
            for subview in cell.contentView.subviews {
                subview.removeFromSuperview()
            }
            cell.prepareForReuse()

            cell.textLabel!.text        = self.page.valueForKey(categories[parent]) as? String
            cell.textLabel!.textColor   = UIColor(red: 35/255.0, green: 31/255.0, blue: 32/255.0, alpha: 1.0)
            cell.textLabel!.font        = UIFont(name: "STHeitiTC-Light", size: 16)
        }
    }
    else {
        // Parent
        cell = tableView.dequeueReusableCellWithIdentifier(parentCellIdentifier, forIndexPath: indexPath)
        cell.textLabel!.text        = self.dataSource[parent].title
        cell.textLabel!.textColor   = UIColor(red: 66/255.0, green: 116/255.0, blue: 185/255.0, alpha: 1.0)
        cell.textLabel!.font        = UIFont(name: "STHeitiTC-Light", size: 20)
    }

    cell.selectionStyle                                       = .None
    cell.textLabel!.translatesAutoresizingMaskIntoConstraints = false
    cell.textLabel!.numberOfLines                             = 0
    cell.textLabel!.lineBreakMode = .ByWordWrapping

    return cell
}

从而产生以下结果:


共3个答案

匿名用户

表视图单元格的高度由表根据属性或的返回值决定;cgfloat/code>从表视图委托。

程序员可能通过UITableViewCell的frame属性为其设置的高度被忽略!

因此,您需要通过编程计算出每个单元格所需的高度。然后需要实现;cgfloat/code>从每个单元格的表视图委托。

如果显示表格视图时单元格的大小发生变化,则需要:

    或/li>使用重新加载表
  • 使用更新单元格

编辑

实际上,由于您在视图中使用了约束,因此它应该在不使用`的情况下工作。

尝试将中的代码替换为:

        cell = tableView.dequeueReusableCellWithIdentifier(childWordsCellIdentifier, forIndexPath: indexPath) as UITableViewCell

        // Reset content
        for subview in cell.contentView.subviews {
            subview.removeFromSuperview()
        }
        cell.prepareForReuse()


        let words                   = self.page.valueForKey("words")!.allObjects as! [Word]
        let wordsInOrder            = words.sort({Int($0.order!) < Int($1.order!) })
        let word                    = wordsInOrder[indexPath.row - 1]


        let wordLabel               = UILabel(frame: CGRectZero)
        wordLabel.text              = word.valueForKey("sanskrit") as? String
        wordLabel.font              = UIFont(name: "EuphemiaUCAS-Bold", size: 16)
        wordLabel.numberOfLines     = 0
        wordLabel.translatesAutoresizingMaskIntoConstraints = false
        wordLabel.layer.borderColor = UIColor.greenColor().CGColor
        wordLabel.layer.borderWidth = 1.0

        let englishWordLabel           = UILabel(frame: CGRectZero)
        englishWordLabel.text          = "Foobar don't want to play my game with my anymore."
        englishWordLabel.font          = UIFont(name: "STHeitiTC-Light", size: 16)
        englishWordLabel.numberOfLines = 0

        let stackView = UIStackView()
        stackView.axis = .Horizontal
        stackView.distribution = .FillProportionally
        stackView.alignment = .Fill  // EDIT
        stackView.spacing = 15
        stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        stackView.layoutMarginsRelativeArrangement = true

        stackView.addArrangedSubview(wordLabel)
        stackView.addArrangedSubview(englishWordLabel)

        stackView.translatesAutoresizingMaskIntoConstraints = false

        cell.contentView.addSubview(stackView)
        cell.contentView.leadingAnchor.constraintEqualToAnchor(stackView.leadingAnchor).active = true
        cell.contentView.topAnchor.constraintEqualToAnchor(stackView.topAnchor).active = true
        cell.contentView.trailingAnchor.constraintEqualToAnchor(stackView.trailingAnchor).active = true
        cell.contentView.bottomAnchor.constraintEqualToAnchor(stackView.bottomAnchor).active = true

        cell.contentView.layoutIfNeeded()

此外,我将使用两个不同的单元格类来执行此任务,而不是删除ContentView中的视图。

请让我知道进展如何!

匿名用户

null

检查,这里我附上了演示。

UITableview单元格根据textsize自动调整大小

输出:-

在viewdidload中

super.viewDidLoad()
        self.tblView.estimatedRowHeight = 100;
        self.tblView.rowHeight = UITableViewAutomaticDimension;
        self.tblView.setNeedsLayout()
        self.tblView.layoutIfNeeded()

不要忘记设置UILabel属性的

编辑:-如果您需要关于如何将约束设置为UILabel逐步指南,

选中此链接,

根据文本调整UILabel高度

编辑:-这里我有两个标签在单元格根据你的上面的图像。就像这样设置约束。

标签1:-顶部,前导,(高度和宽度根据您的要求)

标签2:-顶部,底部,从标签1开始,从Superview开始,从Superview开始

匿名用户

您想要实现的功能可以通过来自tableView委托的heightForRowAtIndexPath的简单实现来完成。

如果你不确定什么单元格应该有什么高度,你可以在运行时计算它。