我想在不同的 UIViewControllers 中重用相同的 UIView 对象作为表头。
我有一个 ArticleViewController 类;
@interface ArticleViewController : UIViewController {
UIView *headerView;
}
- (UIView *)headerView;
@end
然后我实现headerView
get 访问器来延迟加载对象;
#import "ArticleViewController.h"
@implementation ArticleViewController
- (UIView *)headerView {
if(headerView)
return headerView;
float w = [[self view] bounds].size.width;
CGRect headerFrame = CGRectMake(0, 0, w, 64);
CGRect labelFrame = CGRectMake(8, 8, w - 16, 48);
UILabel *headerText = [[UILabel alloc] initWithFrame:labelFrame];
[headerText setNumberOfLines:0];
[headerText setFont:[UIFont boldSystemFontOfSize:14.0]];
[headerText setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
headerView = [[UIView alloc] initWithFrame:headerFrame];
[headerView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
[headerView addSubview:headerText];
return headerView;
}
@end
在另一个视图控制器中,我想重用相同的 headerView 对象,因此我已经声明了我的接口;
@interface CitationViewController : UIViewController {
UIView *headerView;
}
@property (nonatomic, retain) UIView *headerView;
@end
在将其推送到我的 UINavController之前,我会[citationViewController setHeaderView:headerView];
分配我的headerView
内部 。ArticleViewController
citationViewController
一切正常,当新视图加载时,我得到相同的标题。问题是当我弹出CitationViewController
UINavController 并返回到旧视图时,我headerView
在ArticleViewController
.
我试过只传递一个指向指针的指针,但我在获取**UIView
and&headerView
编译时遇到了麻烦。我以为我可以只在内存中拥有一个对象,并且两个视图都有自己的指向它的指针。我没走多远,就去找别的路了。
我在 UITableView 的标题中使用视图,我认为这可能是这个问题;UITableView 部分页眉和部分页脚没有更新(重绘问题),但重新加载数据并没有解决它。
然后我意识到我没有增加保留计数,headerView
所以当我将它传递给CitationViewController
并且减少保留计数时,我将释放对象。因此,我[headerView retain]
在调用 setter 之前添加了一个调用,但这似乎并没有在我重新加载旧视图时显示标题。
我是否需要在我的 get 访问器中有某种保留模式?自定义 getter 示例始终具有原始类型或简单对象,问题是因为其中有另一个 UIView 对象headerView
作为子视图吗?
我还考虑过将其更改@property (retain)
为拥有assign
或copy
陷入困境,因为我没有实施copyWithZone
协议并且不知道如何实施。
我一直在阅读所有这些不同的方面并孤立地理解它们,但似乎无法将它们统一为一个连贯的整体。我在这一切中误解了什么?