0

我想在不同的 UIViewControllers 中重用相同的 UIView 对象作为表头。

我有一个 ArticleViewController 类;

@interface ArticleViewController : UIViewController {
    UIView *headerView;
}

- (UIView *)headerView;

@end

然后我实现headerViewget 访问器来延迟加载对象;

#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内部 。ArticleViewControllercitationViewController

一切正常,当新视图加载时,我得到相同的标题。问题是当我弹出CitationViewControllerUINavController 并返回到旧视图时,我headerViewArticleViewController.

我试过只传递一个指向指针的指针,但我在获取**UIViewand&headerView编译时遇到了麻烦。我以为我可以只在内存中拥有一个对象,并且两个视图都有自己的指向它的指针。我没走多远,就去找别的路了。

我在 UITableView 的标题中使用视图,我认为这可能是这个问题;UITableView 部分页眉和部分页脚没有更新(重绘问题),但重新加载数据并没有解决它。

然后我意识到我没有增加保留计数,headerView所以当我将它传递给CitationViewController并且减少保留计数时,我将释放对象。因此,我[headerView retain]在调用 setter 之前添加了一个调用,但这似乎并没有在我重新加载旧视图时显示标题。

我是否需要在我的 get 访问器中有某种​​保留模式?自定义 getter 示例始终具有原始类型或简单对象,问题是因为其中有另一个 UIView 对象headerView作为子视图吗?

我还考虑过将其更改@property (retain)为拥有assigncopy陷入困境,因为我没有实施copyWithZone协议并且不知道如何实施。

我一直在阅读所有这些不同的方面并孤立地理解它们,但似乎无法将它们统一为一个连贯的整体。我在这一切中误解了什么?

4

1 回答 1

0

每个视图对象一次只能出现在一个视图中。当您将视图添加到另一个视图时,它将自动从它所在的任何其他视图中删除。

您要么需要每个视图有一个 headerView 实例,要么添加额外的代码以确保单个对象在视图之间移动。前者是常见的方法(大多数视图对象不会占用足够的内存来担心),而后者则非常不寻常。

于 2010-11-19T01:34:59.073 回答