TableViewCell根据标签大小自动调整高度,而不使用自动布局

时间:2016-01-26 20:12:16

标签: ios swift uitableview

如何使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

    }
}

截图: enter image description here

这使得所有细胞都非常大,甚至只有1行细胞。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

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

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

这种方法的工作方式是为每个索引路径行(理想情况下是某个集合 - 数组)提供一个高度。当您的表格加载单元格时,它会自动为您调整。

答案 1 :(得分:0)

你能说出当你删除heightForRowAtIndexPath方法并在viewDidLoad中添加它时会发生什么:

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 80

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

编辑:我刚读过你不想使用自动布局。我不认为如果这种情况仍然适用于那种情况。

答案 2 :(得分:0)

我不是100%确定没有Autolayout但您可以设置估计的行高和尺寸。所以在你的viewDidLoad中输入这个

    self.tableView.estimatedRowHeight = //Largest Cell Height
    self.tableView.rowHeight = UITableViewAutomaticDimension
相关问题