简体   繁体   English

iOS 7的动态表视图单元格高度

[英]Dynamic Table view cell height for iOS 7

I have a view controller containing tableview. 我有一个包含tableview的视图控制器。 Table view consists of custom cell containing single label. 表视图由包含单个标签的自定义单元格组成。 I have text of varying length which are to be shown in those cells. 我有不同长度的文本,将在这些单元格中显示。 The problem i am facing is that, the cells are not getting expanded to the appropriate height. 我面临的问题是,细胞没有扩展到适当的高度。 I have tried many solutions present in SO but none of them are working so far. 我在SO中尝试了很多解决方案,但到目前为止它们都没有。 Here is the code for view controller 这是视图控制器的代码

class ViewController: UIViewController {

    @IBOutlet var tableView: UITableView!

    let items = [
        "This is the first text",
        "This is the first text and this is the second text","now you may be thinking where is the third text?. Well, There was the first text and second text, now here is the third text",
        "This is the fourth short and sweet text",
        "Slow down you crazy child, you're so ambitious for a juvenile. If you're so smart, tell me why are you still so afraid.","Where's the fire? What's the hurry about. You better cool it off before you burn it out. There's so much to do and so many hours in a day.You got your passion, got your pride. Don't you know that only fools are satisfied. Dream on but don't imagine that they come true. Don't even realise vienna waits for you"]

    var prototypeCell:CustomCell!

    override func viewDidLoad() {
        super.viewDidLoad()

        //setting up tableview
        self.tableView.allowsSelection = false
        self.tableView.dataSource = self
        self.tableView.delegate = self

        configurePrototypeCell()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func configureCell(cell:CustomCell, forIndexPath indexPath:NSIndexPath)
    {
        cell.itemLabel.text = items[indexPath.row]

    }


    func configurePrototypeCell()
    {
        self.prototypeCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomCell
    }


}

extension ViewController:UITableViewDataSource
{
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomCell
        configureCell(cell, forIndexPath: indexPath)
        return cell

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
}

extension ViewController: UITableViewDelegate
{

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        self.prototypeCell.itemLabel.text = items[indexPath.row]
        self.prototypeCell.itemLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.tableView.frame)

        self.prototypeCell.setNeedsLayout()
        self.prototypeCell.layoutIfNeeded()


        let size = self.prototypeCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
        let height = size.height
        return height


    }

    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

}

CustomCell class is subclass of UITableViewCell . CustomCell类是UITableViewCell子类。 It contains UILabel named itemLabel. 它包含名为itemLabel的UILabel

Please try this in custom cell call this from TableviewDelegate method of height to calculate custom cell height. 请在自定义单元格中尝试此操作,从TableviewDelegate高度方法调用此方法来计算自定义单元格高度。

Code: 码:
let size = sizingCell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.estimatedRowHeight = 40;
    tableView.rowHeight = UITableViewAutomaticDimension;
}

This requires Autolayout to be enabled and constraints to be properly set. 这需要启用Autolayout并正确设置约束。

Here I have write code in Objective-C but you can modify it easily in swift. 在这里,我在Objective-C中编写代码,但您可以在swift中轻松修改它。

1 )First of all set the label's constraint like this: 1)首先设置标签的约束,如下所示:

在此输入图像描述

2) Implement below method in your customCell.m file 2)在customCell.m文件中实现以下方法

- (CGFloat)requiredHeight
{
    CGSize size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    NSLog(@"Size :%@",NSStringFromCGSize(size));
    CGFloat minimumHeight = 40.0f; //cell height which you have taken in xib
    if (size.height < minimumHeight)
    {
        return minimumHeight;
    }
    return size.height;
}

3) Make some changes in cellForRow and HeightForRow methods like below : 3)在cellForRow和HeightForRow方法中进行一些更改,如下所示:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.itemLabel.preferredMaxLayoutWidth = tableView.bounds.size.width -36; //Here 36 indicates Leading and Trailing distance of label which you have put in xib
    [cell.itemLabel updateConstraintsIfNeeded];

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

     return [viewAllCell requiredHeight]+[self calculateLabelHeightforText:viewAllCell.Lblname.text andFonts:viewAllCell.Lblname.font andWidth:viewAllCell.Lblname.frame.size.width]-default label height; //
}
-(float)calculateLabelHeightforText:(NSString *)text andFonts:(UIFont *)font andWidth:(float)width
{
    if (text==nil) {
        return 40; //default height
    }
    NSAttributedString *attributedText = [[NSAttributedString alloc]initWithString:text attributes:@{NSFontAttributeName:font}]
    ;
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    return rect.size.height+4;
}

4 ) In viewDidLoad make some change : 4)在viewDidLoad中进行一些更改:

- (void)viewDidLoad {
 [super viewDidLoad];
 self.TblDetail.rowHeight = UITableViewAutomaticDimension;
  self.TblDetail.estimatedRowHeight = 40.0;
}

Try this code, its working for me, 试试这个代码,它适合我,

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

            let str : String! = items[indexPath.row]

            let boundingRect = str.boundingRectWithSize(CGSizeMake(tableView.frame.size.width - 100, CGFloat.max),
                options:NSStringDrawingOptions.UsesLineFragmentOrigin,
                attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 14.0)!], context:nil).size.height + 45.0

            if(boundingRect > 95.0) {
                return boundingRect
            } else {
                return 95
            }

    }

if you get the boundingRect value, then return its dynamically change the height of UITableView, hope its helpful 如果你得到boundingRect值,那么返回它动态改变UITableView的高度,希望它有用

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

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