代码之家  ›  专栏  ›  技术社区  ›  Dave Anderson

如何从延迟加载的get访问器中保留自定义UIView并将其分配给其他视图?

  •  0
  • Dave Anderson  · 技术社区  · 14 年前

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

    我有一个ArticleViewController类;

    @interface ArticleViewController : UIViewController {
        UIView *headerView;
    }
    
    - (UIView *)headerView;
    
    @end
    

    然后我执行 headerView 获取访问器以延迟加载对象;

    #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
    

    我用 [citationViewController setHeaderView:headerView]; 分配我的 头视图 在内部 ArticleViewController 在我推之前 citationViewController 在我的UINavController上。

    一切正常,加载新视图时显示的标题相同。问题是当我打开 CitationViewController 离开UINavController,回到原来的视角我失去了 头视图 对象 ArticleView控制器 .

    我试着把一个指针传给那个指针,但是我很难得到 **UIView &headerView 编译。我想我可以只在内存中有一个对象,两个视图都有自己的指向它的指针。我没走多远就去找别的路了。

    我使用了一个UITableView的头部视图,我认为可能是这个问题; UITableView section header and section footer not updating (redraw problem) 但重新加载数据并不能解决这个问题。

    然后我意识到我没有增加 头视图 所以当我把它交给 引文视图控制器 这会减少我将释放对象的retain计数。所以我加了一个 [headerView retain] 在调用setter之前调用,但当我重新加载旧视图时,似乎没有显示头。

    我需要在get访问器中使用某种保留模式吗?自定义getter示例总是有灵长类或简单对象,这是因为其中有另一个UIView对象 头视图 作为子视图?

    我也考虑过改变 @property (retain) 拥有 assign copy 但由于我没有执行 copyWithZone 但不知道怎么做。

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   grahamparks    14 年前

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

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