2013-07-04 72 views
0

這聽起來可能很傻,但閱讀...如何確保UIView已加載?

我想從由一個故事板實例化一個UIViewController外設置UILabel的文本。我需要確保設置視圖控制器的標籤屬性時,我設置其文本,否則標籤的文本將不會被設置(因爲它不會被加載尚未接收文本值)。

這是我目前的解決方案:

// Show pin entry 
if (!self.pinViewController) { 
    // Load pin view controller 
    self.pinViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"pinScreen"]; 
    self.pinViewController.delegate = self; 
    if (!self.pinViewController.view) { 
     // Wait for pin screen to fully load 
    } 
    [self.pinViewController setMessageText:@"Set a pin for this device"]; 
} 

起初我有一個while循環,循環,直到view的價值不nil,但似乎檢查視圖加載它(這裏提到的這個行爲: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006926-CH3-SW37

我試過用isViewLoaded方法沒有成功。它只是永遠循環。

我已經將上述代碼作爲我當前的解決方案,但感覺不對。

有沒有更好的方法確保UIView已加載?

+0

,如果你做正確,'viewController.view'永遠不會'nil'因爲吸氣會如果視圖尚未創建,則創建該視圖 –

回答

2

我想提出一種替代方法,您不必依賴視圖的可用性。
如果您需要等待視圖加載,然後才能調用viewController上的其他方法,則會破壞封裝,因爲調用PinViewController的viewController必須知道PinViewController的內部工作方式。這通常不是一個好主意。

但是你可以在PinViewController實例中保存像NSStrings這樣的對象,當PinViewController的視圖出現時,根據你以前設置的屬性設置視圖。
如果您需要從viewController外部更改標籤的文本,您還可以創建一個自定義setter來爲您設置label.text。

你的.h

@interface PinViewController : UIViewController 
@property (copy, nonatomic) NSString *messageText; 
// ... 
@end 

而且您的m

@implementation PinViewController 

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 
    self.messageLabel.text = self.messageText; 
} 

// optional, if you want to change the message text from another viewController: 
- (void)setMessageText:(NSString *)messageText { 
    _messageText = messageText; 
    self.messageLabel.text = messageText; 
} 

// ... 

@end 
0

我寧願看到你改變你的邏輯和做這種@MatthiasBauch顯示他的回答方式。然而,要回答你的問題的實際,你可以簡單地以強制其負載設置視圖屬性:

self.pinViewController.view.hidden = NO;