小编典典

自动将自定义UITableViewCell和Label调整为文本

swift

我有一个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行,并且我需要标签的行数尽可能多,并且单元格的大小也适合标签。


阅读 232

收藏
2020-07-07

共1个答案

小编典典

您需要使用自动调整大小的单元格。

tableView.estimatedRowHeight = 100
 tableView.rowHeight =    UITableViewAutomaticDimension

在情节提要或xib中,必须确保在单元格中设置了适当的约束。不要在标签中设置预定义的高度限制。只要确保您给出了顶部和底部约束即可。如果不确定文本,还可以给标签设置最小高度限制。

2020-07-07