I've created a custom UITableViewCell in IB, linked it to the root view controller's property for it, and set it up in CellForRowAtIndexPath. But the height of my drawn cells doesn't match what I setup in IB, advice? Here's some screenshots and the code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *AddressCellIdentifier = @"AddressCellIdent";
UITableViewCell *thisCell = [tableView dequeueReusableCellWithIdentifier:AddressCellIdentifier];
if (thisCell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"AddressCell" owner:self options:nil];
thisCell = addressCell;
self.addressCell = nil;
}
return thisCell ;
}
addressCell is a @property (nonatomic, assign) IBOutlet UITableViewCell *addressCell;, and is linked up in IB to the file's owner (the table view controller).
I'm using the example from Apple's table view programming guide.
This is what I do when creating the table view to ensure the row height matches the row height defined in the cell's nib:
- (UITableView *)tableView
{
if (_tableView == nil) {
_tableView = [[UITableView alloc]
initWithFrame:self.view.bounds
style:UITableViewStylePlain];
_tableView.dataSource = self;
_tableView.delegate = self;
[_tableView
registerNib:[UINib nibWithNibName:@"<CELL NIB NAME>" bundle:nil]
forCellReuseIdentifier:kCellIdentifier];
// Get the cell's root view and set the table's
// rowHeight to the root cell's height.
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"<CELL NIB NAME>"
owner:self
options:nil];
UIView *cellView = (UIView *)nib[0];
if (cellView) {
_tableView.rowHeight = cellView.bounds.size.height;
}
}
return _tableView;
}
I hope this helps.
There are two places in the IB where you need to set the row height. First the custom row height for the cell itself. Click on the cell you want to resize, then click on the Size inspector (ruler) in the Utilities window on the right. Set your row height at the top under the Table View Cell section. Click the Custom checkbox.
Then click on your Table View in the Document Outline window on the left. Go back to the size inspector in Utilities window on the right and set the Row height for the entire table to the desired height.
With this implementation you don't need to add any code to your tableviewcontroller.
You can adjust the height of the cell by using:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat result;
result = 120.0f;
return result;
}
This will work with custom cells.
The delegate's -tableView:heightForRowAtIndexPath:
method is one approach, as WrightsCS says. Another option, if all of the rows will be the same height, is to set the rowHeight
property of the table view itself. (The former has the advantage of letting you return arbitrary values for each row.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With