繁体   English   中英

从superView中删除自定义视图

[英]Remove Custom View from superView

我有我自己的UIView:

#import <UIKit/UIKit.h>

@interface MultipleSlotsClientView : UIView


-(IBAction)didPressCloseBtn:(id)sender;

@end

这是实施:

@implementation MultipleSlotsClientView

- (id)initWithFrame:(CGRect)frame {
    self = [[[[NSBundle mainBundle] loadNibNamed:@"MultipleSlotsClientView" owner:self options:nil] objectAtIndex:0] retain];
    if (self) {
        self.frame = frame;
    }
    return self;
}

#pragma mark
#pragma mark IBAction

-(IBAction)didPressCloseBtn:(id)sender {
    [self removeFromSuperview];
}

@end

我有一个连接到didPressCloseBtn方法的btn,当我按下按钮时调用的方法,但View不会从didPressCloseBtn删除。

这是我如何分配UIView并添加它:

MultipleSlotsClientView *multiView = [[[MultipleSlotsClientView alloc] initWithFrame:self.view.frame] autorelease];
[self.view addSubview:multiView];

知道为什么视图不会消失吗?

只需尝试连接如下截图,不要连接到FileOwner。 在此输入图像描述

步骤1在NSObject类类中编写以下方法

+ (id)loadNibNamed:(NSString *)NibName {
    NSObject *cl = nil;
    if (NSClassFromString(NibName) != nil) {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed:NibName owner:self options:nil];
        for (id cls in arr) {
            if([cls isKindOfClass:NSClassFromString(NibName)])
            {
                cl = cls;
                break;
            }
        }
    }
    return cl;
}

步骤:2调用相应的类

MultipleSlotsClientView *multiView = [MultipleSlotsClientView loadNibNamed:@"MultipleSlotsClientView"]
[self.view addSubview:multiView];

而且无需在“initWithFrame”中编写任何内容。 尝试这个。 它可能适合你。

这是评论的答案。 只是因为你不能很好地格式化评论。 这是为什么你在代码中泄漏内存以及如何编写代码来克服这个问题。

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Do something here if you have to.
        // Currently there is no reason for overwriting intiWithFrame: at all. 

    }
    return self;
}

而不是:

MultipleSlotsClientView *multiView = [[[MultipleSlotsClientView alloc] initWithFrame:self.view.frame] autorelease];

做就是了:

MultipleSlotsClientView *multiView= [[[[NSBundle mainBundle] loadNibNamed:@"MultipleSlotsClientView" owner:self options:nil] objectAtIndex:0] autorelease];
multiView.frame = self.view.frame;

好吧,你是应该保留还是自动发布它,或者根本不依赖于其他代码。 假设您将multiView添加到子视图层次结构(将保留它),autorelease就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM