iOS: Dynamic Height For UITableViewCell

前端 未结 3 367
故里飘歌
故里飘歌 2020-12-20 21:43

I\'m using iOS9 XCode7 I need to change the height of cell Dynamically according to labelText Height

I have used:

self.tableView.ro         


        
3条回答
  •  北海茫月
    2020-12-20 22:13

    I'm not quite sure what this sentence means (a screenshot would've helped):

    "I need to change the height of cell Dynamically according to labelText Height"

    So, you have a UITableViewCell, containing a UILabel, and want each cell in your table to have a height depending on that cell's label ?

    Here's the code I use.

    In my UITableViewCell class, I'll define a static function to measure, and return the height of my .xib file:

    @implementation MikesTableViewCell
    
    ...
    
    +(CGSize)preferredSize
    {
        static NSValue *sizeBox = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            // Assumption: The XIB file name matches this UIView subclass name.
            NSString* nibName = NSStringFromClass(self);
            UINib *nib = [UINib nibWithNibName:nibName bundle:nil];
    
            // Assumption: The XIB file only contains a single root UIView.
            UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject];
    
            sizeBox = [NSValue valueWithCGSize:rootView.frame.size];
        });
        return [sizeBox CGSizeValue];
    }
    
    @end
    

    Then, in my UIViewController class, I'll tell my UITableView to use this cell, find out it's height.

    @property (nonatomic) float rowHeight;
    
    UINib *cellNib = [UINib nibWithNibName:@"MikesTableViewCell" bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:@"CustomerCell"];
    
    rowHeight = [MikesTableViewCell preferredSize].height;
    
    ...
    
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return (float)rowHeight;
    }
    

    Again, this might not be exactly what you're looking for, but I hope this helps.

提交回复
热议问题