2010-08-16 56 views
1

我想顯示一個簡單的加載對話框,當我的應用程序發生某些事情時。我想我會創建一個新的視圖,爲其添加一個標籤,然後將該視圖設置爲當前視圖的子視圖。iPhone:添加「加載」子視圖

當這樣做時,我什麼都看不到!

這裏是我怎麼寫我的方法:

- (void)showLoading { 
    UIView *loading = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; 
    loading.backgroundColor = [UIColor blackColor]; 
    UILabel *txt = [[UILabel alloc] initWithFrame:CGRectMake(198, 9, 94, 27)]; 
    txt.text = @"Loading..."; 
    txt.textColor = [UIColor whiteColor]; 
    [loading addSubview:txt]; 
    [super.view addSubview:loading]; 
    [super.view bringSubviewToFront:loading]; 
    [loading release]; 
    [txt release]; 
} 

我這樣做完全錯了嗎?

編輯: 我把它添加到viewDidLoad方法,它的作品我多麼希望:

loading = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)]; 
    loading.backgroundColor = [UIColor blackColor]; 
    UILabel *txt = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 94, 27)]; 
    txt.text = @"Loading..."; 
    txt.textColor = [UIColor whiteColor]; 
    [loading addSubview:txt]; 
    [txt release]; 
    [self.view addSubview:loading]; 
    [self.view bringSubviewToFront:loading]; 

但是從方法加載的時候,它似乎滯後,並沒有顯示出來了一點。

回答

2

儘管這並不直接回答你的問題,但我建議從GitHub中抓取MBProgressHUD並使用它代替靜態標籤。看起來更好,更少的代碼供你直接維護等。你可以在http://github.com/matej/MBProgressHUD找到它

我使用它的方式是通過創建UITableViewController的子類並定義一些顯示和隱藏HUD視圖的方法。從那裏,當我加載或完成加載時,我會調用每個相關的方法。

具體來說,我有四種方法:-hudView,-showLoadingUI,-showLoadingUIWithText:和-hideLoadingUI。

-hudView創建一個新的MBProgressHUD對象(如果尚不存在),並將其添加到當前視圖([self.view addSubview:hudView])。

-showLoadingUI調用-showLoadingUIWithText:使用默認標題,-showLoadingUIWithText:只是取消隱藏MBProgressHUD併爲其設置標籤值(self.hudView.labelText = @「foo」;)。

-hideLoadingUI隱藏hudView([self.hudView hide:YES])。

+0

我想在顯示HUD時顯示HUD,但由於某種原因,它會一直等待循環顯示HUD。這是正常的嗎? – 2010-08-16 02:37:17

+0

這是一個正常的錯誤:試圖從主線程或Web線程以外的線程獲取Web鎖。這可能是從輔助線程調用UIKit的結果。現在崩潰...? – 2010-08-16 02:56:43

+0

通過在主線程中運行我的UI代碼修復了錯誤。 – 2010-08-16 20:55:37

1

首先,我不認爲UIView有方法叫做init。你可以稱它爲超級。您應該調用的適當方法是- (id)initWithFrame:(CGRect)aRect。該框架是您想要顯示的視圖的大小。 More here

另一件事是你爲什麼叫[super.view addSubView:],我認爲它應該是self.view,不是嗎?

+0

是的,[self.view addSubView:loading] 您可能想要考慮將它(加載視圖)分配給一個實例變量,以便您可以跟蹤它,以便您可以稍後從視圖中刪除它。 – 2010-08-16 02:13:53

+0

如果他不想分配它,我認爲沒關係。因爲如果目的只是顯示一次,並釋放整個視圖時釋放。但是如果他想在此之前刪除它,他應該有一個實例變量 – vodkhang 2010-08-16 02:16:32