[英]How to access UITableViewController variable from within a subclass'ed UITableViewCell?
How do I access UITableViewController
parameter from within a subclass'ed UITableViewCell
? 如何从子类的
UITableViewCell
访问UITableViewController
参数?
I have a parameter in the UITableViewController
for the font size (ie users can change font size). 我在
UITableViewController
有一个字体大小的参数(即用户可以更改字体大小)。 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). 因此,在我需要自定义子类的
UITableViewCell
的layoutSubviews
方法需要重新布局自身时(因为其标签位置将取决于字体),将需要访问最新字体。
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
? 所以我的问题是,从我的自定义子类
UITableViewCell
出发,尤其是在layoutSubviews
方法内,如何访问UITableViewController
的实例变量“ uiFont”参数?
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. 有几种方法可以执行此操作:通过应用程序委托上的属性访问UITableViewController(可以使用
[UIApplication sharedApplication].delegate
从任何地方访问该属性),在tableView:cellForRowAtIndexPath:
创建该单元格时,请为该单元格提供对UITableViewController的引用tableView:cellForRowAtIndexPath:
或者遵循单元格视图中的UIResponder链,直到找到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:
. 您可能应该只在表视图上调用
reloadData
使其重新创建所有单元格,然后在tableView:cellForRowAtIndexPath:
设置字体。 Or if the font setting should persist, you could store it in NSUserDefaults and have the cells listen for NSUserDefaultsDidChangeNotification
. 或者,如果字体设置应该保留,则可以将其存储在NSUserDefaults中,并让单元格监听
NSUserDefaultsDidChangeNotification
。
Accessing the UITableViewController
object from within your cell isn't a good approach in terms of design. 就设计而言,从单元内访问
UITableViewController
对象不是一种好方法。 What you should be doing is creating an ivar in the table cell itself to store the UIFont
object: 您应该做的是在表格单元格中创建一个ivar来存储
UIFont
对象:
@interface CustomCell : UITableViewCell {
UIFont *font;
}
@property (nonatomic, retain) UIFont *font;
And then in your tableView:cellForRowAtIndexPath
method, set the font of the cell: 然后在
tableView:cellForRowAtIndexPath
方法中,设置单元格的字体:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
[cell setFont:uiFont];
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.