我的表格视图单元格中有一个标题和一个正文。 我试图让身体包裹起来,但我遇到了问题。
这是我在视图控制器中使用的代码
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("mainCell") as? mainCell {
cell.mainHeader.text = (mainHeader[indexPath.row])
cell.mainBody.text = (mainBody[indexPath.row])
cell.mainBody.numberOfLines = 0
cell.mainBody.lineBreakMode = NSLineBreakMode.ByWordWrapping
return cell
} else {
return mainCell()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainHeader.count
}
}
我搜索并认为 numberOfLines = 0 和 lineBreakMode = NSLineBreakMode 会起作用,但显然不是。
对不起,如果这很简单,提前感谢。
@Daven
我知道这可能无济于事,但我认为我没有,或者如果我有,我不确定它是什么。 还更新了原始代码,其中包含我的 VC 中除变量之外的所有内容
我有这个用于我的自定义单元格
import UIKit
class mainCell: UITableViewCell {
@IBOutlet weak var mainHeader: UILabel!
@IBOutlet weak var mainBody: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell (text:String) {
mainHeader.text = text
mainBody.text = text
}
}
要使您的单元格随着标签的增长而扩展,您需要确保已完成一些操作。 将tableView
的estimatedRowHeight
设置为一个值,例如
tableView.estimatedRowHeight = 200.0;
tableView.rowHeight = UITableViewAutomaticDimension
或通过此方法:
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 200.00
}
您也可以选择使用此方法,但如果所有单元格的高度都不同,则没有必要:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
您可能还会发现本教程很有帮助(这是我:)使用的)。 它显示了自动布局约束的外观。 有关自调整大小单元格的更多信息也在这里。
假设您希望单元格在文本长度超过一行时扩展,则希望使用委托函数将单元格高度设置为自动:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
并使用以下方法设置估计的行高
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return currentInfoSelectorOption.rowHeight + 100
}
然后在单元格中使用自动布局来设置高度。为此,可以将单元格的顶部和底部距离约束设置为常量值,并将标签行数设置为 0。这应该允许标签扩展并推动单元格