繁体   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