【问题标题】:Dynamic Table view cell height for iOS 7iOS 7 的动态表格视图单元格高度
【发布时间】:2016-05-05 18:30:08
【问题描述】:

我有一个包含 tableview 的视图控制器。表格视图由包含单个标签的自定义单元格组成。我有不同长度的文本,这些文本将显示在这些单元格中。我面临的问题是,细胞没有扩大到适当的高度。我已经尝试了 SO 中存在的许多解决方案,但到目前为止它们都没有奏效。 这是视图控制器的代码

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 类是UITableViewCell 的子类。它包含名为 itemLabel 的 UILabel

【问题讨论】:

  • 设置itemLabel的行数=0,换行模式为自动换行和UITableviewAutomaticDimention
  • iOS 7 支持Swift 吗?
  • @AechoLiu 是的

标签: ios swift uitableview


【解决方案1】:

请在自定义单元格中尝试这个,从高度的 TableviewDelegate 方法调用这个来计算自定义单元格高度。

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

【讨论】:

  • 谢谢!我在做prototypeCell。 contentView .systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).
【解决方案2】:
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.estimatedRowHeight = 40;
    tableView.rowHeight = UITableViewAutomaticDimension;
}

这需要启用Autolayout 并正确设置约束。

【讨论】:

  • 这只适用于 iOS 8.0+ 而我需要 iOS 7.0 的解决方案
【解决方案3】:

这里我用 Objective-C 写过代码,但是你可以很容易地用 swift 修改它。

1 )首先像这样设置标签的约束:

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) 对 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 ) 在 vi​​ewDidLoad 中进行一些更改:

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

【讨论】:

    【解决方案4】:

    试试这个代码,它对我有用,

    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
                }
    
        }
    

    如果你得到boundingRect值,然后返回它动态改变UITableView的高度,希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-16
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2015-02-24
      • 1970-01-01
      相关资源
      最近更新 更多