2016-05-05 168 views
1

我有一個包含tableview的視圖控制器。表視圖由包含單個標籤的自定義單元組成。我有不同長度的文本要顯示在這些單元格中。我面臨的問題是,細胞沒有擴大到適當的高度。我曾嘗試過很多解決方案,但目前爲止它們都沒有工作。 下面是視圖控制器的代碼iOS 7的動態表格視圖單元格高度

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

+0

set itemLabel的LIne = 0的數量和換行模式換行和UITableviewAutomaticDimention –

+0

iOS 7支持'Swift'嗎? – AechoLiu

+1

@AechoLiu yes yes – idocode

回答

3

請在自定義單元格中調用此方法從TableviewDelegate方法的高度計算自定義單元格高度。

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

+0

謝謝!我正在做prototypeCell。 ** contentView ** .systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)。 – idocode

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

這需要Autolayout啓用和約束,以正確設置。

+1

這隻適用於iOS 8.0+,而我需要iOS 7.0的解決方案 – idocode

0

在這裏我已經在Objective-C中編寫代碼,但是您可以在swift中輕鬆修改它。所有的

1)首先設置標籤的約束是這樣的:

enter image description here

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)在viewDidLoad中做出一些改變:

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

試試這個代碼,它的工作對我來說,

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的高度,希望它的幫助

相關問題