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

时间:2016-02-18 02:45:39

标签: ios swift uitableview networking cell

我希望使用heightForRowAtIndexPath获取表格单元格的高度。我的原型单元格中有两个标签和一个图像。这是故事板:enter image description here

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

有很多Objective-C答案,但我无法让它发挥作用。有关如何使用Swift执行此操作的任何想法?

2 个答案:

答案 0 :(得分:0)

我也帮助过你。请检查一下:

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

希望它能帮助您找出问题所在。

答案 1 :(得分:0)

简单易用的尝试

override func viewDidLoad() {
    super.viewDidLoad()

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

从故事板通过检查员设置了一些属性,如

  1. 将两个标签的行数保持为0

  2. 换行作为自动换行

  3. 从约束方

    1. 不要给出高度约束

    2. 我认为你可能给出的最重要的事情就是 对细胞进行uiimageview的底部约束,这样就可以了 问题