Changing font size and dynamically changing cell row height for Accessibilty

The iPhone is great for people with vision problems. As it turns out, most people start to lose the ability to focus in our forties – called presbyopia.  So, yeah maybe most people using mobile phones are younger than 40, maybe, but for those of us getting on in years it’s nice to adjust the text size in our iPhones.  This can be done by going to the general settings of the iPhone, going to accessibility and tapping on the “Large Text” option which leads to a slider.  However, unless developers code apps appropriately, this will cause some problems in an app.

First, it’s important to use “textStyles” for fonts, the “Headline” or “Subheadline,” either in the interface builder or in code.  This will allow the font to be changed when users change text size in their iPhones accessibility settings.  But then this can cause problems in sizing various elements. For example, say we have a table view cell that has a certain height that’s just fine for the default text we use.  But when the text is enlarged by a certain amount it will look awful and in some cases spill off the cell (particularly for custom cells).

Here’s what I did (with help of course) to get around this problem:

In the Cocoa frame work for TableViewControllers there’s a method called “heightForRowAtIndexPath” that you can use to change the height of a specific cell, or in my case, set a constant height for all cells.  Let’s say that we know we want the cell to be as high as the text plus 10 for margin’s sake.  That means, no matter how large the text gets there will always be a margin.  We can set up a dummy label using the text size the user has set, find out what size that is and set the row height as that size plus 10.  Here’s sample code:

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        let label = UILabel()
        label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
        label.text = "Placeholder Text"
        let size = label.sizeThatFits(CGSizeMake(view.width, CGFloat.max))
        return size.height + 10

}

It’s the “sizeThatFits” method on the label that does the magic.  We always use “CGFloat.max” as the height and the width is actually irrelevant.  This method returns the size of the label that fits for the current text.  An viola!  Now whenever text size is changed the cell heights will also change.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>