我正在编写一个消息应用程序,它有一个 TableView ,可以在两个用户之间输出消息。我遇到的问题是调整表行的大小以适应整个 UILabel。截至目前,我没有连接数据库来显示任何消息,只有预定义的字符串充当虚拟消息,以确保表行大小正确调整。
我有一个函数可以确定所需的高度对于文本标签,但是我无法根据此约束调整每一行的大小。感谢您的宝贵时间
代码:
//
// 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()
}
}
最佳答案
我强烈建议使用 xib 文件并在那里设置自动布局。那么您的估计高度就会按预期工作。
除此之外,您只需通过 heightForRowAtIndexPath
调用它即可返回计算出的高度。这样您将为每个单元格使用单独的高度。例如:
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return requiredHeight(self.messages.objectAtIndex(indexPath.row) as! String)
}
同样,我会首先尝试自动布局。
关于ios - 如何更改表格行的高度以适合 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873350/