ios - 当我使用几种不同的方式显示单元格时,是否可以在 UITableViewCell 中有不同的高度?

标签 ios iphone swift uitableview autolayout

我花了好几天时间想弄清楚这个问题,但似乎没有解决方案。我有一个非常基本的 UITableView 单元格,里面有两个标签。其中之一是单行,第二个是多行。第二个高度会有所不同。这是我尝试生成的示例(UITableViewCells 中的 UIStackViews):

enter image description here

通过阅读数百篇 SO 帖子、数百篇博客、搜索 Apple Developer 网站,似乎有无数种方法可以编写此代码。在尝试了数百种不同的方式之后,我仍然无法像这样显示文本。我认为一些问题是因为我在一个 UITableView 中使用了 3 不同的 UITableView 单元变体。

这是我最近一次尝试 cellForRowAtIndexPath 的代码:

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
}

产生这个:

enter image description here

最佳答案

我建议您不要为此使用堆栈 View 。只需根据您的要求使用带标签的自定义单元格,单元格将根据标签文本大小自动调整大小。

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

UITableview cell Autoresize According to textsize

输出:-

enter image description here

在viewdidload中

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

不要忘记设置 UILabel 属性的 Numberoflines=0

enter image description here

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

检查此链接,

Adjust UILabel height depending on the text

编辑:- 在这里,我根据上面的图片在单元格中添加了 2 个标签。像这样设置约束。

enter image description here

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

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

关于ios - 当我使用几种不同的方式显示单元格时,是否可以在 UITableViewCell 中有不同的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37235605/

相关文章:

javascript - PhoneGap FileReader/readAsDataURL 不触发回调

iphone - 如何在UIView的子类中调用UIView变量中的drawrect?

ios - 无法在我的音乐播放器应用程序上播放音乐

ios - 谷歌地图 - reverseGeocodeCoordinate 不会打印新加坡的地址

arrays - 如何在 Swift 中将两个数组合二为一?

ios - 使用 instruments 命令行实用程序启动特定硬件版本的 iOS 模拟器

ios - 如何为 iOS 存折创建 "generic type pass"?

ios - 传递数据不会更新字符串

iphone - 从 MVC (iOS) 中的异步操作返回结果

ios - 如何在 Swift 中创建分组条形图?