2010-01-13 86 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]; 
    } 
}