简体   繁体   English

如何更改表格行的高度以适合UILabel

[英]How to change height of table row to fit UILabel


I am writing a messaging application which has a table view that outputs messages between two users. 我正在编写一个消息传递应用程序,它具有一个在两个用户之间输出消息的表视图。 The problem I have run into is resizing the table rows to fit the entire UILabel. 我遇到的问题是调整表行的大小以适合整个UILabel。 As of right now, I do not have a database hooked up to display any messages, just predefined strings that are acting as dummy messages to make sure that the table rows resize correctly. 截至目前,我还没有连接数据库来显示任何消息,只是预定义的字符串充当虚假消息,以确保表行的大小正确调整。
I have a function that determines the height required for a text label, however I am having trouble making each row resize themselves to this constraint. 我有一个确定文本标签所需高度的函数,但是我无法使每行调整到此约束的大小。 Thank you for your time 感谢您的时间
Code: 码:

//
//  chatViewController.swift
//  collaboration
//
//  Created by nick on 11/21/15.
//  Copyright © 2015 Supreme Leader. All rights reserved.
//

import UIKit

class chatViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var testLabel: UILabel!

var messages: NSMutableArray = NSMutableArray()

func tableView(tableView: UITableView, numberOfRowsInSection Section: Int) -> Int {
    return self.messages.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! chatTableViewCell
    cell.messageLabel?.text = self.messages.objectAtIndex(indexPath.row) as? String
    print(requiredHeight(self.messages.objectAtIndex(indexPath.row) as! String))

    tableView.estimatedRowHeight = requiredHeight(self.messages.objectAtIndex(indexPath.row) as! String)
    tableView.rowHeight = UITableViewAutomaticDimension

    return cell
}

func requiredHeight(text:String) -> CGFloat {
    let font = UIFont(name: "Helvetica", size: 16.0)
    let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, CGFloat.max))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()
    return label.frame.height
}

override func viewDidLoad() {
    super.viewDidLoad()
    let receivedUsername = NSUserDefaults.standardUserDefaults().stringForKey("usernameToMessageWith")
    testLabel.text = "\(receivedUsername! as String)"
    messages.addObject("dfsdfdfsdfsdfsdf")
    messages.addObject("You: and i i iiiknkjdf lorem ipsum i really like economics class because i can program as opposed to actually doing work")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

}

I would strongly recommend using xib file and setting autolayout there. 我强烈建议您使用xib文件并在那里设置自动布局。 Then your estimated height would work as expected. 然后,您的估计身高将按预期工作。

Other then that, you can simply return calculated height calling it form heightForRowAtIndexPath . 除此之外,您可以简单地返回计算出的高度,以heightForRowAtIndexPath形式调用它。 That way you will use separate height for each cell. 这样,您将为每个单元格使用单独的高度。 For instance: 例如:

override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
        return requiredHeight(self.messages.objectAtIndex(indexPath.row) as! String)
}

Again, I would try autolayout first. 同样,我会先尝试自动布局。

I hope I understood correctly. 我希望我能正确理解。 After looking at your code I would suggest the following: 查看您的代码后,我建议以下内容:

Use AutoLayout. 使用自动版式。

Set the subviews with Trailing/Leading and Top/Bottom Constraints in relation to the uitableviewcell. 设置与uitableviewcell相关的尾随/前导和顶部/底部约束的子视图。

You can then use Apple's AutomaticDimension feature by activating it once. 然后,可以通过激活一次使用Apple的AutomaticDimension功能。

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    self.tableView.estimatedRowHeight = 44.0
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.reloadData()
}

Do not use the custom row height feature in your prototype cells. 不要在原型单元中使用自定义行高功能。 Do not calculate the row height automatically. 不要自动计算行高。 Set the rowHeight to UITableViewAutomaticDimension once and not within the cellForRowAtIndexPath method. 一次将rowHeight设置为UITableViewAutomaticDimension,而不是在cellForRowAtIndexPath方法中。

Everything should work fine then. 一切都应该正常工作。

Based on your comment, additional steps for your solution: Please check: The UILabel properties: "Lines" should be set to "0" and "Line Breaks" should be set to "Word Wrap" 根据您的评论,解决方案的其他步骤:请检查:UILabel属性:“行”应设置为“ 0”,“换行符”应设置为“自动换行”

In your storyboard table view cell inspector, you can see the cell row height is fixed. 在情节提要表视图单元格检查器中,您可以看到单元格行高是固定的。 So in the view did load, set the estimated row height to the one in storyboard and set the row height to get its height automatically. 因此,在视图中确实已加载,将情节提要中的估计行高设置为1,并设置行高以自动获得其高度。 Also inspect the label in storyboard and set Lines = 0 to show multiple lines. 同时检查情节提要中的标签,并将“行数”设置为0以显示多行。

override func viewDidLoad() {
     super.viewDidLoad()

     tableView.estimatedRowHeight = tableView.rowHeight
     tableView.rowHeight = UITableViewAutomaticDimension
}

You should apply auto layout constraints to UILabel with respect to content view through a storyboard or programmatically. 您应该通过情节提要或以编程方式将UILayout的自动布局约束应用于UILabel Set leading , trailing , top and bottom constraints equals to zero . 设置约束为零 Also apply aspect ratio to UILabel. 还将宽高比应用于UILabel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM