2009-07-31 132 views
30

我正在學習如何在iPhone上開發,我買了一本名爲Beginning iPhone 3的書開發探索SDK。我有點後決定拋棄Interface Builder。我仍然在IB中設計所有視圖,但是我用代碼編寫了所有視圖,只使用nib文件獲取控件的框架。iPhone Dev - 手動創建UIButton

所以現在我需要做一個UIButton,並且文檔與其他控件不同。我嘗試使用initWithFrame:,和其他方法buttonWithType:,我認爲它是autoreleased,但無論如何我無法得到一個按鈕出現在屏幕上。有人可以寫一些代碼在本地創建一個標題按鈕,我可以改變,然後我可以添加到我的意見子視圖和發佈,所以我可以看到它是如何做到的?

回答

83

我想嘗試這樣的事:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    myButton.frame = CGRectMake(20, 20, 200, 44); // position in the parent view and set the size of the button 
    [myButton setTitle:@"Click Me!" forState:UIControlStateNormal]; 
    // add targets and actions 
    [myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    // add to a view 
    [superView addSubview:myButton]; 

免責聲明:就在這裏輸入此。目前我無法訪問我的Mac,因此無法對其進行測試。

P.S.任何不使用Interface Builder的特殊原因?只是好奇。

+1

假設選擇器`buttonClicked:`存在,這是完全有效的,並且是一個很好的解決方法。 +1 – Tim 2009-07-31 03:09:29