自动调整自定义的UITableViewCell和标签中的文字
我有一个自定义的UITableViewCell
只有一个标签。 当我在StackOverflow上阅读时,我还将Interface Builder中的行数设置为0。
import UIKit class CommonListViewCell: UITableViewCell { @IBOutlet var background: UIView! @IBOutlet var titleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code titleLabel.font = UIFont(name: "roboto", size: titleLabel.font.pointSize) NSLog("CommonListViewCell font changed") } }
这里是视图控制器与UITableView
一起工作的部分:
override func viewDidLoad() { super.viewDidLoad() self.lvMain.delegate = self; self.lvMain.dataSource = self; self.lvMain.registerNib(UINib(nibName: "CommonListViewCell", bundle: nil), forCellReuseIdentifier: "commonlistidentifier") self.lvMain.estimatedRowHeight = 100 self.lvMain.rowHeight = UITableViewAutomaticDimension } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("commonlistidentifier", forIndexPath: indexPath) as! CommonListViewCell // Configure the cell... cell.titleLabel?.text = prayerList[indexPath.row].name cell.titleLabel?.sizeToFit() setLabelFont(cell.titleLabel!) Utils.nightCheck([cell.titleLabel!]) return cell }
所以, .sizeToFit()
不会改变任何东西,它仍然会将1行上的文本进行椭圆化处理,而且我需要标签的数量尽可能多,而且单元格的大小也适合标签。
你需要使用自我大小的细胞。
tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension
在你的故事板或xib中,你必须确定你在单元格中设置了适当的限制。 不要在标签中设置预定义的高度限制。 只要确保你给上限和下限。 如果您对文字不太确定,则还可以对标签给出最小高度限制。
试试这个代码:
注:两种方法都应该工作。在Swift 3中testing。
方法1:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.estimatedRowHeight = 44.0 // standard tableViewCell height tableView.rowHeight = UITableViewAutomaticDimension return yourArrayName.count }
方法2:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension }
注意:您需要将此代码放入cellForRowAt中
yourCellName.sizeToFit() cell.textLabel?.numberOfLines = 0
输出: