[英]UIButton how to remove from UIView?
I've set up a Button and add it to a view. 我已经设置了一个Button并将其添加到视图中。 I want to add a "done" button to the UIKeyboardTypeNumberPad. 我想向UIKeyboardTypeNumberPad添加一个“完成”按钮。 Here's my code. 这是我的代码。
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];
}
Everything works great until I want to remove the button if I've got a Kayboard of type NumbersAndPunctuation for example. 例如,如果我有一个NumbersAndPunctuation类型的Kayboard,一切都会很好,直到我想删除按钮为止。
If I click the button I use [(UIButton)*sender removeFromSuperview];
如果单击按钮,则使用[(UIButton)*sender removeFromSuperview];
to prevent memory leaks. 以防止内存泄漏。
But how do I remove the button from within an other function? 但是,如何从其他功能中删除按钮?
Thanks a lot! 非常感谢!
Some other guys did ask that question somewhere else but didn't get a answer. 其他一些人确实在其他地方问过这个问题,但没有得到答案。 I'am sure you can help :) 我确定您可以提供帮助:)
// 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];
}
}
You should store a reference to the button, instead of using a local variable. 您应该存储对按钮的引用,而不是使用局部变量。 For example: 例如:
Header file: 头文件:
@interface myObject : NSObject {
UIButton *doneButton;
...
Implementation file: 实施文件:
doneButton = [UIButton buttonWithType: UIButtonTypeCustom
...
To remove it (assuming you're in the same object: 删除它(假设您在同一个对象中:
[doneButton removeFromSuperview];
However, Apple may not take kindly to you adding buttons to their keyboard. 但是,Apple可能不希望您在键盘上添加按钮。
您可以在.h文件中声明按钮,这样便可以从所有类方法中访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.