我正在使用数字键盘,我正在向左下角添加一个完成键。我想从键盘上删除此按钮,因为后来我想使用普通键盘,完成按钮仍然显示。我在全球宣布UIButton并在其上调用removeFromSuperview。什么都没发生。此外,如果我使用与添加它相同的方法调用removeFromSuperview,它会成功删除该按钮。这是一些代码。
-(void)addHideKeyboardButtonToKeyboard{
// Locate non-UIWindow.
keyboardWindow=nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
if (!keyboardWindow) return;
// Locate UIKeyboard.
UIView *foundKeyboard = nil;
for (UIView *possibleKeyboard in [keyboardWindow subviews]) {
// iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) {
possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
}
if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) {
foundKeyboard = possibleKeyboard;
break;
}
}
if (foundKeyboard) {
// create custom button
NSString *deviceType = [UIDevice currentDevice].model;
if(!([deviceType isEqualToString:@"iPad"] || [deviceType isEqualToString:@"iPad Simulator" ]))
{
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(textFieldShouldReturn:) forControlEvents:UIControlEventTouchUpInside];
[foundKeyboard addSubview:doneButton];
}
}
}
并删除doneButton
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[doneButton removeFromSuperView];
}
答案 0 :(得分:0)
一个可行的选择是将doneButton设置为nil,然后在需要时重新分配并初始化它......不像错误的removeFromSuperview:那么简单,但仍然是一个选项。如果我错了,请纠正我,因为我认为我建议的方法可能会导致内存泄漏。
答案 1 :(得分:0)
addHideKeyboard是一个添加到NSNotificationCenter的选择器,这意味着每次键盘出现时,都会重新添加完成按钮。
答案 2 :(得分:0)
由于您是通过NotificationCenter
完成的,因此在移出此viewController时可能需要删除observer
(可能在加载新的ViewController
之前或解除当前控制器。)< / p>
因此,假设您已将NotificationCenter
添加到需要“完成按钮”的ViewDidLoad
的{{1}}中。
xxxViewController
现在,一旦你移到[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(addHideKeyboardButtonToKeyboard:)
name:UIKeyboardWillShowNotification
object:nil];
这样的地方,然后先删除yyyViewController
。
observer
我知道,这是一种历史问题,但它现在才引起我的注意。