2012-06-21 43 views
-1

我目前正在設計一個應用程序,需要動態創建對象,然後在ViewController中顯示它們。我的問題是涉及文檔來嘗試創建我需要的對象。我已經做了一些搜索,甚至試圖坐下來弄清楚,但唉,我沒有什麼可以證明的。我已經知道如何動態創建ViewController,但我似乎無法獲取任何對象。用iPhone代碼創建/顯示界面對象[Objective-C]

有沒有人知道我可以如何使用XCode中的Objective-C動態創建對象(說一個按鈕和一個滑塊)?

回答

1

在代碼中創建一個按鈕是簡單

- (void)addButton { 

    // Create button 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

    // Set the frame (location and size) 
    [button setFrame:CGRectMake(0, 0, 40, 30)]; 

    // Set what happens when you touch the button 
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; 

    // Set button text 
    [button.titleLabel setText:@"Button"]; 

    // Add button to view 
    [self.view addSubview:button]; 

} 

很多界面元素遵循類似patter- alloc和初始化該目的,設置幀並將其添加到的視圖。

+0

非常感謝斯科特!我找不到像您提供的那樣簡單直接的答案。我知道這比我想象的要簡單得多。 –

+0

我習慣於使用界面構建器 - 我想要自己編碼的挑戰,以及需要將其用於當前項目。 我將如何去釋放動態創建的對象? –

+0

調用[button removeFromSuperview]將其從視圖層次結構中刪除。如果以前保留它,則需要將其釋放。如果你不需要將它保存在超級視圖之外,你不需要保留它,因爲超級視圖會保留它,只要記得在調用removeFromSuperview之後將指針設置爲零,或者你將留下一個搖晃的指針。 – Taum