简体   繁体   中英

How to make the height of custom UITableViewCell dynamic for each cell made in the UITableView?

我必须相对于单元格中的图像数量使UITableViewCell的高度动态变化。

Add following lines of code in your viewDidLoad() :

tableView.estimatedRowHeight = 200.0
tableView.rowHeight = UITableViewAutomaticDimension

where estimatedRowHeight is the maximum height you want to set for UITableViewCell.

Also, add this delegate method and return UITableViewAutomaticDimension :

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

set the UITableView's rowHight property to UITableViewAutomaticDimension and set the estimated row height to what the most common height is. Then in your layout of the cell make sure there are constraints between all of the visual elements vertically and the cell will be laid out properly. The vertical constraints should be something like:

V:|-(5)-[imageOne]-[imageTwo]-|

Where "|" is the cell's content view.

实现委托方法:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath (NSIndexPath *)indexPath
@interface yourController : UIViewController<UITableViewDelegate,UITableViewDataSource>

set delegate in view did load

- (void)viewDidLoad {
[super viewDidLoad];

tableview.delegate=self;
tableview.dataSource=self;

}

now method of height of table view cell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

return 40;//your value
}

in cell

- (CGFloat)cellHeight {
    [self layoutIfNeeded];
    return CGRectGetMaxY(_imageview.frame) + 10;
}

the imageView is the last view in cell. It only needs maxY of the lastView

in controller

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    OJTopicRootCell *cell = (OJTopicRootCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellHeight;

}

Use the estimatedHeight methods to quickly calcuate guessed values which will allow for fast load times of the table. If these methods are implemented, the above -tableView:heightForXXX calls will be deferred until views are ready to be displayed, so more expensive logic can be placed there. - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(7_0); - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0); - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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