Siamaster
Siamaster

Reputation: 977

ios uitableviewcell item equal height to superview storyboard interface builder

In order to get a consistent size ratio between my views and the device, I make an equal width/height constraint between the view and the superview. However, when designing a UITableViewCell or a UICollectionViewCell, I can't find this option in the interface builder. I need to set a ratio between a view inside a cell and the superview. What is the cleanest way to accomplish this behavior?

Upvotes: 1

Views: 587

Answers (2)

Yuchen
Yuchen

Reputation: 33086

You cannot do this in the storyboard and have to do it in code:

For UITableView:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return tableView.frame.size.width;
}

For UICollectionView:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{
    int columns = 2; // Change this to whatever you want
    float width = collectionView.frame.size.width / columns;
    return CGSizeMake(width, width);
}

Upvotes: 1

rkyr
rkyr

Reputation: 3251

If you want to make your UITableViewCell the same size as superview of its table, you should do this:

1) Setup constraints to UITableView to equal width/height to superview, also setup its origin (for example center x/y in superview).

2) Return size for cell:

case UITableViewCell:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return tableView.frame.size.height;
}

case UICollectionViewCell:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  return collectionView.frame.size;
}

Upvotes: 0

Related Questions