如何在Cocoa中清除NSView上的所有对象

时间:2013-07-23 07:37:52

标签: objective-c macos nsview

我希望在调用任何函数之前清除添加到NSVIew的所有对象。 我怎么能这样做?

2 个答案:

答案 0 :(得分:5)

我使用以下功能

-(void)clearAllSubviewsOfView :(NSView *)parent
{
    for (NSView *subview in [parent subviews]) {
        [subview removeFromSuperview];
    }
}

答案 1 :(得分:0)

你可以做这样的事情:

// TSClearSupporting.h

@protocol TSClearSupporting <NSObject>
- (void) clear;
@end

// TSTextField.h

#import <Cocoa/Cocoa.h>
#import "TSClearSupporting.h"

@interface TSTextField : NSTextField <TSClearSupporting>
@end

// TSTextField.m

#import "TSTextField.h"

@implementation TSTextField
- (void) clear
{
    self.stringValue = @"";
}
@end

// TSMainView.m

#import "TSMainView.h"
#import "TSClearSupporting.h"

@implementation TSMainView

- (IBAction) clearAll: (id)sender
{
    NSArray* subViews = self.subviews;

    for (NSView* view in subViews)
    {
        if ([view conformsToProtocol: @protocol(TSClearSupporting)])
        {
            [view performSelector: @selector(clear)];
        }
    }
}