簡體   English   中英

UIButton如何從UIView中刪除?

[英]UIButton how to remove from UIView?

我已經設置了一個Button並將其添加到視圖中。 我想向UIKeyboardTypeNumberPad添加一個“完成”按鈕。 這是我的代碼。

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]; 以防止內存泄漏。

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

非常感謝!

其他一些人確實在其他地方問過這個問題,但沒有得到答案。 我確定您可以提供幫助:)

// 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];
    }
}

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

頭文件:

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

實施文件:

doneButton = [UIButton buttonWithType: UIButtonTypeCustom
...

刪除它(假設您在同一個對象中:

[doneButton removeFromSuperview];

但是,Apple可能不希望您在鍵盤上添加按鈕。

您可以在.h文件中聲明按鈕,這樣便可以從所有類方法中訪問

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM