Skip to content

Instantly share code, notes, and snippets.

@simondec
Last active August 29, 2015 14:19
Show Gist options
  • Save simondec/37608882518721e6d28b to your computer and use it in GitHub Desktop.
Save simondec/37608882518721e6d28b to your computer and use it in GitHub Desktop.
Variable Cell Height TableView
#import <UIKit.h>
@interface VariableCellHeightViewController: UITableViewController
@end
#import "VariableCellHeightViewController.h"
@interface VariableCellHeightViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic) UITableView *tableView;
@end
@implementation VariableCellHeightViewController
- (void)viewDidLoad {
[super viewDidLoad];
// The following line is strangely required for Automatic Dimension to work. The value doesn't seem important at all.
self.tableView.estimatedRowHeight = 20;
self.tableView.rowHeight = UITableViewAutomaticDimension;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
[self.view addSubview:self.tableView];
self.tableView.frame = self.view.bounds;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *testString = @"Hello Apple";
NSString *finalString = [NSString string];
for (NSInteger i = 0; i <= indexPath.row; i++) {
finalString = [finalString stringByAppendingString:[NSString stringWithFormat:@" %@", testString]];
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.text = finalString;
cell.textLabel.preferredMaxLayoutWidth = self.view.bounds.size.width;
return cell;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment