[英]How do I retain my custom UIView from my lazy loading get accessor and assign it to other views?
我想在不同的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
我使用[citationViewController setHeaderView:headerView];
在我將citationViewController
推headerView
ArticleViewController
之前,在ArticleViewController
分配我的headerView。
一切正常,加載新視圖時顯示相同的標題。 問題是,當我從UINavController中彈出CitationViewController
並返回到舊視圖時,我在ArticleViewController
丟失了headerView
對象。
我嘗試僅將指針傳遞給該指針,但無法編譯**UIView
和&headerView
。 我以為我可以在內存中只有一個對象,並且兩個視圖都有指向它的指針。 我走不遠,去尋找另一種方式。
我在UITableView的標題中使用該視圖,我認為可能是這個問題。 UITableView節的頁眉和節的頁腳未更新(重繪問題),但重新加載數據無法解決。
然后我意識到我沒有增加headerView
的保留計數,因此當我將其傳遞給CitationViewController
,這會減少保留計數,我將headerView
該對象。 因此,在調用setter之前,我添加了一個[headerView retain]
調用,但是當我重新加載舊視圖時,似乎並沒有保持標題的顯示。
我的get訪問器中是否需要某種保留模式? 自定義getter示例始終具有基本類型或簡單對象,這是問題所在,因為headerView
還有另一個UIView對象作為子視圖嗎?
我還考慮過更改@property (retain)
以進行assign
或copy
但是由於我未實現copyWithZone
協議並且不確定如何進行而陷入困境。
我一直在閱讀所有這些不同方面,並孤立地理解它們,但是似乎無法將它們統一為一個整體。 在這一切中我誤解了什么?
每個視圖對象一次只能出現在一個視圖中。 將視圖添加到另一個視圖時,該視圖將自動從其所在的任何其他視圖中刪除。
您要么需要每個視圖擁有一個headerView實例,要么添加額外的代碼以確保單個對象在視圖之間移動。 前者是常見的方法(大多數視圖對象不會占用足夠的內存來擔心),而后者則是非常不尋常的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.