I would like the UITableView
's row height to respond to changes in the user's preferred text size. For example, when the preferred text size increases, I would like to increase the row height by a proportional amount. Here's what I have so far:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
// observe when user changes preferred text size
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preferredContentSizeChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];
}
- (void)preferredContentSizeChanged:(NSNotification *)notification
{
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
// leverage Text Kit's Dynamic Type
cell.textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
cell.textLabel.text = @"All work and no play...";
return cell;
}
So what's the best way to calculate a row height that reflects the user's preferred text size?
use this method:
Add below code to cellForRowAtIndexPath
I have recently accomplished this and found it to be very simple. Instead of using
sizeWithFont:
you should use the newboundingRectWithSize:options:attributes:context
method in iOS 7.Set up your table view cell as usual and specify the
preferredFontForTextStyle:
on your text label as such:Then to correctly determine the size of the text label, evaluate the
boundingRectWithSize:options:attributes:context
to calculate the required height.You may want to subclass your table view cell also to listen for
UIContentSizeCategoryDidChangeNotification
notifications at which point you can update your UI when the user changes their preferences in Settings.appShould you require additional padding around the text label, you can define a constant value such as
With this in place, you can either add a constant value to the value returned from
tableView:heightForRowAtIndexPath:
Or you could inset the frame returned from
boundingRectWithSize:options:attributes:context
as such: