UITableView - dynamic cell height controlled by cell itself

天涯浪子 提交于 2019-12-04 19:50:10

OK, after some struggling, here's what I ended up with, which kind of works.

  1. I created a simple class to contain information related to one cell:
@interface CommentInfo : NSObject
{
    int ID;
    NSString *Name;
    NSString *Date;
    NSString *Content;
    BOOL IsFull;
    float Height;
}

@property (readonly) int ID;
@property (readonly) NSString *Name;
@property (readonly) NSString *Date;
@property (readonly) NSString *Content;
@property (readwrite, assign) float Height;
@property (readwrite, assign) BOOL IsFull;

- (id)initWithID:(int)_id withName:(NSString *)_name withDate:(NSString *)_date withText:(NSString *)_text;

@end

Don't worry too much about all the properties - the most important one is the Height.

  1. In my controller (which is also the delegate for the table view), I keep the data as an NSMutableArray of pointers to objects of type CommentInfo.

  2. In cellForRowAtIndexPath I get the corresponding pointer and pass it to the custom cell implementation during construction, where it is stored. I also set self as a delegate to the cell.

  3. In the custom cell implementation, when I need to expand/change the height, I update the Height property in the CommentInfo object and call a method in the delegate to update the display.

  4. When this updateDisplay method is called, I simple do the following:

[CommentsTable beginUpdates];
[CommentsTable endUpdates];
  1. In heightForRowAtIndexPath method, I retrieve the corresponding pointer to CommentInfo and read the Height property. As the pointer is the same between the controller and the cell, any changes to this property will be visible in both classes.

Job done.

Implement the method UITableViewDelegate – tableView:heightForRowAtIndexPath: in your table delegate. If you want to define height on a per-cell basis, you could 'forward' this call to the cell's class by calling your own tableView:cellForRowAtIndexPath: method in tableView:heightForRowAtIndexPath.

Update: Implemented in code. The error was caused by an incorrect method signature in the delegate calling tableView:cellForRowAtIndexPath.

In the custom UITableViewCell implementation:

- (CGFloat)requiredHeight
{
    if(isFull)
    {
        CGSize labelSize = [LblTitle.text sizeWithFont: [LblContent font]
                                     constrainedToSize: CGSizeMake(300.0f, 300.0f) 
                                         lineBreakMode: UILineBreakModeTailTruncation];
        return 42.0f + labelSize.height;
    }
    else
    {
        return 60.0f;
    }
}

In owner file (UITableViewDelegate):

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OOCommentCell *cell = (OOCommentCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return [cell requiredHeight];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!