ios - 自动将其中的自定义 UITableViewCell 和 Label 调整为文本

标签 ios swift uitableview uilabel

我有一个自定义 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 一起工作的 View Controller 部分:

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

在您的 Storyboard或 xib 中,您必须确保在您的单元格中设置适当的约束。 不要在标签中设置预定义的高度限制。只要确保你给出了顶部和底部的约束。如果你对文字不确定,你也可以给标签一个最小高度限制。

关于ios - 自动将其中的自定义 UITableViewCell 和 Label 调整为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40216729/

相关文章:

Swift:重复调用通过身份函数传递的闭包会导致 EXC_BAD_ACCESS code=2

ios - UITableview:无法从其数据源获取单元格

ios - 如何从字符串中删除特定的 html 片段

ios - 为什么GCD,ObjC和Swift之间的性能差距如此之大

ios - 在加载 tableView 时展开可选值时意外发现 nil

ios - swift Alamofire : How to validate both a valid request and a valid response code

android - 我应该在 Xamarin.Forms 的什么地方放置 TabbedPage 的图标

ios - 连接到 LTE 时,应用程序无法访问互联网连接

ios - 仅在 UITableView 中循环遍历 textFields

ios - Xamarin.iOS - 使用 NSUserDefaults 在 UITableView 中保存选中状态