ios - 在类似于App Store "Description"Cell的UITableViewCell中扩展UITextView

标签 ios iphone swift uitableview uitextview

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

注意:我在 Storyboard 中使用了 AutoLayout。

我有一个 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 进行一些技巧处理,但这些方法返回的结果完全相同。

谁能告诉我为什么这没有按预期工作?

最佳答案

你需要告诉 TextView 你应该尝试这样说:

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 - 在类似于App Store "Description"Cell的UITableViewCell中扩展UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366548/

相关文章:

iphone - 开发 iPod 需要哪些软件和硬件?在电脑上?

iphone - iOS:在 iCloud 中备份核心数据数据库?

ios - webview 在 swift 3 中打开 native fb 应用程序?

ios - 本地通知不在从日期选择器中选择的确切时间工作,但在 swift 3 中几秒钟后

ios - 在不处于编辑模式时对 tableView 中的行重新排序

ios - 为什么 (isMovingToParentViewController) 中的代码不在 viewDidLayoutSubviews() 中运行

html - WKWebView:加载本地html时如何将文本插入HTML

iphone - 检测两个图像之间的像素碰撞/重叠

iphone - 如何检查 iPhone 上使用的缓存磁盘空间量

ios - Xcode 13.2 中为 iOS 13 宣布的 Swift Concurrency - 他们是如何实现这一目标的?