2010-01-13 83 views
1

我已經設置了一個按鈕並將其添加到視圖中。我想向UIKeyboardTypeNumberPad添加一個「完成」按鈕。這是我的代碼。UIButton如何從UIView中刪除?

UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    doneButton.frame = CGRectMake(0, 163, 106, 53); 
    doneButton.adjustsImageWhenHighlighted = NO; 
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal]; 
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted]; 
    [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside]; 

    // locate keyboard view 
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; 
    UIView* keyboard; 
    for(int i=0; i<[tempWindow.subviews count]; i++) { 
     keyboard = [tempWindow.subviews objectAtIndex:i]; 
     // keyboard view found; add the custom button to it 
     if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) 
      [keyboard addSubview:doneButton]; 
    } 

一切都很好,直到我想要刪除按鈕,例如我有一個類型爲NumbersAndPunctuation的Kayboard。

如果我點擊按鈕,我使用[(UIButton)*sender removeFromSuperview]; 來防止內存泄漏。

但是,如何從其他功能中刪除按鈕?

非常感謝!

其他一些人確實在別的地方問過這個問題,但沒有得到答案。我確信你可以幫助:)

回答

2

你應該存儲對按鈕的引用,而不是使用局部變量。例如:

頭文件

@interface myObject : NSObject { 
    UIButton *doneButton; 
    ... 

實現文件:

doneButton = [UIButton buttonWithType: UIButtonTypeCustom 
... 

要刪除它(假設你在同一個對象是:

[doneButton removeFromSuperview]; 

不過,蘋果可能不會友善地向您的鍵盤添加按鈕。

+0

訪問謝謝, 我已經嘗試過,但沒有成功。我的整個鍵盤被刪除... 一些其他開發者成功提交了應用程序與額外的按鈕:) 希望我的也被接受。 – rdesign 2010-01-13 14:02:30

+0

我用過,但是當我觸摸另一個鍵盤時,「完成」按鈕仍然存在 – user1561904 2013-05-07 17:19:31

0

你可以在你的.h文件中聲明你的按鈕,這樣你就可以得到所有的類方法

+0

感謝你,以及我已經嘗試過了。它使我困惑,但它,它刪除了整個鍵盤... – rdesign 2010-01-13 14:07:16

+0

你們都是對的。我已經創建了一個新的應用程序。我從頭開始編碼,它工作。 ...混亂。非常感謝! – rdesign 2010-01-13 14:26:14

7
// Where self is a UIView subclass 
NSLog(@"subviews: %@",self.subviews); 
for(id view in self.subviews){ 
    if ([view isKindOfClass:[UIButton class]]) { 
     NSLog(@"Removing a button!"); 
     [view removeFromSuperview]; 
    } 
}