Greg
Greg

Reputation: 34798

How to access UITableViewController variable from within a subclass'ed UITableViewCell?

How do I access UITableViewController parameter from within a subclass'ed UITableViewCell?

I have a parameter in the UITableViewController for the font size (i.e. users can change font size). So the layoutSubviews method in my custom subclassed UITableViewCell will need to access the latest font when it needs to re-layout itself (as it label positions will depend on the font).

So my question, from with my custom subclassed UITableViewCell, and specifically within the layoutSubviews method, how do I access the "uiFont" parameter which is an instance variable from the UITableViewController?

Upvotes: 1

Views: 1104

Answers (2)

Anomie
Anomie

Reputation: 94804

There are a few ways to do it: access the UITableViewController via a property on the application delegate (which you can access from anywhere using [UIApplication sharedApplication].delegate), give the cell a reference to the UITableViewController when you create it in tableView:cellForRowAtIndexPath:, or follow the UIResponder chain from the cell view until you find a UITableViewController.

But really, this is probably a poor architecture. You should probably just call reloadData on the table view to have it recreate all the cells, and set the font in tableView:cellForRowAtIndexPath:. Or if the font setting should persist, you could store it in NSUserDefaults and have the cells listen for NSUserDefaultsDidChangeNotification.

Upvotes: 4

indragie
indragie

Reputation: 18122

Accessing the UITableViewController object from within your cell isn't a good approach in terms of design. What you should be doing is creating an ivar in the table cell itself to store the UIFont object:

@interface CustomCell : UITableViewCell {
    UIFont *font;
}
@property (nonatomic, retain) UIFont *font;

And then in your tableView:cellForRowAtIndexPath method, set the font of the cell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    [cell setFont:uiFont];
    ...
}

Upvotes: 2

Related Questions