【问题标题】:Get height of table cell in based on content根据内容获取表格单元格的高度
【发布时间】:2016-02-18 13:54:33
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios swift uitableview networking cell


    【解决方案1】:

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

    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
      }
    }
    

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

    【讨论】:

      【解决方案2】:

      很简单,试试这个

      override func viewDidLoad() {
          super.viewDidLoad()
      
          tableView.estimatedRowHeight = 200.0
          self.tableView.rowHeight = UITableViewAutomaticDimension
        }
      

      并从故事板通过检查器设置一些属性,例如

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

      2. 换行作为自动换行

      从约束方面

      1. 不给予高度限制

      2. 我认为你可能给出的最重要的事情是 使用单元格对 uiimageview 的底部约束,因此它会使 问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 2012-04-21
        • 2021-07-15
        • 2017-07-16
        • 1970-01-01
        相关资源
        最近更新 更多