【问题标题】:TableViewCell automatic resize height by label size without using auto layoutUITableViewCell 按标签大小自动调整高度而不使用自动布局
【发布时间】:2016-01-26 20:12:16
【问题描述】:

如何使 TableViewCell 改变高度以使 UILabel 适合?

我没有在我的项目中使用自动布局,因为这是一个大项目,我也不打算改变它——所以我需要一个没有自动布局的修复程序。

这是我的CommentsViewController.swift 代码:

import UIKit
import Parse
import ActiveLabel

class CommentsViewController: UITableViewController, UITextFieldDelegate {

    var commentsArray: [String] = []
    var currentObjID = ""
    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        self.textField.delegate = self

        queryComments()

    }

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

    func queryComments(){
        self.commentsArray.removeAll()
        let query = PFQuery(className:"currentUploads")
        query.whereKey("objectId", equalTo: self.currentObjID)
        query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) -> Void in
            if error == nil {
                if let objects = objects {
                    for object in objects {

                        let list: AnyObject? = object.objectForKey("comments")

                        self.commentsArray = list! as! NSArray as! [String]
                        self.tableView.reloadData()
                        self.textField.text = ""
                    }
                }
            } else {
                print("\(error?.userInfo)")
            }
        }
        self.sendButton.enabled = true
        self.refreshButton.enabled = true
    }

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

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commentsArray.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell:TableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell;

        if self.commentsArray.count > indexPath.row{
            cell.commentsText.font = UIFont.systemFontOfSize(15.0)
            cell.commentsText.text = commentsArray[commentsArray.count - 1 - indexPath.row]
            cell.commentsText.numberOfLines = 0
        }

        return cell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let height:CGFloat = self.calculateHeightForString(commentsArray[indexPath.row])
        return height + 70.0
    }

    func calculateHeightForString(inString:String) -> CGFloat
    {
        let messageString = inString
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(15.0)]
        let attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
        let rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )//hear u will get nearer height not the exact value
        let requredSize:CGRect = rect
        return requredSize.height  //to include button's in your tableview

    }
}

截图:

这使得所有单元格都非常大,即使是只有 1 行的单元格。有什么想法吗?

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    如果没有自动布局,我不能 100% 确定,但您可以设置估计的行高和尺寸。所以在你的 viewDidLoad 中输入这个

        self.tableView.estimatedRowHeight = //Largest Cell Height
        self.tableView.rowHeight = UITableViewAutomaticDimension
    

    【讨论】:

      【解决方案2】:

      你能说出当你删除 heightForRowAtIndexPath 方法并将它添加到你的 viewDidLoad 时会发生什么吗:

          tableView.rowHeight = UITableViewAutomaticDimension
          tableView.estimatedRowHeight = 80
      

      通过这两行,我们指示 tableview 计算单元格的大小与其内容匹配并动态呈现。

      编辑:我刚刚读到您不想使用自动布局。我认为在这种情况下这是否仍然有效。

      【讨论】:

      • 它不起作用。我可以在同一个情节提要中仅在该视图控制器上使用自动布局吗?
      • 是的,你可以。如果您有自定义单元格,只需将每一侧的标签固定到内容视图并将 numberOfLines 设置为 0。如果您使用默认单元格,则不必使用自动布局,然后只需设置numberOfLines 为 0。
      • 你能告诉我单元格中的约束吗?你是否删除了 heightForRow....?
      • 如前所述,我没有使用自动布局 :),是的,我确实删除了
      • 是的,这很合乎逻辑,因为您必须使用自动布局来使其工作,正如我所提到的。如果它只是你想显示的文本,我建议你使用默认的 UITableviewcell 并将 numberOfLines 设置为 0 理论上应该也可以工作。
      【解决方案3】:

      您可以使用 heightForRowAtIndexPath 来编辑表格单元格的高度。这是一个委托方法,您可以在子类化和设置 tableview 的委托属性(IBoutlet 或 view.delegate = self)后使用

      如果您还不知道标签的高度,请查看此主题:how to give dynamic height to UIlabel programatically in swift?

      这种工作方式是您将为每个索引路径行指定一个高度(最好是在某个集合 - 数组之外)。当您的表格加载单元格时,它会自动为您调整。

      【讨论】:

      • 我应该使用女巫的答案以获得最佳质量,我应该将代码放在哪里?
      • 您可能需要与该链接类似的代码才能传递给您的 heightForRowAtIndexPath
      • 您能告诉我您将如何更改我的代码以使其正常工作吗?
      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 2021-07-24
      • 2014-04-29
      相关资源
      最近更新 更多