从superView中删除自定义视图

时间:2013-05-15 09:16:49

标签: iphone ios objective-c

我有自己的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不会从superview中删除。

这是我分配UIView并添加它的方式:

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

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

3 个答案:

答案 0 :(得分:2)

尝试连接如下截图,不要连接到FileOwner。enter image description here

答案 1 :(得分:0)

Step-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”中编写任何内容。 试试这个。它可能适合你。

答案 2 :(得分:0)

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

- (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就可以了。