自动将自定义UITableViewCell和Label调整为文本 [英] auto adjust custom UITableViewCell and Label in it to the text

查看:49
本文介绍了自动将自定义UITableViewCell和Label调整为文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的UITableViewCell,其中只有一个Label.当我在StackOverflow上阅读时,我还将Interface Builder中的行数设置为0.

I have a custom UITableViewCell that only has one Label in it. I also set number of lines in Interface Builder to 0 as I read on StackOverflow.

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一起使用的视图控制器部分:

Here's the view controller's part to work with 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行,并且我需要标签的行数尽可能多,并且单元格的大小也适合标签.

So, .sizeToFit() doesn't change anything—it still ellipsize the text on 1 line, and I need the label to be as many lines as it needed, and the size of the cell also be fitting for the label.

推荐答案

您需要使用自定义尺寸的单元格.

You need to use self sizing cells.

tableView.estimatedRowHeight = 100
 tableView.rowHeight =    UITableViewAutomaticDimension

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

In your storyboard or xib you have to make sure that you set proper constraints in your cells. Do not set a predefined height constraint in your label. Just make sure you give top and bottom constraints. If you are not sure about the text , you can also give a minimum height constraint to the label.

这篇关于自动将自定义UITableViewCell和Label调整为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆