我想創建一個自定義類別來擴展UIViewController的功能,並且在這個類別中,我想存儲一個指向視圖的指針以供重用。我正在使用Ole Begemann所述的關聯參考。然而,儘管關聯引用本身可以存儲和檢索UIView,但將UIView添加到currentView會將該視圖添加爲子視圖,但後續比較(例如[self.view.subviews containsObject:self.storedView]
)將始終返回NO
,即使self.storedView
(關聯引用)確實已添加到self.view
。此外,即使已將self.storedView
添加到視圖層次結構中,代碼self.storedView.superview
也會始終打開nil
。我猜這是因爲我不完全瞭解聯想參考如何工作。關聯引用的視圖層次結構持久性的問題
任何想法可能會出錯?如果有幫助,我可以提供代碼示例。
謝謝!
UPDATE 1:這裏是我如何通過一個關聯參考創建該種類self.storedView
然後試圖添加和從視圖控制器的view
經由IBAction
方法除去它的代碼片段(關聯?) 。
// UIViewController+TestCategory.m
#import <objc/runtime.h>
static char const * const StoredViewKey = "storedView";
- (void)setStoredView:(UIView *)storedView
{
objc_setAssociatedObject(self, StoredViewKey, storedView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)storedView
{
UIView *storedView = objc_getAssociatedObject(self, StoredViewKey);
if (!storedView)
{
storedView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width/2.0, self.view.bounds.size.height/2.0)];
[storedView setBackgroundColor:[UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:0.25]];
[storedView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin)];
}
return storedView;
}
- (IBAction)buttonActionAddStoredView:(id)sender
{
if (![self.view.subviews containsObject:self.storedView]) // always returns YES
{
[self.view addSubview:self.storedView];
}
}
- (IBAction)buttonActionRemoveStoredView:(id)sender
{
if ([self.view.subviews containsObject:self.storedView]) // always returns NO
{
[self.storedView removeFromSuperview];
}
}
請顯示您存儲關聯參考的代碼。它絕對不應該有你所描述的問題。 – RyanR
嗨RyanR:剛添加的代碼!謝謝參觀。 –