ios - 根据内容获取表格单元格的高度

标签 ios swift uitableview networking cell

我想使用 heightForRowAtIndexPath 获取表格单元格的高度。我的原型(prototype)单元中有两个标签和一张图像。这是 Storyboard:enter image description here

我在使用 tableView.estimatedRowHeight = 100tableView.rowHeight = UITableViewAutomaticDimension 时遇到问题,因为单元格的大小变化很大,所以我想手动执行此操作。我认为最好根据上图中显示的标题标签或作者标签来调整其大小,因为图像将是静态大小。

有很多 Objective-C 答案,但我无法让它发挥作用。关于如何使用 Swift 做到这一点有什么想法吗?

最佳答案

我也做了同样的事情来帮助你。请检查一下:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

  @IBOutlet weak var tableView: UITableView!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    tableView.estimatedRowHeight = 132.0
    self.tableView.rowHeight = UITableViewAutomaticDimension
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell

    if indexPath.row == 0 {
      cell.myTitle.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    }

    cell.myTitle.numberOfLines = 0
    cell.myAuthor.numberOfLines = 0

    return cell
  }

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

  }

  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
  }
}

enter image description here enter image description here

希望它能帮助您解决问题。

关于ios - 根据内容获取表格单元格的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35471849/

相关文章:

iphone - 如何实现像 Instagram 一样的粘性标题功能?

ios - 如何在iTunes Connect中将状态为 “Prepare for Submission”的当前版本应用替换为新版本?

ios - 如何在 Keychain 中安装 Apple 推送通知服务证书?

ios - 对于 in 循环结果有时在 EXC_BAD_ACCESS

ios - 是否可以为多个项目呈现 UIDocumentInteractionController?

ios - 在 CGRectMake、Swift、UIkit 中使用变量

android - Swift 中的 Base64 编码不会在 Android 中解码

ios - 在单元格中,如何定位和调整从带有自动布局的 Nib 创建的 View 的大小?

ios - 向导航 Controller 添加工具栏

iphone - UIAtionSheet 与 UITableView