在iOS App Store中,有一个用于描述应用程序的单元格。如果文本太长,则该单元格具有蓝色的“更多”按钮,该按钮将扩展该单元格以适合整个文本。 “新增功能”部分具有相同的功能,详细介绍了最新更新的信息。我尝试实现此问题。

注意:我正在我的情节提要中使用自动版式。

我有一个UITableViewController子类和一个UITableViewCell子类。

import UIKit

class SystemDetailDescriptionTableViewCell: UITableViewCell {

    static let defaultHeight: CGFloat = 44

    @IBOutlet weak var descriptionTextView: UITextView!

}

descriptionTextView在AutoLayout中的顶部,底部,左侧和右侧均设置为0。

接下来,我们有一个UITableViewController子类。我的第一个想法是使用heightForRowAtIndexPath方法。
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.section == 0 {
        if self.didExpandDescriptionCell {
            if let cell = tableView.dequeueReusableCellWithIdentifier(StoryboardPrototypeCellIdentifiers.descriptionCell) as? SystemDetailDescriptionTableViewCell {
                return cell.descriptionTextView.contentSize.height
            }
        }
        return SystemDetailDescriptionTableViewCell.defaultHeight
    }
    return tableView.rowHeight
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 0 {
        self.didExpandDescriptionCell = true
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    } else {
        if let link = self.links?[indexPath.row] {
            self.performSegueWithIdentifier(StoryboardSegueIdentifiers.toVideoView, sender: link)
        }
    }
}

问题在于contentSize的大小无法正确调整为文本的整个长度。相反,它大约是文本的3/4。我听说此方法不适用于AutoLayout,而需要使用LayoutManager进行一些技巧,但是这些方法返回的结果完全相同。

谁能给我一些见解,为什么它不能按预期工作?

最佳答案

您需要告诉文本视图您应该尝试说出以下内容:

let newSize = cell.descriptionTextView.sizeThatFits(CGSize(width: cell.descriptionTextView.bounds.size.width, height: CGFloat.max))
cell.descriptionTextViewHeightConstraint.constant = newSize.height
return newSize.height

您需要为内容获取适当的高度,然后将约束更新为新的高度(如果已设置高度约束),然后更新单元格高度。此代码假定该单元格中仅存在descriptionTextView,并且需要零填充。

关于ios - 在UITableViewCell中扩展UITextView类似于App Store的“描述”单元格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34366548/

10-09 07:11
查看更多