2015-10-02 63 views
0

我在内容视图中采取了两个视图。 “发布容器视图”(红色背景)的高度根据标签的高度动态计算(全部使用Autolayout完成)。如何使用Autolayout动态设置UITableView单元的高度?

现在我想,如果“邮政集装箱视图”(红色背景)的高度将增加,那么单元格视图的高度自动增加。我想用自动布局来做到这一点。

我想使用Autolay来计算UITableview单元的高度。怎么做 ?

单元格高度=邮政容器视图(柔性按标签高度)+图像容器图高度(300修复)

我已经看到这种类型的方法,但不知道如何实现我的代码?

- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell 
{ 

    sizingCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.MyTableView.frame), CGRectGetHeight(sizingCell.bounds)); 

    [sizingCell setNeedsLayout]; 
    [sizingCell layoutIfNeeded]; 

    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
    return size.height + 1.0f; // Add 1.0f for the cell separator height 
} 
+0

提供更多详细信息 – baydi

+0

请参阅更新 –

+0

使用长宽比 – baydi

回答

1

为了计算细胞的高度:

CGFloat height ; // take global variable 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
     height = cell.PostContainerView.frame.size.height ; 
} 


- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath 
{ 
    height = height + 300 //(300 is Fix height of Image Container View) ; 
    return height ; 
} 
1

您是否想计算高度或者使用tableView来计算高度本身,考虑您的自动布局配置?

要做到这一点,没有实现的委托方法heightForRowAtIndexPathestimatedHeightForRowAtIndexPath代替(你想要的那一刻任何值)。

tableView将确定考虑到自动布局约束的单元格的高度。 请注意,有时您需要在更新后在您的手机上拨打layoutIfNeeded。 (在的cellForRowAtIndexPath为例)

+0

我想增加TableViewCell的高度,但是我必须为它做什么constarint。 –

+0

考虑到您的实际配置和使用我的解释,您的单元格应该调整好。同时检查您是否将标签(多行)的numberOfLines设置为“0”。 您可以通过编程方式更改Post Container View的高度约束(使用NSLayoutConstraint的IBOutlet并使用_constant_属性进行播放),并查看单元格高度更改,从而检查它是否工作正常。 – dosdos

+0

我已经给Post Container View和label做了所有constaraint,它工作正常,现在我的posint是,单元格的高度当Post Container View的高度会增加时如何计算? –

0

使用此Extension类字符串:

import UIKit 

extension String {  
    func sizeOfString (font: UIFont, constrainedToWidth width: Double) -> CGSize { 
     return NSString(string: self).boundingRectWithSize(CGSize(width: width, height: DBL_MAX), 
      options: NSStringDrawingOptions.UsesLineFragmentOrigin, 
      attributes: [NSFontAttributeName: font], 
      context: nil).size 
    } } 

UITableView代表计算UILabel宽度:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {   
     let item = "hkxzghkfjkgjkfxkj jjhghdjajfjkshgjkhkkn jhkhhgdfgjkhsfjkdghhhsxzgnfshgfhk jhsfgfhjfhghj " 
     let widthOfLabel = Double(view.frame.size.width) - 30 
     let textHeight = item.sizeOfString(UIFont.systemFont(14), constrainedToWidth: widthOfLabel) 
      return (padding + textHeight.height) 
    } 
相关问题