简体   繁体   English

Swift iOS为UITableViewCell()自动调整UILabel的高度

[英]Swift iOS auto adjust height for UILabel for UITableViewCell()

How do I make it auto resize the height of each cell based on the length of textLabel? 如何根据textLabel的长度自动调整每个单元格的高度? Ideally I would like textLabel to be wrapped as well, so the textLabel can take however many lines it needs. 理想情况下,我也希望包装textLabel,因此textLabel可以采用所需的许多行。 Below codes are what I have currently: 以下代码是我目前拥有的代码:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let notification = self.fetchedTweetsArray[indexPath.row]

        let cell = UITableViewCell()
        cell.textLabel?.text = notification
        return cell
    }

First of all your cellForRowAtIndex should be like this 首先,您的cellForRowAtIndex应该是这样的

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
     let cell : CustomCell! = tableView.dequeueReusableCellWithIdentifier("ID_CustomCell", forIndexPath: indexPath)  as! CustomCell

cell.selectionStyle =  UITableViewCellSelectionStyle.None

cell.lblData.text = "CustomCell....."
return cell

}

No of lines for UILabel should be zero. UILabel的行数不应为零。

在此处输入图片说明

Now as per height of UILabel you have to calculate dynamic height for each cell and keep it in mutable array so later on you can use in heightForRowAtIndex. 现在,根据UILabel的高度,您必须计算每个单元格的动态高度并将其保持在可变数组中,以便以后可以在heightForRowAtIndex中使用。

Make sure auto resizing like this on UILabel 确保在UILabel上像这样自动调整大小

在此处输入图片说明

Just made a sample code, you can download and observe. 刚制作了示例代码,即可下载并观察。

Download sample code 下载示例代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM