带有自动高度标签的Swift tableview单元格自动高度 [英] Swift tableview cell auto height with auto height label
问题描述
我在使用 swift 时遇到了一些问题.需要制作表格视图,并且在每个单元格中都有带有文字的图像.
I have some problems with swift. Need to make tableview and in every cell to have image with text inside.
这是我目前所做的:
第一个问题:
标签应该是自动高度,现在它打破了字符串..
Label should be auto height, now it breaks string..
第二个问题:
图像也需要自动高度,并且取决于标签高度.
Image needs to be auto height too, and to depends on label height.
第三个问题:
Row 需要根据其内部自动调整高度.
Row needs to be autoheight depending on its inside.
TableViewController 代码:
TableViewController code:
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 44.0;
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.registerNib(UINib(nibName: "QuoteTableViewCell", bundle: nil), forCellReuseIdentifier: "QuoteCell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("QuoteCell", forIndexPath: indexPath) as! QuoteTableViewCell
cell.item = results[indexPath.row]
return cell
}
单元格代码:
class QuoteTableViewCell: UITableViewCell {
var item: Quote! {
didSet {
setupCell()
}
}
@IBOutlet weak var imageField: UIView!
@IBOutlet weak var textField: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setupCell() {
self.imageField.backgroundColor = UIColor(patternImage: UIImage(named: "Bg")!)
textField.text = item.text
}
}
推荐答案
要使标签的高度适应其内容,请在 Storyboard 中将其行数设置为 0.
To have the label adapt its height to its contents, set its Lines number to 0 in Storyboard.
如果你想在它旁边放一张图片,为什么不把两个控件放在一个水平的 StackView 中?
If you want to have an image next to it, why not to put both controls into one horizontal StackView?
并且要让 tableView 行高适应单元格内容(即标签高度),只需将其 rowHeight 设置为自动:
And to have the tableView row height adapt to the cell contents (i.e. label height), just set it's rowHeight to automatic:
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 90.0;
这篇关于带有自动高度标签的Swift tableview单元格自动高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!